` can be included. (Defines NV_ENABLE_PROFILER, on by default)
+- `enable_simd`: Enable usage of any SIMD extension. (Defines NV_ENABLE_SIMD, on by default)
+- `use_doubles`: Use double-precision floats. (Defines NV_USE_DOUBLE_PRECISION, off by default)
-If successful, the unit tests will be run and results will be shown on the terminal.
\ No newline at end of file
+For instance, if you didn't want to build example demos and just the static library, you could do `$ meson configure -Dbuild_examples=false`.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1d51e50..f4aec84 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -82,8 +82,8 @@ void nv_some_function(...);
// Enums are in PascalCase, with their fields being the enum name + field name in full caps
typedef enum {
- nv_SomeEnum_FIELD1,
- nv_SomeEnum_FIELD2,
+ nvSomeEnum_FIELD1,
+ nvSomeEnum_FIELD2,
...
-} nv_SomeEnum;
+} nvSomeEnum;
```
\ No newline at end of file
diff --git a/README.md b/README.md
index 712f64a..36bb8ff 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,13 @@
![](https://raw.githubusercontent.com/kadir014/kadir014.github.io/master/assets/novaphysics.png)
-
+
-Nova Physics is a lightweight and easy to use 2D physics engine.
+Nova Physics is a lightweight and easy to use 2D physics engine designed with game development in mind.
+
+
You can also read this page in
@@ -18,38 +20,37 @@ Nova Physics is a lightweight and easy to use 2D physics engine.
# Features
- Simple and user-friendly interface
+- Portable codebase with no dependencies
- Rigid body dynamics
-- Primitive shape collisions (circle, rect, polygon, AABB)
-- Broad-phase strategies (Spatial hashing & BVH-tree)
-- Physical material properties (friction, restitution and density)
-- Joint constraints (spring, distance, hinge ..)
-- Great stacking stability and collision persistence
-- [Erin Catto's](https://box2d.org/files/ErinCatto_SequentialImpulses_GDC2006.pdf) iterative sequential impulse solver algorithm
+- Discrete collision detection
+ - Circle shape
+ - Convex polygon shape
+ - Testing shapes against shapes
+ - Testing shapes against point
+ - Ray casting
+- One-shot contact manifold generation between shapes
+- Multiple shapes per body
+- Broadphase strategies
+ - Bruteforce
+ - Bounding volume hierarchy tree
+- Material properties (friction, restitution and density)
+- Constraints between bodies
+ - Distance constraint - can also behave like spring
+ - Hinge constraint
+ - Spline path constraint
+- [Erin Catto's](https://box2d.org/files/ErinCatto_SequentialImpulses_GDC2006.pdf) sequential impulse solver algorithm
+- Great stacking stability
- Semi-implicit (symplectic) Euler integrator
-- Collision event callbacks
-- Sleeping bodies to reduce CPU load
-- Attractive forces
+- Collision filtering with masks and grouping
- Built-in profiler
-- Portable codebase with no dependencies
-- Various interactive example demos using SDL2
-
-
-
-# Roadmap & Future
-Nova Physics is still in its early stages as in `0.x.x` versions. There is a large room of improvement and optimization of the API and engine's itself. Here are some of the important points that needs a touch before reaching the `1.x.x` milestone:
+- Optional double-precision mode
+- Various interactive demos using SDL2 & OpenGL
-- ### Better & faster broad-phase
- Current broad-phase strategies available in Nova are a spatial hash grid and a BVH (bounding volume hierarchy) tree. Both are fast but there is still room for improvement, especially for BVH-tree construction and multi-threaded SHG tasks.
-- ### Python binding
- Nova Physics's Python module ([here](https://github.com/kadir014/nova-physics-python)) is still WIP. I plan it to have an easy-to-use Pythonic interface. Other language binding contributions are also always welcome!
+# Building
+The library uses C99 standard and depends only on the C STL.
-
-
-# Installing & Building
-Development libraries are always shipped with the most recent release under the name of `nova-physics-X.X.X-devel.zip` (or `.tar.gz`). You can download the archive [here](https://github.com/kadir014/nova-physics/releases) and link `libnova.a` (or `libnova.lib`) with your favorite compiler to use Nova Physics in your project.
-
-But if you want (*or need*) to build Nova Physics from scratch on your own, use [the building guide](https://github.com/kadir014/nova-physics/blob/main/BUILDING.md#building-nova-physics-static-libraries).
+For further instructions see [here](BUILDING.md).
@@ -57,29 +58,33 @@ But if you want (*or need*) to build Nova Physics from scratch on your own, use
-Example demos are in [examples](https://github.com/kadir014/nova-physics/blob/main/examples/) directory, use [the example building guide](https://github.com/kadir014/nova-physics/blob/main/BUILDING.md#running-nova-physics-example-demos) to run examples.
+Example demos are in [examples](https://github.com/kadir014/nova-physics/blob/main/examples/) directory, enable building demos option in the build system (if not already enabled).
# Documentation
-You can access the documentations [here](https://nova-physics.rtfd.io).
+You can access the documentation including the API reference [here](https://nova-physics.rtfd.io).
+
+If you are just getting started, you can use the [introduction page](https://nova-physics.readthedocs.io/en/latest/getting_started/index.html).
# Resources & References
-Following are some of the many great resources that helped me to build Nova Physics to this state.
-- **Erin Catto**, [GDC Presentations](https://box2d.org/publications/)
+Nova is a passion and learning project for me, and following are some of the many great resources that helped me along the way.
+- **Erin Catto**, [GDC Presentations](https://box2d.org/publications/) and [Box2D](https://github.com/erincatto/box2c)
- **Chris Hecker**, [Rigid Body Dynamics](https://chrishecker.com/Rigid_Body_Dynamics)
+- **Ian Millington**, [Game Physics Engine Development](https://www.r-5.org/files/books/computers/algo-list/realtime-3d/Ian_Millington-Game_Physics_Engine_Development-EN.pdf)
+- **Christer Ericson**, [Real-Time Collision Detection](https://www.r-5.org/files/books/computers/algo-list/realtime-3d/Christer_Ericson-Real-Time_Collision_Detection-EN.pdf)
+- **Dirk Gregorius**, [Robust Contact Creation for Physics Simulations](http://media.steampowered.com/apps/valve/2015/DirkGregorius_Contacts.pdf)
- **Randy Gaul**, [Game Physics Articles](https://tutsplus.com/authors/randy-gaul)
- **Allen Chou**, [Physics Blogs](https://allenchou.net/category/physics/)
+- **Jacco Bikker**, [How to build a BVH](https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/)
- **Marjin Tamis** & **Giuseppe Maggiore**, [Constraint Based Physics Solver](http://mft-spirit.nl/files/MTamis_ConstraintBasedPhysicsSolver.pdf)
- **Micheal Manzke**, [Multiple Contact Resolution](https://www.scss.tcd.ie/~manzkem/CS7057/cs7057-1516-10-MultipleContacts-mm.pdf)
-- **Dirk Gregorius**, [Robust Contact Creation for Physics Simulations](http://media.steampowered.com/apps/valve/2015/DirkGregorius_Contacts.pdf)
-- **Andrew Sevenson**, [Separating Axis Theorem Explanation](https://www.sevenson.com.au/programming/sat/)
# License
[MIT](LICENSE) © Kadir Aksoy
-Nova Physics is, and always will be, free and open-source. Although we would greatly appreciate [donations!](https://www.buymeacoffee.com/kadir014)
\ No newline at end of file
+Nova Physics is, and always will be, free and open-source. Although I would greatly appreciate [sponsorships!](https://github.com/sponsors/kadir014)
\ No newline at end of file
diff --git a/benchmarks/README.md b/benchmarks/README.md
index e4b4199..b13d386 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -4,39 +4,15 @@ All benchmarks were run on:
- Intel i5 6402P 4-core @ 2.8GHz
- 16GB DDR4 RAM
-Chipmunk2D and Box2D tests are used as a baseline to see how Nova Physics has progressed so far performance-wise. All benchmark scenes use the same configuration among all engines; 10 velocity and position iterations, 60Hz simulation.
+Chipmunk2D and Box2D tests are used as references to see how Nova Physics has progressed so far performance-wise. All benchmarks uses the same configuration among all engines:
+- 1/60 seconds of timestep
+- 10 velocity solving iterations
+- 10 position/relax iterations
+- Continous collision detection is disabled
+- Sleeping is disabled
+- Warm-starting is enabled
Data points gathered for each benchmark includes thousands of simulation steps for each engine to converge to an accurate result.
-## Mixer (`mixer.c`)
-6000 steps, 1500 objects constantly moving
-| Physics Engine | Average physics time (ms) |
-|----------------------|---------------------------|
-| Nova `0.5.1` | 23.65 |
-| Nova `0.7.0` | 10.44 |
-| Box2D `2.3.1` | 10.90 |
-| Box2D `3.0.0 alpha` | - |
-| Chipmunk2D `7.0.3` | 4.33 |
-
-
-## Boxes (`boxes.c`)
-5000 steps, 3500 objects minimal movement
-| Physics Engine | Average physics time (ms) |
-|----------------------|---------------------------|
-| Nova `0.5.1` | 73.70 |
-| Nova `0.7.0` | 32.21 |
-| Box2D `2.3.1` | 46.43 |
-| Box2D `3.0.0 alpha` | - |
-| Chipmunk2D `7.0.3` | 17.41 |
-
-
-## Ball Pool (`ball_pool.c`)
-4000 steps, 9000 objects average movement
-| Physics Engine | Average physics time (ms) |
-|----------------------|---------------------------|
-| Nova `0.5.1` | 126.76 |
-| Nova `0.7.0` | 62.09 |
-| Box2D `2.3.1` | 71.38 |
-| Box2D `3.0.0 alpha` | - |
-| Chipmunk2D `7.0.3` | 41.69 |
\ No newline at end of file
+# TODO: Update benchmarks with 1.0.0
\ No newline at end of file
diff --git a/benchmarks/ball_pool.c b/benchmarks/ball_pool.c
deleted file mode 100644
index da5cc1e..0000000
--- a/benchmarks/ball_pool.c
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include
-#include "benchmark_base.h"
-#include "novaphysics/novaphysics.h"
-
-
-/**
- * @file ball_pool.c
- *
- * @brief Ball pool benchmark. 9000 objects with average movement.
- */
-
-
-enum {
- BENCHMARK_ITERS = 4000,
- BENCHMARK_HERTZ = 60,
- BENCHMARK_VELOCITY_ITERATIONS = 10,
- BENCHMARK_POSITION_ITERATIONS = 10,
- BENCHMARK_CONSTRAINT_ITERATIONS = 5
-};
-
-
-int main(int argc, char *argv[]) {
- // Setup benchmark
-
- nvSpace *space = nvSpace_new();
-
- Benchmark bench = Benchmark_new(BENCHMARK_ITERS, space);
-
- nvMaterial ground_mat = (nvMaterial){1.0, 0.0, 0.7};
-
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 74.0),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, ground);
-
- nvBody *ceiling = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, -2.0),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, ceiling);
-
- nvBody *wall_left = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 100.0),
- NV_VEC2(64.0 - 50.0, 36.0),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, wall_left);
-
- nvBody *wall_right = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 100.0),
- NV_VEC2(64.0 + 50.0, 36.0),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, wall_right);
-
- size_t rows = 90;
- size_t cols = 100;
- nv_float size = 0.75;
-
- for (size_t y = 0; y < rows; y++) {
- for (size_t x = 0; x < cols; x++) {
- nvBody *ball = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(size / 2.0),
- NV_VEC2(
- 64.0-50.0 + size*4.0 + ((nv_float)x) * size + (nv_float)((x*x + y*y) % 10) / 10.0,
- 70.0 - ((nv_float)y) * size
- ),
- 0.0,
- (nvMaterial){1.0, 0.0, 0.0}
- );
-
- nvSpace_add(space, ball);
- }
- }
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID) {
- nvSpace_set_SHG(space, space->shg->bounds, 0.75, 0.75);
- nvSpace_enable_multithreading(space, 0);
- }
-
- // Run benchmark
- for (size_t i = 0; i < bench.iters; i++) {
- nv_float dt = 1.0 / (nv_float)BENCHMARK_HERTZ;
-
- Benchmark_start(&bench);
-
- nvSpace_step(
- space,
- dt,
- BENCHMARK_VELOCITY_ITERATIONS,
- BENCHMARK_POSITION_ITERATIONS,
- BENCHMARK_CONSTRAINT_ITERATIONS,
- 1
- );
-
- Benchmark_stop(&bench);
- }
-
- Benchmark_results(&bench);
-
-
- nvSpace_free(space);
-}
\ No newline at end of file
diff --git a/benchmarks/benchmark_base.h b/benchmarks/benchmark_base.h
index 3970ec5..2d6d420 100644
--- a/benchmarks/benchmark_base.h
+++ b/benchmarks/benchmark_base.h
@@ -145,15 +145,16 @@ typedef struct {
double *times;
double *integrate_accelerations;
double *broadphase;
- double *update_resolutions;
- double *narrowphase;
- double *presolve_collisions;
- double *solve_positions;
- double *solve_velocities;
- double *integrate_velocities;
+ double *broadphase_finalize;
double *bvh_build;
double *bvh_traverse;
double *bvh_destroy;
+ double *narrowphase;
+ double *presolve;
+ double *warmstart;
+ double *solve_velocities;
+ double *solve_positions;
+ double *integrate_velocities;
size_t _index;
FILE *output;
} Benchmark;
@@ -165,22 +166,25 @@ Benchmark Benchmark_new(size_t iters, nvSpace *space) {
Benchmark bench;
bench.space = space;
- bench.timer = (nvPrecisionTimer *)malloc(sizeof(nvPrecisionTimer));
- bench.global_timer = (nvPrecisionTimer *)malloc(sizeof(nvPrecisionTimer));
+ bench.timer = NV_NEW(nvPrecisionTimer);
+ bench.global_timer = NV_NEW(nvPrecisionTimer);
+
nvPrecisionTimer_start(bench.global_timer);
+
bench.iters = iters;
- bench.times = (double *)malloc(sizeof(double) * bench.iters);
- bench.integrate_accelerations = (double *)malloc(sizeof(double) * bench.iters);
- bench.broadphase = (double *)malloc(sizeof(double) * bench.iters);
- bench.update_resolutions = (double *)malloc(sizeof(double) * bench.iters);
- bench.narrowphase = (double *)malloc(sizeof(double) * bench.iters);
- bench.presolve_collisions = (double *)malloc(sizeof(double) * bench.iters);
- bench.solve_positions = (double *)malloc(sizeof(double) * bench.iters);
- bench.solve_velocities = (double *)malloc(sizeof(double) * bench.iters);
- bench.integrate_velocities = (double *)malloc(sizeof(double) * bench.iters);
- bench.bvh_build = (double *)malloc(sizeof(double) * bench.iters);
- bench.bvh_traverse = (double *)malloc(sizeof(double) * bench.iters);
- bench.bvh_destroy = (double *)malloc(sizeof(double) * bench.iters);
+ bench.times = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.integrate_accelerations = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.broadphase = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.broadphase_finalize = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.narrowphase = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.presolve = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.solve_velocities = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.warmstart = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.solve_positions = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.integrate_velocities = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.bvh_build = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.bvh_traverse = (double *)NV_MALLOC(sizeof(double) * bench.iters);
+ bench.bvh_destroy = (double *)NV_MALLOC(sizeof(double) * bench.iters);
bench._index = 0;
srand(time(NULL));
@@ -200,39 +204,38 @@ static inline void Benchmark_stop(Benchmark *bench) {
nvPrecisionTimer_stop(bench->timer);
nvPrecisionTimer_stop(bench->global_timer);
- bench->times[bench->_index] = bench->timer->elapsed;
-
- if (space) {
- bench->integrate_accelerations[bench->_index] = space->profiler.integrate_accelerations;
- bench->broadphase[bench->_index] = space->profiler.broadphase;
- bench->update_resolutions[bench->_index] = space->profiler.update_resolutions;
- bench->narrowphase[bench->_index] = space->profiler.narrowphase;
- bench->presolve_collisions[bench->_index] = space->profiler.presolve_collisions;
- bench->solve_positions[bench->_index] = space->profiler.solve_positions;
- bench->solve_velocities[bench->_index] = space->profiler.solve_velocities;
- bench->integrate_velocities[bench->_index] = space->profiler.integrate_velocities;
- bench->bvh_build[bench->_index] = space->profiler.bvh_build;
- bench->bvh_traverse[bench->_index] = space->profiler.bvh_traverse;
- bench->bvh_destroy[bench->_index] = space->profiler.bvh_destroy;
-
- // Append frame stats to output file
- fprintf(
- bench->output,
- "%f:%f:%f:%f:%f:%f:%f:%f:%f:%f:%f:%f\n",
- bench->timer->elapsed * 1000,
- space->profiler.integrate_accelerations * 1000,
- space->profiler.broadphase * 1000,
- space->profiler.update_resolutions * 1000,
- space->profiler.narrowphase * 1000,
- space->profiler.presolve_collisions * 1000,
- space->profiler.solve_positions * 1000,
- space->profiler.solve_velocities * 1000,
- space->profiler.integrate_velocities * 1000,
- space->profiler.bvh_build * 1000,
- space->profiler.bvh_traverse * 1000,
- space->profiler.bvh_destroy * 1000
- );
- }
+ bench->times[bench->_index] = space->profiler.step;
+ bench->integrate_accelerations[bench->_index] = space->profiler.integrate_accelerations;
+ bench->broadphase[bench->_index] = space->profiler.broadphase;
+ bench->broadphase_finalize[bench->_index] = space->profiler.broadphase_finalize;
+ bench->narrowphase[bench->_index] = space->profiler.narrowphase;
+ bench->presolve[bench->_index] = space->profiler.presolve;
+ bench->warmstart[bench->_index] = space->profiler.warmstart;
+ bench->solve_positions[bench->_index] = space->profiler.solve_positions;
+ bench->solve_velocities[bench->_index] = space->profiler.solve_velocities;
+ bench->integrate_velocities[bench->_index] = space->profiler.integrate_velocities;
+ bench->bvh_build[bench->_index] = space->profiler.bvh_build;
+ bench->bvh_traverse[bench->_index] = space->profiler.bvh_traverse;
+ bench->bvh_destroy[bench->_index] = space->profiler.bvh_free;
+
+ // Append frame stats to output file
+ fprintf(
+ bench->output,
+ "%f:%f:%f:%f:%f:%f:%f:%f:%f:%f:%f:%f:%f\n",
+ space->profiler.step * 1000,
+ space->profiler.integrate_accelerations * 1000,
+ space->profiler.broadphase * 1000,
+ space->profiler.broadphase_finalize * 1000,
+ space->profiler.bvh_build * 1000,
+ space->profiler.bvh_traverse * 1000,
+ space->profiler.bvh_free * 1000,
+ space->profiler.narrowphase * 1000,
+ space->profiler.presolve * 1000,
+ space->profiler.warmstart * 1000,
+ space->profiler.solve_velocities * 1000,
+ space->profiler.solve_positions * 1000,
+ space->profiler.integrate_velocities * 1000
+ );
double elapsed = bench->global_timer->elapsed;
@@ -275,29 +278,17 @@ void Benchmark_results(Benchmark *bench) {
// Overwrite progress bbar
printf(" \n\033[1G\033[1A\n");
- char *text_multithreading = "disabled";
- unsigned long long text_thread_count = 0;
-
- if (bench->space) {
- text_multithreading = (bench->space->multithreading) ? "enabled" : "disabled";
- text_thread_count = (unsigned long long)bench->space->thread_count;
- }
-
printf(
"Nova Physics benchmark finished successfully.\n"
"=============================================\n"
"Benchmark took %02d:%02d:%02d\n"
- "Nova version: %d.%d.%d\n"
+ "Nova version: %s\n"
"Compiled with %s\n"
- "Platform: %s\n"
- "Multithreading: %s\n"
- "Thread count: %llu\n",
+ "Platform: %s\n",
ela_hours, ela_mins, ela_secs,
- NV_VERSION_MAJOR, NV_VERSION_MINOR, NV_VERSION_PATCH,
+ NV_VERSION_STRING,
BENCHMARK_COMPILER_STR,
- BENCHMARK_PLATFORM_STR,
- text_multithreading,
- text_thread_count
+ BENCHMARK_PLATFORM_STR
);
Stats stats0;
@@ -316,63 +307,69 @@ void Benchmark_results(Benchmark *bench) {
print_stats(stats2);
Stats statsa;
- calculate_stats(&statsa, bench->update_resolutions, bench->iters);
- printf("\nUpdate resolutions:\n---------------------\n");
+ calculate_stats(&statsa, bench->broadphase_finalize, bench->iters);
+ printf("\nBroad-phase finalize:\n---------------------\n");
print_stats(statsa);
+ Stats statsb;
+ calculate_stats(&statsb, bench->bvh_build, bench->iters);
+ printf("\nBVH-tree build:\n---------------------\n");
+ print_stats(statsb);
+
+ Stats stats8;
+ calculate_stats(&stats8, bench->bvh_traverse, bench->iters);
+ printf("\nBVH-tree traverse:\n---------------------\n");
+ print_stats(stats8);
+
+ Stats stats9;
+ calculate_stats(&stats9, bench->bvh_destroy, bench->iters);
+ printf("\nBVH-tree destroy:\n---------------------\n");
+ print_stats(stats9);
+
Stats stats7;
calculate_stats(&stats7, bench->narrowphase, bench->iters);
printf("\nNarrow-phase:\n---------------------\n");
print_stats(stats7);
Stats stats3;
- calculate_stats(&stats3, bench->presolve_collisions, bench->iters);
- printf("\nPresolve collisions:\n---------------------\n");
+ calculate_stats(&stats3, bench->presolve, bench->iters);
+ printf("\nPresolve:\n---------------------\n");
print_stats(stats3);
- Stats stats4;
- calculate_stats(&stats4, bench->solve_positions, bench->iters);
- printf("\nSolve positions:\n---------------------\n");
- print_stats(stats4);
+ Stats statsw;
+ calculate_stats(&statsw, bench->warmstart, bench->iters);
+ printf("\nWarmstarting:\n---------------------\n");
+ print_stats(statsw);
Stats stats5;
calculate_stats(&stats5, bench->solve_velocities, bench->iters);
printf("\nSolve velocities:\n---------------------\n");
print_stats(stats5);
+ // Stats stats4;
+ // calculate_stats(&stats4, bench->solve_positions, bench->iters);
+ // printf("\nSolve positions:\n---------------------\n");
+ // print_stats(stats4);
+
Stats stats6;
calculate_stats(&stats6, bench->integrate_velocities, bench->iters);
printf("\nIntegrate velocities:\n---------------------\n");
print_stats(stats6);
- Stats statsb;
- calculate_stats(&statsb, bench->bvh_build, bench->iters);
- printf("\nBVH-tree build:\n---------------------\n");
- print_stats(statsb);
-
- Stats stats8;
- calculate_stats(&stats8, bench->bvh_traverse, bench->iters);
- printf("\nBVH-tree traverse:\n---------------------\n");
- print_stats(stats8);
-
- Stats stats9;
- calculate_stats(&stats9, bench->bvh_destroy, bench->iters);
- printf("\nBVH-tree destroy:\n---------------------\n");
- print_stats(stats9);
-
- free(bench->timer);
- free(bench->times);
- free(bench->integrate_accelerations);
- free(bench->broadphase);
- free(bench->update_resolutions);
- free(bench->narrowphase);
- free(bench->presolve_collisions);
- free(bench->solve_positions);
- free(bench->solve_velocities);
- free(bench->integrate_velocities);
- free(bench->bvh_build);
- free(bench->bvh_traverse);
- free(bench->bvh_destroy);
+ NV_FREE(bench->timer);
+ NV_FREE(bench->times);
+ NV_FREE(bench->integrate_accelerations);
+ NV_FREE(bench->broadphase);
+ NV_FREE(bench->broadphase_finalize);
+ NV_FREE(bench->narrowphase);
+ NV_FREE(bench->presolve);
+ NV_FREE(bench->warmstart);
+ NV_FREE(bench->solve_positions);
+ NV_FREE(bench->solve_velocities);
+ NV_FREE(bench->integrate_velocities);
+ NV_FREE(bench->bvh_build);
+ NV_FREE(bench->bvh_traverse);
+ NV_FREE(bench->bvh_destroy);
fclose(bench->output);
}
diff --git a/benchmarks/boxes.c b/benchmarks/boxes.c
deleted file mode 100644
index 4b377f7..0000000
--- a/benchmarks/boxes.c
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include
-#include "benchmark_base.h"
-#include "novaphysics/novaphysics.h"
-
-
-/**
- * @file boxes.c
- *
- * @brief Boxes benchmark. 3500 objects with minimal movement.
- */
-
-
-enum {
- BENCHMARK_ITERS = 5000,
- BENCHMARK_HERTZ = 60,
- BENCHMARK_VELOCITY_ITERATIONS = 10,
- BENCHMARK_POSITION_ITERATIONS = 10,
- BENCHMARK_CONSTRAINT_ITERATIONS = 5
-};
-
-
-int main(int argc, char *argv[]) {
- // Setup benchmark
-
- nvSpace *space = nvSpace_new();
-
- Benchmark bench = Benchmark_new(BENCHMARK_ITERS, space);
-
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(89.0, 5.0),
- NV_VEC2(64.0, 72),
- 0.0,
- (nvMaterial){1.0, 0.1, 0.7}
- );
-
- nvSpace_add(space, ground);
-
- nvBody *wall_l = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 80.0),
- NV_VEC2(22.0, 36.0),
- 0.0,
- (nvMaterial){1.0, 0.1, 0.7}
- );
-
- nvSpace_add(space, wall_l);
-
- nvBody *wall_r = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 80.0),
- NV_VEC2(128.0 - 22.0, 36.0),
- 0.0,
- (nvMaterial){1.0, 0.1, 0.7}
- );
-
- nvSpace_add(space, wall_r);
-
- // Create stacked boxes
-
- int cols = 70; // Columns of the stack
- int rows = 50; // Rows of the stack
- nv_float size = 1.0; // Size of the boxes
- nv_float s2 = size / 2.0;
- nv_float ygap = 0.0;
- nv_float starty = 67.0;
-
- for (size_t y = 0; y < rows; y++) {
- for (size_t x = 0; x < cols; x++) {
-
- nv_float sizen = frand(3.75 / 10.0, 18.75 / 10.0);
-
- nvBody *box = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(sizen, sizen),
- NV_VEC2(
- 1280.0 / 20.0 - (nv_float)cols * s2 + s2 + size * x,
- starty - size - y * (size + ygap)
- ),
- 0.0,
- (nvMaterial){1.0, 0.1, 0.2}
- );
-
- nvSpace_add(space, box);
- }
- }
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID) {
- nvSpace_set_SHG(space, space->shg->bounds, 1.9, 1.9);
- nvSpace_enable_multithreading(space, 0);
- }
-
- // Run benchmark
- for (size_t i = 0; i < bench.iters; i++) {
- nv_float dt = 1.0 / (nv_float)BENCHMARK_HERTZ;
-
- Benchmark_start(&bench);
-
- nvSpace_step(
- space,
- dt,
- BENCHMARK_VELOCITY_ITERATIONS,
- BENCHMARK_POSITION_ITERATIONS,
- BENCHMARK_CONSTRAINT_ITERATIONS,
- 1
- );
-
- Benchmark_stop(&bench);
- }
-
- Benchmark_results(&bench);
-
-
- nvSpace_free(space);
-}
\ No newline at end of file
diff --git a/benchmarks/main.c b/benchmarks/main.c
new file mode 100644
index 0000000..69f4db4
--- /dev/null
+++ b/benchmarks/main.c
@@ -0,0 +1,56 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include
+#include "benchmark_base.h"
+#include "novaphysics/novaphysics.h"
+
+#include "scenes/scene_pyramid.h"
+
+
+/**
+ * @file benchmarks/main.c
+ *
+ * @brief Nova benchmarks entry point.
+ */
+
+
+enum {
+ BENCHMARK_ITERS = 1000,
+ BENCHMARK_HERTZ = 60,
+ BENCHMARK_VELOCITY_ITERATIONS = 10
+};
+
+
+int main(int argc, char *argv[]) {
+ nvSpace *space = nvSpace_new();
+ space->settings.velocity_iterations = BENCHMARK_VELOCITY_ITERATIONS;
+
+ // Pyramid scene
+ {
+ Benchmark bench = Benchmark_new(BENCHMARK_ITERS, space);
+
+ Pyramid_setup(space);
+
+ for (size_t i = 0; i < bench.iters; i++) {
+ nv_float dt = 1.0 / (nv_float)BENCHMARK_HERTZ;
+
+ Benchmark_start(&bench);
+ nvSpace_step(space, dt);
+ Benchmark_stop(&bench);
+ }
+
+ Benchmark_results(&bench);
+
+ nvSpace_clear(space, true);
+ }
+
+ nvSpace_free(space);
+}
\ No newline at end of file
diff --git a/benchmarks/mixer.c b/benchmarks/mixer.c
deleted file mode 100644
index a3b645f..0000000
--- a/benchmarks/mixer.c
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include
-#include "benchmark_base.h"
-#include "novaphysics/novaphysics.h"
-
-
-/**
- * @file mixer.c
- *
- * @brief Mixer benchmark. 1500 objects constantly moving.
- */
-
-
-enum {
- BENCHMARK_ITERS = 6000,
- BENCHMARK_HERTZ = 60,
- BENCHMARK_VELOCITY_ITERATIONS = 10,
- BENCHMARK_POSITION_ITERATIONS = 10,
- BENCHMARK_CONSTRAINT_ITERATIONS = 5
-};
-
-
-void update(nvSpace *space, int counter) {
- if (counter == 0) return;
-
- nvBody *mixer = space->bodies->data[5];
-
- nv_float angle = ((nv_float)counter) / 25.0;
-
- nvVector2 next_pos = NV_VEC2(
- nv_cos(angle) * 17.0 + 64.0,
- nv_sin(angle) * 17.0 + (72.0 - 25.0)
- );
-
- nvVector2 delta = nvVector2_sub(next_pos, mixer->position);
-
- mixer->linear_velocity = nvVector2_add(mixer->linear_velocity, delta);
-}
-
-
-int main(int argc, char *argv[]) {
- // Setup benchmark
-
- nvSpace *space = nvSpace_new();
-
- Benchmark bench = Benchmark_new(BENCHMARK_ITERS, space);
-
- nvMaterial ground_mat = (nvMaterial){1.0, 0.1, 0.6};
- nvMaterial mixer_mat = (nvMaterial){5.0, 0.03, 0.1};
- nvMaterial basic_mat = (nvMaterial){1.0, 0.0, 0.25};
-
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(80.0, 5.0),
- NV_VEC2(64.0, 72.0 - 2.5),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, ground);
-
- nvBody *ceiling = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(80.0, 5.0),
- NV_VEC2(64.0, 2.5),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, ceiling);
-
- nvBody *wall_l = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 75.0),
- NV_VEC2(64.0 - 40.0 + 2.5, 36.0),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, wall_l);
-
- nvBody *wall_r = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 75.0),
- NV_VEC2(64.0 + 40.0 - 2.5, 36.0),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, wall_r);
-
- nvBody *mixer = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(4.0),
- NV_VEC2(94.0, 72.0 - 25.0),
- 0.0,
- mixer_mat
- );
-
- nvSpace_add(space, mixer);
-
- // Create stacked mixed shapes
-
- int cols = 50; // Columns of the stack
- int rows = 30; // Rows of the stack
- nv_float size = 1.33; // Size of the shapes
- nv_float s2 = size * 2.0;
-
- for (size_t y = 0; y < rows; y++) {
-
- for (size_t x = 0; x < cols; x++) {
-
- int r = (x + y) % 4;
-
- nvBody *body;
-
- // Circle
- if (r == 0) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(size / 2.0),
- NV_VEC2(
- 64.0 - 2.3 - ((nv_float)cols * size) / 2.0 + s2 + size * x,
- 62.5 - 2.5 - s2 - y * size
- ),
- 0.0,
- basic_mat
- );
- }
-
- // Box
- else if (r == 1) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(size, size),
- NV_VEC2(
- 64.0 - 2.3 - ((nv_float)cols * size) / 2.0 + s2 + size * x,
- 62.5 - 2.5 - s2 - y * size
- ),
- 0.0,
- basic_mat
- );
- }
-
- // Pentagon
- else if (r == 2) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(5, size),
- NV_VEC2(
- 64.0 - 2.3 - ((nv_float)cols * size) / 2.0 + s2 + size * x,
- 62.5 - 2.5 - s2 - y * size
- ),
- 0.0,
- basic_mat
- );
- }
-
- // Triangle
- else if (r == 3) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(3, size),
- NV_VEC2(
- 64.0 - 2.3 - ((nv_float)cols * size) / 2.0 + s2 + size * x,
- 62.5 - 2.5 - s2 - y * size
- ),
- 0.0,
- basic_mat
- );
- }
-
- nvSpace_add(space, body);
- }
- }
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID) {
- nvSpace_set_SHG(space, space->shg->bounds, size + size * 0.2, size + size * 0.2);
- nvSpace_enable_multithreading(space, 0);
- }
-
- // Run benchmark
- for (size_t i = 0; i < bench.iters; i++) {
- nv_float dt = 1.0 / (nv_float)BENCHMARK_HERTZ;
-
- Benchmark_start(&bench);
-
- nvSpace_step(
- space,
- dt,
- BENCHMARK_VELOCITY_ITERATIONS,
- BENCHMARK_POSITION_ITERATIONS,
- BENCHMARK_CONSTRAINT_ITERATIONS,
- 1
- );
-
- Benchmark_stop(&bench);
- }
-
- Benchmark_results(&bench);
-
-
- nvSpace_free(space);
-}
\ No newline at end of file
diff --git a/benchmarks/scenes/scene_pyramid.h b/benchmarks/scenes/scene_pyramid.h
new file mode 100644
index 0000000..9dc0f0a
--- /dev/null
+++ b/benchmarks/scenes/scene_pyramid.h
@@ -0,0 +1,59 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NV_BENCHMARK_SCENE_PYRAMID_H
+#define NV_BENCHMARK_SCENE_PYRAMID_H
+
+#include "novaphysics/novaphysics.h"
+
+
+void Pyramid_setup(nvSpace *space) {
+ nvSpace_set_broadphase(space, nvBroadPhaseAlg_BVH);
+
+
+ nvRigidBody *ground;
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(128.0, 5.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+
+ nvSpace_add_rigidbody(space, ground);
+
+
+ size_t pyramid_base = 100;
+ nv_float size = 1.0;
+ nv_float s2 = size / 2.0;
+ nv_float y_gap = 0.0;
+ nv_float start_y = 72.0 - 2.5 - 2.5 - s2;
+
+ for (size_t y = 0; y < pyramid_base; y++) {
+ for (size_t x = 0; x < pyramid_base - y; x++) {
+ nvRigidBody *box;
+ nvRigidBodyInitializer box_init = nvRigidBodyInitializer_default;
+ box_init.type = nvRigidBodyType_DYNAMIC;
+ box_init.position = NV_VECTOR2(
+ 64.0 - (pyramid_base * s2 - s2) + x * size + y * s2,
+ start_y - y * (size + y_gap - 0.01) // Sink a little so collisions happen in first frame
+ );
+ box_init.material = (nvMaterial){.density=1.0, .restitution=0.0, .friction=0.5};
+ box = nvRigidBody_new(box_init);
+
+ nvShape *box_shape = nvBoxShape_new(size, size, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvSpace_add_rigidbody(space, box);
+ }
+ }
+}
+
+
+#endif
\ No newline at end of file
diff --git a/docs/_static/collision_aabbxaabb.png b/docs/_static/collision_aabbxaabb.png
deleted file mode 100644
index 9a0c14b..0000000
Binary files a/docs/_static/collision_aabbxaabb.png and /dev/null differ
diff --git a/docs/_static/collision_aabbxpoint.png b/docs/_static/collision_aabbxpoint.png
deleted file mode 100644
index b0f950c..0000000
Binary files a/docs/_static/collision_aabbxpoint.png and /dev/null differ
diff --git a/docs/_static/collision_circlexcircle.png b/docs/_static/collision_circlexcircle.png
deleted file mode 100644
index d0a4c8c..0000000
Binary files a/docs/_static/collision_circlexcircle.png and /dev/null differ
diff --git a/docs/_static/collision_circlexpoint.png b/docs/_static/collision_circlexpoint.png
deleted file mode 100644
index e6473bb..0000000
Binary files a/docs/_static/collision_circlexpoint.png and /dev/null differ
diff --git a/docs/_static/collision_polygonxcircle.png b/docs/_static/collision_polygonxcircle.png
deleted file mode 100644
index 19fe11b..0000000
Binary files a/docs/_static/collision_polygonxcircle.png and /dev/null differ
diff --git a/docs/conf.py b/docs/conf.py
index 4f8bf59..56f07fc 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -14,7 +14,7 @@
# General information about the project.
project = "Nova Physics"
-copyright = "2023, Kadir Aksoy"
+copyright = "2024, Kadir Aksoy"
author = "Kadir Aksoy"
html_static_path = ["_static"]
diff --git a/docs/getting_started/index.rst b/docs/getting_started/index.rst
index 73ad1a0..490aa79 100644
--- a/docs/getting_started/index.rst
+++ b/docs/getting_started/index.rst
@@ -2,9 +2,9 @@
Getting Started
===============
-Nova Physics is a lightweight 2D rigid body physics engine. It is designed with game development in mind, however you can utilize it anywhere you need to simulate rigid body dynamics. It is written in portable C with no dependencies other than the standard library, meaning anyone can easily write a binding for their favored programming language.
+Nova Physics is a lightweight 2D rigid body physics engine. It is designed with game development in mind. It is written in portable C with no dependencies other than the standard library, meaning anyone can easily write a binding for their favored programming language.
-Nova Physics is, and always will be, free and open-source. It is licensed under MIT, meaning you don't need to pay to use Nova Physics in your projects. Altough we would greatly appreciate `donations! `_
+Nova Physics is, and always will be, free and open-source.
Hello World
===========
@@ -19,34 +19,46 @@ After installing (you can follow :doc:`installing`), you are ready for your firs
int main() {
- // Create an empty space
+ // Create an empty simulation space
nvSpace *space = nvSpace_new();
- // Create a ground body with a rectangle shape
- // Making it static means the body will never move no matter what.
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(10.0, 1.0), // A rectangle shape.
- NV_VEC2(0.0, 30.0), // NV_VEC2 is a utility macro to quickly creating vectors.
- 0.0,
- nvMaterial_CONCRETE // You can specify a custom material as well.
- );
- // Add the body to the space.
- nvSpace_add(space, ground);
+ /* Create a ground body with a rectangle shape. */
- // Now create a ball that is going to fall to the ground.
- nvBody *ball = nvBody_new(
- nvBodyType_DYNAMIC, // Notice the dynamic type. The ball will move in space.
- nvCircleShape_new(1.5), // Circle shape with radius of 1.5
- NV_VEC2(0.0, 0.0),
- 0.0,
- nvMaterial_RUBBER // Giving the ball a rubber material, so it bounces
- );
+ // The initializer struct is used to set basic properties of a body before creation.
+ // Making the motion type static means the body will never move under simulation.
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_STATIC;
+ body_init.position = NV_VECTOR2(0.0, 20.0); // NV_VECTOR2 is a utility macro to quickly initialize vectors.
+ body_init.material = nvMaterial_CONCRETE; // You can initialize a custom material as well.
+ nvRigidBody *ground = nvRigidBody_new(body_init);
- nvSpace_add(space, ball);
+ // After creating the rigid body, we have to assign a shape.
+ nvShape *ground_shape = nvBoxShape_new(10.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
- // The scene is set up. Now we only have to simulate it!
+ // We can finally add ground body to space.
+ nvSpace_add_rigidbody(space, ground);
+
+
+ /* Now create a ball that is going to fall and bounce off the ground. */
+
+ // We can use the same initializer struct by changing the necessary fields.
+ // This time the motion type have to by dynamic so the ball can be simulated under physical forces.
+ // We also initialize a custom material with restitution 0.85, so it can bounce
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(0.0, 0.0);
+ body_init.material = (nvMaterial){.density=1.0, .restitution=0.85, .friction=0.1};
+ nvRigidBody *ball = nvRigidBody_new(body_init);
+
+ // Now we assign a circle shape to our body with radius 1.0
+ nvShape *ball_shape = nvCircleShape(nvVector2_zero, 1.0);
+ nvRigidBody_add_shape(ball, ball_shape);
+
+ nvSpace_add_rigidbody(space, ground);
+
+
+ /* The scene is set up. Now we only have to simulate it! */
// This is the time step length the engine going to simulate the space in.
nv_float dt = 1.0 / 60.0;
@@ -55,19 +67,22 @@ After installing (you can follow :doc:`installing`), you are ready for your firs
nv_float duration = 5.0;
for (nv_float t = 0.0; t < duration; t += dt) {
+ nvVector2 position = nvRigidBody_get_position(ball);
+ nvVector2 velocity = nvRigidBody_get_linear_velocity(ball);
+
printf(
"Ball is at (%.2f, %.2f) with velocity (%.2f, %.2f) at time %.2f.\n",
- ball->position.x, ball->position.y,
- ball->linear_velocity.x, ball->linear_velocity.y,
+ position.x, position.y,
+ velocity.x, velocity.y,
t
);
- // Simulate the space
- nvSpace_step(space, dt, 10, 10, 5, 1);
+ // Advance the simulation.
+ nvSpace_step(space, dt);
}
// Free the space and all resources it used.
- // Space also manages the bodies and constraints we add to it.
+ // Space also manages the bodies, shapes and constraints we add to it.
// Unless you removed them manually, in that case you have to free your bodies.
nvSpace_free(space);
}
diff --git a/docs/installing.rst b/docs/installing.rst
index 167493d..58b1f95 100644
--- a/docs/installing.rst
+++ b/docs/installing.rst
@@ -4,9 +4,7 @@ Installing
Nova Physics is cross-platform, tested on following and should work on many more:
-* Windows 7, 10, 11
-* Manjaro (Arch), Ubuntu (Debian), Fedora
+* Windows 10, 11
+* Manjaro (Arch), Mint (Debian), Fedora
-Development libraries are always shipped with the most recent release under the name of :code:`nova-physics-X.X.X-devel.zip/tar.gz`. You can download the development package `here `__ and link :code:`libnova.a` static library and headers to use Nova Physics in your project.
-
-Or you can use Nova Physics's build system to build the static library on your machine yourself. You can check out `here `__ for more information about the build system.
\ No newline at end of file
+You can use the `building guide `__ to build the library.
\ No newline at end of file
diff --git a/docs/reference/array.rst b/docs/reference/array.rst
deleted file mode 100644
index d45c4cc..0000000
--- a/docs/reference/array.rst
+++ /dev/null
@@ -1,22 +0,0 @@
-=====
-Array
-=====
-
-.. doxygenstruct:: nvArray
- :members:
-
-
-Methods
-=======
-
-.. doxygenfunction:: nvArray_new
-
-.. doxygenfunction:: nvArray_free
-
-.. doxygenfunction:: nvArray_free_each
-
-.. doxygenfunction:: nvArray_add
-
-.. doxygenfunction:: nvArray_pop
-
-.. doxygenfunction:: nvArray_remove
\ No newline at end of file
diff --git a/docs/reference/body.rst b/docs/reference/body.rst
deleted file mode 100644
index 792cb48..0000000
--- a/docs/reference/body.rst
+++ /dev/null
@@ -1,54 +0,0 @@
-====
-Body
-====
-
-.. doxygenstruct:: nvBody
- :members:
-
-
-Enums
-=====
-
-.. doxygenenum:: nvBodyType
-
-
-Methods
-=======
-
-.. doxygenfunction:: nvBody_new
-
-.. doxygenfunction:: nvBody_free
-
-.. doxygenfunction:: nvBody_calc_mass_and_inertia
-
-.. doxygenfunction:: nvBody_set_mass
-
-.. doxygenfunction:: nvBody_set_inertia
-
-.. doxygenfunction:: nvBody_integrate_accelerations
-
-.. doxygenfunction:: nvBody_integrate_velocities
-
-.. doxygenfunction:: nvBody_apply_attraction
-
-.. doxygenfunction:: nvBody_apply_force
-
-.. doxygenfunction:: nvBody_apply_force_at
-
-.. doxygenfunction:: nvBody_apply_impulse
-
-.. doxygenfunction:: nvBody_apply_pseudo_impulse
-
-.. doxygenfunction:: nvBody_sleep
-
-.. doxygenfunction:: nvBody_awake
-
-.. doxygenfunction:: nvBody_get_aabb
-
-.. doxygenfunction:: nvBody_get_kinetic_energy
-
-.. doxygenfunction:: nvBody_get_rotational_energy
-
-.. doxygenfunction:: nvBody_get_is_attractor
-
-.. doxygenfunction:: nvBody_local_to_world
\ No newline at end of file
diff --git a/docs/reference/collision.rst b/docs/reference/collision.rst
new file mode 100644
index 0000000..736926b
--- /dev/null
+++ b/docs/reference/collision.rst
@@ -0,0 +1,21 @@
+=========
+Collision
+=========
+
+.. doxygenfunction:: nv_collide_circle_x_circle
+
+.. doxygenfunction:: nv_collide_circle_x_point
+
+.. doxygenfunction:: nv_collide_polygon_x_circle
+
+.. doxygenfunction:: nv_collide_polygon_x_polygon
+
+.. doxygenfunction:: nv_collide_polygon_x_point
+
+.. doxygenfunction:: nv_collide_aabb_x_aabb
+
+.. doxygenfunction:: nv_collide_aabb_x_point
+
+.. doxygenfunction:: nv_collide_ray_x_circle
+
+.. doxygenfunction:: nv_collide_ray_x_polygon
\ No newline at end of file
diff --git a/docs/reference/constraints/distance_constraint.rst b/docs/reference/constraints/distance_constraint.rst
new file mode 100644
index 0000000..5a3a1cf
--- /dev/null
+++ b/docs/reference/constraints/distance_constraint.rst
@@ -0,0 +1,45 @@
+===================
+Distance Constraint
+===================
+
+.. doxygenstruct:: nvDistanceConstraint
+
+.. doxygenstruct:: nvDistanceConstraintInitializer
+
+
+Methods
+=======
+
+.. doxygenfunction:: nvDistanceConstraint_new
+
+.. doxygenfunction:: nvDistanceConstraint_get_body_a
+
+.. doxygenfunction:: nvDistanceConstraint_get_body_b
+
+.. doxygenfunction:: nvDistanceConstraint_set_length
+
+.. doxygenfunction:: nvDistanceConstraint_get_length
+
+.. doxygenfunction:: nvDistanceConstraint_set_anchor_a
+
+.. doxygenfunction:: nvDistanceConstraint_get_anchor_a
+
+.. doxygenfunction:: nvDistanceConstraint_set_anchor_b
+
+.. doxygenfunction:: nvDistanceConstraint_get_anchor_b
+
+.. doxygenfunction:: nvDistanceConstraint_set_max_force
+
+.. doxygenfunction:: nvDistanceConstraint_get_max_force
+
+.. doxygenfunction:: nvDistanceConstraint_set_spring
+
+.. doxygenfunction:: nvDistanceConstraint_get_spring
+
+.. doxygenfunction:: nvDistanceConstraint_set_hertz
+
+.. doxygenfunction:: nvDistanceConstraint_get_hertz
+
+.. doxygenfunction:: nvDistanceConstraint_set_damping
+
+.. doxygenfunction:: nvDistanceConstraint_get_damping
\ No newline at end of file
diff --git a/docs/reference/constraints/hinge_constraint.rst b/docs/reference/constraints/hinge_constraint.rst
new file mode 100644
index 0000000..0407a7f
--- /dev/null
+++ b/docs/reference/constraints/hinge_constraint.rst
@@ -0,0 +1,37 @@
+================
+Hinge Constraint
+================
+
+.. doxygenstruct:: nvHingeConstraint
+
+.. doxygenstruct:: nvHingeConstraintInitializer
+
+
+Methods
+=======
+
+.. doxygenfunction:: nvHingeConstraint_new
+
+.. doxygenfunction:: nvHingeConstraint_get_body_a
+
+.. doxygenfunction:: nvHingeConstraint_get_body_b
+
+.. doxygenfunction:: nvHingeConstraint_set_anchor
+
+.. doxygenfunction:: nvHingeConstraint_get_anchor
+
+.. doxygenfunction:: nvHingeConstraint_set_limits
+
+.. doxygenfunction:: nvHingeConstraint_get_limits
+
+.. doxygenfunction:: nvHingeConstraint_set_upper_limit
+
+.. doxygenfunction:: nvHingeConstraint_get_upper_limit
+
+.. doxygenfunction:: nvHingeConstraint_set_lower_limit
+
+.. doxygenfunction:: nvHingeConstraint_get_lower_limit
+
+.. doxygenfunction:: nvHingeConstraint_set_max_force
+
+.. doxygenfunction:: nvHingeConstraint_get_max_force
\ No newline at end of file
diff --git a/docs/reference/constraints/index.rst b/docs/reference/constraints/index.rst
new file mode 100644
index 0000000..525cf25
--- /dev/null
+++ b/docs/reference/constraints/index.rst
@@ -0,0 +1,33 @@
+===========
+Constraints
+===========
+
+.. toctree::
+ :maxdepth: 1
+
+ distance_constraint.rst
+ hinge_constraint.rst
+ spline_constraint.rst
+
+
+Base Constraint
+===============
+
+.. doxygenstruct:: nvConstraint
+ :members:
+
+.. doxygenenum:: nvConstraintType
+
+.. doxygenfunction:: nvConstraint_free
+
+
+Coefficient Mixing
+==================
+
+.. doxygenenum:: nvCoefficientMix
+
+
+Contact Position Correction
+===========================
+
+.. doxygenenum:: nvContactPositionCorrection
\ No newline at end of file
diff --git a/docs/reference/constraints/spline_constraint.rst b/docs/reference/constraints/spline_constraint.rst
new file mode 100644
index 0000000..3312d58
--- /dev/null
+++ b/docs/reference/constraints/spline_constraint.rst
@@ -0,0 +1,29 @@
+=================
+Spline Constraint
+=================
+
+.. doxygenstruct:: nvSplineConstraint
+
+.. doxygenstruct:: nvSplineConstraintInitializer
+
+
+Methods
+=======
+
+.. doxygenfunction:: nvSplineConstraint_new
+
+.. doxygenfunction:: nvSplineConstraint_get_body
+
+.. doxygenfunction:: nvSplineConstraint_set_anchor
+
+.. doxygenfunction:: nvSplineConstraint_get_anchor
+
+.. doxygenfunction:: nvSplineConstraint_set_max_force
+
+.. doxygenfunction:: nvSplineConstraint_get_max_force
+
+.. doxygenfunction:: nvSplineConstraint_set_control_points
+
+.. doxygenfunction:: nvSplineConstraint_get_control_points
+
+.. doxygenfunction:: nvSplineConstraint_get_number_of_control_points
\ No newline at end of file
diff --git a/docs/reference/contact.rst b/docs/reference/contact.rst
new file mode 100644
index 0000000..839a40a
--- /dev/null
+++ b/docs/reference/contact.rst
@@ -0,0 +1,9 @@
+=======
+Contact
+=======
+
+.. doxygenstruct:: nvContactEvent
+ :members:
+
+.. doxygenstruct:: nvContactListener
+ :members:
\ No newline at end of file
diff --git a/docs/reference/errors.rst b/docs/reference/errors.rst
new file mode 100644
index 0000000..bb92101
--- /dev/null
+++ b/docs/reference/errors.rst
@@ -0,0 +1,5 @@
+======
+Errors
+======
+
+.. doxygenfunction:: nv_get_error
\ No newline at end of file
diff --git a/docs/reference/index.rst b/docs/reference/index.rst
index aeca87d..988ddaa 100644
--- a/docs/reference/index.rst
+++ b/docs/reference/index.rst
@@ -6,11 +6,12 @@ API Reference
:maxdepth: 1
space.rst
- body.rst
+ rigidbody.rst
shape.rst
material.rst
- constraint.rst
- resolution.rst
+ constraints/index.rst
+ contact.rst
+ collision.rst
vector2.rst
aabb.rst
- array.rst
\ No newline at end of file
+ errors.rst
\ No newline at end of file
diff --git a/docs/reference/resolution.rst b/docs/reference/resolution.rst
deleted file mode 100644
index af696cc..0000000
--- a/docs/reference/resolution.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-==========
-Resolution
-==========
-
-.. doxygenenum:: nvResolutionState
-
-.. doxygenstruct:: nvResolution
- :members:
-
-.. doxygenstruct:: nvContact
- :members:
\ No newline at end of file
diff --git a/docs/reference/rigidbody.rst b/docs/reference/rigidbody.rst
new file mode 100644
index 0000000..2b612cb
--- /dev/null
+++ b/docs/reference/rigidbody.rst
@@ -0,0 +1,111 @@
+==========
+Rigid Body
+==========
+
+.. doxygenstruct:: nvRigidBody
+
+.. doxygenstruct:: nvRigidBodyInitializer
+
+
+Enums
+=====
+
+.. doxygenenum:: nvRigidBodyType
+
+
+Methods
+=======
+
+.. doxygenfunction:: nvRigidBody_new
+
+.. doxygenfunction:: nvRigidBody_free
+
+.. doxygenfunction:: nvRigidBody_set_user_data
+
+.. doxygenfunction:: nvRigidBody_get_user_data
+
+.. doxygenfunction:: nvRigidBody_get_space
+
+.. doxygenfunction:: nvRigidBody_get_id
+
+.. doxygenfunction:: nvRigidBody_set_type
+
+.. doxygenfunction:: nvRigidBody_get_type
+
+.. doxygenfunction:: nvRigidBody_set_position
+
+.. doxygenfunction:: nvRigidBody_get_position
+
+.. doxygenfunction:: nvRigidBody_set_angle
+
+.. doxygenfunction:: nvRigidBody_get_angle
+
+.. doxygenfunction:: nvRigidBody_set_linear_velocity
+
+.. doxygenfunction:: nvRigidBody_get_linear_velocity
+
+.. doxygenfunction:: nvRigidBody_set_angular_velocity
+
+.. doxygenfunction:: nvRigidBody_get_angular_velocity
+
+.. doxygenfunction:: nvRigidBody_set_linear_damping_scale
+
+.. doxygenfunction:: nvRigidBody_get_linear_damping_scale
+
+.. doxygenfunction:: nvRigidBody_set_angular_damping_scale
+
+.. doxygenfunction:: nvRigidBody_get_angular_damping_scale
+
+.. doxygenfunction:: nvRigidBody_set_gravity_scale
+
+.. doxygenfunction:: nvRigidBody_get_gravity_scale
+
+.. doxygenfunction:: nvRigidBody_set_material
+
+.. doxygenfunction:: nvRigidBody_get_material
+
+.. doxygenfunction:: nvRigidBody_set_mass
+
+.. doxygenfunction:: nvRigidBody_get_mass
+
+.. doxygenfunction:: nvRigidBody_set_inertia
+
+.. doxygenfunction:: nvRigidBody_get_inertia
+
+.. doxygenfunction:: nvRigidBody_set_collision_group
+
+.. doxygenfunction:: nvRigidBody_get_collision_group
+
+.. doxygenfunction:: nvRigidBody_set_collision_category
+
+.. doxygenfunction:: nvRigidBody_get_collision_category
+
+.. doxygenfunction:: nvRigidBody_set_collision_mask
+
+.. doxygenfunction:: nvRigidBody_get_collision_mask
+
+.. doxygenfunction:: nvRigidBody_add_shape
+
+.. doxygenfunction:: nvRigidBody_remove_shape
+
+.. doxygenfunction:: nvRigidBody_iter_shapes
+
+.. doxygenfunction:: nvRigidBody_apply_force
+
+.. doxygenfunction:: nvRigidBody_apply_force_at
+
+.. doxygenfunction:: nvRigidBody_apply_torque
+
+.. doxygenfunction:: nvRigidBody_apply_impulse
+
+.. doxygenfunction:: nvRigidBody_enable_collisions
+
+.. doxygenfunction:: nvRigidBody_disable_collisions
+
+.. doxygenfunction:: nvRigidBody_reset_velocities
+
+.. doxygenfunction:: nvRigidBody_get_aabb
+
+.. doxygenfunction:: nvRigidBody_get_kinetic_energy
+
+.. doxygenfunction:: nvRigidBody_get_rotational_energy
\ No newline at end of file
diff --git a/docs/reference/shape.rst b/docs/reference/shape.rst
index d752cb1..fe52579 100644
--- a/docs/reference/shape.rst
+++ b/docs/reference/shape.rst
@@ -3,7 +3,6 @@ Shape
=====
.. doxygenstruct:: nvShape
- :members:
Enums
@@ -27,4 +26,10 @@ Methods
.. doxygenfunction:: nvConvexHullShape_new
-.. doxygenfunction:: nvShape_free
\ No newline at end of file
+.. doxygenfunction:: nvShape_free
+
+.. doxygenfunction:: nvShape_get_aabb
+
+.. doxygenfunction:: nvShape_calculate_mass
+
+.. doxygenfunction:: nvPolygon_transform
\ No newline at end of file
diff --git a/docs/reference/space.rst b/docs/reference/space.rst
index cec81c0..050ab6c 100644
--- a/docs/reference/space.rst
+++ b/docs/reference/space.rst
@@ -3,9 +3,17 @@ Space
=====
.. doxygenstruct:: nvSpace
+
+.. doxygenstruct:: nvSpaceSettings
:members:
+Enums
+=====
+
+.. doxygenenum:: nvBroadPhaseAlg
+
+
Methods
=======
@@ -13,22 +21,36 @@ Methods
.. doxygenfunction:: nvSpace_free
+.. doxygenfunction:: nvSpace_set_gravity
+
+.. doxygenfunction:: nvSpace_get_gravity
+
.. doxygenfunction:: nvSpace_set_broadphase
-.. doxygenfunction:: nvSpace_set_SHG
+.. doxygenfunction:: nvSpace_get_broadphase
-.. doxygenfunction:: nvSpace_clear
+.. doxygenfunction:: nvSpace_get_settings
-.. doxygenfunction:: nvSpace_add
+.. doxygenfunction:: nvSpace_get_profiler
-.. doxygenfunction:: nvSpace_remove
+.. doxygenfunction:: nvSpace_set_contact_listener
-.. doxygenfunction:: nvSpace_kill
+.. doxygenfunction:: nvSpace_get_contact_listener
+
+.. doxygenfunction:: nvSpace_clear
+
+.. doxygenfunction:: nvSpace_add_rigidbody
+
+.. doxygenfunction:: nvSpace_remove_rigidbody
.. doxygenfunction:: nvSpace_add_constraint
-.. doxygenfunction:: nvSpace_step
+.. doxygenfunction:: nvSpace_remove_constraint
+
+.. doxygenfunction:: nvSpace_iter_bodies
-.. doxygenfunction:: nvSpace_enable_sleeping
+.. doxygenfunction:: nvSpace_iter_constraints
+
+.. doxygenfunction:: nvSpace_step
-.. doxygenfunction:: nvSpace_disable_sleeping
\ No newline at end of file
+.. doxygenfunction:: nvSpace_cast_ray
\ No newline at end of file
diff --git a/docs/reference/vector2.rst b/docs/reference/vector2.rst
index aba9122..ad82aaf 100644
--- a/docs/reference/vector2.rst
+++ b/docs/reference/vector2.rst
@@ -9,16 +9,7 @@ Vector2
.. doxygenvariable:: nvVector2_zero
-Macros
-======
-
-.. doxygendefine:: NV_VEC2
-
-.. doxygenfunction:: NV_VEC2_NEW
-
-.. doxygendefine:: NV_TO_VEC2
-
-.. doxygendefine:: NV_TO_VEC2P
+.. doxygendefine:: NV_VECTOR2
Methods
@@ -54,4 +45,8 @@ Methods
.. doxygenfunction:: nvVector2_dist
-.. doxygenfunction:: nvVector2_normalize
\ No newline at end of file
+.. doxygenfunction:: nvVector2_normalize
+
+.. doxygenfunction:: nvVector2_lerp
+
+.. doxygenfunction:: nvVector2_is_zero
\ No newline at end of file
diff --git a/docs/translations/README_tr.md b/docs/translations/README_tr.md
index 3467ade..78c8aa2 100644
--- a/docs/translations/README_tr.md
+++ b/docs/translations/README_tr.md
@@ -1,55 +1,56 @@
![](https://raw.githubusercontent.com/kadir014/kadir014.github.io/master/assets/novaphysics.png)
-
+
-Nova Physics, hafif ve kullanımı kolay bir 2B fizik motorudur.
+Nova Physics, oyun geliştirme düşünülerek tasarlanan hafif ve kullanımı kolay bir 2B fizik motorudur.
+
+
Bu sayfayı ayrıca şu dillerde okuyabilirsin
-
-
+
+
# Özellikler
- Basit ve kullanıcı-dostu arayüz
+- Dış bağımlılığı olmayan portable codebase
- Katı cisim dinamiği
-- Basit şekil çarpışmaları (daire, dikdörtgen, çokgen, AABB)
-- Broad-phase stratejileri (Spatial hashing & BVH-ağacı)
-- Fiziksel materyal özellikleri (sürtünme kuvveti, elastiklik ve yoğunluk)
-- Eklem kısıtlamaları (yay, uzaklık, menteşe ..)
-- Gayet iyi yığın dengesi ve çarpışma sürekliliği
-- [Erin Catto'nun](https://box2d.org/files/ErinCatto_SequentialImpulses_GDC2006.pdf) iteratif "sequential impulse" çözücü algoritması
+- Süreksiz çarpışma tespiti
+ - Daire şekli
+ - Dışbükey (konveks) çokgen şekli
+ - Şekilleri diğer şekillere karşı test etme
+ - Şekilleri noktaya karşı test etme
+ - Ray casting
+- Şekiller arasında one-shot contact manifoldu oluşturma
+- Cisim başına birden fazla şekil
+- Broadphase stratejileri
+ - Bruteforce
+ - Bounding volume hierarchy tree
+- Materyal özellikleri (sürtünme, sekme (elastiklik) ve özkütle)
+- Cisimler arası kısıtlamalar (constraints)
+ - Uzaklık kısıtlaması - yay gibi de davranabilir
+ - Menşete (hinge) kısıtlaması
+ - Spline yol kısıtlaması
+- [Erin Catto'nun](https://box2d.org/files/ErinCatto_SequentialImpulses_GDC2006.pdf) 'sequential impulses' algoritması
+- Gayet iyi stacking stabilitesi
- Semi-implicit (symplectic) Euler integrasyonu
-- Çarpışma eventleri
-- CPU yükünü azaltmak için cisimleri uyutma
-- Çekici güçler
-- Birleşik profiler
-- Dış bağımlılığı olmayan taşınabilir codebase
-- SDL2 kullanan çeşitli etkileşimli örnek demolar
-
-
-
-# Yol Haritası & Gelecek
-Nova Physics `0.x.x` sürümleri boyunca hala daha erken aşamalarında. Motorun ve API'ın hala optimizasyon ve gelişme anlamında kat edecek yolu var. `1.x.x` kilometre taşından önce değinilmesi gereken bazı noktalar:
-
-- ### Daha iyi ve hızlı broad-phase
- Nova'da şuan kullanılabilir olan broad-phase stratejileri spatial hash grid ve BVH (kaplayan alan hiyerarşisi) ağacı. İkisi de hızlı ama hala geliştirilebilirler, özellikle BVH-ağacının oluşumu ve multi-thread kullanan SHG.
-
-- ### Python Binding
- Nova Physics'in Python modülü ([burada](https://github.com/kadir014/nova-physics-python)) hala WIP. Kullanımı kolay ve Pythonic bir arayüzü olmasını istiyorum. Başka diller için bindinglere her zaman açığız!
-
+- Maskeler ve gruplama ile çarpışma filtreleme
+- Built-in profiler
+- Opsiyonel double-precision modu
+- SDL2 & OpenGL kullanan çeşitli etkileşimli örnek demoları
# Yükleme & Derleme
-Geliştirme kütüphaneleri her zaman son sürümle beraber `nova-physics-X.X.X-devel.zip` (veya `.tar.gz`) ismiyle yüklenirler. Arşivi [buradan](https://github.com/kadir014/nova-physics/releases) indirip `libnova.a` (veya `libnova.lib`) 'i favori derleyicinizle kullanabilirsiniz.
-
-Fakat eğer Nova Physics'i baştan kendiniz derlemek istiyor (veya gerek duyuyorsanız), [derleme kılavuzunu](https://github.com/kadir014/nova-physics/blob/main/BUILDING.md#building-nova-physics-static-libraries) kullanın.
+Kütüphane sadece C99 standardı ve C STL'ini kullanır.
+
+Daha fazla talimat için [buraya bakın.](BUILDING.md)
@@ -57,37 +58,33 @@ Fakat eğer Nova Physics'i baştan kendiniz derlemek istiyor (veya gerek duyuyor
-Örnek demoları [examples](https://github.com/kadir014/nova-physics/blob/main/examples/) klasöründe, demoları çalıştırmak için [demoları derleme kılavuzunu](https://github.com/kadir014/nova-physics/blob/main/BUILDING.md#running-nova-physics-example-demos) kullanın
+Örnek demoları [examples](https://github.com/kadir014/nova-physics/blob/main/examples/) klasöründe bulunuyor, build sisteminde demoları buildleme opsiyonunu etkinleştirin (eğer zaten değilse).
# Dökümantasyon
-Dökümantasyona [buradan](https://nova-physics.rtfd.io) erişebilirsiniz.
+API referansını da içeren dökümantasyona [buradan](https://nova-physics.rtfd.io) erişebilirsiniz.
+
+Eğer daha yeni başlıyorsanız, [giriş sayfasını](https://nova-physics.readthedocs.io/en/latest/getting_started/index.html) kullanabilirsiniz.
# Kaynaklar & Referanslar
-Aşağıdakiler Nova Physics'i yazarken bana yardımcı olan müthiş kaynaklardan bazıları.
-- **Erin Catto**, [GDC Presentations](https://box2d.org/publications/)
+Nova benim için bir tutku ve öğrenme projesi, ve aşağıdakiler şuana kadar bana yardımcı olan bir sürü harika kaynaktan bazıları.
+- **Erin Catto**, [GDC Presentations](https://box2d.org/publications/) ve [Box2D](https://github.com/erincatto/box2c)
- **Chris Hecker**, [Rigid Body Dynamics](https://chrishecker.com/Rigid_Body_Dynamics)
+- **Ian Millington**, [Game Physics Engine Development](https://www.r-5.org/files/books/computers/algo-list/realtime-3d/Ian_Millington-Game_Physics_Engine_Development-EN.pdf)
+- **Christer Ericson**, [Real-Time Collision Detection](https://www.r-5.org/files/books/computers/algo-list/realtime-3d/Christer_Ericson-Real-Time_Collision_Detection-EN.pdf)
+- **Dirk Gregorius**, [Robust Contact Creation for Physics Simulations](http://media.steampowered.com/apps/valve/2015/DirkGregorius_Contacts.pdf)
- **Randy Gaul**, [Game Physics Articles](https://tutsplus.com/authors/randy-gaul)
- **Allen Chou**, [Physics Blogs](https://allenchou.net/category/physics/)
+- **Jacco Bikker**, [How to build a BVH](https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/)
- **Marjin Tamis** & **Giuseppe Maggiore**, [Constraint Based Physics Solver](http://mft-spirit.nl/files/MTamis_ConstraintBasedPhysicsSolver.pdf)
- **Micheal Manzke**, [Multiple Contact Resolution](https://www.scss.tcd.ie/~manzkem/CS7057/cs7057-1516-10-MultipleContacts-mm.pdf)
-- **Dirk Gregorius**, [Robust Contact Creation for Physics Simulations](http://media.steampowered.com/apps/valve/2015/DirkGregorius_Contacts.pdf)
-- **Andrew Sevenson**, [Separating Axis Theorem Explanation](https://www.sevenson.com.au/programming/sat/)
-# Lisans
+# License
[MIT](LICENSE) © Kadir Aksoy
-Nova Physics her zaman ücretsiz ve açık-kaynak olacaktır. Fakat [bağışlara](https://www.buymeacoffee.com/kadir014) her zaman açığız!
-
-# Çeviri Notu
-Türkçeye çevrilirken bozulmak zorunda kalan veya anlamını koruyamayan / karşılığı olmayan kelimeler ve teknik terimler (alfabetik sırayla):
-- **AABB (Axis Aligned Bounding Box)**: Bir cismi veya şekli kapsayan olabilecek en küçük, eksenlere hizalanmış kutu.
-- **Kısıtlama (constraint)**: Kısıtlama fizik motorlarının temelidir diyebiliriz. Cisimlerin uzay içerisinde nasıl davranacağını, nasıl davranamayacağını belirler. Cisimleri "kısıtlar".
-- **Çarpışma**: İki cismin birbirine değmesi.
-- **Eklem (joint)**: Eklemler, iki cismin birbirine bağlı olduğu bir kısıtlamadır. Cisimlerin özgürlük derecelerinden (degrees of freedom) birini veya birden çoğunu kıstlar.
-- **Stacking (yığın)**: Basitçe birbirinin üstüne oturtulmuş cisimlerdir. Fizik motorlarının dengesini ve stabilitesini ölçmek için iyi bir benchmarktır.
\ No newline at end of file
+Nova Physics her zaman ücretsiz ve açık-kaynak olacaktır. Fakat [bağışlara](https://www.buymeacoffee.com/kadir014) her zaman açığız!
\ No newline at end of file
diff --git a/examples/arch.h b/examples/arch.h
deleted file mode 100644
index 74696cd..0000000
--- a/examples/arch.h
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void ArchExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- /*
- Messiest example code lol.
- */
-
- // Create ground
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 52.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
- // Create arch bricks
-
- nvArray *vertices;
- nvVector2 center;
- nvBody *brick;
- nv_float offset = 6.248; // Center the arch on window
-
- nvBodyType type = nvBodyType_DYNAMIC;
-
- nvMaterial brick_material = {
- .density = nvMaterial_CONCRETE.density,
- .restitution = 0.0,
- .friction = 0.87
- };
-
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.0, 10.0));
- nvArray_add(vertices, NV_VEC2_NEW(-3.0, -10.0));
- nvArray_add(vertices, NV_VEC2_NEW(3.0, -10.0));
- nvArray_add(vertices, NV_VEC2_NEW(3.0, 10.0));
-
- center = NV_VEC2(37.0 + offset, 40.0);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
-
- vertices = nvArray_new();
- nvSpace_add(space, brick);
- nvArray_add(vertices, NV_VEC2_NEW(-3.37051, 2.01043));
- nvArray_add(vertices, NV_VEC2_NEW(-2.57128, -2.59853));
- nvArray_add(vertices, NV_VEC2_NEW(3.3123, -1.42232));
- nvArray_add(vertices, NV_VEC2_NEW(2.62949, 2.01043));
-
- center = NV_VEC2(37.37051247175112 + offset, 27.989574474497488);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
-
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.69994, 1.31674));
- nvArray_add(vertices, NV_VEC2_NEW(-2.00674, -3.06906));
- nvArray_add(vertices, NV_VEC2_NEW(3.52304, -0.74063));
- nvArray_add(vertices, NV_VEC2_NEW(2.18364, 2.49295));
-
- center = NV_VEC2(38.499172871158635 + offset, 24.07430324643775);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.88472, 0.56029));
- nvArray_add(vertices, NV_VEC2_NEW(-1.34989, -3.42758));
- nvArray_add(vertices, NV_VEC2_NEW(3.58955, -0.02142));
- nvArray_add(vertices, NV_VEC2_NEW(1.64506, 2.88872));
-
- center = NV_VEC2(40.37715210034996 + offset, 20.44495368947912);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.91062, -0.22805));
- nvArray_add(vertices, NV_VEC2_NEW(-0.62189, -3.65331));
- nvArray_add(vertices, NV_VEC2_NEW(3.50369, 0.70324));
- nvArray_add(vertices, NV_VEC2_NEW(1.02882, 3.17811));
-
- center = NV_VEC2(42.93788365978014 + offset, 17.245415320448792);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.77047, -1.01318));
- nvArray_add(vertices, NV_VEC2_NEW(0.1501, -3.72907));
- nvArray_add(vertices, NV_VEC2_NEW(3.26526, 1.39887));
- nvArray_add(vertices, NV_VEC2_NEW(0.35512, 3.34337));
-
- center = NV_VEC2(46.086462558558765 + offset, 14.605285192196277);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.46577, -1.75765));
- nvArray_add(vertices, NV_VEC2_NEW(0.93341, -3.64354));
- nvArray_add(vertices, NV_VEC2_NEW(2.88297, 2.0309));
- nvArray_add(vertices, NV_VEC2_NEW(-0.35061, 3.37029));
-
- center = NV_VEC2(49.70232959755557 + offset, 12.63387023459242);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-3.00774, -2.42417));
- nvArray_add(vertices, NV_VEC2_NEW(1.69133, -3.39353));
- nvArray_add(vertices, NV_VEC2_NEW(2.37458, 2.56744));
- nvArray_add(vertices, NV_VEC2_NEW(-1.05817, 3.25026));
-
- center = NV_VEC2(53.6434729985393 + offset, 11.414508451893218);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-2.41742, -2.97876));
- nvArray_add(vertices, NV_VEC2_NEW(2.38579, -2.98567));
- nvArray_add(vertices, NV_VEC2_NEW(1.76582, 2.98221));
- nvArray_add(vertices, NV_VEC2_NEW(-1.73418, 2.98221));
-
- center = NV_VEC2(57.75223084482941 + offset, 10.99973799079986);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-1.72449, -3.39388));
- nvArray_add(vertices, NV_VEC2_NEW(2.98065, -2.43694));
- nvArray_add(vertices, NV_VEC2_NEW(1.08829, 3.25682));
- nvArray_add(vertices, NV_VEC2_NEW(-2.34446, 2.574));
-
- center = NV_VEC2(61.86250626106478 + offset, 11.40794776790177);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-0.96471, -3.65106));
- nvArray_add(vertices, NV_VEC2_NEW(3.44527, -1.77374));
- nvArray_add(vertices, NV_VEC2_NEW(0.37651, 3.3821));
- nvArray_add(vertices, NV_VEC2_NEW(-2.85707, 2.0427));
-
- center = NV_VEC2(65.80786856008876 + offset, 12.622063106398585);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-0.17661, -3.74221));
- nvArray_add(vertices, NV_VEC2_NEW(3.75723, -1.02955));
- nvArray_add(vertices, NV_VEC2_NEW(-0.33524, 3.35813));
- nvArray_add(vertices, NV_VEC2_NEW(-3.24538, 1.41363));
-
- center = NV_VEC2(69.42975471434727 + offset, 14.590528358586543);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(0.60204, -3.66947));
- nvArray_add(vertices, NV_VEC2_NEW(3.90393, -0.24184));
- nvArray_add(vertices, NV_VEC2_NEW(-1.01555, 3.19309));
- nvArray_add(vertices, NV_VEC2_NEW(-3.49042, 0.71821));
-
- center = NV_VEC2(72.5849420578588 + offset, 17.23044170526779);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(1.33721, -3.44374));
- nvArray_add(vertices, NV_VEC2_NEW(3.88283, 0.55123));
- nvArray_add(vertices, NV_VEC2_NEW(-1.63777, 2.90133));
- nvArray_add(vertices, NV_VEC2_NEW(-3.58227, -0.00882));
-
- center = NV_VEC2(75.15166146173956 + offset, 20.43234698383862);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(2.00044, -3.08245));
- nvArray_add(vertices, NV_VEC2_NEW(3.70051, 1.31358));
- nvArray_add(vertices, NV_VEC2_NEW(-2.18078, 2.50122));
- nvArray_add(vertices, NV_VEC2_NEW(-3.52017, -0.73236));
-
- center = NV_VEC2(77.03405638154811 + offset, 24.0660294928454);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(2.56956, -2.6071));
- nvArray_add(vertices, NV_VEC2_NEW(3.37109, 2.01328));
- nvArray_add(vertices, NV_VEC2_NEW(-2.62891, 2.01328));
- nvArray_add(vertices, NV_VEC2_NEW(-3.31173, -1.41946));
-
- center = NV_VEC2(78.1650095847842 + offset, 27.98671617839755);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
-
- vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(3.0, -10.0));
- nvArray_add(vertices, NV_VEC2_NEW(3.0, 10.0));
- nvArray_add(vertices, NV_VEC2_NEW(-3.0, 10.0));
- nvArray_add(vertices, NV_VEC2_NEW(-3.0, -10.0));
-
- center = NV_VEC2(78.536096356631 + offset, 40.0);
- brick = nvBody_new(type, nvPolygonShape_new(vertices), center, 0.0, brick_material);
- nvSpace_add(space, brick);
-}
\ No newline at end of file
diff --git a/examples/assets/FiraCode-Medium.ttf b/examples/assets/FiraCode-Medium.ttf
new file mode 100644
index 0000000..7a9c38e
Binary files /dev/null and b/examples/assets/FiraCode-Medium.ttf differ
diff --git a/examples/assets/FiraCode-Regular.ttf b/examples/assets/FiraCode-Regular.ttf
deleted file mode 100644
index b8a44d2..0000000
Binary files a/examples/assets/FiraCode-Regular.ttf and /dev/null differ
diff --git a/examples/assets/example_arch.png b/examples/assets/example_arch.png
deleted file mode 100644
index 64ce9ee..0000000
Binary files a/examples/assets/example_arch.png and /dev/null differ
diff --git a/examples/assets/example_bridge.png b/examples/assets/example_bridge.png
deleted file mode 100644
index 6a4fb4b..0000000
Binary files a/examples/assets/example_bridge.png and /dev/null differ
diff --git a/examples/assets/example_chains.png b/examples/assets/example_chains.png
deleted file mode 100644
index 5cdc707..0000000
Binary files a/examples/assets/example_chains.png and /dev/null differ
diff --git a/examples/assets/example_circle_stack.png b/examples/assets/example_circle_stack.png
deleted file mode 100644
index 5013c4c..0000000
Binary files a/examples/assets/example_circle_stack.png and /dev/null differ
diff --git a/examples/assets/example_cloth.png b/examples/assets/example_cloth.png
deleted file mode 100644
index 983d7c5..0000000
Binary files a/examples/assets/example_cloth.png and /dev/null differ
diff --git a/examples/assets/example_domino.png b/examples/assets/example_domino.png
deleted file mode 100644
index 0b7a34d..0000000
Binary files a/examples/assets/example_domino.png and /dev/null differ
diff --git a/examples/assets/example_fountain.png b/examples/assets/example_fountain.png
deleted file mode 100644
index 5383c6d..0000000
Binary files a/examples/assets/example_fountain.png and /dev/null differ
diff --git a/examples/assets/example_hull.png b/examples/assets/example_hull.png
deleted file mode 100644
index 0114eef..0000000
Binary files a/examples/assets/example_hull.png and /dev/null differ
diff --git a/examples/assets/example_mould.png b/examples/assets/example_mould.png
deleted file mode 100644
index ae9208b..0000000
Binary files a/examples/assets/example_mould.png and /dev/null differ
diff --git a/examples/assets/example_newtonscradle.png b/examples/assets/example_newtonscradle.png
deleted file mode 100644
index b5e37a9..0000000
Binary files a/examples/assets/example_newtonscradle.png and /dev/null differ
diff --git a/examples/assets/example_orbit.png b/examples/assets/example_orbit.png
deleted file mode 100644
index 6244b3e..0000000
Binary files a/examples/assets/example_orbit.png and /dev/null differ
diff --git a/examples/assets/example_pool.png b/examples/assets/example_pool.png
deleted file mode 100644
index 6eee771..0000000
Binary files a/examples/assets/example_pool.png and /dev/null differ
diff --git a/examples/assets/example_pyramid.png b/examples/assets/example_pyramid.png
deleted file mode 100644
index 9c32341..0000000
Binary files a/examples/assets/example_pyramid.png and /dev/null differ
diff --git a/examples/assets/example_spring_car.png b/examples/assets/example_spring_car.png
deleted file mode 100644
index 3b1f7b1..0000000
Binary files a/examples/assets/example_spring_car.png and /dev/null differ
diff --git a/examples/assets/example_springs.png b/examples/assets/example_springs.png
deleted file mode 100644
index 321c64d..0000000
Binary files a/examples/assets/example_springs.png and /dev/null differ
diff --git a/examples/assets/example_stack.png b/examples/assets/example_stack.png
deleted file mode 100644
index f67de2e..0000000
Binary files a/examples/assets/example_stack.png and /dev/null differ
diff --git a/examples/assets/example_vbounce.png b/examples/assets/example_vbounce.png
deleted file mode 100644
index 963f08b..0000000
Binary files a/examples/assets/example_vbounce.png and /dev/null differ
diff --git a/examples/assets/example_vfriction.png b/examples/assets/example_vfriction.png
deleted file mode 100644
index 3e41642..0000000
Binary files a/examples/assets/example_vfriction.png and /dev/null differ
diff --git a/examples/assets/examplegif.gif b/examples/assets/examplegif.gif
index 9e3c382..9be9bea 100644
Binary files a/examples/assets/examplegif.gif and b/examples/assets/examplegif.gif differ
diff --git a/examples/assets/introgif.gif b/examples/assets/introgif.gif
new file mode 100644
index 0000000..f7c21fa
Binary files /dev/null and b/examples/assets/introgif.gif differ
diff --git a/examples/bridge.h b/examples/bridge.h
deleted file mode 100644
index 4c80bdf..0000000
--- a/examples/bridge.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void BridgeExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create grounds & bridge
-
- nvBody *ground_left = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(30.0, 40.0),
- NV_VEC2(10.0, 52.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground_left);
-
- int n = 17; // Parts of the bridge
- double width = 78.0 / (double)n; // Width of one part of the bridge
- double w2 = width / 2.0;
-
- for (size_t i = 0; i < n; i++) {
- nvBody *bridge_part = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(width, 2.0),
- NV_VEC2(25.0 + w2 + i * width, 33.0),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, bridge_part);
- }
-
- nvBody *ground_right = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(30.0, 40.0),
- NV_VEC2(118.0, 52.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground_right);
-
-
- // Link bridge parts with distance joint constraints
- for (size_t i = 1; i < n + 2; i++) {
- nvVector2 anchor_a;
- nvVector2 anchor_b;
-
- // Offset anchors by a tiny amount so they don't intersect
- double offset = w2 / 3.0;
-
- // Link to left ground
- if (i == 1) {
- anchor_a = NV_VEC2(15.0, -20.0);
- anchor_b = NV_VEC2(-w2, 0.0);
- offset /= 2.0;
- }
- // Link to right ground
- else if (i == n + 1) {
- anchor_a = NV_VEC2(w2, 0.0);
- anchor_b = NV_VEC2(-15, -20.0);
- offset /= 2.0;
- }
- // Link between bridge parts
- else {
- anchor_a = NV_VEC2(w2 - offset, 0.0);
- anchor_b = NV_VEC2(-w2 + offset, 0.0);
- }
-
- nvBody *a = (nvBody *)space->bodies->data[i];
- nvBody *b = (nvBody *)space->bodies->data[i + 1];
-
- nvConstraint *link;
-
- // Link with a spring to the grounds
- if (i == 1 || i == n + 1) {
- link = nvSpring_new(
- a, b,
- anchor_a, anchor_b,
- offset,
- 10000.0,
- 500.0
- );
- }
- else {
- link = nvDistanceJoint_new(
- a, b,
- anchor_a, anchor_b,
- offset * 2.0 + 0.25
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-
- //Create boxes on top of the bridge
- for (size_t y = 0; y < 8; y++) {
- for (size_t x = 0; x < 8; x++) {
- nvBody *box = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(2.0, 2.0),
- NV_VEC2(64.0 + x * 2.0 - ((2.0 * 8.0) / 2.0), 10.0 + y * 2.0),
- 0.0,
- nvMaterial_WOOD
- );
-
- nvSpace_add(space, box);
- }
- }
-}
\ No newline at end of file
diff --git a/examples/chains.h b/examples/chains.h
deleted file mode 100644
index c2aceda..0000000
--- a/examples/chains.h
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void ChainsExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- nv_float pos_ratio0 = 60.0;
- nv_float pos_ratio1 = 180.0;
-
- // Create rectangle chain parts
-
- int length = 20; // Length of the chain
- nv_float width = 0.7; // Width of the chain parts
- nv_float height = 1.4; // Height of the chain parts
-
- for (size_t i = 0; i < length; i++) {
- nvBody *chain_part = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(width, height),
- NV_VEC2(
- 1280.0 / 20.0 - 1280.0 / pos_ratio1,
- 10 + i * height
- ),
- 0.0,
- (nvMaterial){1.0, 0.0, 0.0}
- );
- chain_part->collision_group = 1;
- nvSpace_add(space, chain_part);
-
- // Temporary solution to avoid constraints exploding
- nvBody_apply_force(chain_part, NV_VEC2((nv_float)(i%10)*50.0, 0.0));
- }
-
- // Link chain parts
-
- nv_float link_length = height; // Length of each link
-
- for (size_t i = 0; i < length; i++) {
- nvConstraint *link;
- if (i == 0) {
- link = nvSpring_new(
- NULL,
- (nvBody *)space->bodies->data[i + 1],
- NV_VEC2(1280.0 / 20.0 - 1280.0 / pos_ratio1, 10.0),
- NV_VEC2(0.0, -height / 2.0 + 0.001),
- 1.0, 600.0, 25.0
- );
- }
- else {
- link = nvDistanceJoint_new(
- (nvBody *)space->bodies->data[i],
- (nvBody *)space->bodies->data[i + 1],
- NV_VEC2(0.0, height / 2.0 - 0.001),
- NV_VEC2(0.0, -height / 2.0 + 0.001),
- link_length
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-
- // Cache this to accurately create & link other chain bodies
- size_t old_length = space->bodies->size - 1;
-
-
- // Create circle chain parts
-
- length = 30; // Length of the chain
- nv_float radius = 0.7; // Radius of the chain parts
-
- for (size_t i = 0; i < length; i++) {
- nvBody *chain_part = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(radius),
- NV_VEC2(
- 1280.0 / 20.0 - 1280.0 / pos_ratio0,
- 10 + i * radius * 2.0
- ),
- 0.0,
- (nvMaterial){1.0, 0.0, 0.0}
- );
- chain_part->collision_group = 2;
- nvSpace_add(space, chain_part);
-
- // Temporary solution to avoid constraints exploding
- nvBody_apply_force(chain_part, NV_VEC2((nv_float)(i%10)*50.0, 0.0));
- }
-
- // Link chain parts
-
- for (size_t i = old_length; i < old_length + length; i++) {
- nvConstraint *link;
- if (i == old_length) {
- link = nvSpring_new(
- NULL,
- (nvBody *)space->bodies->data[i + 1],
- NV_VEC2(1280.0 / 20.0 - 1280.0 / pos_ratio0, 10.0),
- NV_VEC2(0.0, -height / 2.0 + 0.001),
- 1.0, 600.0, 25.0
- );
- }
- else {
- link = nvDistanceJoint_new(
- (nvBody *)space->bodies->data[i],
- (nvBody *)space->bodies->data[i + 1],
- nvVector2_zero,
- nvVector2_zero,
- radius * 2.0 + 0.01
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-
- // Cache this to accurately create & link other chain bodies
- old_length = space->bodies->size - 1;
-
-
- // Create chain parts
-
- length = 15; // Length of the chain
- nv_float size = 1.0; // Size of the chain parts
-
- for (size_t i = 0; i < length; i++) {
- nvBody *chain_part = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(size, size),
- NV_VEC2(
- 1280.0 / 20.0 + 1280.0 / pos_ratio0,
- 10 + i * (size + 0.5) / 3.0
- ),
- 0.0,
- (nvMaterial){1.0, 0.0, 0.0}
- );
- chain_part->collision_group = 3;
- nvSpace_add(space, chain_part);
- }
-
- // Link chain parts with springs
-
- link_length = 0.5;
- nv_float spring_stiffness = 120.0;
- nv_float spring_damping = 35.0;
-
- for (size_t i = old_length; i < old_length + length; i++) {
- nvConstraint *link;
- if (i == old_length) {
- link = nvSpring_new(
- NULL,
- (nvBody *)space->bodies->data[i + 1],
- NV_VEC2(1280.0 / 20.0 + 1280.0 / pos_ratio0, 10.0),
- NV_VEC2(-size / 2.0, -height / 2.0 + 0.001),
- 1.0, 600.0, 25.0
- );
- }
- else {
- link = nvSpring_new(
- (nvBody *)space->bodies->data[i],
- (nvBody *)space->bodies->data[i + 1],
- NV_VEC2(size / 2.0, size / 2.0),
- NV_VEC2(-size / 2.0, -size / 2.0),
- link_length, spring_stiffness, spring_damping
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-
- old_length = space->bodies->size - 1;
-
- // Create chain parts
-
- length = 30; // Length of the chain
- width = 0.75; // Width of the chain parts
- height = 1.5; // Height of the chain parts
-
- for (size_t i = 0; i < length; i++) {
- nvBody *chain_part = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(width, height),
- NV_VEC2(
- 1280.0 / 20.0 + 1280.0 / pos_ratio1,
- 10 + i * height
- ),
- 0.0,
- (nvMaterial){1.0, 0.0, 0.0}
- );
- chain_part->collision_group = 4;
- nvSpace_add(space, chain_part);
-
- // Temporary solution to avoid constraints exploding
- nvBody_apply_force(chain_part, NV_VEC2((nv_float)(i%10)*50.0, 0.0));
- }
-
- // Link chain parts
-
- for (size_t i = old_length; i < old_length + length; i++) {
- nvConstraint *link;
- if (i == old_length) {
- link = nvSpring_new(
- NULL,
- (nvBody *)space->bodies->data[i + 1],
- NV_VEC2(1280.0 / 20.0 + 1280.0 / pos_ratio1, 10.0),
- NV_VEC2(0.0, -height / 2.0 + 0.001),
- 1.0, 600.0, 25.0
- );
- }
- else {
- link = nvHingeJoint_new(
- (nvBody *)space->bodies->data[i],
- (nvBody *)space->bodies->data[i + 1],
- nvVector2_add(
- ((nvBody *)space->bodies->data[i])->position,
- NV_VEC2(0.0, height/2.0)
- )
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-}
\ No newline at end of file
diff --git a/examples/circle_stack.h b/examples/circle_stack.h
deleted file mode 100644
index 856be6b..0000000
--- a/examples/circle_stack.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void CircleStackExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create ground & walls
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- (nvVector2){64.0, 70.0},
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
- // Create stacked circles
-
- int cols = 12; // Columns of the stack
- int rows = 30; // Rows of the stack
- double size = 1.0; // Size of the circles
- double s2 = size * 2.0;
-
- for (size_t y = 0; y < rows; y++) {
-
- for (size_t x = 0; x < cols; x ++) {
-
- nvBody *ball = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(size),
- NV_VEC2(
- 128.0 / 2.0 - 38.0 - ((double)cols * s2) / 2.0 + size + s2 * (x * 4.5),
- 62.5 - 2.5 - size - y * s2
- ),
- 0.0,
- nvMaterial_BASIC
- );
-
- nvSpace_add(space, ball);
- }
- }
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID)
- nvSpace_set_SHG(space, space->shg->bounds, 2.0, 2.0);
-}
\ No newline at end of file
diff --git a/examples/clock.h b/examples/clock.h
new file mode 100644
index 0000000..85f0c3b
--- /dev/null
+++ b/examples/clock.h
@@ -0,0 +1,91 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_EXAMPLE_CLOCK_H
+#define NOVAPHYSICS_EXAMPLE_CLOCK_H
+
+
+#include
+#include
+
+#include "SDL.h"
+
+
+typedef struct {
+ double frequency;
+ double accumulated_fps;
+ double frame_time_full;
+ double fps;
+ double dt;
+ double start;
+ double time;
+ uint64_t timer_start;
+ uint64_t timer_end;
+ uint64_t timer_full_end;
+ uint32_t fps_counter;
+} Clock;
+
+
+Clock *Clock_new() {
+ Clock *clock = NV_MALLOC(sizeof(Clock));
+
+ clock->frequency = (double)SDL_GetPerformanceFrequency();
+ clock->accumulated_fps = 0.0;
+ clock->frame_time_full = 1.0;
+ clock->fps = 0.0;
+ clock->dt = 0.0;
+ clock->start = (double)SDL_GetPerformanceCounter() / clock->frequency;
+ clock->time = 0.0;
+ clock->timer_start = 0;
+ clock->timer_end = 0;
+ clock->timer_full_end = 0;
+ clock->fps_counter = 0;
+
+ return clock;
+}
+
+void Clock_free(Clock *clock) {
+ if (!clock) return;
+
+ NV_FREE(clock);
+}
+
+void Clock_tick(Clock *clock, double target_fps) {
+ double start = (double)clock->timer_start / clock->frequency;
+
+ clock->timer_end = SDL_GetPerformanceCounter();
+
+ double frame_time = ((double)clock->timer_end / clock->frequency - start) * 1000.0;
+
+ clock->fps_counter++;
+ clock->accumulated_fps += 1000.0 / clock->frame_time_full;
+ if (clock->fps_counter >= 10) {
+ clock->fps = clock->accumulated_fps / (double)10;
+
+ clock->fps_counter = 0;
+ clock->accumulated_fps = 0.0;
+ }
+
+ double target_wait_time = 1000.0 / target_fps;
+ if (frame_time < target_wait_time) {
+ SDL_Delay((uint32_t)(target_wait_time - frame_time));
+ }
+
+ clock->timer_full_end = SDL_GetPerformanceCounter();
+ clock->frame_time_full = ((double)clock->timer_full_end / clock->frequency - start) * 1000.0;
+ clock->dt = clock->frame_time_full / 1000.0;
+
+ clock->timer_start = SDL_GetPerformanceCounter();
+
+ clock->time = (double)SDL_GetPerformanceCounter() / clock->frequency - clock->start;
+}
+
+
+#endif
\ No newline at end of file
diff --git a/examples/cloth.h b/examples/cloth.h
deleted file mode 100644
index 3275144..0000000
--- a/examples/cloth.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void ClothExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Basically disable broadphase
- nvSpace_set_SHG(space, (nvAABB){0.0, 0.0, 1.0, 1.0}, 1.0, 1.0);
-
- int cols = get_slider_setting("Columns");
- int rows = get_slider_setting("Rows");
- nv_float size = 0.75;
- nv_float gap = get_slider_setting("Gap");
-
- for (nv_float y = 0.0; y < rows; y++) {
- for (nv_float x = 0.0; x < cols; x++) {
-
- nvBodyType type;
- if ((y == 0.0 && x == 0.0) || (y == 0.0 && x == cols - 1)) type = nvBodyType_STATIC;
- else type = nvBodyType_DYNAMIC;
- type = nvBodyType_DYNAMIC;
-
- nvBody *ball = nvBody_new(
- type,
- nvCircleShape_new(size),
- NV_VEC2(
- 64.0 + x * (size + gap) - ((size + gap) * (nv_float)cols / 2.0),
- y * (size + gap) + 10.0
- ),
- 0.0,
- (nvMaterial){0.3 / 2.0, 0.0, 0.0}
- );
- ball->enable_collision = false;
- nvSpace_add(space, ball);
- }
- }
-
- nvConstraint *link;
- nv_float link_stiffness = 600.0;
- nv_float link_damping = 5.0;
- bool use_springs = true;
-
- for (size_t y = 0; y < rows; y++) {
- for (size_t x = 0; x < cols; x++) {
- if (x > 0) {
- nvBody *body0 = space->bodies->data[y * cols + x + 1];
- nvBody *body1 = space->bodies->data[y * cols + (x - 1) + 1];
-
- if (use_springs) {
- link = nvSpring_new(
- body0, body1,
- nvVector2_zero, nvVector2_zero,
- size + gap,
- link_stiffness, link_damping
- );
- }
- else {
- link = nvDistanceJoint_new(
- body0, body1,
- nvVector2_zero, nvVector2_zero,
- size + gap
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-
- if (y > 0) {
- nvBody *body0 = space->bodies->data[(y - 1) * cols + x + 1];
- nvBody *body1 = space->bodies->data[y * cols + x + 1];
-
- if (use_springs) {
- link = nvSpring_new(
- body0, body1,
- nvVector2_zero, nvVector2_zero,
- size + gap,
- link_stiffness, link_damping
- );
- }
- else {
- link = nvDistanceJoint_new(
- body0, body1,
- nvVector2_zero, nvVector2_zero,
- size + gap
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
-
- else {
- nvBody *body0 = NULL;
- nvBody *body1 = space->bodies->data[y * cols + x + 1];
-
- if (use_springs) {
- link = nvSpring_new(
- body0, body1,
- NV_VEC2(body1->position.x, body1->position.y - size - gap), nvVector2_zero,
- size + gap,
- link_stiffness, link_damping
- );
- }
- else {
- link = nvDistanceJoint_new(
- body0, body1,
- NV_VEC2(body1->position.x, body1->position.y - size - gap), nvVector2_zero,
- size + gap
- );
- }
-
- nvSpace_add_constraint(space, link);
- }
- }
- }
-
- // Apply horizontal force to some cloth nodes to avoid freaking out
- for (size_t i = 0; i < space->bodies->size; i++) {
- if (i > 1000) {
- nvBody *body = space->bodies->data[i];
- nvBody_apply_force(body, NV_VEC2(0.1, 0.0));
- }
- }
-
- example->switches[4]->on = false; // Disable drawing constraints
-}
-
-
-void ClothExample_init(ExampleEntry *entry) {
- add_slider_setting(entry, "Columns", SliderType_INTEGER, 50, 5, 100);
- add_slider_setting(entry, "Rows", SliderType_INTEGER, 50, 5, 100);
- add_slider_setting(entry, "Gap", SliderType_FLOAT, 0.3, 0.05, 1.0);
-}
\ No newline at end of file
diff --git a/examples/common.h b/examples/common.h
new file mode 100644
index 0000000..c3a85e6
--- /dev/null
+++ b/examples/common.h
@@ -0,0 +1,422 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_EXAMPLE_COMMON_H
+#define NOVAPHYSICS_EXAMPLE_COMMON_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#define NK_INCLUDE_FIXED_TYPES
+#define NK_INCLUDE_STANDARD_IO
+#define NK_INCLUDE_STANDARD_VARARGS
+#define NK_INCLUDE_DEFAULT_ALLOCATOR
+#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+#define NK_INCLUDE_FONT_BAKING
+#define NK_INCLUDE_DEFAULT_FONT
+#define NK_IMPLEMENTATION
+#define NK_SDL_GL3_IMPLEMENTATION
+#include "nuklear/nuklear.h"
+#include "nuklear/nuklear_sdl_gl3.h"
+
+#define SDL_MAIN_HANDLED
+#include "SDL.h"
+
+#include "novaphysics/novaphysics.h"
+#include "novaphysics/bvh.h"
+
+#ifdef NV_WINDOWS
+ #include
+ #include // To gather memory usage information
+#endif
+
+
+typedef struct {
+ double r, g, b, a;
+} FColor;
+
+static inline FColor FColor_lerp(FColor a, FColor b, double t) {
+ return (FColor){
+ a.r + (b.r - a.r) * t,
+ a.g + (b.g - a.g) * t,
+ a.b + (b.b - a.b) * t,
+ a.a + (b.a - a.a) * t,
+ };
+}
+
+
+/**
+ * @brief Mouse information.
+ */
+typedef struct {
+ int x;
+ int y;
+ nv_bool left;
+ nv_bool right;
+ nv_bool middle;
+} Mouse;
+
+/**
+ * @brief Example settings used for initialization.
+ */
+typedef struct {
+ unsigned int window_width;
+ unsigned int window_height;
+} ExampleSettings;
+
+typedef struct {
+ FColor dynamic_body;
+ FColor static_body;
+ FColor distance_constraint;
+ FColor hinge_constraint;
+ FColor spline_constraint;
+ FColor ui_accent;
+ FColor ui_text;
+} ExampleTheme;
+
+/**
+ * @brief Example context.
+ */
+typedef struct {
+ SDL_Window *window;
+ SDL_GLContext gl_ctx;
+ struct nk_context *ui_ctx;
+ unsigned int window_width;
+ unsigned int window_height;
+ nv_bool fullscreen;
+ ExampleTheme theme;
+ Mouse mouse;
+ nvVector2 camera;
+ double zoom;
+ nvVector2 before_zoom;
+ nvVector2 after_zoom;
+ nvVector2 pan_start;
+ nvSpace *space;
+} ExampleContext;
+
+typedef void ( *ExampleCallback)(ExampleContext *);
+
+/**
+ * @brief Example demo entry.
+ */
+typedef struct {
+ char *name;
+ ExampleCallback setup;
+ ExampleCallback update;
+} ExampleEntry;
+
+#define EXAMPLE_MAX_ENTRIES 100
+extern ExampleEntry example_entries[EXAMPLE_MAX_ENTRIES];
+extern size_t example_count;
+size_t current_example;
+
+/**
+ * @brief Register an example demo.
+ */
+void ExampleEntry_register(
+ char *name,
+ ExampleCallback setup,
+ ExampleCallback update
+);
+
+/**
+ * @brief Set the current example demo.
+ */
+void ExampleEntry_set_current(char *name);
+
+
+/**
+ * @brief Return random nv_float in given range.
+ *
+ * @param lower Min range
+ * @param higher Max range
+ * @return nv_float
+ */
+static inline float frand(float lower, float higher) {
+ float normal = rand() / (float)RAND_MAX;
+ return lower + normal * (higher - lower);
+}
+
+/**
+ * @brief Return random nv_uint32 in given range.
+ *
+ * @param lower Min range
+ * @param higher Max range
+ * @return nv_uint32
+ */
+static inline nv_uint32 u32rand(nv_uint32 lower, nv_uint32 higher) {
+ return (rand() % (higher - lower + 1)) + lower;
+}
+
+
+/**
+ * @brief Get current memory usage of this process in bytes.
+ *
+ * Returns 0 if it fails to gather information.
+ *
+ * @return size_t
+ */
+size_t get_current_memory_usage() {
+ #ifdef NV_WINDOWS
+
+ // https://learn.microsoft.com/en-us/windows/win32/psapi/collecting-memory-usage-information-for-a-process
+
+ HANDLE current_process = GetCurrentProcess();
+ PROCESS_MEMORY_COUNTERS_EX pmc;
+
+ if (GetProcessMemoryInfo(current_process, (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc))) {
+ return pmc.WorkingSetSize;
+ }
+ else {
+ return 0;
+ }
+
+ #else
+
+ FILE *status = fopen("/proc/self/status", "r");
+
+ if (status) {
+ char line[128];
+ while (fgets(line, 128, status) != NULL) {
+ if (strncmp(line, "VmSize:", 7) == 0) {
+ char *val = line + 7;
+ fclose(status);
+ return strtoul(val, NULL, 10) * 1024;
+ }
+ }
+ }
+
+ fclose(status);
+ return 0;
+
+ #endif
+}
+
+
+/**
+ * @brief Generate n-cornered star shape.
+ *
+ * @param body Body to add the shapes to
+ * @param n Corner count
+ * @param r Radius
+ */
+void add_star_shape(nvRigidBody *body, nv_uint32 n, nv_float r) {
+ nv_float base = r * (nv_float)tanf(NV_PI / (nv_float)n);
+
+ nvVector2 p0 = NV_VECTOR2(-base * 0.5, 0.0);
+ nvVector2 p1 = NV_VECTOR2(base * 0.5, 0.0);
+ nvVector2 p2 = NV_VECTOR2(0.0, r);
+
+ for (nv_uint32 i = 0; i < n; i++) {
+ nv_float an = (nv_float)i * (2.0 * NV_PI / (nv_float)n);
+
+ nvVector2 t0 = nvVector2_rotate(p0, an);
+ nvVector2 t1 = nvVector2_rotate(p1, an);
+ nvVector2 t2 = nvVector2_rotate(p2, an);
+
+ nvShape *tri = nvPolygonShape_new((nvVector2[3]){t0, t1, t2}, 3, nvVector2_zero);
+ nvRigidBody_add_shape(body, tri);
+ }
+}
+
+/**
+ * @brief Generate a circular softbody with spring distance constraints.
+ *
+ * @param example
+ * @param center
+ * @param n
+ * @param radius
+ * @param particle_radius
+ */
+void create_circle_softbody(
+ ExampleContext *example,
+ nvVector2 center,
+ size_t n,
+ nv_float radius,
+ nv_float particle_radius
+) {
+ nvVector2 arm = NV_VECTOR2(radius, 0.0);
+ nvRigidBody **particles = NV_MALLOC(sizeof(nvRigidBody *) * n);
+
+ // Create particles
+ for (size_t i = 0; i < n; i++) {
+ arm = nvVector2_rotate(arm, 2.0 * NV_PI / (nv_float)n);
+
+ nvRigidBodyInitializer particle_init = nvRigidBodyInitializer_default;
+ particle_init.type = nvRigidBodyType_DYNAMIC;
+ particle_init.position = nvVector2_add(center, arm);
+ particle_init.material = (nvMaterial){.density=1.0, .restitution=0.0, .friction=0.2};
+ nvRigidBody *particle = nvRigidBody_new(particle_init);
+
+ nvShape *shape = nvCircleShape_new(nvVector2_zero, particle_radius);
+ nvRigidBody_add_shape(particle, shape);
+
+ //nvRigidBody_set_inertia(particle, 0.0);
+ nvSpace_add_rigidbody(example->space, particle);
+ particles[i] = particle;
+ }
+
+ nvDistanceConstraintInitializer spring_init = nvDistanceConstraintInitializer_default;
+ spring_init.spring = true;
+ spring_init.hertz = 0.6;
+ spring_init.damping = 0.07;
+
+ // Create edge links
+ for (size_t i = 0; i < n; i++) {
+ nvRigidBody *a = particles[i];
+ nvRigidBody *b = particles[(i + 1) % n];
+ spring_init.a = a;
+ spring_init.b = b;
+
+ nvVector2 dir_a = nvVector2_normalize(nvVector2_sub(center, nvRigidBody_get_position(a)));
+ nvVector2 dir_b = nvVector2_normalize(nvVector2_sub(center, nvRigidBody_get_position(b)));
+
+ nvVector2 anchor_a0 = nvVector2_mul(dir_a, particle_radius);
+ nvVector2 anchor_a1 = nvVector2_mul(dir_a, -particle_radius);
+
+ nvVector2 anchor_b0 = nvVector2_mul(dir_b, particle_radius);
+ nvVector2 anchor_b1 = nvVector2_mul(dir_b, -particle_radius);
+
+ nvVector2 anchor_a0_world = nvVector2_add(nvRigidBody_get_position(a), anchor_a0);
+ nvVector2 anchor_a1_world = nvVector2_add(nvRigidBody_get_position(a), anchor_a1);
+ nvVector2 anchor_b0_world = nvVector2_add(nvRigidBody_get_position(b), anchor_b0);
+ nvVector2 anchor_b1_world = nvVector2_add(nvRigidBody_get_position(b), anchor_b1);
+
+ nv_float length = nvVector2_len(nvVector2_sub(anchor_a0_world, anchor_b0_world));
+ spring_init.length = length;
+ spring_init.anchor_a = anchor_a0;
+ spring_init.anchor_b = anchor_b0;
+ nvSpace_add_constraint(example->space, nvDistanceConstraint_new(spring_init));
+
+ length = nvVector2_len(nvVector2_sub(anchor_a1_world, anchor_b1_world));
+ spring_init.length = length;
+ spring_init.anchor_a = anchor_a1;
+ spring_init.anchor_b = anchor_b1;
+ nvSpace_add_constraint(example->space, nvDistanceConstraint_new(spring_init));
+
+ length = nvVector2_len(nvVector2_sub(anchor_a0_world, anchor_b1_world));
+ spring_init.length = length;
+ spring_init.anchor_a = anchor_a0;
+ spring_init.anchor_b = anchor_b1;
+ nvSpace_add_constraint(example->space, nvDistanceConstraint_new(spring_init));
+
+ length = nvVector2_len(nvVector2_sub(anchor_a1_world, anchor_b0_world));
+ spring_init.length = length;
+ spring_init.anchor_a = anchor_a1;
+ spring_init.anchor_b = anchor_b0;
+ nvSpace_add_constraint(example->space, nvDistanceConstraint_new(spring_init));
+ }
+
+ spring_init.hertz *= 0.6;
+
+ // Create inner links
+ for (size_t i = 0; i < n; i++) {
+ for (size_t j = i + 2; j < n; j++) {
+ nvRigidBody *a = particles[i];
+ nvRigidBody *b = particles[j];
+
+ nv_float length = nvVector2_len(nvVector2_sub(nvRigidBody_get_position(b), nvRigidBody_get_position(a)));
+ spring_init.a = a;
+ spring_init.b = b;
+ spring_init.length = length;
+ spring_init.anchor_a = nvVector2_zero;
+ spring_init.anchor_b = nvVector2_zero;
+
+ nvSpace_add_constraint(example->space, nvDistanceConstraint_new(spring_init));
+ }
+ }
+
+ NV_FREE(particles);
+}
+
+
+nvVector2 catmull_rom(nvVector2 p0, nvVector2 p1, nvVector2 p2, nvVector2 p3, nv_float t) {
+ nv_float t2 = t * t;
+ nv_float t3 = t2 * t;
+
+ nv_float x = 0.5 * ((2.0 * p1.x) +
+ (-p0.x + p2.x) * t +
+ (2.0 * p0.x - 5.0 * p1.x + 4.0 * p2.x - p3.x) * t2 +
+ (-p0.x + 3.0 * p1.x - 3.0 * p2.x + p3.x) * t3);
+
+ nv_float y = 0.5 * ((2 * p1.y) +
+ (-p0.y + p2.y) * t +
+ (2.0 * p0.y - 5.0 * p1.y + 4.0 * p2.y - p3.y) * t2 +
+ (-p0.y + 3.0 * p1.y - 3.0 * p2.y + p3.y) * t3);
+
+ return NV_VECTOR2(x, y);
+}
+
+void sample_spline(nvSplineConstraint *spline, nvVector2 *sample_points, size_t num_samples) {
+ nvVector2 *controls = spline->controls;
+ size_t num_controls = spline->num_controls;
+ size_t num_segments = num_controls - 3;
+
+ size_t sample_per_segment = num_samples / num_segments;
+
+ size_t sample_i = 0;
+ for (size_t i = 0; i < num_segments; i++) {
+ for (size_t j = 0; j < sample_per_segment; j++) {
+ nv_float t = (nv_float)j / (nv_float)(sample_per_segment - 1);
+ nvVector2 p0 = controls[i];
+ nvVector2 p1 = controls[i + 1];
+ nvVector2 p2 = controls[i + 2];
+ nvVector2 p3 = controls[i + 3];
+ nvVector2 p = catmull_rom(p0, p1, p2, p3, t);
+ sample_points[sample_i++] = p;
+ }
+ }
+}
+
+
+void bvh_calc_depth(nvBVHNode *node, size_t depth) {
+ if (!node) return;
+ node->depth = depth;
+ bvh_calc_depth(node->left, depth + 1);
+ bvh_calc_depth(node->right, depth + 1);
+}
+
+static inline nv_int64 max3(nv_int64 a, nv_int64 b, nv_int64 c) {
+ nv_int64 max_value = a;
+
+ if (b > max_value) {
+ max_value = b;
+ }
+
+ if (c > max_value) {
+ max_value = c;
+ }
+
+ return max_value;
+}
+
+nv_int64 bvh_max_depth(nvBVHNode *node) {
+ if (!node)
+ return -1;
+
+ if (node->is_leaf)
+ return node->depth;
+
+ nv_int64 left_max_depth = bvh_max_depth(node->left);
+ nv_int64 right_max_depth = bvh_max_depth(node->right);
+
+ return max3(node->depth, left_max_depth, right_max_depth);
+}
+
+
+#endif
\ No newline at end of file
diff --git a/examples/constraints.h b/examples/constraints.h
deleted file mode 100644
index ada9484..0000000
--- a/examples/constraints.h
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void ConstraintsExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 72.0),
- 0.0,
- nvMaterial_CONCRETE
- );
- nvSpace_add(space, ground);
-
- nvBody *wall0 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(0.5, 72.0),
- NV_VEC2(128.0 / 3.0, 36.0),
- 0.0,
- nvMaterial_CONCRETE
- );
- nvSpace_add(space, wall0);
-
- nvBody *wall1 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(0.5, 72.0),
- NV_VEC2(128.0 / 3.0 * 2.0, 36.0),
- 0.0,
- nvMaterial_CONCRETE
- );
- nvSpace_add(space, wall1);
-
-
- /* Spring Constraint */
-
- nvBody *circle = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(4.0, 4.0),
- NV_VEC2(128.0 / 6.0, 17.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, circle);
-
- nvConstraint *spring = nvSpring_new(
- NULL, circle,
- NV_VEC2(128.0 / 6.0, 5.0), NV_VEC2(0.0, -2.0),
- 10.0, 100.0, 5.0
- );
- nvSpace_add_constraint(space, spring);
-
- nvBody *bridge0 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 6.0 - 5.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge0);
-
- nvBody *bridge1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 6.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge1);
-
- nvBody *bridge2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 6.0 + 5.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge2);
-
- nvConstraint *bridge_spring0 = nvSpring_new(
- NULL, bridge0,
- NV_VEC2(128.0 / 6.0 - 10.0, 36.0), NV_VEC2(0.0, 0.0),
- 6.0, 300.0, 20.0
- );
- nvSpace_add_constraint(space, bridge_spring0);
-
- nvConstraint *bridge_spring1 = nvSpring_new(
- bridge0, bridge1,
- NV_VEC2(0.0, 0.0), NV_VEC2(0.0, 0.0),
- 6.0, 300.0, 20.0
- );
- nvSpace_add_constraint(space, bridge_spring1);
-
- nvConstraint *bridge_spring2 = nvSpring_new(
- bridge1, bridge2,
- NV_VEC2(0.0, 0.0), NV_VEC2(0.0, 0.0),
- 6.0, 300.0, 20.0
- );
- nvSpace_add_constraint(space, bridge_spring2);
-
- nvConstraint *bridge_spring3 = nvSpring_new(
- NULL, bridge2,
- NV_VEC2(128.0 / 6.0 + 10.0, 36.0), NV_VEC2(0.0, 0.0),
- 6.0, 300.0, 20.0
- );
- nvSpace_add_constraint(space, bridge_spring3);
-
- nvBody *triangle = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(3, 5.5),
- NV_VEC2(128.0 / 6.0 - 10.0, 60.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, triangle);
-
- nvBody *hexagon = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(6, 5.5),
- NV_VEC2(128.0 / 6.0 + 10.0, 60.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, hexagon);
-
- nvConstraint *shape_spring = nvSpring_new(
- triangle, hexagon,
- NV_VEC2(1.7, 0.0), NV_VEC2(-1.7, 0.0),
- 10.0, 200.0, 25.0
- );
- nvSpace_add_constraint(space, shape_spring);
-
-
- /* Distance Joint Constraint */
-
- circle = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(4.0, 4.0),
- NV_VEC2(128.0 / 2.0, 17.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, circle);
-
- nvConstraint *dist_joint = nvDistanceJoint_new(
- NULL, circle,
- NV_VEC2(128.0 / 2.0, 5.0), NV_VEC2(0.0, -2.0),
- 10.0
- );
- nvSpace_add_constraint(space, dist_joint);
-
- bridge0 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 2.0 - 5.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge0);
-
- bridge1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 2.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge1);
-
- bridge2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 2.0 + 5.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge2);
-
- nvConstraint *bridge_dist0 = nvDistanceJoint_new(
- NULL, bridge0,
- NV_VEC2(128.0 / 2.0 - 10.0, 36.0), NV_VEC2(0.0, 0.0),
- 6.0
- );
- nvSpace_add_constraint(space, bridge_dist0);
-
- nvConstraint *bridge_dist1 = nvDistanceJoint_new(
- bridge0, bridge1,
- NV_VEC2(0.0, 0.0), NV_VEC2(0.0, 0.0),
- 6.0
- );
- nvSpace_add_constraint(space, bridge_dist1);
-
- nvConstraint *bridge_dist2 = nvDistanceJoint_new(
- bridge1, bridge2,
- NV_VEC2(0.0, 0.0), NV_VEC2(0.0, 0.0),
- 6.0
- );
- nvSpace_add_constraint(space, bridge_dist2);
-
- nvConstraint *bridge_dist3 = nvDistanceJoint_new(
- NULL, bridge2,
- NV_VEC2(128.0 / 2.0 + 10.0, 36.0), NV_VEC2(0.0, 0.0),
- 6.0
- );
- nvSpace_add_constraint(space, bridge_dist3);
-
- triangle = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(3, 5.5),
- NV_VEC2(128.0 / 2.0 - 10.0, 60.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, triangle);
-
- hexagon = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(6, 5.5),
- NV_VEC2(128.0 / 2.0 + 10.0, 60.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, hexagon);
-
- nvConstraint *shape_dist = nvDistanceJoint_new(
- triangle, hexagon,
- NV_VEC2(1.7, 0.0), NV_VEC2(-1.7, 0.0),
- 10.0
- );
- nvSpace_add_constraint(space, shape_dist);
-
-
- /* Hinge Joint Constraint */
-
- circle = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(4.0, 4.0),
- NV_VEC2(128.0 / 1.2, 17.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, circle);
-
- nvConstraint *hinge_joint = nvHingeJoint_new(
- NULL, circle,
- NV_VEC2(128.0 / 1.2, 5.0)
- );
- nvSpace_add_constraint(space, hinge_joint);
-
- bridge0 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 1.2 - 2.4, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge0);
-
- bridge1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 1.2, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge1);
-
- bridge2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 1.2 + 2.4, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge2);
-
- nvBody *bridge3 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 1.2 - 1.2*4.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge3);
-
- nvBody *bridge4 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.2),
- NV_VEC2(128.0 / 1.2 + 1.2*4.0, 36.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, bridge4);
-
- nvConstraint *bridge_hingea = nvHingeJoint_new(
- NULL, bridge3,
- NV_VEC2(128.0 / 1.2 - 1.2 * 5.0, 36.0)
- );
- nvSpace_add_constraint(space, bridge_hingea);
-
- nvConstraint *bridge_hinge0 = nvHingeJoint_new(
- bridge3, bridge0,
- NV_VEC2(128.0 / 1.2 - 1.2 * 3.0, 36.0)
- );
- nvSpace_add_constraint(space, bridge_hinge0);
-
- nvConstraint *bridge_hinge1 = nvHingeJoint_new(
- bridge0, bridge1,
- NV_VEC2(128.0 / 1.2 - 1.2 * 1.0, 36.0)
- );
- nvSpace_add_constraint(space, bridge_hinge1);
-
- nvConstraint *bridge_hinge2 = nvHingeJoint_new(
- bridge1, bridge2,
- NV_VEC2(128.0 / 1.2 + 1.2 * 1.0, 36.0)
- );
- nvSpace_add_constraint(space, bridge_hinge2);
-
- nvConstraint *bridge_hinge3 = nvHingeJoint_new(
- bridge4, bridge2,
- NV_VEC2(128.0 / 1.2 + 1.2 * 3.0, 36.0)
- );
- nvSpace_add_constraint(space, bridge_hinge3);
-
- nvConstraint *bridge_hingeb = nvHingeJoint_new(
- bridge4, NULL,
- NV_VEC2(128.0 / 1.2 + 1.2 * 5.0, 36.0)
- );
- nvSpace_add_constraint(space, bridge_hingeb);
-
- triangle = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(3, 5.5),
- NV_VEC2(128.0 / 1.2 - 10.0, 60.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, triangle);
-
- hexagon = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(6, 5.5),
- NV_VEC2(128.0 / 1.2 + 10.0, 60.0),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, hexagon);
-
- nvConstraint *shape_hinge = nvHingeJoint_new(
- triangle, hexagon,
- NV_VEC2(128.0 / 1.2, 60.0)
- );
- nvSpace_add_constraint(space, shape_hinge);
-}
\ No newline at end of file
diff --git a/examples/demos/demo_bouncing.h b/examples/demos/demo_bouncing.h
new file mode 100644
index 0000000..2e5867d
--- /dev/null
+++ b/examples/demos/demo_bouncing.h
@@ -0,0 +1,48 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void Bouncing_setup(ExampleContext *example) {
+ nvRigidBody *ground;
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground_init.material = (nvMaterial){.density=1.0, .restitution=1.0, .friction=0.5};
+ ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(102.0, 5.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+
+ nvSpace_add_rigidbody(example->space, ground);
+
+
+ for (size_t x = 0; x < 100; x++) {
+ nv_float e = (nv_float)x / 100.0;
+
+ nvRigidBody *ball;
+ nvRigidBodyInitializer ball_init = nvRigidBodyInitializer_default;
+ ball_init.type = nvRigidBodyType_DYNAMIC;
+ ball_init.position = NV_VECTOR2(
+ (nv_float)x + 14.0,
+ 0.0
+ );
+ ball_init.material = (nvMaterial){.density=1.0, .restitution=e, .friction=0.5};
+ ball = nvRigidBody_new(ball_init);
+
+ // Radius just under 0.5 so balls don't collide horizontally
+ nvShape *shape = nvCircleShape_new(nvVector2_zero, 0.49);
+ nvRigidBody_add_shape(ball, shape);
+
+ nvSpace_add_rigidbody(example->space, ball);
+ }
+}
+
+void Bouncing_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_compound.h b/examples/demos/demo_compound.h
new file mode 100644
index 0000000..7e4490f
--- /dev/null
+++ b/examples/demos/demo_compound.h
@@ -0,0 +1,48 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void Compound_setup(ExampleContext *example) {
+ nvRigidBody *ground;
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(128.0, 5.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+
+ nvSpace_add_rigidbody(example->space, ground);
+
+
+ nv_float w = 4.0;
+ for (size_t y = 0; y < 10; y++) {
+ for (size_t x = 0; x < 10; x++) {
+
+ nvRigidBody *body;
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(
+ 64.0 - w * (10.0 * 0.5) + x * w,
+ 50.0 - y * w
+ );
+ body_init.material = (nvMaterial){.density=1.0, .restitution=0.2, .friction=0.3};
+ body = nvRigidBody_new(body_init);
+
+ nv_uint32 corners = u32rand(4, 8);
+ add_star_shape(body, corners, 2.0);
+
+ nvSpace_add_rigidbody(example->space, body);
+ }
+ }
+}
+
+void Compound_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_contact_event.h b/examples/demos/demo_contact_event.h
new file mode 100644
index 0000000..d9c0b86
--- /dev/null
+++ b/examples/demos/demo_contact_event.h
@@ -0,0 +1,83 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void ContactEvent_added_callback(nvSpace *space, nvContactEvent event, void *user_arg) {
+ nvRigidBody *void_ground = (nvRigidBody *)user_arg;
+
+ if (event.body_a == void_ground) {
+ nvSpace_remove_rigidbody(space, event.body_b);
+ }
+ else if (event.body_b == void_ground) {
+ nvSpace_remove_rigidbody(space, event.body_a);
+ }
+}
+
+void ContactEvent_setup(ExampleContext *example) {
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground_init.material = (nvMaterial){.density=1.0, .restitution=1.0, .friction=0.5};
+ nvRigidBody *void_ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(30.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(void_ground, ground_shape);
+
+ nvSpace_add_rigidbody(example->space, void_ground);
+
+
+ ground_init.position = NV_VECTOR2(30.0, 30.0);
+ ground_init.angle = NV_PI / 4.0 + 0.3;
+ nvRigidBody *ramp0 = nvRigidBody_new(ground_init);
+
+ nvShape *ramp0_shape = nvBoxShape_new(90.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(ramp0, ramp0_shape);
+
+ nvSpace_add_rigidbody(example->space, ramp0);
+
+
+ ground_init.position = NV_VECTOR2(64.0 + 34.0, 30.0);
+ ground_init.angle = -NV_PI / 4.0 - 0.3;
+ nvRigidBody *ramp1 = nvRigidBody_new(ground_init);
+
+ nvShape *ramp1_shape = nvBoxShape_new(90.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(ramp1, ramp1_shape);
+
+ nvSpace_add_rigidbody(example->space, ramp1);
+
+
+ nvContactListener listener = {
+ .on_contact_added = ContactEvent_added_callback,
+ .on_contact_persisted = NULL,
+ .on_contact_removed = NULL
+ };
+
+ nvSpace_set_contact_listener(example->space, listener, void_ground);
+}
+
+size_t spawn_frame = 0;
+
+void ContactEvent_update(ExampleContext *example) {
+ if (spawn_frame % 5 == 0) {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(frand(64.0 - 50.0, 64.0 + 50.0), -15.0);
+ body_init.material = (nvMaterial){.density=1.0, .restitution=1.0, .friction=0.5};
+ nvRigidBody *body = nvRigidBody_new(body_init);
+
+ nvShape *body_shape = nvNGonShape_new(u32rand(3, 6), 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(body, body_shape);
+
+ nvSpace_add_rigidbody(example->space, body);
+ }
+
+ spawn_frame++;
+}
\ No newline at end of file
diff --git a/examples/demos/demo_damping.h b/examples/demos/demo_damping.h
new file mode 100644
index 0000000..2dd6459
--- /dev/null
+++ b/examples/demos/demo_damping.h
@@ -0,0 +1,64 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void Damping_add_body0(nvSpace *space, nv_float y, nv_float linear_damping_scale) {
+ nvRigidBodyInitializer box_init = nvRigidBodyInitializer_default;
+ box_init.type = nvRigidBodyType_DYNAMIC;
+ box_init.position = NV_VECTOR2(40.0, y + 5.0);
+ nvRigidBody *box = nvRigidBody_new(box_init);
+
+ nvShape *box_shape = nvBoxShape_new(1.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvRigidBody_set_linear_damping_scale(box, linear_damping_scale);
+ nvRigidBody_apply_force(box, NV_VECTOR2(1000.0, 0.0));
+
+ nvSpace_add_rigidbody(space, box);
+}
+
+void Damping_add_body1(nvSpace *space, nv_float y, nv_float angular_damping_scale) {
+ nvRigidBodyInitializer box_init = nvRigidBodyInitializer_default;
+ box_init.type = nvRigidBodyType_DYNAMIC;
+ box_init.position = NV_VECTOR2(40.0, y + 35.0);
+ nvRigidBody *box = nvRigidBody_new(box_init);
+
+ nvShape *box_shape = nvBoxShape_new(2.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvRigidBody_set_angular_damping_scale(box, angular_damping_scale);
+ nvRigidBody_apply_torque(box, 1000.0);
+
+ nvSpace_add_rigidbody(space, box);
+}
+
+
+void Damping_setup(ExampleContext *example) {
+ nvSpace_set_gravity(example->space, nvVector2_zero);
+
+ // Damping scale 1.0 (100%) means the damping value specified in nvSpaceSettings
+ // is not affected by this body's scale factor
+
+ // linear damping 0% -> 50,000%
+ // body with 0% damping scale will keep moving whereas others will start to slow down
+ for (nv_float i = 0.0; i < 10.0; i += 1.0) {
+ Damping_add_body0(example->space, i * 2.0, i * 50.0);
+ }
+
+ // angular damping 0% -> 50,000%
+ // body with 0% damping scale will keep rotating whereas others will start to slow down
+ for (nv_float i = 0.0; i < 10.0; i += 1.0) {
+ Damping_add_body1(example->space, i * 4.0, i * 50.0);
+ }
+}
+
+void Damping_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_density.h b/examples/demos/demo_density.h
new file mode 100644
index 0000000..c4766bd
--- /dev/null
+++ b/examples/demos/demo_density.h
@@ -0,0 +1,55 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void Density_setup(ExampleContext *example) {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.position = NV_VECTOR2(64.0, 45.0);
+ nvRigidBody *bowl = nvRigidBody_new(body_init);
+
+ nvRigidBody_add_shape(bowl, nvBoxShape_new(45.0, 1.0, NV_VECTOR2(0.0, 12.5)));
+ nvRigidBody_add_shape(bowl, nvBoxShape_new(1.0, 25.0, NV_VECTOR2(-22.5, 0.0)));
+ nvRigidBody_add_shape(bowl, nvBoxShape_new(1.0, 25.0, NV_VECTOR2(22.5, 0.0)));
+
+ nvSpace_add_rigidbody(example->space, bowl);
+
+
+ // Box bodies with density 1.0
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ for (size_t i = 0; i < 600; i++) {
+ body_init.position = NV_VECTOR2(frand(64.0 - 22.0, 64.0 + 22.0), frand(45.0 - 10.0, 45.0 + 12.0));
+ body_init.angle = frand(-NV_PI, NV_PI);
+
+ nvRigidBody *box = nvRigidBody_new(body_init);
+
+ nvShape *box_shape = nvBoxShape_new(0.7, 1.3, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvSpace_add_rigidbody(example->space, box);
+ }
+
+
+ // Dense balls
+ body_init.material.density = 50.0;
+ for (size_t i = 0; i < 3; i++) {
+ body_init.position = NV_VECTOR2(64.0 - 15.0 + (nv_float)i * 14.0, 45.0 - 20.0);
+
+ nvRigidBody *ball = nvRigidBody_new(body_init);
+
+ nvShape *ball_shape = nvCircleShape_new(nvVector2_zero, 1.0);
+ nvRigidBody_add_shape(ball, ball_shape);
+
+ nvSpace_add_rigidbody(example->space, ball);
+ }
+}
+
+void Density_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_distance_constraint.h b/examples/demos/demo_distance_constraint.h
new file mode 100644
index 0000000..970e594
--- /dev/null
+++ b/examples/demos/demo_distance_constraint.h
@@ -0,0 +1,202 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void DistanceConstraint_setup(ExampleContext *example) {
+ {
+ // High mass ratio double pendulum
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(64.0, 15.0);
+ nvRigidBody *body0 = nvRigidBody_new(body_init);
+
+ nvShape *body0_shape = nvCircleShape_new(nvVector2_zero, 0.5);
+ nvRigidBody_add_shape(body0, body0_shape);
+
+ nvSpace_add_rigidbody(example->space, body0);
+
+
+ body_init.position = NV_VECTOR2(64.0, 20.0);
+ body_init.material.density = 2.0;
+ nvRigidBody *body1 = nvRigidBody_new(body_init);
+
+ nvShape *body1_shape = nvCircleShape_new(nvVector2_zero, 2.3);
+ nvRigidBody_add_shape(body1, body1_shape);
+
+ nvSpace_add_rigidbody(example->space, body1);
+
+
+ nvDistanceConstraintInitializer cons_init = nvDistanceConstraintInitializer_default;
+ cons_init.a = NULL;
+ cons_init.b = body0;
+ cons_init.length = 5.0;
+ cons_init.anchor_a = NV_VECTOR2(64.0, 10.0);
+ nvConstraint *dist0_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist0_cons);
+
+ cons_init.a = body0;
+ cons_init.b = body1;
+ cons_init.anchor_a = nvVector2_zero;
+ nvConstraint *dist1_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist1_cons);
+ }
+
+ // High mass ratio spring double pendulum
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(74.0, 15.0);
+ nvRigidBody *body0 = nvRigidBody_new(body_init);
+
+ nvShape *body0_shape = nvCircleShape_new(nvVector2_zero, 0.5);
+ nvRigidBody_add_shape(body0, body0_shape);
+
+ nvSpace_add_rigidbody(example->space, body0);
+
+
+ body_init.position = NV_VECTOR2(74.0, 20.0);
+ body_init.material.density = 2.0;
+ nvRigidBody *body1 = nvRigidBody_new(body_init);
+
+ nvShape *body1_shape = nvCircleShape_new(nvVector2_zero, 2.3);
+ nvRigidBody_add_shape(body1, body1_shape);
+
+ nvSpace_add_rigidbody(example->space, body1);
+
+
+ nvDistanceConstraintInitializer cons_init = nvDistanceConstraintInitializer_default;
+ cons_init.a = NULL;
+ cons_init.b = body0;
+ cons_init.length = 5.0;
+ cons_init.anchor_a = NV_VECTOR2(74.0, 10.0);
+ cons_init.spring = true;
+ cons_init.hertz = 1.2;
+ cons_init.damping = 0.1;
+ nvConstraint *dist0_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist0_cons);
+
+ cons_init.a = body0;
+ cons_init.b = body1;
+ cons_init.anchor_a = nvVector2_zero;
+ nvConstraint *dist1_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist1_cons);
+ }
+
+ // Double pendulum
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(64.0, 40.0);
+ nvRigidBody *body0 = nvRigidBody_new(body_init);
+
+ nvShape *body0_shape = nvCircleShape_new(nvVector2_zero, 0.5);
+ nvRigidBody_add_shape(body0, body0_shape);
+
+ nvSpace_add_rigidbody(example->space, body0);
+
+
+ body_init.position = NV_VECTOR2(64.0, 45.0);
+ nvRigidBody *body1 = nvRigidBody_new(body_init);
+
+ nvShape *body1_shape = nvCircleShape_new(nvVector2_zero, 0.5);
+ nvRigidBody_add_shape(body1, body1_shape);
+
+ nvSpace_add_rigidbody(example->space, body1);
+
+
+ nvDistanceConstraintInitializer cons_init = nvDistanceConstraintInitializer_default;
+ cons_init.a = NULL;
+ cons_init.b = body0;
+ cons_init.length = 5.0;
+ cons_init.anchor_a = NV_VECTOR2(64.0, 35.0);
+ nvConstraint *dist0_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist0_cons);
+
+ cons_init.a = body0;
+ cons_init.b = body1;
+ cons_init.anchor_a = nvVector2_zero;
+ nvConstraint *dist1_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist1_cons);
+ }
+
+ // Spring double pendulum
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(74.0, 40.0);
+ nvRigidBody *body0 = nvRigidBody_new(body_init);
+
+ nvShape *body0_shape = nvCircleShape_new(nvVector2_zero, 0.5);
+ nvRigidBody_add_shape(body0, body0_shape);
+
+ nvSpace_add_rigidbody(example->space, body0);
+
+
+ body_init.position = NV_VECTOR2(74.0, 45.0);
+ nvRigidBody *body1 = nvRigidBody_new(body_init);
+
+ nvShape *body1_shape = nvCircleShape_new(nvVector2_zero, 0.5);
+ nvRigidBody_add_shape(body1, body1_shape);
+
+ nvSpace_add_rigidbody(example->space, body1);
+
+
+ nvDistanceConstraintInitializer cons_init = nvDistanceConstraintInitializer_default;
+ cons_init.a = NULL;
+ cons_init.b = body0;
+ cons_init.length = 5.0;
+ cons_init.anchor_a = NV_VECTOR2(74.0, 35.0);
+ cons_init.spring = true;
+ cons_init.hertz = 1.2;
+ cons_init.damping = 0.1;
+ nvConstraint *dist0_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist0_cons);
+
+ cons_init.a = body0;
+ cons_init.b = body1;
+ cons_init.anchor_a = nvVector2_zero;
+ nvConstraint *dist1_cons = nvDistanceConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, dist1_cons);
+ }
+
+ // Spring parameters
+ {
+ nvDistanceConstraintInitializer cons_init = nvDistanceConstraintInitializer_default;
+ cons_init.a = NULL;
+ cons_init.length = 5.0;
+ cons_init.spring = true;
+
+ // Spring frequency 0.25 -> 5.0
+
+ for (size_t x = 0; x < 10; x++) {
+ cons_init.hertz = 0.25 + (nv_float)x * 0.475;
+ cons_init.damping = 0.1;
+
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(90.0 + (nv_float)x * 6.0, 12.0);
+ nvRigidBody *body = nvRigidBody_new(body_init);
+ nvShape *body_shape = nvRectShape_new(1.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(body, body_shape);
+ nvSpace_add_rigidbody(example->space, body);
+
+ cons_init.b = body;
+ cons_init.anchor_a = NV_VECTOR2(90.0 + (nv_float)x * 6.0, 10.0);
+
+ nvSpace_add_constraint(example->space, nvDistanceConstraint_new(cons_init));
+ }
+ }
+ }
+}
+
+void DistanceConstraint_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_friction.h b/examples/demos/demo_friction.h
new file mode 100644
index 0000000..570c1ee
--- /dev/null
+++ b/examples/demos/demo_friction.h
@@ -0,0 +1,47 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void Friction_add_ramp(nvSpace *space, nv_float y, nv_float friction) {
+ nvRigidBodyInitializer ramp_init = nvRigidBodyInitializer_default;
+ ramp_init.position = NV_VECTOR2(64.0, y);
+ ramp_init.angle = 0.35;
+ ramp_init.material = (nvMaterial){.density=1.0, .restitution=0.0, .friction=0.1};
+ nvRigidBody *ramp = nvRigidBody_new(ramp_init);
+
+ nvShape *ramp_shape = nvBoxShape_new(100.0, 0.2, nvVector2_zero);
+ nvRigidBody_add_shape(ramp, ramp_shape);
+
+ nvSpace_add_rigidbody(space, ramp);
+
+ nvRigidBodyInitializer box_init = nvRigidBodyInitializer_default;
+ box_init.type = nvRigidBodyType_DYNAMIC;
+ box_init.position = NV_VECTOR2(19.0, y - 18.0);
+ //box_init.angle = 0.35;
+ box_init.material = (nvMaterial){.density=1.0, .restitution=0.0, .friction=friction};
+ nvRigidBody *box = nvRigidBody_new(box_init);
+
+ nvShape *box_shape = nvBoxShape_new(1.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvSpace_add_rigidbody(space, box);
+}
+
+
+void Friction_setup(ExampleContext *example) {
+ // Friction constant [0.0, 2.0]
+ for (nv_float i = 0.0; i < 10.0; i += 1.0) {
+ Friction_add_ramp(example->space, i * 5.0, i * 0.2);
+ }
+}
+
+void Friction_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_hinge_constraint.h b/examples/demos/demo_hinge_constraint.h
new file mode 100644
index 0000000..3f19c72
--- /dev/null
+++ b/examples/demos/demo_hinge_constraint.h
@@ -0,0 +1,115 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void HingeConstraint_setup(ExampleContext *example) {
+
+ // Three bricks showing angular limits
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_STATIC;
+ body_init.position = NV_VECTOR2(50.0, 15.0);
+ nvRigidBody *body0 = nvRigidBody_new(body_init);
+
+ nvShape *body0_shape = nvRectShape_new(4.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(body0, body0_shape);
+
+ nvSpace_add_rigidbody(example->space, body0);
+
+
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(50.0 + 4.0, 15.0);
+ nvRigidBody *body1 = nvRigidBody_new(body_init);
+
+ nvShape *body1_shape = nvRectShape_new(4.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(body1, body1_shape);
+
+ nvSpace_add_rigidbody(example->space, body1);
+
+
+ body_init.position = NV_VECTOR2(50.0 - 4.0, 15.0);
+ nvRigidBody *body2 = nvRigidBody_new(body_init);
+
+ nvShape *body2_shape = nvRectShape_new(4.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(body2, body2_shape);
+
+ nvSpace_add_rigidbody(example->space, body2);
+
+
+ nvHingeConstraintInitializer cons_init = nvHingeConstraintInitializer_default;
+ cons_init.a = body0;
+ cons_init.b = body1;
+ cons_init.anchor = NV_VECTOR2(50.0 + 2.0, 15.0);
+ cons_init.enable_limits = true;
+ cons_init.lower_limit = -NV_PI * 0.5;
+ cons_init.upper_limit = NV_PI * 0.5;
+ nvConstraint *hinge_cons0 = nvHingeConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, hinge_cons0);
+
+ cons_init.a = body0;
+ cons_init.b = body2;
+ cons_init.anchor = NV_VECTOR2(50.0 - 2.0, 15.0);
+ cons_init.lower_limit = 0.0;
+ cons_init.upper_limit = NV_PI * 0.25;
+ nvConstraint *hinge_cons1 = nvHingeConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, hinge_cons1);
+
+ // Ignore collision of bodies connected with hinge constraint
+ hinge_cons0->ignore_collision = true;
+ hinge_cons1->ignore_collision = true;
+ }
+
+
+ // Create a bridge with restricted angle
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+
+ nvRigidBody *prev;
+ for (size_t i = 0; i < 7; i++) {
+ body_init.position = NV_VECTOR2(50.0 + (nv_float)i * 4, 30.0);
+ nvRigidBody *body = nvRigidBody_new(body_init);
+ nvShape *body_shape = nvRectShape_new(4.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(body, body_shape);
+ nvSpace_add_rigidbody(example->space, body);
+
+ // If this is the first segment, connect to world
+ // Else, connect to previous segment
+ nvRigidBody *a;
+ nvRigidBody *b;
+ if (i == 0) {
+ a = NULL;
+ b = body;
+ }
+ else {
+ a = prev;
+ b = body;
+ }
+
+ nvHingeConstraintInitializer cons_init = nvHingeConstraintInitializer_default;
+ cons_init.a = a;
+ cons_init.b = b;
+ cons_init.anchor = NV_VECTOR2(50.0 + (nv_float)i * 4 - 2.0, 30.0);
+ cons_init.enable_limits = true;
+ cons_init.lower_limit = 0.0;
+ cons_init.upper_limit = 0.0;
+ nvConstraint *hinge_cons = nvHingeConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, hinge_cons);
+
+ hinge_cons->ignore_collision = true;
+
+ prev = body;
+ }
+ }
+}
+
+void HingeConstraint_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_pyramid.h b/examples/demos/demo_pyramid.h
new file mode 100644
index 0000000..d5ef0c3
--- /dev/null
+++ b/examples/demos/demo_pyramid.h
@@ -0,0 +1,98 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+int pyramid_base = 25;
+float pyramid_air_gap = 1.0;
+float pyramid_box_size = 1.0;
+
+void Pyramid_setup(ExampleContext *example) {
+ nvRigidBody *ground;
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(128.0, 5.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+
+ nvSpace_add_rigidbody(example->space, ground);
+
+
+ nv_float size = pyramid_box_size;
+ nv_float s2 = size / 2.0;
+ nv_float y_gap = pyramid_air_gap;
+ nv_float start_y = 72.0 - 2.5 - 2.5 - s2;
+
+ for (size_t y = 0; y < pyramid_base; y++) {
+ for (size_t x = 0; x < pyramid_base - y; x++) {
+ nvRigidBody *box;
+ nvRigidBodyInitializer box_init = nvRigidBodyInitializer_default;
+ box_init.type = nvRigidBodyType_DYNAMIC;
+ box_init.position = NV_VECTOR2(
+ 64.0 - (pyramid_base * s2 - s2) + x * size + y * s2,
+ start_y - y * (size + y_gap - 0.01) // Sink a little so collisions happen in first frame
+ );
+ box_init.material = (nvMaterial){.density=1.0, .restitution=0.0, .friction=0.5};
+ box = nvRigidBody_new(box_init);
+
+ nvShape *box_shape = nvBoxShape_new(size, size, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvSpace_add_rigidbody(example->space, box);
+ }
+ }
+}
+
+void Pyramid_update(ExampleContext *example) {
+ char display_buf[8];
+ const float ratio[] = {0.25f, 0.62f, 0.13f};
+ bool changed = false;
+
+ {
+ nk_layout_row(example->ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example->ui_ctx, "Base", NK_TEXT_LEFT);
+
+ if (nk_slider_int(example->ui_ctx, 3, &pyramid_base, 100, 1))
+ changed = true;
+
+ sprintf(display_buf, "%d", pyramid_base);
+ nk_label(example->ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example->ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example->ui_ctx, "Air gap", NK_TEXT_LEFT);
+
+ if (nk_slider_float(example->ui_ctx, 0.0f, &pyramid_air_gap, 1.0f, 0.1f))
+ changed = true;
+
+ sprintf(display_buf, "%3.1f", pyramid_air_gap);
+ nk_label(example->ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example->ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example->ui_ctx, "Box size", NK_TEXT_LEFT);
+
+ if (nk_slider_float(example->ui_ctx, 0.5f, &pyramid_box_size, 2.5f, 0.1f))
+ changed = true;
+
+ sprintf(display_buf, "%3.1f", pyramid_box_size);
+ nk_label(example->ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+
+ if (changed) {
+ nvSpace_clear(example->space, true);
+ Pyramid_setup(example);
+ }
+}
\ No newline at end of file
diff --git a/examples/demos/demo_rocks.h b/examples/demos/demo_rocks.h
new file mode 100644
index 0000000..9d74ba0
--- /dev/null
+++ b/examples/demos/demo_rocks.h
@@ -0,0 +1,60 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void Rocks_setup(ExampleContext *example) {
+ nvRigidBody *ground;
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground_init.material = (nvMaterial){.density=1.0, .restitution=0.1, .friction=0.5};
+ ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(102.0, 5.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+
+ nvSpace_add_rigidbody(example->space, ground);
+
+
+ size_t num_points = 20;
+ #ifdef NV_COMPILER_MSVC
+ nvVector2 *points = NV_MALLOC(sizeof(nvVector2) * num_points);
+ #else
+ nvVector2 points[num_points];
+ #endif
+
+
+ for (size_t i = 0; i < 50; i++) {
+ // Fill convex hull points randomly
+ for (size_t j = 0; j < num_points; j++) {
+ points[j] = NV_VECTOR2(frand(-2.0, 2.0), frand(-2.0, 2.0));
+ }
+
+ nvRigidBody *rock;
+ nvRigidBodyInitializer rock_init = nvRigidBodyInitializer_default;
+ rock_init.type = nvRigidBodyType_DYNAMIC;
+ rock_init.position = NV_VECTOR2(frand(64.0 - 25.0, 64.0 + 25.0), frand(10.0, 50.0));
+ rock_init.material = (nvMaterial){.density=1.0, .restitution=0.05, .friction=0.7};
+ rock = nvRigidBody_new(rock_init);
+
+ nvShape *shape = nvConvexHullShape_new(points, num_points, nvVector2_zero, true);
+ nvRigidBody_add_shape(rock, shape);
+
+ nvSpace_add_rigidbody(example->space, rock);
+ }
+
+
+ #ifdef NV_COMPILER_MSVC
+ NV_FREE(points);
+ #endif
+}
+
+void Rocks_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_softbody.h b/examples/demos/demo_softbody.h
new file mode 100644
index 0000000..337f8b9
--- /dev/null
+++ b/examples/demos/demo_softbody.h
@@ -0,0 +1,53 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+nvRigidBody *softbody_frame;
+
+void SoftBody_setup(ExampleContext *example) {
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.type = nvRigidBodyType_DYNAMIC;
+ ground_init.position = NV_VECTOR2(64.0, 72.0);
+ nvRigidBody *ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(51.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+ nvShape *wall0_shape = nvBoxShape_new(1.0, 51.0, NV_VECTOR2(-25.0, -25.0));
+ nvRigidBody_add_shape(ground, wall0_shape);
+ nvShape *wall1_shape = nvBoxShape_new(1.0, 51.0, NV_VECTOR2(25.0, -25.0));
+ nvRigidBody_add_shape(ground, wall1_shape);
+ nvShape *ceiling_shape = nvBoxShape_new(51.0, 1.0, NV_VECTOR2(0.0, -50.0));
+ nvRigidBody_add_shape(ground, ceiling_shape);
+
+ nvSpace_add_rigidbody(example->space, ground);
+
+ softbody_frame = ground;
+
+
+ nvHingeConstraintInitializer cons_init = nvHingeConstraintInitializer_default;
+ cons_init.a = NULL;
+ cons_init.b = ground;
+ cons_init.anchor = NV_VECTOR2(64.0, 72.0 - 25.0);
+ nvConstraint *hinge_cons0 = nvHingeConstraint_new(cons_init);
+ nvSpace_add_constraint(example->space, hinge_cons0);
+
+
+ nv_float size = 5.5;
+ for (size_t y = 0; y < 7; y++) {
+ for (size_t x = 0; x < 6; x++) {
+ nvVector2 pos = NV_VECTOR2(64.0 - (size * (5.0*0.5)) + x * size + (y % 2) * size/2.0, 67.0 - y * size);
+ create_circle_softbody(example, pos, 12, 2.5, 0.6);
+ }
+ }
+}
+
+void SoftBody_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_spline_constraint.h b/examples/demos/demo_spline_constraint.h
new file mode 100644
index 0000000..acb69fe
--- /dev/null
+++ b/examples/demos/demo_spline_constraint.h
@@ -0,0 +1,47 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+void SplineConstraint_setup(ExampleContext *example) {
+ {
+ nvRigidBodyInitializer body_init = nvRigidBodyInitializer_default;
+ body_init.type = nvRigidBodyType_DYNAMIC;
+ body_init.position = NV_VECTOR2(30.0, 15.0);
+ nvRigidBody *body = nvRigidBody_new(body_init);
+
+ nvShape *body_shape = nvBoxShape_new(2.0, 2.0, nvVector2_zero);
+ nvRigidBody_add_shape(body, body_shape);
+
+ nvSpace_add_rigidbody(example->space, body);
+
+ nvSplineConstraintInitializer cons_init = nvSplineConstraintInitializer_default;
+ cons_init.body = body;
+ cons_init.anchor = NV_VECTOR2(30.0, 15.0);
+ nvConstraint *spline_cons = nvSplineConstraint_new(cons_init);
+
+ nvVector2 points[8] = {
+ NV_VECTOR2(20.0, 10.0),
+ NV_VECTOR2(25.0, 20.0),
+ NV_VECTOR2(30.0, 15.0),
+ NV_VECTOR2(35.0, 20.0),
+ NV_VECTOR2(40.0, 10.0),
+ NV_VECTOR2(45.0, 15.0),
+ NV_VECTOR2(50.0, 10.0),
+ NV_VECTOR2(55.0, 20.0)
+ };
+ nvSplineConstraint_set_control_points(spline_cons, points, 8);
+
+ nvSpace_add_constraint(example->space, spline_cons);
+ }
+}
+
+void SplineConstraint_update(ExampleContext *example) {}
\ No newline at end of file
diff --git a/examples/demos/demo_stack.h b/examples/demos/demo_stack.h
new file mode 100644
index 0000000..ec407a6
--- /dev/null
+++ b/examples/demos/demo_stack.h
@@ -0,0 +1,99 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "../common.h"
+
+
+int stack_rows = 10;
+int stack_cols = 3;
+float stack_box_size = 1.5;
+
+void Stack_setup(ExampleContext *example) {
+ nvRigidBody *ground;
+ nvRigidBodyInitializer ground_init = nvRigidBodyInitializer_default;
+ ground_init.position = NV_VECTOR2(64.0, 72.0 - 2.5);
+ ground = nvRigidBody_new(ground_init);
+
+ nvShape *ground_shape = nvBoxShape_new(128.0, 5.0, nvVector2_zero);
+ nvRigidBody_add_shape(ground, ground_shape);
+
+ nvSpace_add_rigidbody(example->space, ground);
+
+
+ nv_float start_y = 72.0 - 2.5 - 2.5 - stack_box_size / 2.0;
+
+ for (size_t y = 0; y < stack_rows; y++) {
+ // Random horizontal offset for each row
+ float offset = frand(-0.1f, 0.1f);
+
+ for (size_t x = 0; x < stack_cols; x++) {
+
+ nvRigidBody *box;
+ nvRigidBodyInitializer box_init = nvRigidBodyInitializer_default;
+ box_init.type = nvRigidBodyType_DYNAMIC;
+ box_init.position = NV_VECTOR2(
+ 64.0 - stack_box_size * ((nv_float)stack_cols * 0.5) + x * stack_box_size + offset,
+ start_y - y * (stack_box_size - 0.01) // Sink a little so collisions happen in first frame
+ );
+ box_init.material = (nvMaterial){.density=1.0, .restitution=0.1, .friction=0.6};
+ box = nvRigidBody_new(box_init);
+
+ nvShape *box_shape = nvBoxShape_new(stack_box_size, stack_box_size, nvVector2_zero);
+ nvRigidBody_add_shape(box, box_shape);
+
+ nvSpace_add_rigidbody(example->space, box);
+ }
+ }
+}
+
+void Stack_update(ExampleContext *example) {
+ char display_buf[8];
+ const float ratio[] = {0.25f, 0.62f, 0.13f};
+ bool changed = false;
+
+ {
+ nk_layout_row(example->ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example->ui_ctx, "Rows", NK_TEXT_LEFT);
+
+ if (nk_slider_int(example->ui_ctx, 1, &stack_rows, 100, 1))
+ changed = true;
+
+ sprintf(display_buf, "%d", stack_rows);
+ nk_label(example->ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example->ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example->ui_ctx, "Columns", NK_TEXT_LEFT);
+
+ if (nk_slider_int(example->ui_ctx, 1, &stack_cols, 30, 1))
+ changed = true;
+
+ sprintf(display_buf, "%d", stack_cols);
+ nk_label(example->ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example->ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example->ui_ctx, "Box size", NK_TEXT_LEFT);
+
+ if (nk_slider_float(example->ui_ctx, 0.5f, &stack_box_size, 2.5f, 0.1f))
+ changed = true;
+
+ sprintf(display_buf, "%3.1f", stack_box_size);
+ nk_label(example->ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+
+ if (changed) {
+ nvSpace_clear(example->space, true);
+ Stack_setup(example);
+ }
+}
\ No newline at end of file
diff --git a/examples/domino.h b/examples/domino.h
deleted file mode 100644
index 05b769f..0000000
--- a/examples/domino.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void DominoExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create platforms
- nvBody *platform0 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(80.0, 2.0),
- NV_VEC2(64.0, 18.0 + 5.0),
- 0.0,
- nvMaterial_BASIC
- );
-
- nvSpace_add(space, platform0);
-
- nvBody *platform1 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(80.0, 2.0),
- NV_VEC2(64.0, 36.0 + 5.0),
- 0.0,
- nvMaterial_BASIC
- );
-
- nvSpace_add(space, platform1);
-
- nvBody *platform2 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(80.0, 2.0),
- NV_VEC2(64.0, 54.0 + 5.0),
- 0.0,
- nvMaterial_BASIC
- );
-
- nvSpace_add(space, platform2);
-
- // Create dominos
- for (int y = 0; y < 3; y++) {
- for (int x = 0; x < 18; x++) {
- nvBody *domino = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(1.0, 7.0),
- NV_VEC2(64.0 - 40.0 + 0.5 + x * 4.65, 18.0 * (y + 1) - 1.0 - 3.5 + 5.0),
- 0.0,
- nvMaterial_BASIC
- );
-
- nvSpace_add(space, domino);
-
- // Push the first domino block
- if (x == 0 && y == 0) {
- nvBody_apply_force_at(domino, NV_VEC2(900.0, 0.0), NV_VEC2(0.0, -3.0));
- }
- }
- }
-
- // Link end dominos
-
- nvConstraint *hinge_joint_0 = nvHingeJoint_new(
- NULL, (nvBody *)space->bodies->data[(18 * 1 - 1) + 4],
- NV_VEC2(64.0 + 40.0 - 0.5, 18.0 + 6.5)
- );
-
- nvSpace_add_constraint(space, hinge_joint_0);
-
- nvConstraint *hinge_joint_1 = nvHingeJoint_new(
- NULL, (nvBody *)space->bodies->data[18 + 4],
- NV_VEC2(64.0 - 40.0 + 0.5, 36.0 + 6.5)
- );
-
- nvSpace_add_constraint(space, hinge_joint_1);
-}
\ No newline at end of file
diff --git a/examples/example.c b/examples/example.c
deleted file mode 100644
index 8e3718e..0000000
--- a/examples/example.c
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include
-#include "example.h"
-
-#include "arch.h"
-#include "bridge.h"
-#include "chains.h"
-#include "circle_stack.h"
-#include "cloth.h"
-#include "constraints.h"
-#include "domino.h"
-#include "fountain.h"
-#include "hull.h"
-#include "newtons_cradle.h"
-#include "orbit.h"
-#include "pool.h"
-#include "pyramid.h"
-#include "spring_car.h"
-#include "stack.h"
-#include "varying_bounce.h"
-#include "varying_friction.h"
-
-
-/**
- * @file example.h
- *
- * @brief Entry point for example demos.
- */
-
-
-ExampleEntry example_entries[100] = {NULL};
-size_t example_count = 0;
-size_t current_example = 0;
-
-void Example_register(
- char *name,
- Example_callback setup_callback,
- Example_callback update_callback,
- void (* register_callback)(ExampleEntry *)
-) {
- example_entries[example_count] = (ExampleEntry){
- .name=name,
- .slider_settings=nvArray_new(), //TODO: free
- .setup_callback=setup_callback,
- .update_callback=update_callback
- };
- if (register_callback) register_callback(&example_entries[example_count]);
- example_count++;
-}
-
-void Example_set_current(char *name) {
- for (size_t i = 0; i < example_count; i++) {
- if (!strcmp(name, example_entries[i].name)) {
- current_example = i;
- return;
- }
- }
-}
-
-
-int main(int argc, char *argv[]) {
- Example_register("Arch", ArchExample_setup, NULL, NULL);
- Example_register("Bridge", BridgeExample_setup, NULL, NULL);
- Example_register("Chains", ChainsExample_setup, NULL, NULL);
- Example_register("Circle Stack", CircleStackExample_setup, NULL, NULL);
- Example_register("Cloth", ClothExample_setup, NULL, ClothExample_init);
- Example_register("Constraints", ConstraintsExample_setup, NULL, NULL);
- Example_register("Domino", DominoExample_setup, NULL, NULL);
- Example_register("Fountain", FountainExample_setup, FountainExample_update, FountainExample_init);
- Example_register("Hull", HullExample_setup, NULL, NULL);
- Example_register("Newton's Cradle", NewtonsCradleExample_setup, NULL, NULL);
- Example_register("Orbit", OrbitExample_setup, NULL, NULL);
- Example_register("Pool", PoolExample_setup, NULL, NULL);
- Example_register("Pyramid", PyramidExample_setup, NULL, PyramidExample_init);
- Example_register("Spring Car", SpringCarExample_setup, SpringCarExample_update, NULL);
- Example_register("Stack", StackExample_setup, NULL, NULL);
- Example_register("Varying Bounce", VaryingBounceExample_setup, NULL, NULL);
- Example_register("Varying Friction", VaryingFrictionExample_setup, NULL, NULL);
-
- Example *example = Example_new(
- 1280, 720,
- "Nova Physics Example Demos",
- 165.0,
- 1.0/60.0, // 60Hz = 1/60 dt
- ExampleTheme_DARK
- );
-
- Example_set_current("Pyramid");
-
- Example_run(example);
-
- Example_free(example);
-
- return 0;
-}
\ No newline at end of file
diff --git a/examples/example.h b/examples/example.h
deleted file mode 100644
index 7484e56..0000000
--- a/examples/example.h
+++ /dev/null
@@ -1,3921 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_EXAMPLE_H
-#define NOVAPHYSICS_EXAMPLE_H
-
-#include
-#include
-#include
-#include
-#include // Required on OSX for some reason
-#include
-#include
-#include "novaphysics/novaphysics.h"
-
-#ifdef NV_WINDOWS
-
- #include // To gather memory usage information
-
-#endif
-
-
-/**
- * @file example.h
- *
- * @brief This header defines everything needed to setup & run a basic
- * SDL2 application for Nova Physics example demos.
- *
- * Utility functions:
- * ------------------
- * MAX
- * irand
- * frand
- * brand
- * hsv_to_rgb
- * fhsv_to_rgb
- * get_current_memory_usage
- *
- * Drawing functions:
- * ------------------
- * draw_circle
- * fill_circle
- * draw_polygon
- * draw_aaline
- * draw_aapolygon
- * draw_aacircle
- * draw_text
- * draw_text_from_right
- * draw_text_middle
- * draw_spring
- * draw_dashed_line
- *
- * Example, UI and helper structs:
- * -------------------------
- * Mouse
- * ToggleSwitch
- * Slider
- * ExampleTheme
- * Example
- *
- * Main loop functions:
- * --------------------
- * draw_ui
- * draw_constraints
- * draw_bodies
- * draw_cloth
- * draw_SHG
- * draw_BVH
- * UI elements update & draw
- */
-
-
-struct _Example;
-
-
-/******************************************************************************
-
- Utility functions
-
-******************************************************************************/
-
-
-#define MAX(x, y) (((x) > (y)) ? (x) : (y))
-
-/**
- * @brief Return random integer in given range.
- *
- * @param lower Min range
- * @param higher Max range
- * @return int
- */
-int irand(int lower, int higher) {
- return (rand() % (higher - lower + 1)) + lower;
-}
-
-/**
- * @brief Return random nv_float in given range.
- *
- * @param lower Min range
- * @param higher Max range
- * @return nv_float
- */
-nv_float frand(nv_float lower, nv_float higher) {
- nv_float normal = rand() / (nv_float)RAND_MAX;
- return lower + normal * (higher - lower);
-}
-
-/**
- * @brief Return random boolean.
- *
- * @return bool
- */
-bool brand() {
- return irand(0, 1);
-}
-
-/**
- * @brief Convert color from HSV space to RGB space.
- *
- * @param hsv HSV color
- * @return SDL_Color
- */
-SDL_Color hsv_to_rgb(SDL_Color hsv) {
- SDL_Color rgb;
- int8_t region, remainder, p, q, t;
-
- if (hsv.g == 0) {
- rgb.r = hsv.b;
- rgb.g = hsv.b;
- rgb.b = hsv.b;
- return rgb;
- }
-
- region = hsv.r / 43;
- remainder = (hsv.r - (region * 43)) * 6;
-
- p = (hsv.b * (255 - hsv.g)) >> 8;
- q = (hsv.b * (255 - ((hsv.g * remainder) >> 8))) >> 8;
- t = (hsv.b * (255 - ((hsv.g * (255 - remainder)) >> 8))) >> 8;
-
- switch (region) {
- case 0:
- rgb.r = hsv.b; rgb.g = t; rgb.b = p;
- break;
-
- case 1:
- rgb.r = q; rgb.g = hsv.b; rgb.b = p;
- break;
-
- case 2:
- rgb.r = p; rgb.g = hsv.b; rgb.b = t;
- break;
-
- case 3:
- rgb.r = p; rgb.g = q; rgb.b = hsv.b;
- break;
-
- case 4:
- rgb.r = t; rgb.g = p; rgb.b = hsv.b;
- break;
-
- default:
- rgb.r = hsv.b; rgb.g = p; rgb.b = q;
- break;
- }
-
- return rgb;
-}
-
-/**
- * @brief Convert color from HSV (float) space to RGB space.
- *
- * @param hsv HSV color
- * @return SDL_Color
- */
-SDL_Color fhsv_to_rgb(double h, double s, double v) {
- // Copied from https://stackoverflow.com/a/6930407
-
- double hh, p, q, t, ff;
- long i;
- SDL_Color out;
-
- if (s <= 0.0) { // < is bogus, just shuts up warnings
- out.r = v * 255;
- out.g = v * 255;
- out.b = v * 255;
- return out;
- }
-
- hh = h;
- if(hh >= 360.0) hh = 0.0;
- hh /= 60.0;
- i = (long)hh;
- ff = hh - i;
- p = v * (1.0 - s);
- q = v * (1.0 - (s * ff));
- t = v * (1.0 - (s * (1.0 - ff)));
-
- switch(i) {
- case 0:
- out.r = v * 255;
- out.g = t * 255;
- out.b = p * 255;
- break;
-
- case 1:
- out.r = q * 255;
- out.g = v * 255;
- out.b = p * 255;
- break;
-
- case 2:
- out.r = p * 255;
- out.g = v * 255;
- out.b = t * 255;
- break;
-
-
- case 3:
- out.r = p * 255;
- out.g = q * 255;
- out.b = v * 255;
- break;
-
- case 4:
- out.r = t * 255;
- out.g = p * 255;
- out.b = v * 255;
- break;
-
- case 5:
- default:
- out.r = v * 255;
- out.g = p * 255;
- out.b = q * 255;
- break;
- }
-
- return out;
-}
-
-/**
- * @brief Linear interpolate between two colors.
- *
- * @param color0 First color
- * @param color1 Second color
- * @param t Interpolation ratio
- * @return SDL_Color
- */
-SDL_Color color_lerp(SDL_Color color0, SDL_Color color1, float t) {
- SDL_Color result;
-
- result.r = (nv_uint8)(color0.r + t * (color1.r - color0.r));
- result.g = (nv_uint8)(color0.g + t * (color1.g - color0.g));
- result.b = (nv_uint8)(color0.b + t * (color1.b - color0.b));
-
- return result;
-}
-
-/**
- * @brief Get current memory usage of this process in bytes.
- *
- * Returns 0 if it fails to gather information.
- *
- * @return size_t
- */
-size_t get_current_memory_usage() {
- #ifdef NV_WINDOWS
-
- // https://learn.microsoft.com/en-us/windows/win32/psapi/collecting-memory-usage-information-for-a-process
-
- HANDLE current_process = GetCurrentProcess();
- PROCESS_MEMORY_COUNTERS_EX pmc;
-
- if (GetProcessMemoryInfo(current_process, (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc))) {
- return pmc.WorkingSetSize;
- }
- else {
- return 0;
- }
-
- #else
-
- FILE *status = fopen("/proc/self/status", "r");
-
- if (status) {
- char line[128];
- while (fgets(line, 128, status) != NULL) {
- if (strncmp(line, "VmSize:", 7) == 0) {
- char *val = line + 7;
- fclose(status);
- return strtoul(val, NULL, 10) * 1024;
- }
- }
- }
-
- fclose(status);
- return 0;
-
- #endif
-}
-
-
-#define FNV_PRIME 1099511628211ULL
-#define FNV_BASIS 14695981039346656037ULL
-
-nv_uint64 FNV1a(const char *str) {
- nv_uint64 hash = FNV_BASIS;
-
- for (size_t i = 0; str[i] != '\0'; i++) {
- hash ^= (nv_uint64)str[i];
- hash *= FNV_PRIME;
- }
-
- return hash;
-}
-
-uint32_t FNV1a_u32(uint32_t value) {
- const uint32_t FNV_prime = 16777619;
- uint32_t hash = 2166136261;
-
- for (int i = 0; i < sizeof(uint32_t); ++i) {
- hash ^= (value & 0xFF);
- hash *= FNV_prime;
- value >>= 8;
- }
-
- return hash;
-}
-
-typedef struct {
- char *string;
- SDL_Texture *texture;
- nv_uint64 last_access;
-} CachedText;
-
-nv_uint64 cached_text_hash(void *item) {
- CachedText *c = (CachedText *)item;
- return FNV1a(c->string);
-}
-
-
-/******************************************************************************
-
- Drawing functions
-
-******************************************************************************/
-
-
-
-/**
- * @brief Draw circle.
- *
- * Reference: https://discourse.libsdl.org/t/query-how-do-you-draw-a-circle-in-sdl2-sdl2/33379
- *
- * @param renderer SDL Renderer
- * @param cx Circle center X
- * @param cy Circle center Y
- * @param radius Circle radius
- */
-void draw_circle(
- SDL_Renderer *renderer,
- int cx,
- int cy,
- int radius
-) {
- int diameter = (radius * 2);
-
- int x = (radius - 1);
- int y = 0;
- int tx = 1;
- int ty = 1;
- int error = (tx - diameter);
-
- while (x >= y) {
- // Each of the following renders an octant of the circle
- SDL_RenderDrawPoint(renderer, cx + x, cy - y);
- SDL_RenderDrawPoint(renderer, cx + x, cy + y);
- SDL_RenderDrawPoint(renderer, cx - x, cy - y);
- SDL_RenderDrawPoint(renderer, cx - x, cy + y);
- SDL_RenderDrawPoint(renderer, cx + y, cy - x);
- SDL_RenderDrawPoint(renderer, cx + y, cy + x);
- SDL_RenderDrawPoint(renderer, cx - y, cy - x);
- SDL_RenderDrawPoint(renderer, cx - y, cy + x);
-
- if (error <= 0) {
- ++y;
- error += ty;
- ty += 2;
- }
-
- if (error > 0) {
- --x;
- tx += 2;
- error += (tx - diameter);
- }
- }
-}
-
-/**
- * @brief Fill circle.
- *
- * @param renderer SDL Renderer
- * @param x Circle center X
- * @param y Circle center Y
- * @param radius Circle radius
- * @param color
- */
-void fill_circle(SDL_Renderer *renderer, int x, int y, int radius) {
- for (int w = 0; w < radius * 2; w++) {
- for (int h = 0; h < radius * 2; h++) {
- int dx = radius - w;
- int dy = radius - h;
- if ((dx * dx + dy * dy) <= (radius * radius))
- {
- SDL_RenderDrawPoint(renderer, x + dx, y + dy);
- }
- }
- }
-}
-
-/**
- * @brief Draw polygon.
- *
- * @param renderer SDL Renderer
- * @param vertices Vertices
- */
-void draw_polygon(SDL_Renderer *renderer, nvArray *vertices) {
- size_t n = vertices->size;
-
- for (size_t i = 0; i < n; i++) {
- nvVector2 va = NV_TO_VEC2(vertices->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices->data[(i + 1) % n]);
-
- SDL_RenderDrawLineF(
- renderer,
- va.x, va.y,
- vb.x, vb.y
- );
- }
-}
-
-/**
- * Utility functions for anti-aliased functions
- */
-
-static inline void _aa_swap(nv_float *a, nv_float *b) {
- nv_float temp = *a;
- *a = *b;
- *b = temp;
-}
-
-static inline int _aa_ipart(nv_float x) {
- return (int)x;
-}
-
-static inline int _aa_fround(nv_float x) {
- return _aa_ipart(x + 0.5);
-}
-
-static inline nv_float _aa_fpart(nv_float x) {
- return x - _aa_ipart(x);
-}
-
-static inline nv_float _aa_rfpart(nv_float x) {
- return 1.0 - _aa_fpart(x);
-}
-
-static inline void _aa_pixel(
- SDL_Renderer *renderer,
- nv_float x,
- nv_float y,
- nv_float a,
- int r,
- int g,
- int b
-) {
- SDL_SetRenderDrawColor(renderer, r, g, b, (nv_uint8)(a * 255));
- SDL_RenderDrawPointF(renderer, x, y);
-}
-
-static inline void _aa_pixel4(
- SDL_Renderer *renderer,
- nv_float x,
- nv_float y,
- nv_float dx,
- nv_float dy,
- nv_float alpha,
- nv_uint8 r,
- nv_uint8 g,
- nv_uint8 b
-) {
- SDL_SetRenderDrawColor(renderer, r, g, b, (nv_uint8)alpha);
- SDL_RenderDrawPointF(renderer, x + dx, y + dy);
- SDL_RenderDrawPointF(renderer, x - dx, y + dy);
- SDL_RenderDrawPointF(renderer, x + dx, y - dy);
- SDL_RenderDrawPointF(renderer, x - dx, y - dy);
-}
-
-/**
- * @brief Draw anti-aliased line.
- *
- * Reference: https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm
- *
- * @param renderer SDL Renderer
- * @param x0 Starting point X
- * @param y0 Starting point Y
- * @param x1 End point X
- * @param y1 End point Y
- */
-void draw_aaline(
- SDL_Renderer *renderer,
- nv_float x0,
- nv_float y0,
- nv_float x1,
- nv_float y1
-) {
- bool steep = nv_fabs(y1 - y0) > nv_fabs(x1 - x0);
-
- nv_uint8 r, g, b, a;
- SDL_GetRenderDrawColor(renderer, &r, &g, &b, &a);
-
- if (steep) {
- _aa_swap(&x0, &y0);
- _aa_swap(&x1, &y1);
- }
- if (x0 > x1) {
- _aa_swap(&x0, &x1);
- _aa_swap(&y0, &y1);
- }
-
- nv_float dx = x1 - x0;
- nv_float dy = y1 - y0;
-
- nv_float gradient;
- if (dx == 0.0) gradient = 1.0;
- else gradient = dy / dx;
-
- // Handle first endpoint
- int xend = _aa_fround(x0);
- nv_float yend = y0 + gradient * (xend - x0);
- nv_float xgap = _aa_rfpart(x0 + 0.5);
- int xpxl1 = xend; // For main loop
- int ypxl1 = _aa_ipart(yend);
-
- if (steep) {
- _aa_pixel(renderer, ypxl1, xpxl1, _aa_rfpart(yend) * xgap, r, g, b);
- _aa_pixel(renderer, ypxl1 + 1, xpxl1, _aa_fpart(yend) * xgap, r, g, b);
- }
- else {
- _aa_pixel(renderer, xpxl1, ypxl1, _aa_rfpart(yend) * xgap, r, g, b);
- _aa_pixel(renderer, xpxl1, ypxl1 + 1, _aa_fpart(yend) * xgap, r, g, b);
- }
-
- nv_float intery = yend + gradient; // First Y intersection
-
- // Handle second endpoint
- xend = _aa_fround(x1);
- yend = y1 + gradient * (xend - x1);
- xgap = _aa_fpart(x1 + 0.5);
- int xpxl2 = xend; // For main loop
- int ypxl2 = _aa_ipart(yend);
-
- if (steep) {
- _aa_pixel(renderer, ypxl2, xpxl2, _aa_rfpart(yend) * xgap, r, g, b);
- _aa_pixel(renderer, ypxl2 + 1, xpxl2, _aa_fpart(yend) * xgap, r, g, b);
- }
- else {
- _aa_pixel(renderer, xpxl2, ypxl2, _aa_rfpart(yend) * xgap, r, g, b);
- _aa_pixel(renderer, xpxl2, ypxl2 + 1, _aa_fpart(yend) * xgap, r, g, b);
- }
-
- // Main loop
- if (steep) {
- for (int x = xpxl1 + 1; x <= xpxl2 - 1; x++) {
- _aa_pixel(renderer, _aa_ipart(intery), x, _aa_rfpart(intery), r, g, b);
- _aa_pixel(renderer, _aa_ipart(intery) + 1, x, _aa_fpart(intery), r, g, b);
- intery += gradient;
- }
- }
- else {
- for (int x = xpxl1 + 1; x <= xpxl2 - 1; x++) {
- _aa_pixel(renderer, x, _aa_ipart(intery), _aa_rfpart(intery), r, g, b);
- _aa_pixel(renderer, x, _aa_ipart(intery) + 1, _aa_fpart(intery), r, g, b);
- intery += gradient;
- }
- }
-}
-
-/**
- * @brief Draw anti-aliased polygon.
- *
- * @param renderer SDL Renderer
- * @param vertices Vertices
- */
-void draw_aapolygon(SDL_Renderer *renderer, nvArray *vertices) {
- size_t n = vertices->size;
-
- for (size_t i = 0; i < n; i++) {
- nvVector2 va = NV_TO_VEC2(vertices->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices->data[(i + 1) % n]);
-
- draw_aaline(
- renderer,
- va.x, va.y,
- vb.x, vb.y
- );
- }
-}
-
-/**
- * @brief Draw anti-aliased circle
- *
- * Reference: https://create.stephan-brumme.com/antialiased-circle/#antialiased-circle-wu
- *
- * @param renderer SDL Renderer
- * @param cx Circle center X
- * @param cy Circle center Y
- * @param radius Circle radius
- * @param r Color R
- * @param g Color G
- * @param b Color B
- */
-void draw_aacircle(
- SDL_Renderer *renderer,
- nv_float cx,
- nv_float cy,
- nv_float radius,
- nv_uint8 r,
- nv_uint8 g,
- nv_uint8 b
-) {
- // + 0.3 is for arbitrary correction
- nv_float rx = radius + 0.3;
- nv_float ry = radius + 0.3;
- nv_float rx2 = rx * rx;
- nv_float ry2 = ry * ry;
-
- nv_float max_alpha = 255.0;
-
- nv_float q = _aa_fround(rx2 / nv_sqrt(rx2 + ry2));
- for (nv_float x = 0; x <= q; x++) {
- nv_float y = ry * nv_sqrt(1 - x * x / rx2);
- nv_float error = y - floor(y);
-
- nv_float alpha = _aa_fround(error * max_alpha);
-
- _aa_pixel4(renderer, cx, cy, x, floor(y), alpha, r, g, b);
- _aa_pixel4(renderer, cx, cy, x, floor(y) - 1, max_alpha - alpha, r, g, b);
- }
-
- q = _aa_fround(ry2 / nv_sqrt(rx2 + ry2));
- for (nv_float y = 0; y <= q; y++) {
- nv_float x = rx * nv_sqrt(1 - y * y / ry2);
- nv_float error = x - floor(x);
-
- nv_float alpha = _aa_fround(error * max_alpha);
-
- _aa_pixel4(renderer, cx, cy, floor(x), y, alpha, r, g, b);
- _aa_pixel4(renderer, cx, cy, floor(x) - 1, y, max_alpha - alpha, r, g, b);
- }
-}
-
-void draw_dashed_line(
- SDL_Renderer *renderer,
- int x0,
- int y0,
- int x1,
- int y1,
- int dash_length,
- int gap_length
-) {
- nvVector2 start = {x0, y0};
- nvVector2 end = {x1, y1};
- nvVector2 delta = nvVector2_sub(end, start);
- double dist = nvVector2_len(delta);
- nvVector2 dir = nvVector2_normalize(delta);
-
- double step = 0.0;
- while (step < dist) {
- nvVector2 step_start = nvVector2_add(start, nvVector2_mul(dir, step));
- nvVector2 step_end = nvVector2_add(start, nvVector2_mul(dir, step + dash_length));
- SDL_RenderDrawLine(renderer, step_start.x, step_start.y, step_end.x, step_end.y);
- step += dash_length + gap_length;
- }
-}
-
-
-
-/******************************************************************************
-
- Example & helper structs
-
-******************************************************************************/
-
-
-
-/**
- * @brief Mouse information struct.
- */
-typedef struct {
- int x; /**< X coordinate of mouse. */
- int y; /**< Y coordinate of mouse. */
-
- nv_float px; /**< X coordinate of mouse in physics space. */
- nv_float py; /**< Y coordinate of mouse in physics space. */
-
- nvVector2 before_zoom;
- nvVector2 after_zoom;
-
- bool left; /**< Is left button pressed? */
- bool middle; /**< Is wheel pressed? */
- bool right; /**< Is right button pressed? */
-} Mouse;
-
-
-/**
- * @brief Toggle switch UI element.
- */
-typedef struct {
- int x; /**< X coordinate. */
- int y; /**< Y coordinate. */
- int size; /**< Size of the toggle switch in height. */
- bool on; /**< Whether the switch is toggled or not. */
- bool changed; /**< Internal flag to track state change. */
-} ToggleSwitch;
-
-
-typedef enum {
- SliderType_INTEGER,
- SliderType_FLOAT
-} SliderType;
-
-/**
- * @brief Slider UI element.
- */
-typedef struct {
- int x;
- int cx;
- int y;
- int width;
- nv_float value;
- nv_float max;
- nv_float min;
- bool pressed;
- SliderType type;
-} Slider;
-
-
-typedef struct {
- int x;
- int y;
- int width;
- int height;
- char *text;
- bool hovered;
- bool pressed;
- void ( *callback)(void *);
-} Button;
-
-
-/**
- * @brief Example visual theme enum.
- */
-typedef enum {
- ExampleTheme_LIGHT, /**< Light theme. */
- ExampleTheme_DARK /**< Dark theme. */
-} ExampleTheme;
-
-
-// Example callback type
-typedef void ( *Example_callback)(struct _Example *example);
-
-
-// ToggleSwitch_update forward declaration
-void ToggleSwitch_update(struct _Example *example, ToggleSwitch *tg);
-
-// ToggleSwitch_draw forward declaration
-void ToggleSwitch_draw(struct _Example *example, ToggleSwitch *tg);
-
-
-// Slider_update forward declaration
-void Slider_update(struct _Example *example, Slider *s);
-
-// Slider_draw forward declaration
-void Slider_draw(struct _Example *example, Slider *s);
-
-
-// Button_update forward declaration
-void Button_update(struct _Example *example, Button *b);
-
-// Button_draw forward declaration
-void Button_draw(struct _Example *example, Button *b, TTF_Font *font);
-
-
-typedef struct {
- double percent;
- size_t index;
-} GraphData;
-
-
-/**
- * @brief Example base struct.
- */
-struct _Example {
- int width; /**< Window width. */
- int height; /**< Window height. */
- SDL_Window *window; /**< SDL Window instance. */
- SDL_Renderer *renderer; /**< SDL Renderer instance. */
- SDL_Texture *texture; /**< SDL Texture instance. */
-
- Mouse mouse; /**< Mouse information struct. */
- const nv_uint8 *keys; /**< Array of pressed keys. */
-
- nv_float max_fps; /**< Targe FPS. */
- nv_float fps; /**< Current FPS. */
- nv_float dt; /**< Delta-time. */
-
- nvSpace *space; /**< Nova Physics space instance. */
- nv_float hertz; /**< Simulation hertz. */
-
- bool selected;
-
- size_t switch_count; /**< Count of toggle switches. */
- ToggleSwitch **switches; /**< Array of toggle switches. */
-
- size_t slider_count; /**< Count of sliders. */
- Slider **sliders; /**< Array of sliders. */
-
- size_t button_count;
- Button **buttons;
-
- // Theme colors
- SDL_Color bg_color;
- SDL_Color text_color;
- SDL_Color alt_text_color;
- SDL_Color body_color;
- SDL_Color static_color;
- SDL_Color sleep_color;
- SDL_Color spring_color;
- SDL_Color distancejoint_color;
- SDL_Color hingejoint_color;
- SDL_Color aabb_color;
- SDL_Color ui_color;
- SDL_Color ui_color2;
- SDL_Color velocity_color;
-
- SDL_Color *profiler_palette;
-
- bool draw_ui; /**< Whether to draw the UI or not. */
-
- // Profiling stats
- nv_float step_time;
- nv_float step_counter;
- nv_float step_avg;
- nv_float render_time;
- nv_float render_counter;
- nv_float render_avg;
- nv_float total_energy;
- nv_float total_le;
- nv_float total_ae;
- int counter;
-
- int cloth_example_cols;
- int cloth_example_rows;
-
- nvHashMap *cached_texts;
-
- nvVector2 camera;
- nv_float camera_speed;
- nv_float zoom;
- nv_float zoom_scale;
- nvVector2 pan_start;
-
- GraphData *last_graph;
- size_t graph_counter;
- double max_memory_usage;
-
- double *fps_graph_data;
- double *memory_graph_data;
- size_t fps_graph_size;
- size_t memory_graph_size;
-};
-
-typedef struct _Example Example;
-
-
-typedef void ( *Example_callback)(Example *);
-
-
-typedef struct {
- char *name;
- nvArray *slider_settings;
- Example_callback init_callback;
- Example_callback setup_callback;
- Example_callback update_callback;
-} ExampleEntry;
-
-typedef struct {
- char *name;
- Slider *slider;
-} SliderSetting;
-
-void add_slider_setting(
- ExampleEntry *entry,
- char *setting,
- SliderType type,
- nv_float value,
- nv_float min,
- nv_float max
-) {
- // TODO: Free setting and slider
-
- SliderSetting *slider_setting = NV_NEW(SliderSetting);
- if (!slider_setting) NV_ERROR("Memory error at add_slider_setting");
-
- slider_setting->name = setting;
-
- Slider *slider = NV_NEW(Slider);
- if (!slider) NV_ERROR("Memory error at add_slider_setting");
-
- slider->x = 0;
- slider->y = 0;
- slider->width = 80;
- slider->value = value;
- slider->min = min;
- slider->max = max;
- slider->type = type;
- slider->cx = slider->x + ((slider->value-slider->min) / (slider->max - slider->min)) * slider->width;
- slider->pressed = false;
-
- slider_setting->slider = slider;
-
- nvArray_add(entry->slider_settings, slider_setting);
-}
-
-extern ExampleEntry example_entries[100];
-extern size_t example_count;
-size_t current_example;
-
-nv_float get_slider_setting(char *name) {
- ExampleEntry entry = example_entries[current_example];
-
- for (size_t i = 0; i < entry.slider_settings->size; i++) {
- SliderSetting *setting = entry.slider_settings->data[i];
- if (!strcmp(name, setting->name)) {
- return setting->slider->value;
- }
- }
-
- return 0.0;
-}
-
-
-// Transform position from world space to screen space
-nvVector2 world_to_screen(Example *example, nvVector2 world_pos) {
- return nvVector2_mul(nvVector2_sub(world_pos, example->camera), example->zoom);
-}
-
-// Transform position from screen space to world space
-nvVector2 screen_to_world(Example *example, nvVector2 screen_pos) {
- return nvVector2_add(nvVector2_div(screen_pos, example->zoom), example->camera);
-}
-
-
-/**
- * Contact drawer callback
- */
-static void after_callback(nvHashMap *res_arr, void *user_data) {
- Example *example = (Example *)user_data;
-
- if (!example->switches[2]->on) return;
-
- size_t iter = 0;
- void *item;
- while (nvHashMap_iter(res_arr, &iter, &item)) {
-
- nvResolution *res = item;
-
- nv_float radius = 0.1 * example->zoom;
-
- nvVector2 cp;
- SDL_Color color;
-
- if (res->contact_count == 1) {
- nvContact contact = res->contacts[0];
- cp = world_to_screen(example, contact.position);
-
- if (!nv_collide_aabb_x_point((nvAABB){0.0, 0.0, example->width, example->height}, cp)) {
- continue;
- }
-
- if (
- nvVector2_dist2(
- NV_VEC2(example->mouse.x, example->mouse.y),
- cp
- ) < 5 * 5
- ) {
- color = (SDL_Color){181, 242, 75, 255};
-
- if (example->mouse.right) {
- nv_print_Resolution(res);
-
- nvVector2 a = world_to_screen(example, res->a->position);
- nvVector2 b = world_to_screen(example, res->b->position);
-
- draw_aacircle(example->renderer, a.x, a.y, 0.3 * example->zoom, color.r, color.g, color.b);
- draw_aacircle(example->renderer, b.x, b.y, 0.3 * example->zoom, color.r, color.g, color.b);
- }
-
- } else {
- color = (SDL_Color){242, 75, 81, 255};
- }
-
- if (res->state == 2) {
- color = (SDL_Color){227, 208, 98, 255};
- }
-
- draw_aacircle(example->renderer, cp.x, cp.y, radius, color.r, color.g, color.b);
- }
-
- else if (res->contact_count == 2) {
- nvContact contact1 = res->contacts[0];
- nvContact contact2 = res->contacts[1];
-
- nvVector2 c1 = world_to_screen(example, contact1.position);
- nvVector2 c2 = world_to_screen(example, contact2.position);
-
- if (nv_collide_aabb_x_point((nvAABB){0.0, 0.0, example->width, example->height}, c1)) {
- if (
- nvVector2_dist2(
- NV_VEC2(example->mouse.x, example->mouse.y),
- c1
- ) < 10 * 10
- ) {
- if (example->mouse.right) {nv_print_Resolution(res);}
- color = (SDL_Color){181, 242, 75, 255};
-
- } else {
- color = (SDL_Color){242, 75, 81, 255};
- }
-
- if (res->state == 2) {
- color = (SDL_Color){227, 208, 98, 255};
- }
-
- draw_aacircle(example->renderer, c1.x, c1.y, radius, color.r, color.g, color.b);
- }
-
- if (nv_collide_aabb_x_point((nvAABB){0.0, 0.0, example->width, example->height}, c2)) {
- if (
- nvVector2_dist2(
- NV_VEC2(example->mouse.x, example->mouse.y),
- c2
- ) < 10 * 10
- ) {
- if (example->mouse.right) {nv_print_Resolution(res);}
- color = (SDL_Color){181, 242, 75, 255};
-
- } else {
- color = (SDL_Color){242, 75, 81, 255};
- }
-
- if (res->state == 2) {
- color = (SDL_Color){227, 208, 98, 255};
- }
-
- draw_aacircle(example->renderer, c2.x, c2.y, radius, color.r, color.g, color.b);
- }
- }
- }
-}
-
-/**
- * @brief Create new example instance.
- *
- * @param width Window width
- * @param height Window height
- * @param title Window title
- * @param max_fps Window max FPS
- * @param hertz Simulation hertz
- * @return Example
- */
-Example *Example_new(
- int width,
- int height,
- char *title,
- nv_float max_fps,
- nv_float hertz,
- ExampleTheme theme
-) {
- Example *example = NV_NEW(Example);
- if (!example) NV_ERROR("Couldn't initialize example.\n");
-
- // Initialize SDL2 and extensions
-
- if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
- printf("SDL2 could not be initialized. Error: %s\n", SDL_GetError());
- exit(1);
- }
-
- if (TTF_Init() != 0) {
- printf("SDL2_ttf could not be initialized. Error: %s\n", TTF_GetError());
- exit(1);
- }
-
- // Enable linear filtering for textures
- SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
-
- example->width = width;
- example->height = height;
-
- example->window = SDL_CreateWindow(
- title,
- SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
- width, height,
- SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE
- );
-
- SDL_SetWindowMinimumSize(example->window, 1280, 720);
-
- example->renderer = SDL_CreateRenderer(
- example->window, -1, SDL_RENDERER_ACCELERATED);
-
- example->texture = SDL_CreateTexture(
- example->renderer,
- SDL_PIXELFORMAT_ARGB8888,
- SDL_TEXTUREACCESS_STREAMING,
- width, height
- );
-
- // For anti-aliased drawing functions
- SDL_SetRenderDrawBlendMode(example->renderer, SDL_BLENDMODE_BLEND);
-
- SDL_Surface *window_icon = SDL_LoadBMP("assets/novaicon.bmp");
- SDL_SetWindowIcon(example->window, window_icon);
- SDL_FreeSurface(window_icon);
-
- example->mouse = (Mouse){0, 0, 0.0, 0.0, nvVector2_zero, nvVector2_zero, false, false, false};
- example->keys = SDL_GetKeyboardState(NULL);
-
- example->max_fps = max_fps;
- example->fps = max_fps;
- example->dt = 1.0 / max_fps;
-
- example->space = nvSpace_new();
- example->hertz = hertz;
-
- example->selected = false;
-
- example->space->callback_user_data = example;
- example->space->after_collision = after_callback;
-
- // Light theme
- if (theme == ExampleTheme_LIGHT) {
- example->bg_color = (SDL_Color){255, 255, 255, 255};
- example->text_color = (SDL_Color){0, 0, 0, 255};
- example->alt_text_color = (SDL_Color){90, 90, 96, 255};
- example->body_color = (SDL_Color){40, 40, 44, 255};
- example->static_color = (SDL_Color){123, 124, 138, 255};
- example->sleep_color = (SDL_Color){176, 132, 77, 255};
- example->spring_color = (SDL_Color){56, 255, 169, 255};
- example->distancejoint_color = (SDL_Color){74, 201, 255, 255};
- example->hingejoint_color = (SDL_Color){140, 106, 235, 255};
- example->aabb_color = (SDL_Color){252, 127, 73, 255};
- example->ui_color = (SDL_Color){97, 197, 255, 255};
- example->ui_color2 = (SDL_Color){255, 255, 255, 255};
- example->velocity_color = (SDL_Color){169, 237, 43, 255};
- }
- // Dark theme
- else if (theme == ExampleTheme_DARK) {
- example->bg_color = (SDL_Color){32, 32, 36, 255};
- example->text_color = (SDL_Color){255, 255, 255, 255};
- example->alt_text_color = (SDL_Color){153, 167, 191, 255};
- example->body_color = (SDL_Color){237, 244, 255, 255};
- example->static_color = (SDL_Color){116, 126, 143, 255};
- example->sleep_color = (SDL_Color){227, 196, 157, 255};
- example->spring_color = (SDL_Color){56, 255, 169, 255};
- example->distancejoint_color = (SDL_Color){74, 201, 255, 255};
- example->hingejoint_color = (SDL_Color){140, 106, 235, 255};
- example->aabb_color = (SDL_Color){252, 127, 73, 255};
- example->ui_color = (SDL_Color){66, 164, 245, 255};
- example->ui_color2 = (SDL_Color){0, 0, 0, 255};
- example->velocity_color = (SDL_Color){197, 255, 71, 255};
- }
-
- example->profiler_palette = malloc(sizeof(SDL_Color) * 11);
-
- example->profiler_palette[0] = (SDL_Color){0, 22, 134};
- example->profiler_palette[1] = (SDL_Color){94, 43, 255};
- example->profiler_palette[2] = (SDL_Color){200, 0, 255};
- example->profiler_palette[3] = (SDL_Color){238, 47, 123};
- example->profiler_palette[4] = (SDL_Color){195, 33, 0};
- example->profiler_palette[5] = (SDL_Color){255, 145, 0};
- example->profiler_palette[6] = (SDL_Color){255, 243, 110};
- example->profiler_palette[7] = (SDL_Color){124, 228, 39};
- example->profiler_palette[8] = (SDL_Color){11, 146, 121};
- example->profiler_palette[9] = (SDL_Color){66, 164, 245};
- example->profiler_palette[10] = (SDL_Color){255, 255, 213};
-
- // Profiling stats
- example->step_time = 0.0;
- example->render_time = 0.0;
- example->step_avg = 0.0;
- example->render_avg = 0.0;
- example->step_counter = 0.0;
- example->render_counter = 0.0;
- example->total_ae = 0.0;
- example->total_energy = 0.0;
- example->total_le = 0.0;
- example->counter = 0;
-
- example->draw_ui = true;
-
- example->cloth_example_cols = 0;
- example->cloth_example_rows = 0;
-
- example->cached_texts = nvHashMap_new(sizeof(CachedText), 0, cached_text_hash);
-
- example->camera = nvVector2_zero;//NV_VEC2(1280.0 / 20.0, 720.0 / 20.0);
- example->camera_speed = 75.0;
- example->zoom = 10.0;
- example->zoom_scale = 0.075;
- example->pan_start = nvVector2_zero;
-
- example->last_graph = malloc(sizeof(GraphData) * 11);
- example->graph_counter = 0;
-
- for (size_t j = 0; j < 11; j++) {
- example->last_graph[j] = (GraphData){0.0, 0};
- }
-
- example->max_memory_usage = 0.0;
-
- example->fps_graph_data = calloc(240, sizeof(double) * 240);
- example->memory_graph_data = calloc(240, sizeof(double) * 240);
- example->fps_graph_size = 0;
- example->memory_graph_size = 0;
-
- return example;
-}
-
-/**
- * @brief Free space allocated by example.
- *
- * @param example Example to free
- */
-void Example_free(Example *example) {
- SDL_DestroyRenderer(example->renderer);
- SDL_DestroyWindow(example->window);
- nvSpace_free(example->space);
-
- free(example->sliders);
- free(example->switches);
-
- for (size_t i = 0; i < example_count; i++) {
- ExampleEntry entry = example_entries[i];
-
- for (size_t j = 0; j < entry.slider_settings->size; j++) {
- SliderSetting *setting = entry.slider_settings->data[j];
- Slider *slider = setting->slider;
-
- free(setting);
- free(slider);
- }
-
- nvArray_free(entry.slider_settings);
- }
-
- size_t l = 0;
- void *map_val;
- while (nvHashMap_iter(example->cached_texts, &l, &map_val)) {
- CachedText *cached_text = map_val;
- SDL_DestroyTexture(cached_text->texture);
- free(cached_text->string);
- }
- nvHashMap_free(example->cached_texts);
-
- free(example->profiler_palette);
- free(example->last_graph);
-
- free(example->fps_graph_data);
- free(example->memory_graph_data);
-
- free(example);
-}
-
-
-
-/******************************************************************************
-
- Main loop functions
-
-******************************************************************************/
-
-
-/* We have to move some drawing functions here because they have Example as arg. */
-
-/**
- * @brief Draw spring.
- *
- * @param example Example
- * @param renderer SDL Renderer
- * @param cons Constraint
- * @param aa Anit-aliasing
- * @param color Color
- */
-void draw_spring(
- struct _Example *example,
- SDL_Renderer *renderer,
- nvConstraint *cons,
- bool aa,
- SDL_Color color
-) {
- nvSpring *spring = (nvSpring *)cons->def;
-
- nvVector2 ap;
- nvVector2 bp;
-
- // Transform anchor and body positions
- if (cons->a == NULL) {
- ap = world_to_screen(example, spring->anchor_a);
- } else {
- nvVector2 ra = nvVector2_rotate(spring->anchor_a, cons->a->angle);
- ap = nvVector2_add(cons->a->position, ra);
- ap = world_to_screen(example, ap);
- }
- if (cons->b == NULL) {
- bp = world_to_screen(example, spring->anchor_b);
- } else {
- nvVector2 rb = nvVector2_rotate(spring->anchor_b, cons->b->angle);
- bp = nvVector2_add(cons->b->position, rb);
- bp = world_to_screen(example, bp);
- }
-
- nvVector2 delta = nvVector2_sub(bp, ap);
- nvVector2 dir = nvVector2_normalize(delta);
- nv_float dist = nvVector2_len(delta);
- nv_float offset = (dist - spring->length * example->zoom) / (spring->length * example->zoom);
- nv_float steps = NV_PI / 3.0;
- nv_float stretch = 1.0 + offset;
-
- if (aa) {
- draw_aacircle(
- renderer,
- ap.x, ap.y,
- 0.2 * example->zoom,
- color.r, color.g, color.b
- );
-
- draw_aacircle(
- renderer,
- bp.x, bp.y,
- 0.2 * example->zoom,
- color.r, color.g, color.b
- );
- }
- else {
- draw_circle(
- renderer,
- ap.x, ap.y,
- 0.2 * example->zoom
- );
-
- draw_circle(
- renderer,
- bp.x, bp.y,
- 0.2 * example->zoom
- );
- }
-
- nvVector2 s = nvVector2_zero;
- nvVector2 e = nvVector2_zero;
-
- for (nv_float step = 0.0; step < dist; step += steps) {
- nv_float next_step = step + steps;
-
- nv_float w = ((spring->length / 1.25) - offset);
- if (w < 0.0) w = 0.0;
-
- s = nvVector2_mul(dir, step);
- s = nvVector2_add(s, nvVector2_mul(nvVector2_perp(dir), sin(step / stretch) * w));
- e = nvVector2_mul(dir, next_step);
- e = nvVector2_add(e, nvVector2_mul(nvVector2_perp(dir), sin(next_step / stretch) * w));
-
- if (aa)
- draw_aaline(renderer, ap.x + s.x, ap.y + s.y, ap.x + e.x, ap.y + e.y);
- else
- SDL_RenderDrawLine(renderer, ap.x + s.x, ap.y + s.y, ap.x + e.x, ap.y + e.y);
- }
-}
-
-/**
- * @brief Draw text.
- *
- * @param font TTF Font
- * @param renderer SDL Renderer
- * @param text Text
- * @param x X
- * @param y Y
- * @param color SDL Color
- */
-void draw_text(
- struct _Example *example,
- TTF_Font *font,
- SDL_Renderer *renderer,
- char *text,
- int x,
- int y,
- SDL_Color color
-) {
- CachedText *cached_text = nvHashMap_get(example->cached_texts, &(CachedText){.string=text});
- SDL_Texture *text_tex;
-
- if (cached_text) {
- text_tex = cached_text->texture;
- nvHashMap_set(example->cached_texts, &(CachedText){.string=cached_text->string, .texture=text_tex, .last_access=time(NULL)});
- }
-
- else {
- SDL_Surface *text_surf = TTF_RenderText_Blended(font, text, color);
- text_tex = SDL_CreateTextureFromSurface(renderer, text_surf);
- SDL_FreeSurface(text_surf);
-
- char *text_h = strdup(text);
- nvHashMap_set(example->cached_texts, &(CachedText){.string=text_h, .texture=text_tex, .last_access=time(NULL)});
- }
-
- int width, height;
- SDL_QueryTexture(text_tex, NULL, NULL, &width, &height);
-
- SDL_Rect text_rect = {x, y, width, height};
-
- SDL_RenderCopy(renderer, text_tex, NULL, &text_rect);
-}
-
-/**
- * @brief Draw text aligned to right.
- *
- * @param font TTF Font
- * @param renderer SDL Renderer
- * @param text Text
- * @param x X
- * @param y Y
- * @param color SDL Color
- */
-void draw_text_from_right(
- struct _Example *example,
- TTF_Font *font,
- SDL_Renderer *renderer,
- char *text,
- int x,
- int y,
- SDL_Color color
-) {
- CachedText *cached_text = nvHashMap_get(example->cached_texts, &(CachedText){.string=text});
- SDL_Texture *text_tex;
-
- if (cached_text) {
- text_tex = cached_text->texture;
- nvHashMap_set(example->cached_texts, &(CachedText){.string=cached_text->string, .texture=text_tex, .last_access=time(NULL)});
- }
-
- else {
- SDL_Surface *text_surf = TTF_RenderText_Blended(font, text, color);
- text_tex = SDL_CreateTextureFromSurface(renderer, text_surf);
- SDL_FreeSurface(text_surf);
-
- char *text_h = strdup(text);
- nvHashMap_set(example->cached_texts, &(CachedText){.string=text_h, .texture=text_tex, .last_access=time(NULL)});
- }
-
- int width, height;
- SDL_QueryTexture(text_tex, NULL, NULL, &width, &height);
-
- SDL_Rect text_rect = {example->width - width - x, y, width, height};
-
- SDL_RenderCopy(renderer, text_tex, NULL, &text_rect);
-}
-
-void draw_text_middle(
- struct _Example *example,
- TTF_Font *font,
- SDL_Renderer *renderer,
- char *text,
- int x,
- int y,
- int width,
- int height,
- SDL_Color color
-) {
- CachedText *cached_text = nvHashMap_get(example->cached_texts, &(CachedText){.string=text});
- SDL_Texture *text_tex;
-
- if (cached_text) {
- text_tex = cached_text->texture;
- nvHashMap_set(example->cached_texts, &(CachedText){.string=cached_text->string, .texture=text_tex, .last_access=time(NULL)});
- }
-
- else {
- SDL_Surface *text_surf = TTF_RenderText_Blended(font, text, color);
- text_tex = SDL_CreateTextureFromSurface(renderer, text_surf);
- SDL_FreeSurface(text_surf);
-
- char *text_h = strdup(text);
- nvHashMap_set(example->cached_texts, &(CachedText){.string=text_h, .texture=text_tex, .last_access=time(NULL)});
- }
-
- int twidth, theight;
- SDL_QueryTexture(text_tex, NULL, NULL, &twidth, &theight);
-
- SDL_Rect text_rect = {x + width/2.0-twidth/2.0, y + height/2.0-theight/2.0, twidth, theight};
-
- SDL_RenderCopy(renderer, text_tex, NULL, &text_rect);
-}
-
-
-static int graph_cmp(const void *a, const void *b) {
- //return (*(GraphData *)b).percent - (*(GraphData *)a).percent;
-
- double value_a = (*(GraphData *)a).percent;
- double value_b = (*(GraphData *)b).percent;
-
- if (value_a < value_b) return 1;
- if (value_a > value_b) return -1;
- return 0;
-}
-
-
-/**
- * @brief Render UI.
- */
-void draw_ui(Example *example, TTF_Font *font) {
- int example_ui_y = 200;
- int example_ui_x = example->width - 250;
-
- if (example->draw_ui) {
- SDL_SetRenderDrawColor(example->renderer, example->ui_color2.r, example->ui_color2.g, example->ui_color2.b, 175);
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){0, 0, 250, example->height});
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){example_ui_x, example_ui_y, 250, 250});
- }
- else {
- SDL_SetRenderDrawColor(example->renderer, example->ui_color2.r, example->ui_color2.g, example->ui_color2.b, 175);
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){0, 0, 220, 56});
- }
-
- // font size + 4 px for leading
- int y_gap = 12 + 4;
-
- //char *text_fps = malloc(sizeof(char) * 32);
- char text_fps[32];
- sprintf(text_fps, "FPS: %.1f", example->fps);
-
- char text_steptime[32];
- sprintf(text_steptime, "Physics: %.2fms", example->step_time);
-
- char text_rendertime[32];
- sprintf(text_rendertime, "Render: %.2fms", example->render_time);
-
- draw_text(example, font, example->renderer, text_fps, 5, 5 + (y_gap*0), example->text_color);
- draw_text(example, font, example->renderer, text_steptime, 5, 5 + (y_gap*1), example->text_color);
- draw_text(example, font, example->renderer, text_rendertime, 5, 5 + (y_gap*2), example->text_color);
-
- if (!example->draw_ui) {
- char text_savg[24];
- sprintf(text_savg, "Avg: %.2fms", example->step_avg);
-
- char text_ravg[24];
- sprintf(text_ravg, "Avg: %.2fms", example->render_avg);
-
- draw_text(example, font, example->renderer, text_savg, 120, 5 + (y_gap*1), example->text_color);
- draw_text(example, font, example->renderer, text_ravg, 120, 5 + (y_gap*2), example->text_color);
-
- return;
- }
-
- char text_memoryload[32];
- size_t memory_used = get_current_memory_usage();
- double memory_used_mb = (double)memory_used / 1048576.0;
- if (memory_used_mb > example->max_memory_usage) example->max_memory_usage = memory_used_mb;
- sprintf(text_memoryload, "Memory: %.1fMB", memory_used_mb);
-
- char text_threads[32];
- sprintf(text_threads, "Threads: %llu", (unsigned long long)example->space->thread_count);
-
- draw_text(example, font, example->renderer, text_memoryload, 5, 5 + (y_gap*3), example->text_color);
- draw_text(example, font, example->renderer, text_threads, 5, 5 + (y_gap*4), example->text_color);
-
-
- char example_title[48];
- sprintf(example_title, "%s example settings", example_entries[current_example].name);
- draw_text(example, font, example->renderer, example_title, example_ui_x + 5, example_ui_y + 5, example->text_color);
-
- SDL_SetRenderDrawColor(
- example->renderer,
- example->alt_text_color.r,
- example->alt_text_color.g,
- example->alt_text_color.b,
- 255
- );
- SDL_RenderDrawLine(
- example->renderer,
- example_ui_x + 5, example_ui_y + 5 + 16 + 2,
- example->width - 5, example_ui_y + 5 + 16 + 2
- );
-
- ExampleEntry entry = example_entries[current_example];
-
- for (size_t i = 0; i < entry.slider_settings->size; i++) {
- SliderSetting *setting = entry.slider_settings->data[i];
- Slider *s = setting->slider;
-
- int slider_x = example_ui_x + 100;
-
- s->x = slider_x;
- s->y = example_ui_y + 67 + 16 * i + 5;
- s->cx = s->x + ((s->value-s->min) / (s->max - s->min)) * s->width;
-
- Slider_update(example, s);
- Slider_draw(example, s);
-
- draw_text(example,
- font,
- example->renderer,
- setting->name,
- example_ui_x + 5,
- example_ui_y + 67 + 16 * i,
- example->text_color
- );
-
- char slider_val[8];
- if (s->type == SliderType_FLOAT)
- sprintf(slider_val, "%.3f", s->value);
- else
- sprintf(slider_val, "%d", (int)s->value);
-
- draw_text(example,
- font,
- example->renderer,
- slider_val,
- slider_x + s->width + 5,
- example_ui_y + 67 + 16 * i,
- example->text_color
- );
- }
-
-
- struct SDL_version sdl_ver;
- SDL_GetVersion(&sdl_ver);
- char text_sdlver[32];
- sprintf(text_sdlver, "SDL %d.%d.%d", sdl_ver.major, sdl_ver.minor, sdl_ver.patch);
-
- char text_novaver[32];
- sprintf(text_novaver, "Nova Physics %s", NV_VERSTR);
-
- char *text_instr = "Click & drag bodies";
- char *text_instr1 = "Reset scene with [R]";
- char *text_instr2 = "Create explosion with [Q]";
- char *text_instr3 = "Toggle UI with [U]";
- char *text_instr4 = "Toggle pause with [PERIOD]";
- char *text_instr5 = "Step by step with [SLASH]";
-
- char text_bodies[32];
- sprintf(text_bodies, "Bodies: %llu", (unsigned long long)example->space->bodies->size);
-
- char text_consts[32];
- sprintf(text_consts, "Constraints: %llu", (unsigned long long)example->space->constraints->size);
-
- char text_attrs[32];
- sprintf(text_attrs, "Attractors: %llu", (unsigned long long)example->space->attractors->size);
-
- char text_ress[32];
- sprintf(text_ress, "Resolutions: %llu", (unsigned long long)example->space->res->count);
-
- char *text_iters = "Velocity iters";
- char *text_citers = "Position iters";
- char *text_cciters = "Constrt. iters";
- char *text_subs = "Substeps";
- char *text_hertz = "Hertz";
-
- char text_iters_f[16];
- sprintf(text_iters_f, "%d", (int)example->sliders[0]->value);
-
- char text_citers_f[16];
- sprintf(text_citers_f, "%d", (int)example->sliders[1]->value);
-
- char text_cciters_f[16];
- sprintf(text_cciters_f, "%d", (int)example->sliders[2]->value);
-
- char text_subs_f[16];
- sprintf(text_subs_f, "%d", (int)example->sliders[3]->value);
-
- char text_hertz_f[32];
- sprintf(text_hertz_f, "%d/sec", (int)example->sliders[4]->value);
-
- double unit_multipler = 1000.0;
- char unit_char = 'm';
- if (!example->switches[11]->on) {
- unit_multipler = 1000000.0;
- unit_char = 'u';
- }
-
- char *text_aa = "Anti-aliasing";
- char *text_fs = "Fill shapes";
- char *text_da = "Draw AABBs";
- char *text_dc = "Draw contacts";
- char *text_dd = "Draw directions";
- char *text_dj = "Draw constraints";
- char *text_dv = "Draw velocities";
- char *text_dg = "Draw broad-phase";
- char *text_s = "Sleeping?";
- char *text_ws = "Warm-starting?";
-
- // Update and render UI widgets
-
- for (size_t i = 0; i < example->switch_count; i++) {
- ToggleSwitch *tg = example->switches[i];
-
- ToggleSwitch_update(example, tg);
- ToggleSwitch_draw(example, tg);
- }
-
- for (size_t i = 0; i < example->slider_count; i++) {
- Slider *s = example->sliders[i];
- Slider_update(example, s);
- Slider_draw(example, s);
- }
-
- for (size_t i = 0; i < example->button_count; i++) {
- Button *b = example->buttons[i];
-
- if (!strcmp(b->text, "Reset scene")) {
- b->x = example->width - 250 + 5;
- }
-
- Button_update(example, b);
- Button_draw(example, b, font);
- }
-
- draw_text_from_right(example, font, example->renderer, text_sdlver, 5, 5 + (y_gap*0), example->text_color);
- draw_text_from_right(example, font, example->renderer, text_novaver, 5, 5 + (y_gap*1), example->text_color);
- draw_text_from_right(example, font, example->renderer, text_instr, 5, 56 + (y_gap*0), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, text_instr1, 5, 56 + (y_gap*1), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, text_instr2, 5, 56 + (y_gap*2), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, text_instr3, 5, 56 + (y_gap*3), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, text_instr4, 5, 56 + (y_gap*4), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, text_instr5, 5, 56 + (y_gap*5), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, "Move the camera with [MOUSE WHL BUTTON]", 5, 56 + (y_gap*6), example->alt_text_color);
- draw_text_from_right(example, font, example->renderer, "Zoom in/out with [MOUSE WHL SCROLL]", 5, 56 + (y_gap*7), example->alt_text_color);
-
- draw_text(example, font, example->renderer, text_bodies, 123, 5 + (y_gap*0), example->text_color);
- draw_text(example, font, example->renderer, text_consts, 123, 5 + (y_gap*1), example->text_color);
- draw_text(example, font, example->renderer, text_attrs, 123, 5 + (y_gap*2), example->text_color);
- draw_text(example, font, example->renderer, text_ress, 123, 5 + (y_gap*3), example->text_color);
-
- draw_text(example, font, example->renderer, text_iters, 5, 10+15 + (y_gap*16), example->text_color);
- draw_text(example, font, example->renderer, text_citers, 5, 15+15 + (y_gap*17), example->text_color);
- draw_text(example, font, example->renderer, text_cciters, 5, 20+15 + (y_gap*18), example->text_color);
- draw_text(example, font, example->renderer, text_subs, 5, 25+15 + (y_gap*19), example->text_color);
- draw_text(example, font, example->renderer, text_hertz, 5, 30+15 + (y_gap*20), example->text_color);
- draw_text(example, font, example->renderer, text_iters_f, 196, 10+15 + (y_gap*16), example->text_color);
- draw_text(example, font, example->renderer, text_citers_f, 196, 15+15 + (y_gap*17), example->text_color);
- draw_text(example, font, example->renderer, text_cciters_f, 196, 20+15 + (y_gap*18), example->text_color);
- draw_text(example, font, example->renderer, text_subs_f, 196, 25+15 + (y_gap*19), example->text_color);
- draw_text(example, font, example->renderer, text_hertz_f, 196, 30+15 + (y_gap*20), example->text_color);
-
- draw_text(example, font, example->renderer, text_aa, 5, 10 + (y_gap*5), example->text_color);
- draw_text(example, font, example->renderer, text_fs, 5, 10 + (y_gap*6), example->text_color);
- draw_text(example, font, example->renderer, text_da, 5, 10 + (y_gap*7), example->text_color);
- draw_text(example, font, example->renderer, text_dc, 5, 10 + (y_gap*8), example->text_color);
- draw_text(example, font, example->renderer, text_dd, 5, 10 + (y_gap*9), example->text_color);
- draw_text(example, font, example->renderer, text_dj, 5, 10 + (y_gap*10), example->text_color);
- draw_text(example, font, example->renderer, text_dv, 5, 10 + (y_gap*11), example->text_color);
- draw_text(example, font, example->renderer, text_dg, 5, 10 + (y_gap*12), example->text_color);
- draw_text(example, font, example->renderer, "Draw positions", 5, 10 + (y_gap*13), example->text_color);
- draw_text(example, font, example->renderer, text_s, 5, 10 + (y_gap*14), example->text_color);
- draw_text(example, font, example->renderer, text_ws, 5, 10 + (y_gap*15), example->text_color);
-
- draw_text(example, font, example->renderer, "Parallel", 144, 10 + (y_gap*5), example->text_color);
-
- char text_threadslider[8];
- sprintf(text_threadslider, "%u", (nv_uint32)example->sliders[5]->value);
-
- draw_text(example, font, example->renderer, text_threadslider, 234, 110, example->text_color);
-
- draw_text(example, font, example->renderer, "Show profiler", 5, 140+15 + (y_gap*15), example->text_color);
- draw_text(example, font, example->renderer, "Show in milliseconds", 5, 140+15 + (y_gap*16), example->text_color);
-
- if (example->memory_graph_size == 240) {
- memmove(example->memory_graph_data, &example->memory_graph_data[1], (240 - 1) * sizeof(double));
- example->memory_graph_data[240 - 1] = memory_used_mb;
- }
- else {
- example->memory_graph_data[example->memory_graph_size] = memory_used_mb;
- example->memory_graph_size++;
- }
-
- if (example->fps_graph_size == 240) {
- memmove(example->fps_graph_data, &example->fps_graph_data[1], (240 - 1) * sizeof(double));
- example->fps_graph_data[240 - 1] = example->fps;
- }
- else {
- example->fps_graph_data[example->fps_graph_size] = example->fps;
- example->fps_graph_size++;
- }
-
- int profiler_y = 5;
-
- if (example->switches[10]->on) {
- SDL_SetRenderDrawColor(example->renderer, example->ui_color2.r, example->ui_color2.g, example->ui_color2.b, 175);
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){250, 0, 540, 201});
-
- double percents[11] = {
- example->space->profiler.integrate_accelerations / example->space->profiler.step * 100.0,
- example->space->profiler.broadphase / example->space->profiler.step * 100.0,
- example->space->profiler.update_resolutions / example->space->profiler.step * 100.0,
- example->space->profiler.narrowphase / example->space->profiler.step * 100.0,
- example->space->profiler.presolve_collisions / example->space->profiler.step * 100.0,
- example->space->profiler.solve_positions / example->space->profiler.step * 100.0,
- example->space->profiler.solve_velocities / example->space->profiler.step * 100.0,
- example->space->profiler.presolve_constraints / example->space->profiler.step * 100.0,
- example->space->profiler.solve_constraints / example->space->profiler.step * 100.0,
- example->space->profiler.integrate_velocities / example->space->profiler.step * 100.0,
- example->space->profiler.remove_bodies / example->space->profiler.step * 100.0
- };
-
- GraphData graph_data[11];
- for (size_t j = 0; j < 11; j++) {
- graph_data[j] = (GraphData){percents[j], j};
- }
-
- char text_profiler0[48];
- sprintf(text_profiler0, "Step: %.2f%cs 100.0%%", example->space->profiler.step * unit_multipler, unit_char);
-
- char text_profiler1[48];
- sprintf(text_profiler1, "Integrate accel.: %.2f%cs %.1f%%", example->space->profiler.integrate_accelerations * unit_multipler, unit_char, percents[0]);
-
- char text_profiler2[48];
- sprintf(text_profiler2, "Broad-phase: %.2f%cs %.1f%%", example->space->profiler.broadphase * unit_multipler, unit_char, percents[1]);
-
- char text_profiler3[48];
- sprintf(text_profiler3, "Update res.: %.2f%cs %.1f%%", example->space->profiler.update_resolutions * unit_multipler, unit_char, percents[2]);
-
- char text_profiler4[48];
- sprintf(text_profiler4, "Narrow-phase: %.2f%cs %.1f%%", example->space->profiler.narrowphase * unit_multipler, unit_char, percents[3]);
-
- char text_profiler5[48];
- sprintf(text_profiler5, "Presolve colls.: %.2f%cs %.1f%%", example->space->profiler.presolve_collisions * unit_multipler, unit_char, percents[4]);
-
- char text_profiler6[48];
- sprintf(text_profiler6, "Solve positions: %.2f%cs %.1f%%", example->space->profiler.solve_positions * unit_multipler, unit_char, percents[5]);
-
- char text_profiler7[48];
- sprintf(text_profiler7, "Solve velocities: %.2f%cs %.1f%%", example->space->profiler.solve_velocities * unit_multipler, unit_char, percents[6]);
-
- char text_profiler8[48];
- sprintf(text_profiler8, "Presolve consts.: %.2f%cs %.1f%%", example->space->profiler.presolve_constraints * unit_multipler, unit_char, percents[7]);
-
- char text_profiler9[48];
- sprintf(text_profiler9, "Solve consts.: %.2f%cs %.1f%%", example->space->profiler.solve_constraints * unit_multipler, unit_char, percents[8]);
-
- char text_profiler10[48];
- sprintf(text_profiler10, "Integrate vels.: %.2f%cs %.1f%%", example->space->profiler.integrate_velocities * unit_multipler, unit_char, percents[9]);
-
- char text_profiler11[48];
- sprintf(text_profiler11, "Remove bodies: %.2f%cs %.1f%%", example->space->profiler.remove_bodies * unit_multipler, unit_char, percents[10]);
-
- int boxsize = 10;
- for (size_t p = 0; p < 11; p++) {
- SDL_SetRenderDrawColor(example->renderer, example->profiler_palette[p].r, example->profiler_palette[p].g, example->profiler_palette[p].b, 255);
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){255, profiler_y + (y_gap*(p+1)) + 3, boxsize, boxsize});
- }
-
- int profiler_text_x = 270;
- draw_text(example, font, example->renderer, text_profiler0, profiler_text_x, profiler_y + (y_gap*0), example->text_color);
- draw_text(example, font, example->renderer, text_profiler1, profiler_text_x, profiler_y + (y_gap*1), example->text_color);
- draw_text(example, font, example->renderer, text_profiler2, profiler_text_x, profiler_y + (y_gap*2), example->text_color);
- draw_text(example, font, example->renderer, text_profiler3, profiler_text_x, profiler_y + (y_gap*3), example->text_color);
- draw_text(example, font, example->renderer, text_profiler4, profiler_text_x, profiler_y + (y_gap*4), example->text_color);
- draw_text(example, font, example->renderer, text_profiler5, profiler_text_x, profiler_y + (y_gap*5), example->text_color);
- draw_text(example, font, example->renderer, text_profiler6, profiler_text_x, profiler_y + (y_gap*6), example->text_color);
- draw_text(example, font, example->renderer, text_profiler7, profiler_text_x, profiler_y + (y_gap*7), example->text_color);
- draw_text(example, font, example->renderer, text_profiler8, profiler_text_x, profiler_y + (y_gap*8), example->text_color);
- draw_text(example, font, example->renderer, text_profiler9, profiler_text_x, profiler_y + (y_gap*9), example->text_color);
- draw_text(example, font, example->renderer, text_profiler10, profiler_text_x, profiler_y + (y_gap*10), example->text_color);
- draw_text(example, font, example->renderer, text_profiler11, profiler_text_x, profiler_y + (y_gap*11), example->text_color);
-
- if (example->space->broadphase_algorithm == nvBroadPhaseAlg_BOUNDING_VOLUME_HIERARCHY) {
- char text_bvh0[48];
- sprintf(text_bvh0, "BVH build: %.2f %cs", example->space->profiler.bvh_build * unit_multipler, unit_char);
-
- char text_bvh1[48];
- sprintf(text_bvh1, "BVH traverse: %.2f %cs", example->space->profiler.bvh_traverse * unit_multipler, unit_char);
-
- char text_bvh2[48];
- sprintf(text_bvh2, "BVH destroy: %.2f %cs", example->space->profiler.bvh_destroy * unit_multipler, unit_char);
-
- draw_text(example, font, example->renderer, text_bvh0, 255, profiler_y + (y_gap*12), example->text_color);
- draw_text(example, font, example->renderer, text_bvh1, 255, profiler_y + (y_gap*13), example->text_color);
- draw_text(example, font, example->renderer, text_bvh2, 255, profiler_y + (y_gap*14), example->text_color);
- }
-
- /* Physics step graph */
-
- draw_text(example, font, example->renderer, "0%", 501, 5, example->text_color);
- draw_text(example, font, example->renderer, "100%", 502+275-29, 5, example->text_color);
-
- SDL_SetRenderDrawColor(example->renderer, example->text_color.r, example->text_color.g, example->text_color.b, 120);
- SDL_RenderDrawLine(example->renderer, 502, 19, 502+275, 19);
- SDL_RenderDrawLine(example->renderer, 255, 19, 486, 19);
-
- float graph_width = 275.0;
- float graph_height = 29.0;
- float graph_x = 502.0;
- float graph_y = 32.0;
-
- qsort(graph_data, 11, sizeof(GraphData), graph_cmp);
-
- example->graph_counter++;
- if (example->graph_counter == 10) {
- example->graph_counter = 0;
-
- for (size_t j = 0; j < 11; j++) {
- example->last_graph[j] = graph_data[j];
- }
- }
-
- for (size_t j = 0; j < 11; j++) {
- double percent = example->last_graph[j].percent / 100.0;
- SDL_Color color = example->profiler_palette[example->last_graph[j].index];
-
- float width = graph_width * percent;
-
- SDL_SetRenderDrawColor(example->renderer, color.r, color.g, color.b, 255);
- SDL_RenderFillRectF(example->renderer, &(SDL_FRect){graph_x, graph_y, width, graph_height});
-
- graph_x += width;
- }
-
- graph_width = 240;
- float res = 1.0;
-
- /* FPS graph */
-
- SDL_SetRenderDrawColor(example->renderer, example->text_color.r, example->text_color.g, example->text_color.b, 255);
- SDL_RenderDrawLine(example->renderer, 534, 80, 534, 80+45);
- SDL_RenderDrawLine(example->renderer, 534, 80+45, 534+graph_width, 80+45);
-
- draw_text(example, font, example->renderer, "FPS", 534-10, 64, example->text_color);
-
- char fps_graph_max[8];
- sprintf(fps_graph_max, "%d", (int)example->max_fps);
- char fps_graph_half[8];
- sprintf(fps_graph_half, "%d", (int)(example->max_fps / 2.0));
- draw_text(example, font, example->renderer, fps_graph_max, 501, 80-3, example->text_color);
- draw_text(example, font, example->renderer, fps_graph_half, 501, 98-3, example->text_color);
- draw_text(example, font, example->renderer, "0", 501, 117-3, example->text_color);
-
- for (size_t x = 1; x < 240 * res; x += res) {
- float p0 = example->fps_graph_data[(int)((float)x/res)] / example->max_fps;
- p0 = nv_fclamp(p0, 0.0, 1.0);
- float v0 = p0 * 45.0;
- float x0 = x + 535;
- float p1 = example->fps_graph_data[(int)((float)x/res) - 1] / example->max_fps;
- p1 = nv_fclamp(p1, 0.0, 1.0);
- float v1 = p0 * 45.0;
- float x1 = (x - res) + 535;
- SDL_Color bar_color = color_lerp((SDL_Color){255, 0, 0}, (SDL_Color){0, 255, 0}, (p0 + p1)/2.0);
- SDL_SetRenderDrawColor(example->renderer, bar_color.r, bar_color.g, bar_color.b, 255);
- SDL_RenderDrawLine(example->renderer, x1, 80+45-v1, x0, 80+45-v0);
- }
-
- /* Memory usage graph */
-
- SDL_SetRenderDrawColor(example->renderer, example->text_color.r, example->text_color.g, example->text_color.b, 255);
- SDL_RenderDrawLine(example->renderer, 534, 147, 534, 147+45);
- SDL_RenderDrawLine(example->renderer, 534, 147+45, 534+graph_width, 147+45);
-
- draw_text(example, font, example->renderer, "Memory", 534-19, 131, example->text_color);
- char memory_graph_max[8];
- sprintf(memory_graph_max, "%d", (int)example->max_memory_usage);
- char memory_graph_half[8];
- sprintf(memory_graph_half, "%d", (int)(example->max_memory_usage / 2.0));
- draw_text(example, font, example->renderer, memory_graph_max, 501, 147-3, example->text_color);
- draw_text(example, font, example->renderer, memory_graph_half, 501, 165-3, example->text_color);
- draw_text(example, font, example->renderer, "0", 501, 184-3, example->text_color);
-
- for (size_t x = 1; x < 240 * res; x += res) {
- float p0 = example->memory_graph_data[(int)((float)x/res)] / example->max_memory_usage;
- float p = p0 * 45;
- SDL_Color bar_color = color_lerp((SDL_Color){255, 66, 66}, (SDL_Color){96, 56, 255}, p0);
- SDL_SetRenderDrawColor(example->renderer, bar_color.r, bar_color.g, bar_color.b, 255);
- SDL_RenderDrawLine(example->renderer, x+535, 147+45-p, x+535, 147+45);
- }
- }
-}
-
-/**
- * @brief Render constraints
- */
-void draw_constraints(Example *example) {
- if (example->switches[4]->on) {
- for (size_t i = 0; i < example->space->constraints->size; i++) {
- nvConstraint *cons = (nvConstraint *)example->space->constraints->data[i];
-
- // Skip cursor body
- if (cons->a == (nvBody *)example->space->bodies->data[0] ||
- cons->b == (nvBody *)example->space->bodies->data[0])
- continue;
-
- // ? Forward declare to avoid errors on GCC < 10
- nvDistanceJoint *dist_joint;
- nvHingeJoint *hinge_joint;
- nvVector2 a, b, ra, rb;
-
- switch (cons->type) {
-
- case nvConstraintType_SPRING:
- SDL_SetRenderDrawColor(
- example->renderer,
- example->spring_color.r,
- example->spring_color.g,
- example->spring_color.b,
- example->spring_color.a
- );
- draw_spring(
- example,
- example->renderer,
- cons,
- example->switches[0]->on,
- example->spring_color
- );
- break;
-
- case nvConstraintType_DISTANCEJOINT:
- dist_joint = (nvDistanceJoint *)cons->def;
-
- SDL_SetRenderDrawColor(
- example->renderer,
- example->distancejoint_color.r,
- example->distancejoint_color.g,
- example->distancejoint_color.b,
- example->distancejoint_color.a
- );
-
- // Transform anchor points
- if (cons->a == NULL) {
- a = world_to_screen(example, dist_joint->anchor_a);
- } else {
- ra = nvVector2_rotate(dist_joint->anchor_a, cons->a->angle);
- a = nvVector2_add(cons->a->position, ra);
- a = world_to_screen(example, a);
- }
- if (cons->b == NULL) {
- b = world_to_screen(example, dist_joint->anchor_b);
- } else {
- rb = nvVector2_rotate(dist_joint->anchor_b, cons->b->angle);
- b = nvVector2_add(cons->b->position, rb);
- b = world_to_screen(example, b);
- }
-
- if (example->switches[0]->on) {
- draw_aaline(
- example->renderer,
- a.x, a.y,
- b.x, b.y
- );
-
- draw_aacircle(
- example->renderer,
- a.x, a.y,
- 0.2 * example->zoom,
- example->distancejoint_color.r,
- example->distancejoint_color.g,
- example->distancejoint_color.b
- );
-
- draw_aacircle(
- example->renderer,
- b.x, b.y,
- 0.2 * example->zoom,
- example->distancejoint_color.r,
- example->distancejoint_color.g,
- example->distancejoint_color.b
- );
- }
- else {
- SDL_RenderDrawLineF(
- example->renderer,
- a.x, a.y,
- b.x, b.y
- );
-
- draw_circle(
- example->renderer,
- a.x, a.y,
- 0.2 * example->zoom
- );
-
- draw_circle(
- example->renderer,
- b.x, b.y,
- 0.2 * example->zoom
- );
- }
-
- break;
-
- case nvConstraintType_HINGEJOINT:
- hinge_joint = (nvHingeJoint *)cons->def;
-
- if (cons->a)
- a = world_to_screen(example,
- nvVector2_add(
- nvVector2_rotate(hinge_joint->anchor_a, cons->a->angle), cons->a->position));
- else
- a = world_to_screen(example, hinge_joint->anchor);
- if (cons->b)
- b = world_to_screen(example,
- nvVector2_add(
- nvVector2_rotate(hinge_joint->anchor_b, cons->b->angle), cons->b->position));
- else
- b = world_to_screen(example, hinge_joint->anchor);
- ra = nvVector2_mul(nvVector2_add(a, b), 0.5);
-
- SDL_SetRenderDrawColor(
- example->renderer,
- example->hingejoint_color.r,
- example->hingejoint_color.g,
- example->hingejoint_color.b,
- example->hingejoint_color.a
- );
-
- if (example->switches[0]->on) {
- draw_aacircle(
- example->renderer,
- ra.x, ra.y,
- 0.5 * example->zoom,
- example->hingejoint_color.r,
- example->hingejoint_color.g,
- example->hingejoint_color.b
- );
-
- draw_aacircle(
- example->renderer,
- a.x, a.y,
- 0.25 * example->zoom,
- example->hingejoint_color.r,
- example->hingejoint_color.g,
- example->hingejoint_color.b
- );
-
- draw_aacircle(
- example->renderer,
- b.x, b.y,
- 0.25 * example->zoom,
- example->hingejoint_color.r,
- example->hingejoint_color.g,
- example->hingejoint_color.b
- );
- }
- else {
- draw_circle(
- example->renderer,
- ra.x, ra.y,
- 0.5 * example->zoom
- );
-
- draw_circle(
- example->renderer,
- a.x, a.y,
- 0.25 * example->zoom
- );
-
- draw_circle(
- example->renderer,
- b.x, b.y,
- 0.25 * example->zoom
- );
- }
-
- break;
- }
- }
- }
-}
-
-/**
- * @brief Render bodies.
- */
-void draw_bodies(Example *example, TTF_Font *font) {
- // Start from 1 because 0 is cursor body
- for (size_t i = 1; i < example->space->bodies->size; i++) {
- nvBody *body = (nvBody *)example->space->bodies->data[i];
-
- nvAABB aabb = nvBody_get_aabb(body);
- nvVector2 aabb_min = world_to_screen(example, NV_VEC2(aabb.min_x, aabb.min_y));
- nvVector2 aabb_max = world_to_screen(example, NV_VEC2(aabb.max_x, aabb.max_y));
-
- // Shape outside of window viewport, don't draw
- if (!nv_collide_aabb_x_aabb((nvAABB){aabb_min.x, aabb_min.y, aabb_max.x, aabb_max.y}, (nvAABB){0.0, 0.0, example->width, example->height})) {
- continue;
- }
-
- SDL_FRect aabb_rect = (SDL_FRect){
- aabb_min.x,
- aabb_min.y,
- aabb_max.x - aabb_min.x,
- aabb_max.y - aabb_min.y
- };
-
- if (example->switches[1]->on) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->aabb_color.r,
- example->aabb_color.g,
- example->aabb_color.b,
- example->aabb_color.a
- );
- SDL_RenderDrawRectF(example->renderer, &aabb_rect);
- }
-
- SDL_Color aacolor;
-
- if (body->type == nvBodyType_STATIC) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->static_color.r,
- example->static_color.g,
- example->static_color.b,
- example->static_color.a
- );
-
- aacolor = example->static_color;
- }
- else {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->body_color.r,
- example->body_color.g,
- example->body_color.b,
- example->body_color.a
- );
-
- aacolor = example->body_color;
- }
-
- if (body->is_sleeping) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->sleep_color.r,
- example->sleep_color.g,
- example->sleep_color.b,
- example->sleep_color.a
- );
-
- aacolor = example->sleep_color;
- }
-
- // Rainbow
- //nv_uint16 r = (nv_uint16)(((nv_float)body->id) / ((nv_float)example->space->bodies->size) * 256.0);
-
- // Incremental
- //nv_uint16 r = body->id % 5;
-
- // Deterministic random
- nv_uint16 r = FNV1a_u32(body->id) % 5;
-
- SDL_Color color;
-
- // Nova palette
- if (r == 0) color = (SDL_Color){255, 212, 0, 255};
- if (r == 1) color = (SDL_Color){70, 51, 163, 255};
- if (r == 2) color = (SDL_Color){234, 222, 218, 255};
- if (r == 3) color = (SDL_Color){217, 3, 104, 255};
- if (r == 4) color = (SDL_Color){130, 2, 99, 255};
-
- // Rainbow
- //color = fhsv_to_rgb(r, 0.38, 1.0);
- //color.a = 255;
-
- // Draw circle bodies
- if (body->shape->type == nvShapeType_CIRCLE) {
- nvVector2 pos = world_to_screen(example, body->position);
- nv_float x = pos.x;
- nv_float y = pos.y;
-
- if (example->switches[0]->on) {
- draw_aacircle(
- example->renderer,
- x, y,
- body->shape->radius * example->zoom,
- aacolor.r,
- aacolor.g,
- aacolor.b
- );
-
- if (example->switches[3]->on) {
- nvVector2 a = (nvVector2){body->shape->radius*example->zoom, 0.0};
- a = nvVector2_rotate(a, body->angle);
-
- draw_aaline(example->renderer, x, y, x+a.x, y+a.y);
- }
- }
- else if (example->switches[9]->on) {
- size_t n = 12;
- SDL_Vertex *vertices = malloc(sizeof(SDL_Vertex) * n);
-
- nvVector2 arm = NV_VEC2(body->shape->radius, 0.0);
- nvVector2 trans;
-
- for (size_t i = 0; i < n; i++) {
- arm = nvVector2_rotate(arm, 2.0 * NV_PI / (nv_float)n);
- trans = world_to_screen(example, nvVector2_add(body->position, arm));
-
- vertices[i] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){trans.x, trans.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
- }
-
- int indices[] = {0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 5, 4, 0, 6, 5, 0, 7, 6, 0, 8, 7, 0, 9, 8, 0, 10, 9, 0, 11, 10};
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, n, indices, 30);
- free(vertices);
-
- if (example->switches[3]->on) {
- nvVector2 a = (nvVector2){body->shape->radius*example->zoom, 0.0};
- a = nvVector2_rotate(a, body->angle);
-
- SDL_SetRenderDrawColor(example->renderer, example->body_color.r, example->body_color.g, example->body_color.b, 255);
-
- SDL_RenderDrawLineF(example->renderer, x, y, x+a.x, y+a.y);
- }
- }
- else {
- int32_t draw_radius = (int32_t)(body->shape->radius * example->zoom);
- draw_circle(
- example->renderer,
- (int32_t)x,
- (int32_t)y,
- draw_radius
- );
-
- if (example->switches[3]->on) {
- nvVector2 a = (nvVector2){body->shape->radius*example->zoom, 0.0};
- a = nvVector2_rotate(a, body->angle);
-
- SDL_RenderDrawLineF(example->renderer, x, y, x+a.x, y+a.y);
- }
- }
- }
-
- // Draw polygon bodies
- else {
- nvBody_local_to_world(body);
-
- nvArray *verts = nvArray_new();
- for (size_t k = 0; k < body->shape->trans_vertices->size; k++) {
- nvVector2 p = world_to_screen(example, NV_TO_VEC2(body->shape->trans_vertices->data[k]));
- nvArray_add(verts, NV_VEC2_NEW(p.x, p.y));
- }
-
- if (example->switches[0]->on)
- draw_aapolygon(example->renderer, verts);
-
- else if (example->switches[9]->on) {
- size_t n = verts->size;
-
- if (n == 3) {
-
- SDL_Vertex *vertices = malloc(sizeof(SDL_Vertex) * n);
-
- for (size_t j = 0; j < n; j++) {
- nvVector2 v = NV_TO_VEC2(verts->data[j]);
-
- vertices[j] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){v.x, v.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
- }
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, n, NULL, 0);
- free(vertices);
- }
-
- else if (n == 4) {
-
- SDL_Vertex *vertices = malloc(sizeof(SDL_Vertex) * n);
-
- for (size_t j = 0; j < n; j++) {
- nvVector2 v = NV_TO_VEC2(verts->data[j]);
-
- vertices[j] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){v.x , v.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
- }
-
- int indices[6] = {0, 2, 1, 0, 3, 2};
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, n, indices, 6);
- free(vertices);
-
- }
-
- else if (n == 5) {
-
- SDL_Vertex *vertices = malloc(sizeof(SDL_Vertex) * n);
-
- for (size_t j = 0; j < n; j++) {
- nvVector2 v = NV_TO_VEC2(verts->data[j]);
-
- vertices[j] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){v.x, v.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
- }
-
- int indices[9] = {0, 2, 1, 0, 3, 2, 0, 4, 3};
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, n, indices, 9);
- free(vertices);
-
- }
-
- else if (n == 6) {
-
- SDL_Vertex *vertices = malloc(sizeof(SDL_Vertex) * n);
-
- for (size_t j = 0; j < n; j++) {
- nvVector2 v = NV_TO_VEC2(verts->data[j]);
-
- vertices[j] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){v.x, v.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
- }
-
- int indices[12] = {0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 5, 4};
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, n, indices, 12);
- free(vertices);
- }
- }
- else
- draw_polygon(example->renderer, verts);
-
- if (example->switches[3]->on) {
- nvVector2 center = nv_polygon_centroid(verts);
- nvVector2 diredge = nvVector2_div(
- nvVector2_add(
- NV_TO_VEC2(verts->data[0]),
- NV_TO_VEC2(verts->data[1])),
- 2.0
- );
-
- if (example->switches[0]->on)
- draw_aaline(
- example->renderer,
- center.x, center.y,
- diredge.x, diredge.y
- );
- else
- SDL_RenderDrawLineF(
- example->renderer,
- center.x, center.y,
- diredge.x, diredge.y
- );
- }
-
- nvArray_free_each(verts, free);
- nvArray_free(verts);
- }
-
- // Draw velocity vectors
- if (example->switches[5]->on && body->type != nvBodyType_STATIC) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->velocity_color.r,
- example->velocity_color.g,
- example->velocity_color.b,
- example->velocity_color.a
- );
-
- nvVector2 vel = nvVector2_mul(body->linear_velocity, 1.0 / 60.0);
-
- nvVector2 v = world_to_screen(example, nvVector2_add(body->position, vel));
-
- nv_float threshold = 0.25 / 10.0;
-
- if (nvVector2_len2(vel) >= threshold) {
- nvVector2 p = nvVector2_mul(body->position, 10.0);
- nvVector2 arrow = nvVector2_mul(nvVector2_normalize(vel), 5.0);
- nvVector2 arrow1 = nvVector2_rotate(arrow, NV_PI / 6.0);
- nvVector2 arrow2 = nvVector2_rotate(arrow, NV_PI * 2.0 - NV_PI / 6.0);
-
- if (example->switches[0]->on) {
- draw_aaline(
- example->renderer,
- p.x, p.y,
- v.x, v.y
- );
-
- draw_aaline(
- example->renderer,
- v.x, v.y,
- v.x - arrow1.x, v.y - arrow1.y
- );
-
- draw_aaline(
- example->renderer,
- v.x, v.y,
- v.x - arrow2.x, v.y - arrow2.y
- );
- }
- else {
- SDL_RenderDrawLineF(
- example->renderer,
- p.x, p.y,
- v.x, v.y
- );
-
- SDL_RenderDrawLineF(
- example->renderer,
- v.x, v.y,
- v.x - arrow1.x, v.y - arrow1.y
- );
-
- SDL_RenderDrawLineF(
- example->renderer,
- v.x, v.y,
- v.x - arrow2.x, v.y - arrow2.y
- );
- }
- }
- }
-
- // Draw center of masses
- if (example->switches[13]->on) {
- nvVector2 com = world_to_screen(example, body->position);
- nvVector2 dir = nvVector2_rotate(NV_VEC2(0.25, 0.0), body->angle);
- nvVector2 axis1 = nvVector2_add(com, nvVector2_mul(dir, example->zoom));
- nvVector2 axis2 = nvVector2_add(com, nvVector2_mul(nvVector2_perpr(dir), example->zoom));
-
- SDL_SetRenderDrawColor(example->renderer, 255, 0, 0, 255);
-
- if (example->switches[0]->on) {
- draw_aaline(example->renderer, com.x, com.y, axis1.x, axis1.y);
- }
- else {
- SDL_RenderDrawLineF(example->renderer, com.x, com.y, axis1.x, axis1.y);
- }
-
- SDL_SetRenderDrawColor(example->renderer, 0, 255, 0, 255);
-
- if (example->switches[0]->on) {
- draw_aaline(example->renderer, com.x, com.y, axis2.x, axis2.y);
- }
- else {
- SDL_RenderDrawLineF(example->renderer, com.x, com.y, axis2.x, axis2.y);
- }
- }
- }
-}
-
-void draw_cloth(Example *example) {
- int cols = example->cloth_example_cols;
- int rows = example->cloth_example_rows;
-
- for (size_t y = 0; y < rows; y++) {
- for (size_t x = 0; x < cols; x++) {
- if (x > 0 && y > 0) {
- nvBody *body0 = example->space->bodies->data[y * cols + x + 1];
- nvBody *body1 = example->space->bodies->data[y * cols + (x - 1) + 1];
- nvBody *body2 = example->space->bodies->data[(y - 1) * cols + x + 1];
- nvBody *body3 = example->space->bodies->data[(y - 1) * cols + (x - 1) + 1];
- nvVector2 pos0 = world_to_screen(example, body0->position);
- nvVector2 pos1 = world_to_screen(example, body1->position);
- nvVector2 pos2 = world_to_screen(example, body2->position);
- nvVector2 pos3 = world_to_screen(example, body3->position);
-
- SDL_Color color;
-
- // Signed area
- nv_float a = ((pos1.x - pos0.x) * (pos2.y - pos0.y) - (pos2.x - pos0.x) * (pos1.y - pos0.y));
- nv_float b = -((pos1.x - pos3.x) * (pos2.y - pos3.y) - (pos2.x - pos3.x) * (pos1.y - pos3.y));
-
- if (a < 0) {
- color = fhsv_to_rgb((x*5 + y*12) % 360, 1.0, 0.5);
- color.a = 255;
- }
- else {
- color = fhsv_to_rgb((x*5 + y*12) % 360, 1.0, 1.0);
- color.a = 255;
- }
-
- #ifdef NV_COMPILER_MSVC
-
- SDL_Vertex *vertices = malloc(sizeof(SDL_Vertex) * 3);
-
- #else
-
- SDL_Vertex vertices[3];
-
- #endif
-
- vertices[0] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){pos0.x, pos0.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
-
- vertices[1] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){pos1.x, pos1.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
-
- vertices[2] = (SDL_Vertex){
- .color = color,
- .position = (SDL_FPoint){pos2.x, pos2.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, 3, NULL, 0);
-
- SDL_Color colorb;
- if (b < 0) {
- colorb = fhsv_to_rgb((x*5 + y*12) % 360, 1.0, 0.5);
- colorb.a = 255;
- }
- else {
- colorb = fhsv_to_rgb((x*5 + y*12) % 360, 1.0, 1.0);
- colorb.a = 255;
- }
-
- vertices[0] = (SDL_Vertex){
- .color = colorb,
- .position = (SDL_FPoint){pos3.x, pos3.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
-
- vertices[1] = (SDL_Vertex){
- .color = colorb,
- .position = (SDL_FPoint){pos1.x, pos1.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
-
- vertices[2] = (SDL_Vertex){
- .color = colorb,
- .position = (SDL_FPoint){pos2.x, pos2.y},
- .tex_coord = (SDL_FPoint){0.0, 0.0}
- };
-
- SDL_RenderGeometry(example->renderer, NULL, vertices, 3, NULL, 0);
-
- #ifdef NV_COMPILER_MSVC
-
- free(vertices);
-
- #endif
- }
- }
- }
-}
-
-void draw_SHG(Example *example, TTF_Font *font) {
- SDL_SetRenderDrawColor(
- example->renderer,
- 70,
- 70,
- 70,
- 255
- );
-
- nvSHG *shg = example->space->shg;
- nvVector2 shg_min = world_to_screen(example, NV_VEC2(shg->bounds.min_x, shg->bounds.min_y));
- nvVector2 shg_max = world_to_screen(example, NV_VEC2(shg->bounds.max_x, shg->bounds.max_y));
-
- // Bounds
- SDL_FRect shg_rect = (SDL_FRect){
- shg_min.x,
- shg_min.y,
- shg_max.x - shg_min.x,
- shg_max.y - shg_min.y
- };
-
- SDL_RenderDrawRectF(example->renderer, &shg_rect);
-
- // Horizontal lines
- for (size_t y = 0; y < shg->rows; y++) {
- nvVector2 start = NV_VEC2(shg->bounds.min_x, shg->bounds.min_y + y * shg->cell_height);
- nvVector2 end = NV_VEC2(shg->bounds.min_x + shg->cols * shg->cell_width, shg->bounds.min_y + y * shg->cell_height);
- start = world_to_screen(example, start);
- end = world_to_screen(example, end);
-
- SDL_RenderDrawLine(
- example->renderer,
- start.x, start.y,
- end.x, end.y
- );
- }
-
- // Vertical lines
- for (size_t x = 0; x < shg->cols; x++) {
- nvVector2 start = NV_VEC2(shg->bounds.min_x + x * shg->cell_width, shg->bounds.min_y);
- nvVector2 end = NV_VEC2(shg->bounds.min_x + x * shg->cell_width, shg->bounds.min_y + shg->rows * shg->cell_height);
- start = world_to_screen(example, start);
- end = world_to_screen(example, end);
-
- SDL_RenderDrawLine(
- example->renderer,
- start.x, start.y,
- end.x, end.y
- );
- }
-
- if (example->space->multithreading) {
- nvAABB dyn_aabb = {NV_INF, NV_INF, -NV_INF, -NV_INF};
- for (size_t i = 0; i < example->space->bodies->size; i++) {
- nvBody *body = example->space->bodies->data[i];
- if (body->type == nvBodyType_STATIC) continue;
- nvAABB aabb = nvBody_get_aabb(body);
-
- dyn_aabb.min_x = nv_fmin(dyn_aabb.min_x, aabb.min_x);
- dyn_aabb.min_y = nv_fmin(dyn_aabb.min_y, aabb.min_y);
- dyn_aabb.max_x = nv_fmax(dyn_aabb.max_x, aabb.max_x);
- dyn_aabb.max_y = nv_fmax(dyn_aabb.max_y, aabb.max_y);
- }
-
- nv_float q = (dyn_aabb.max_x - dyn_aabb.min_x) / (nv_float)example->space->thread_count;
- for (size_t i = 0; i < example->space->bodies->size; i++) {
- nvBody *body = example->space->bodies->data[i];
- if (body->type == nvBodyType_STATIC) continue;
- nvAABB aabb = nvBody_get_aabb(body);
- nvVector2 p = world_to_screen(example, body->position);
-
- for (size_t j = 0; j < example->space->thread_count; j++) {
-
- nv_float s = (nv_float)j / (nv_float)example->space->thread_count * 256.0;
- SDL_Color color = hsv_to_rgb((SDL_Color){(nv_uint8)s, 255, 255});
- SDL_SetRenderDrawColor(example->renderer, color.r, color.g, color.b, 255);
-
- if (j == 0) {
- if (
- aabb.max_x >= dyn_aabb.min_x &&
- body->position.x <= q + dyn_aabb.min_x
- ) {
- draw_circle(example->renderer, p.x, p.y, 0.2 * example->zoom);
- break;
- }
- }
-
- else if (j == (example->space->thread_count - 1)) {
- if (
- aabb.min_x <= dyn_aabb.max_x &&
- body->position.x > q * (nv_float)(example->space->thread_count - 1) + dyn_aabb.min_x
- ) {
- draw_circle(example->renderer, p.x, p.y, 0.2 * example->zoom);
- break;
- }
- }
-
- else {
- if (
- body->position.x > q * (nv_float)(j) + dyn_aabb.min_x &&
- body->position.x <= q * (nv_float)(j + 1) + dyn_aabb.min_x
- ) {
- draw_circle(example->renderer, p.x, p.y, 0.2 * example->zoom);
- break;
- }
- }
- }
- }
-
- for (size_t j = 0; j < example->space->thread_count; j++) {
- SDL_SetRenderDrawColor(
- example->renderer,
- 99,
- 66,
- 66,
- 255
- );
-
- nvVector2 dyn_min = world_to_screen(example, NV_VEC2(dyn_aabb.min_x, dyn_aabb.min_y));
- nvVector2 dyn_max = world_to_screen(example, NV_VEC2(dyn_aabb.max_x, dyn_aabb.max_y));
-
- SDL_RenderDrawRect(
- example->renderer,
- &(SDL_Rect){
- dyn_min.x,
- dyn_min.y,
- dyn_max.x - dyn_min.x,
- dyn_max.y - dyn_min.y
- }
- );
-
- draw_dashed_line(
- example->renderer,
- round((((nv_float)j * q) * example->zoom + dyn_min.x)),
- dyn_min.y,
- round((((nv_float)j * q) * example->zoom + dyn_min.x)),
- dyn_min.y,
- 0.3 * example->zoom,
- 0.5 * example->zoom
- );
- }
- }
-}
-
-void draw_BVH(Example *example, nvBVHNode *node) {
- SDL_SetRenderDrawColor(
- example->renderer,
- 70,
- 70,
- 70,
- 255
- );
-
- SDL_FRect aabb_rect = (SDL_FRect){
- node->aabb.min_x*10.0,
- node->aabb.min_y*10.0,
- (node->aabb.max_x - node->aabb.min_x)*10.0,
- (node->aabb.max_y - node->aabb.min_y)*10.0
- };
-
- SDL_RenderDrawRectF(example->renderer, &aabb_rect);
-
- SDL_SetRenderDrawColor(
- example->renderer,
- 99,
- 66,
- 66,
- 255
- );
-
- if (!node->is_leaf) {
- nv_float width = node->aabb.max_x - node->aabb.min_x;
- nv_float height = node->aabb.max_y - node->aabb.min_y;
-
- if (width > height) {
- nv_float split = 0.0;
- for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
- split += body->position.x;
- }
- split /= (nv_float)node->bodies->size;
-
- draw_dashed_line(
- example->renderer,
- split * 10.0,
- node->aabb.min_y * 10.0,
- split * 10.0,
- node->aabb.max_y * 10.0,
- 3,
- 5
- );
- }
- else {
- nv_float split = 0.0;
- for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
- split += body->position.y;
- }
- split /= (nv_float)node->bodies->size;
-
- draw_dashed_line(
- example->renderer,
- node->aabb.min_x * 10.0,
- split * 10.0,
- node->aabb.max_x * 10.0,
- split * 10.0,
- 3,
- 5
- );
- }
-
- if (node->left != NULL) draw_BVH(example, node->left);
- if (node->right != NULL) draw_BVH(example, node->right);
- }
-}
-
-
-/**
- * @brief Update ToggleSwitch object.
- */
-void ToggleSwitch_update(struct _Example *example, ToggleSwitch *tg) {
- if (example->mouse.x < tg->x + tg->size && example->mouse.x > tg->x &&
- example->mouse.y < tg->y + tg->size && example->mouse.y > tg->y) {
-
- if (!example->selected && example->mouse.left && !tg->changed) {
- tg->on = !tg->on;
- tg->changed = true;
-
- if (tg == example->switches[7]) {
- if (tg->on)
- nvSpace_enable_sleeping(example->space);
- else
- nvSpace_disable_sleeping(example->space);
- }
-
- if (tg == example->switches[8])
- example->space->warmstarting = tg->on;
-
- if (tg == example->switches[12]) {
- if (tg->on)
- nvSpace_enable_multithreading(example->space, example->sliders[5]->value);
- else
- nvSpace_disable_multithreading(example->space);
- }
- }
- }
-}
-
-/**
- * @brief Draw ToggleSwitch object.
- */
-void ToggleSwitch_draw(struct _Example *example, ToggleSwitch *tg) {
- if (tg->on) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->ui_color.r,
- example->ui_color.g,
- example->ui_color.b,
- example->ui_color.a
- );
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){tg->x, tg->y, tg->size, tg->size});
- }
-
- SDL_SetRenderDrawColor(
- example->renderer,
- example->text_color.r,
- example->text_color.g,
- example->text_color.b,
- example->text_color.a
- );
-
- SDL_RenderDrawRect(example->renderer, &(SDL_Rect){tg->x, tg->y, tg->size, tg->size});
-}
-
-/**
- * @brief Update Slider object.
- */
-void Slider_update(struct _Example *example, Slider *s) {
- if (s->pressed) {
- int cx;
- if (example->mouse.x < s->x) cx = s->x;
- else if (example->mouse.x > s->x + s->width) cx = s->x + s->width;
- else cx = example->mouse.x;
- s->cx = cx;
- s->value = s->min + (((nv_float)cx - (nv_float)s->x) / (nv_float)s->width) * (s->max - s->min);
- }
-}
-
-/**
- * @brief Draw Slider object.
- */
-void Slider_draw(struct _Example *example, Slider *s) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->ui_color.r,
- example->ui_color.g,
- example->ui_color.b,
- example->ui_color.a
- );
-
- SDL_RenderFillRectF(
- example->renderer,
- &(SDL_FRect){
- s->x, s->y,
- s->width, 4.0
- }
- );
-
- SDL_SetRenderDrawColor(
- example->renderer,
- example->text_color.r,
- example->text_color.g,
- example->text_color.b,
- example->text_color.a
- );
-
- SDL_RenderDrawRectF(
- example->renderer,
- &(SDL_FRect){
- s->cx, s->y - 2.0,
- 3.0, 8.0
- }
- );
-}
-
-
-void Button_update(struct _Example *example, Button *b) {
- if (!example->selected) {
- if (example->mouse.x < b->x + b->width && example->mouse.x > b->x &&
- example->mouse.y < b->y + b->height && example->mouse.y > b->y) {
-
- b->hovered = true;
-
- if (example->mouse.left) {
- b->pressed = true;
- }
- }
- else
- b->hovered = false;
- }
-}
-
-void Button_draw(struct _Example *example, Button *b, TTF_Font *font) {
- if (b->pressed) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->ui_color.r,
- example->ui_color.g,
- example->ui_color.b,
- example->ui_color.a
- );
-
- SDL_RenderFillRect(example->renderer, &(SDL_Rect){b->x, b->y, b->width, b->height});
-
- SDL_SetRenderDrawColor(
- example->renderer,
- example->text_color.r,
- example->text_color.g,
- example->text_color.b,
- example->text_color.a
- );
- }
- else if (b->hovered) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->ui_color.r,
- example->ui_color.g,
- example->ui_color.b,
- example->ui_color.a
- );
- }
- else {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->text_color.r,
- example->text_color.g,
- example->text_color.b,
- example->text_color.a
- );
- }
-
- SDL_RenderDrawRect(example->renderer, &(SDL_Rect){b->x, b->y, b->width, b->height});
-
- draw_text_middle(example, font, example->renderer, b->text, b->x, b->y, b->width, b->height, example->text_color);
-}
-
-
-void button_callback(Button *button) {
- if (!strcmp(button->text, "Reset scene")) return;
-
- for (size_t i = 0; i < example_count; i++) {
- if (!strcmp(button->text, example_entries[i].name)) {
- current_example = i;
- return;
- }
- }
-}
-
-
-
-/******************************************************************************
-
- Main loop
-
-******************************************************************************/
-
-
-
-/**
- * @brief Entry point of the example.
- *
- * @param example Example to run
- */
-void Example_run(Example *example) {
- bool is_running = true;
- Uint64 start_perf;
- Uint64 start_perf_hi = SDL_GetPerformanceCounter();;
- Uint64 end_perf;
- Uint64 end_perf_hi;
- Uint64 step_time_start;
- Uint64 step_time_end;
- nv_float step_time_f;
- nv_float step_final = 0.0;
- size_t step_count = 0;
- Uint64 render_time_start;
- Uint64 render_time;
- nv_float render_time_f = 0.0;
- nv_float frequency = (nv_float)SDL_GetPerformanceFrequency();
- int frames = 0;
- int fps_every_f = 10;
-
- // Set random seed
- srand(time(NULL));
-
- SDL_Event event;
-
- nvBody *mouse_body = nvBody_new(
- nvBodyType_STATIC,
- nvCircleShape_new(0.1),
- nvVector2_zero,
- 0.0,
- nvMaterial_BASIC
- );
- mouse_body->enable_collision = false;
- nvSpace_add(example->space, mouse_body);
-
- nvBody *selected = NULL;
- nvConstraint *selected_const = NULL;
- nvVector2 selected_posf = nvVector2_zero;
- nvVector2 selected_pos = nvVector2_zero;
-
- TTF_Font *font;
-
- font = TTF_OpenFont("assets/FiraCode-Regular.ttf", 11);
- if (font == NULL) {
- printf("Couldn't load assets/FiraCode-Regular.ttf\n");
- exit(1);
- }
- TTF_SetFontStyle(font, TTF_STYLE_NORMAL);
- TTF_SetFontOutline(font, 0);
- TTF_SetFontKerning(font, 1);
- TTF_SetFontHinting(font, TTF_HINTING_NORMAL);
-
- // MSVC doesn't allow variable length arrays
- size_t switches_n = 14;
- ToggleSwitch **switches = malloc(sizeof(ToggleSwitch) * switches_n);
-
- switches[0] = &(ToggleSwitch){
- .x = 118+6, .y = 63+4+32-5,
- .size = 9, .on = false
- };
-
- switches[1] = &(ToggleSwitch){
- .x = 118+6, .y = 95+4+32-5,
- .size = 9, .on = false
- };
-
- switches[2] = &(ToggleSwitch){
- .x = 118+6, .y = 111+4+32-5,
- .size = 9, .on = false
- };
-
- switches[3] = &(ToggleSwitch){
- .x = 118+6, .y = 127+4+32-5,
- .size = 9, .on = false
- };
-
- switches[4] = &(ToggleSwitch){
- .x = 118+6, .y = 143+4+32-5,
- .size = 9, .on = true
- };
-
- switches[5] = &(ToggleSwitch){
- .x = 118+6, .y = 159+4+32-5,
- .size = 9, .on = false
- };
-
- switches[6] = &(ToggleSwitch){
- .x = 118+6, .y = 175+4+32-5,
- .size = 9, .on = false
- };
-
- switches[7] = &(ToggleSwitch){
- .x = 118+6, .y = 207+4+32-5,
- .size = 9, .on = false
- };
-
- switches[8] = &(ToggleSwitch){
- .x = 118+6, .y = 223+4+32-5,
- .size = 9, .on = true
- };
-
- switches[9] = &(ToggleSwitch){
- .x = 118+6, .y = 79+4+32-5,
- .size = 9, .on = false
- };
-
- switches[10] = &(ToggleSwitch){
- .x = 118+34, .y = 383+15,
- .size = 9, .on = false
- };
-
- switches[11] = &(ToggleSwitch){
- .x = 118+34, .y = 383+16+15,
- .size = 9, .on = true
- };
-
- switches[12] = &(ToggleSwitch){
- .x = 210, .y = 94,
- .size = 9, .on = false
- };
-
- // draw coms
- switches[13] = &(ToggleSwitch){
- .x = 118+6, .y = 192+4+32-5,
- .size = 9, .on = false
- };
-
- example->switches = switches;
- example->switch_count = switches_n;
-
- size_t sliders_n = 6;
- Slider **sliders = malloc(sizeof(Slider) * sliders_n);
-
- int slider_offset = 25;
-
- sliders[0] = &(Slider){
- .x = 135-slider_offset, .y = 271+15,
- .width = 80,
- .min = 1, .max = 50, .value = 10,
- .type=SliderType_INTEGER
- };
- sliders[0]->cx = sliders[0]->x + ((sliders[0]->value-sliders[0]->min) / (sliders[0]->max - sliders[0]->min)) * sliders[0]->width;
-
- sliders[1] = &(Slider){
- .x = 135-slider_offset, .y = 271+15 + (21*1),
- .width = 80,
- .min = 1, .max = 50, .value = 10,
- .type=SliderType_INTEGER
- };
- sliders[1]->cx = sliders[1]->x + ((sliders[1]->value-sliders[1]->min) / (sliders[1]->max - sliders[1]->min)) * sliders[1]->width;
-
- sliders[2] = &(Slider){
- .x = 135-slider_offset, .y = 271+15 + (21*2),
- .width = 80,
- .min = 1, .max = 50, .value = 5,
- .type=SliderType_INTEGER
- };
- sliders[2]->cx = sliders[2]->x + ((sliders[2]->value-sliders[2]->min) / (sliders[2]->max - sliders[2]->min)) * sliders[2]->width;
-
- sliders[3] = &(Slider){
- .x = 135-slider_offset, .y = 271+15 + (21*3),
- .width = 80,
- .min = 1, .max = 10, .value = 1,
- .type=SliderType_INTEGER
- };
- sliders[3]->cx = sliders[3]->x + ((sliders[3]->value-sliders[3]->min) / (sliders[3]->max - sliders[3]->min)) * sliders[3]->width;
-
- sliders[4] = &(Slider){
- .x = 135-slider_offset, .y = 271+15 + (21*4),
- .width = 80,
- .min = 12.0, .max = 240.0, .value = 60.0,
- .type=SliderType_INTEGER
- };
- sliders[4]->cx = sliders[4]->x + ((sliders[4]->value-sliders[4]->min) / (sliders[4]->max - sliders[4]->min)) * sliders[4]->width;
-
- nv_uint32 max_threads = nv_get_cpu_count();
-
- sliders[5] = &(Slider){
- .x = 145, .y = 113,
- .width = 80,
- .min = 1, .max = max_threads, .value = max_threads,
- .type=SliderType_INTEGER
- };
- sliders[5]->cx = sliders[5]->x + ((sliders[5]->value-sliders[5]->min) / (sliders[5]->max - sliders[5]->min)) * sliders[5]->width;
-
- example->sliders = sliders;
- example->slider_count = sliders_n;
-
- size_t buttons_n = 18;
- Button **buttons = malloc(sizeof(Button) * buttons_n);
-
- int button_height = 23;
-
- buttons[0] = &(Button){
- .x=5, .y=445,
- .width=117, .height=button_height,
- .text="Arch",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[1] = &(Button){
- .x=5, .y=445+(button_height+5)*1,
- .width=117, .height=button_height,
- .text="Bridge",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[2] = &(Button){
- .x=5, .y=445+(button_height+5)*2,
- .width=117, .height=button_height,
- .text="Chains",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[3] = &(Button){
- .x=5, .y=445+(button_height+5)*3,
- .width=117, .height=button_height,
- .text="Circle Stack",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[4] = &(Button){
- .x=5, .y=445+(button_height+5)*4,
- .width=117, .height=button_height,
- .text="Cloth",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[5] = &(Button){
- .x=5, .y=445+(button_height+5)*5,
- .width=117, .height=button_height,
- .text="Constraints",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[6] = &(Button){
- .x=5, .y=445+(button_height+5)*6,
- .width=117, .height=button_height,
- .text="Domino",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[7] = &(Button){
- .x=5, .y=445+(button_height+5)*7,
- .width=117, .height=button_height,
- .text="Fountain",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[8] = &(Button){
- .x=127, .y=445+(button_height+5)*0,
- .width=117, .height=button_height,
- .text="Hull",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[9] = &(Button){
- .x=127, .y=445+(button_height+5)*1,
- .width=117, .height=button_height,
- .text="Newton's Cradle",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[10] = &(Button){
- .x=127, .y=445+(button_height+5)*2,
- .width=117, .height=button_height,
- .text="Orbit",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[11] = &(Button){
- .x=127, .y=445+(button_height+5)*3,
- .width=117, .height=button_height,
- .text="Pool",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[12] = &(Button){
- .x=127, .y=445+(button_height+5)*4,
- .width=117, .height=button_height,
- .text="Pyramid",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[13] = &(Button){
- .x=127, .y=445+(button_height+5)*5,
- .width=117, .height=button_height,
- .text="Spring Car",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[14] = &(Button){
- .x=127, .y=445+(button_height+5)*6,
- .width=117, .height=button_height,
- .text="Stack",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[15] = &(Button){
- .x=127, .y=445+(button_height+5)*7,
- .width=117, .height=button_height,
- .text="Varying Bounce",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[16] = &(Button){
- .x=127, .y=445+(button_height+5)*8,
- .width=117, .height=button_height,
- .text="Varying Friction",
- .callback=(void (*)(void *))button_callback
- };
-
- buttons[17] = &(Button){
- .x=example->width - 250 + 5, .y=200+34,
- .width=117, .height=button_height,
- .text="Reset scene",
- .callback=(void (*)(void *))button_callback
- };
-
- example->buttons = buttons;
- example->button_count = buttons_n;
-
- if (example_entries[current_example].setup_callback != NULL)
- example_entries[current_example].setup_callback(example);
-
- nv_uint64 step_counter = 0;
- nv_uint64 render_counter = 0;
- nv_uint64 frame_counter = 0;
-
- bool frame_by_frame = false;
- bool next_frame = false;
-
- while (is_running) {
- start_perf = SDL_GetTicks64();
- next_frame = false;
-
- SDL_GetMouseState(&example->mouse.x, &example->mouse.y);
- example->mouse.before_zoom = screen_to_world(example, NV_VEC2(example->mouse.x, example->mouse.y));
-
- // Handle events
- while(SDL_PollEvent(&event) != 0) {
- if (event.type == SDL_QUIT)
- is_running = false;
-
- else if (event.type == SDL_WINDOWEVENT) {
- if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
- example->width = event.window.data1;
- example->height = event.window.data2;
- }
- }
-
- else if (event.type == SDL_MOUSEBUTTONDOWN) {
- if (event.button.button == SDL_BUTTON_LEFT)
- example->mouse.left = true;
-
- else if (event.button.button == SDL_BUTTON_MIDDLE) {
- example->mouse.middle = true;
- example->pan_start = NV_VEC2(example->mouse.x, example->mouse.y);
- }
-
- else if (event.button.button == SDL_BUTTON_RIGHT)
- example->mouse.right = true;
-
- if (example->mouse.left) {
- selected = NULL;
- if (nv_collide_aabb_x_point((nvAABB){250.0, 0.0, example->width, example->height}, NV_VEC2(example->mouse.x, example->mouse.y))) {
- for (size_t i = 0; i < example->space->bodies->size; i++) {
- nvBody *body = (nvBody *)example->space->bodies->data[i];
- if (body->type == nvBodyType_STATIC) continue;
-
- bool inside = false;
- nvShape *shape = body->shape;
-
- if (shape->type == nvShapeType_POLYGON) {
- nvBody_local_to_world(body);
- inside = nv_collide_polygon_x_point(body, example->mouse.after_zoom);
- }
- else if (shape->type == nvShapeType_CIRCLE) {
- inside = nv_collide_circle_x_point(body, example->mouse.after_zoom);
- }
-
- if (inside) {
- selected = body;
- example->selected = true;
-
- // Transform mouse coordinatets to body local coordinates
- selected_posf = example->mouse.after_zoom;
- selected_posf = nvVector2_sub(selected_posf, selected->position);
- selected_posf = nvVector2_rotate(selected_posf, -selected->angle);
-
- selected_pos = NV_VEC2(selected_posf.x+0.00001, selected_posf.y+0.00001);
-
- nv_float strength = 150.0 * selected->mass / 3.0;
- nv_float damping = 70.0 * selected->mass / 4.0;
-
- if (!strcmp(example_entries[current_example].name, "Cloth")) {
- strength *= 10.0;
- damping *= 2.0;
- }
-
- selected_const = nvSpring_new(
- mouse_body, selected,
- nvVector2_zero, selected_pos,
- 0.0, strength, damping
- );
-
- nvSpace_add_constraint(example->space, selected_const);
-
- if (selected->is_sleeping) nvBody_awake(selected);
-
- break;
- }
- }
- }
-
- for (size_t i = 0; i < example->slider_count; i++) {
- Slider *s = example->sliders[i];
-
- if (example->mouse.x < s->x + s->width && example->mouse.x > s->x &&
- example->mouse.y < s->y + 10.0 && example->mouse.y > s->y - 4.0) {
-
- s->pressed = true;
- break;
- }
- }
-
- for (size_t i = 0; i < example_entries[current_example].slider_settings->size; i++) {
- Slider *s = ((SliderSetting *)example_entries[current_example].slider_settings->data[i])->slider;
-
- if (example->mouse.x < s->x + s->width && example->mouse.x > s->x &&
- example->mouse.y < s->y + 10.0 && example->mouse.y > s->y - 4.0) {
-
- s->pressed = true;
- break;
- }
- }
- }
- }
-
- else if (event.type == SDL_MOUSEBUTTONUP) {
- if (event.button.button == SDL_BUTTON_LEFT) {
- example->mouse.left = false;
- selected = NULL;
- example->selected = false;
-
- if (selected_const != NULL) {
- nvArray_remove(example->space->constraints, selected_const);
- nvConstraint_free(selected_const);
- selected_const = NULL;
- }
-
- for (size_t i = 0; i < switches_n; i++) {
- switches[i]->changed = false;
- }
-
- for (size_t i = 0; i < sliders_n; i++) {
- sliders[i]->pressed = false;
-
- if (i == 5 && switches[12]->on) {
- nvSpace_disable_multithreading(example->space);
- nvSpace_enable_multithreading(example->space, sliders[i]->value);
- }
- }
-
- for (size_t i = 0; i < example_entries[current_example].slider_settings->size; i++) {
- ((SliderSetting *)example_entries[current_example].slider_settings->data[i])->slider->pressed = false;
- }
-
- for (size_t i = 0; i < buttons_n; i++) {
- if (buttons[i]->pressed) {
- buttons[i]->pressed = false;
- if (buttons[i]->callback) {
- selected = NULL;
- if (selected_const != NULL) {
- nvArray_remove(example->space->constraints, selected_const);
- nvConstraint_free(selected_const);
- selected_const = NULL;
- }
-
- nvSpace_clear(example->space);
- example->space->_id_counter = 0;
-
- mouse_body = nvBody_new(
- nvBodyType_STATIC,
- nvCircleShape_new(0.1),
- nvVector2_zero,
- 0.0,
- nvMaterial_BASIC
- );
- mouse_body->enable_collision = false;
- mouse_body->position = NV_VEC2(example->mouse.px, example->mouse.py);
- mouse_body->_cache_aabb = false;
- nvSpace_add(example->space, mouse_body);
-
- example->counter = 0;
-
- buttons[i]->callback(buttons[i]);
-
- example->space->gravity = NV_VEC2(0.0, NV_GRAV_EARTH);
-
- if (example->space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID)
- nvSpace_set_SHG(example->space, (nvAABB){0.0, 0.0, 128.0, 72.0}, 3.0, 3.0);
-
- if (example_entries[current_example].setup_callback != NULL)
- example_entries[current_example].setup_callback(example);
-
- step_count = 0;
- step_final = 0.0;
-
- if (!strcmp(example_entries[current_example].name, "Cloth")) {
- example->cloth_example_cols = get_slider_setting("Columns");
- example->cloth_example_rows = get_slider_setting("Rows");
- }
- }
- }
- }
- }
-
- else if (event.button.button == SDL_BUTTON_MIDDLE)
- example->mouse.middle = false;
-
- else if (event.button.button == SDL_BUTTON_RIGHT)
- example->mouse.right = false;
- }
-
- else if (event.type == SDL_MOUSEWHEEL) {
- if (event.wheel.y > 0) {
- example->zoom *= 1 + example->zoom_scale;
- }
-
- else if (event.wheel.y < 0) {
- example->zoom *= 1 - example->zoom_scale;
- }
- }
-
- else if (event.type == SDL_KEYDOWN) {
- if (event.key.keysym.scancode == SDL_SCANCODE_Q) {
- for (size_t i = 0; i < example->space->bodies->size; i++) {
- nvBody *body = (nvBody *)example->space->bodies->data[i];
- if (body->type == nvBodyType_STATIC) continue;
-
- nvVector2 delta = nvVector2_sub(
- body->position,
- screen_to_world(example, NV_VEC2(example->mouse.x, example->mouse.y))
- );
-
- nv_float strength = 10.0 * pow(10.0, 3.0);
-
- if (!strcmp(example_entries[current_example].name, "Cloth")) {
- strength /= 30.0;
- }
-
- nvVector2 force = nvVector2_mul(delta, strength);
- force = nvVector2_div(force, nvVector2_len(delta));
-
- nvBody_apply_force(body, force);
- }
- }
-
- else if (event.key.keysym.scancode == SDL_SCANCODE_R) {
- example->camera = NV_VEC2(example->width / 20.0, example->height / 20.0);
- example->zoom = 10.0;
- example->pan_start = nvVector2_zero;
- example->mouse.before_zoom = nvVector2_zero;
- example->mouse.after_zoom = nvVector2_zero;
- example->mouse.x = 0;
- example->mouse.y = 0;
-
- selected = NULL;
- if (selected_const != NULL) {
- nvArray_remove(example->space->constraints, selected_const);
- nvConstraint_free(selected_const);
- selected_const = NULL;
- }
-
- nvSpace_clear(example->space);
- example->space->_id_counter = 0;
-
- mouse_body = nvBody_new(
- nvBodyType_STATIC,
- nvCircleShape_new(0.1),
- nvVector2_zero,
- 0.0,
- nvMaterial_BASIC
- );
- mouse_body->enable_collision = false;
- mouse_body->position = nvVector2_zero;
- mouse_body->_cache_aabb = false;
- nvSpace_add(example->space, mouse_body);
-
- example->counter = 0;
-
- if (example_entries[current_example].setup_callback != NULL)
- example_entries[current_example].setup_callback(example);
-
- if (!strcmp(example_entries[current_example].name, "Cloth")) {
- example->cloth_example_cols = get_slider_setting("Columns");
- example->cloth_example_rows = get_slider_setting("Rows");
- }
-
- step_count = 0;
- step_final = 0.0;
-
- }
-
- else if (event.key.keysym.scancode == SDL_SCANCODE_U) {
- example->draw_ui = !example->draw_ui;
- }
-
- else if (event.key.keysym.scancode == SDL_SCANCODE_PERIOD) {
- frame_by_frame = !frame_by_frame;
- }
-
- else if (event.key.keysym.scancode == SDL_SCANCODE_SLASH) {
- next_frame = true;
- }
-
- else if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) {
- is_running = false;
- }
- }
- }
-
- example->mouse.after_zoom = screen_to_world(example, NV_VEC2(example->mouse.x, example->mouse.y));
-
- if (example->mouse.middle) {
- example->camera = nvVector2_sub(example->camera, nvVector2_div(nvVector2_sub(NV_VEC2(example->mouse.x, example->mouse.y), example->pan_start), example->zoom));
- example->pan_start = NV_VEC2(example->mouse.x, example->mouse.y);
- }
-
- example->camera = nvVector2_add(example->camera, nvVector2_sub(example->mouse.before_zoom, example->mouse.after_zoom));
-
- mouse_body->position = example->mouse.before_zoom;
- mouse_body->_cache_aabb = false;
-
- // Call example callback if there is one
- if (!frame_by_frame || (frame_by_frame && next_frame)) {
- if (example_entries[current_example].update_callback != NULL)
- example_entries[current_example].update_callback(example);
- }
-
- render_time_start = SDL_GetPerformanceCounter();
-
- // Clear display
- SDL_SetRenderDrawColor(
- example->renderer,
- example->bg_color.r,
- example->bg_color.g,
- example->bg_color.b,
- 255
- );
- SDL_RenderClear(example->renderer);
-
- if (example->switches[6]->on) {
- switch (example->space->broadphase_algorithm) {
- case nvBroadPhaseAlg_BRUTE_FORCE:
- break;
-
- case nvBroadPhaseAlg_SPATIAL_HASH_GRID:
- draw_SHG(example, font);
- break;
-
- case nvBroadPhaseAlg_BOUNDING_VOLUME_HIERARCHY:
- nvBVHNode *bvh_tree = nvBVHTree_new(example->space->bodies);
- draw_BVH(example, bvh_tree);
- nvBVHTree_free(bvh_tree);
- break;
- }
- }
-
- if (!strcmp(example_entries[current_example].name, "Cloth")) {
- draw_cloth(example);
- }
- else {
- draw_bodies(example, font);
- }
-
- draw_constraints(example);
-
- // Draw the constraint between selected object and mouse
- if (selected) {
- SDL_SetRenderDrawColor(
- example->renderer,
- example->alt_text_color.r,
- example->alt_text_color.g,
- example->alt_text_color.b,
- example->alt_text_color.a
- );
-
- // Transform selection anchor point to world space
- nvVector2 anchor = nvVector2_rotate(selected_posf, selected->angle);
- anchor = world_to_screen(example, nvVector2_add(selected->position, anchor));
- nvVector2 p = world_to_screen(example, mouse_body->position);
-
- if (example->switches[0]->on) {
- draw_aaline(
- example->renderer,
- p.x,
- p.y,
- anchor.x,
- anchor.y
- );
- }
- else {
- SDL_RenderDrawLineF(
- example->renderer,
- p.x,
- p.y,
- anchor.x,
- anchor.y
- );
- }
- }
-
- draw_ui(example, font);
-
- // Sanity control
- if (example->cached_texts->count > 5000) {
- size_t cached_i = 0;
- void *cached_val;
- while (nvHashMap_iter(example->cached_texts, &cached_i, &cached_val)) {
- CachedText *cached_text = (CachedText *)cached_val;
-
- SDL_DestroyTexture(cached_text->texture);
- free(cached_text->string);
- }
-
- nvHashMap_clear(example->cached_texts);
- }
- else {
- nvArray *pending_delete = nvArray_new();
-
- nv_uint64 current_time = time(NULL);
- size_t cached_i = 0;
- void *cached_val;
- while (nvHashMap_iter(example->cached_texts, &cached_i, &cached_val)) {
- CachedText *cached_text = (CachedText *)cached_val;
-
- if (current_time - cached_text->last_access > 5) {
- SDL_DestroyTexture(cached_text->texture);
- // WHY CAN'T I FREE THE STRING HERE ???
- // free(cached_text->string);
- nvArray_add(pending_delete, cached_text->string);
- nvHashMap_remove(example->cached_texts, cached_text);
-
- cached_i = 0;
- }
- }
-
- nvArray_free_each(pending_delete, free);
- nvArray_free(pending_delete);
- }
-
- // Calculate elapsed time during rendering
- render_time = SDL_GetPerformanceCounter() - render_time_start;
- render_time_f = (nv_float)render_time / frequency * 1000.0;
- example->render_time = render_time_f;
- example->render_counter += example->render_time;
- if (render_counter == 15) {
- example->render_avg = example->render_counter / (nv_float)render_counter;
- render_counter = 0;
- example->render_counter = 0.0;
- }
-
-
- // Advance the simulation
- // The only reason of advancing the simulation after rendering is
- // to render contact points more visible. Ideally the main loop
- // would look like: events -> update -> render -> loop
- if (!frame_by_frame || (frame_by_frame && next_frame)) {
- step_time_start = SDL_GetPerformanceCounter();
-
- nvSpace_step(
- example->space,
- 1.0 / example->sliders[4]->value,
- (int)example->sliders[0]->value,
- (int)example->sliders[1]->value,
- (int)example->sliders[2]->value,
- (int)example->sliders[3]->value
- );
-
- step_time_end = SDL_GetPerformanceCounter() - step_time_start;
- step_time_f = (nv_float)step_time_end / frequency * 1000.0;
- example->step_time = step_time_f;
- example->step_counter += example->step_time;
- step_final += example->step_time;
- if (step_counter == 15) {
- example->step_avg = example->step_counter / (double)step_counter;
- step_counter = 0;
- example->step_counter = 0.0;
- }
- }
-
- if (example->space->after_collision != NULL)
- example->space->after_collision(example->space->res, example->space->callback_user_data);
-
- // Update the display
- SDL_RenderPresent(example->renderer);
-
- // Sync current fps with max_fps
- end_perf = SDL_GetTicks64();
-
- Uint64 frame = end_perf - start_perf;
-
- frames++;
- if (frames == fps_every_f) {
- end_perf_hi = SDL_GetPerformanceCounter();
- nv_float start = (nv_float)start_perf_hi / frequency;
- nv_float end = (nv_float)end_perf_hi / frequency;
-
- example->fps = (nv_float)fps_every_f / (end - start);
-
- frames = 0;
- start_perf_hi = SDL_GetPerformanceCounter();
- }
-
- if (frame < (1000 / example->max_fps)) {
- SDL_Delay((1000 / example->max_fps) - frame);
- }
-
- if (!frame_by_frame || (frame_by_frame && next_frame))
- example->counter++;
- step_counter++;
- step_count++;
- render_counter++;
- frame_counter++;
- }
-}
-
-
-#endif
\ No newline at end of file
diff --git a/examples/fountain.h b/examples/fountain.h
deleted file mode 100644
index 1e81168..0000000
--- a/examples/fountain.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void FountainExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create ground & walls
-
- nv_float offset = 0.5;
-
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 72.0 + 2.5 - offset),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
- nvBody *ceiling = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 0 - 2.5 + offset),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ceiling);
-
- nvBody *walll = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 72.0),
- NV_VEC2(0.0 - 2.5 + offset, 36.0),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, walll);
-
- nvBody *wallr = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 72.0),
- NV_VEC2(128.0 + 2.5 - offset, 36.0),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, wallr);
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID) {
- // The boundary can't be divided by 3.0 so some walls are left outside the SHG
- // To solve this just make SHG boundaries slightly bigger
- nvAABB bounds = {0.0, 0.0, 129.0, 75.0};
- nvSpace_set_SHG(space, bounds, 3.0, 3.0);
- }
-}
-
-
-void FountainExample_update(Example *example) {
- nvSpace *space = example->space;
-
- if (space->bodies->size > get_slider_setting("Max bodies")) return;
-
- if (example->counter <= get_slider_setting("Spawn rate")) return;
- else example->counter = 0;
-
- nvMaterial basic_material = {
- .density = 1.0,
- .restitution = 0.1,
- .friction = 0.1
- };
-
- nvBody *body;
- nv_float n = 4;
- nv_float size = 2.5;
- int mode = get_slider_setting("Mode");
-
- for (size_t x = 0; x < n; x++) {
-
- if (mode == 0) {
- int r = ((space->bodies->size % 7) + x) % 4;
-
- // Circle
- if (r == 0) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(size / 2.0 + 0.03),
- NV_VEC2(
- 64.0 - (n * size) / 2.0 + size / 2.0 + size * x,
- 10.0
- ),
- 0.0,
- basic_material
- );
- }
- // Box
- else if (r == 1) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(size, size),
- NV_VEC2(
- 64.0 - (n * size) / 2.0 + size / 2.0 + size* x,
- 10.0
- ),
- 0.0,
- basic_material
- );
- }
- // Pentagon
- else if (r == 2) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(6, size),
- NV_VEC2(
- 64.0 - (n * size) / 2.0 + size / 2.0 + size * x,
- 10.0
- ),
- 0.0,
- basic_material
- );
- }
- // Triangle
- else if (r == 3) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvNGonShape_new(3, size),
- NV_VEC2(
- 64.0 - (n * size) / 2.0 + size / 2.0 + size * x,
- 10.0
- ),
- 0.0,
- basic_material
- );
- }
-
- // Have all bodies have the same mass and inertia
- nvBody_set_mass(body, 3.5);
-
- nvSpace_add(space, body);
-
- // Apply downward force
- nv_float strength = 10.0 * 1e3;
- nvBody_apply_force(body, NV_VEC2(0.0, strength));
- }
-
- else if (mode == 1) {
- body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(frand(1.5, 2.5), frand(2.5, 4.7)),
- NV_VEC2(
- 64.0 - (n * size) / 2.0 + size / 2.0 + size * x,
- 10.0
- ),
- frand(0.0, NV_PI * 2.0),
- basic_material
- );
-
- nvSpace_add(space, body);
-
- nv_float strength = 5.0 * 1e4;
- nvBody_apply_force(body, NV_VEC2(0.0, strength));
- body->torque += frand(1e4, 3.0 * 1e4);
- }
- }
-}
-
-
-void FountainExample_init(ExampleEntry *entry) {
- add_slider_setting(entry, "Max bodies", SliderType_INTEGER, 1500, 500, 2000);
- add_slider_setting(entry, "Spawn rate", SliderType_INTEGER, 5, 1, 10);
- add_slider_setting(entry, "Mode", SliderType_INTEGER, 0, 0, 1);
-
-}
\ No newline at end of file
diff --git a/examples/hull.h b/examples/hull.h
deleted file mode 100644
index 5e77a64..0000000
--- a/examples/hull.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void HullExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create ground
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 62.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
- for (size_t i = 0; i < 20; i++) {
-
- // Random points to generate a convex hull from
- nvArray *points = nvArray_new();
- for (size_t j = 0; j < 15; j++) {
- nvArray_add(points, NV_VEC2_NEW(frand(-7.0, 7.0), frand(-7.0, 7.0)));
- }
-
- nvBody *rock = nvBody_new(
- nvBodyType_DYNAMIC,
- nvConvexHullShape_new(points),
- NV_VEC2(frand(50.0, 78.0), frand(17.0, 35.0)),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, rock);
-
- // The points are not needed after the convex hull generation
- nvArray_free_each(points, free);
- nvArray_free(points);
- }
-}
\ No newline at end of file
diff --git a/examples/main.c b/examples/main.c
new file mode 100644
index 0000000..3a3a9f3
--- /dev/null
+++ b/examples/main.c
@@ -0,0 +1,1824 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "common.h"
+#include "ngl.h"
+#include "clock.h"
+
+// I wish #include "demos/*.h" was a standard :(
+#include "demos/demo_stack.h"
+#include "demos/demo_compound.h"
+#include "demos/demo_pyramid.h"
+#include "demos/demo_softbody.h"
+#include "demos/demo_rocks.h"
+#include "demos/demo_contact_event.h"
+
+#include "demos/demo_distance_constraint.h"
+#include "demos/demo_hinge_constraint.h"
+#include "demos/demo_spline_constraint.h"
+
+#include "demos/demo_bouncing.h"
+#include "demos/demo_friction.h"
+#include "demos/demo_damping.h"
+#include "demos/demo_density.h"
+
+/**
+ * @file examples/main.c
+ *
+ * This file is just the entry point for the opengl app and is pretty crowded.
+ * If you are looking individual demos go to demos/ subfolder.
+ */
+
+
+#define NUKLEAR_MAX_VERTEX_MEMORY 100 * 1024
+#define NUKLEAR_MAX_ELEMENT_MEMORY 25 * 1024
+
+// 500,000 * 24 * 4(bytes) = ~45 MBs of pre allocated vertex memory
+#define EXAMPLE_MAX_TRIANGlES 500000
+#define EXAMPLE_MAX_TRI_VERTICES EXAMPLE_MAX_TRIANGlES * 6
+#define EXAMPLE_MAX_TRI_COLORS EXAMPLE_MAX_TRIANGlES * 4 * 3
+#define EXAMPLE_MAX_LINE_VERTICES EXAMPLE_MAX_TRIANGlES * 2
+#define EXAMPLE_MAX_LINE_COLORS EXAMPLE_MAX_TRIANGlES * 4
+
+#define CIRCLE_VERTICES 20
+
+#define ZOOM_SCALE 0.075
+
+#define ADD_TRIANGLE(x0, y0, x1, y1, x2, y2, r, g, b, a) { \
+ tri_vertices[tri_vertices_index] = (float)x0; \
+ tri_vertices[tri_vertices_index + 1] = (float)y0; \
+ tri_vertices[tri_vertices_index + 2] = (float)x1; \
+ tri_vertices[tri_vertices_index + 3] = (float)y1; \
+ tri_vertices[tri_vertices_index + 4] = (float)x2; \
+ tri_vertices[tri_vertices_index + 5] = (float)y2; \
+ tri_vertices_index += 6; \
+ \
+ for (size_t j = 0; j < 3; j++) { \
+ tri_colors[tri_colors_index] = (float)r; \
+ tri_colors[tri_colors_index + 1] = (float)g; \
+ tri_colors[tri_colors_index + 2] = (float)b; \
+ tri_colors[tri_colors_index + 3] = (float)a; \
+ tri_colors_index += 4; \
+ } \
+ \
+ vao0_count += 3; \
+}
+
+#define ADD_LINE(x, y, r, g, b, a) { \
+ line_vertices[line_vertices_index] = (float)x; \
+ line_vertices[line_vertices_index + 1] = (float)y; \
+ line_vertices_index += 2; \
+ \
+ line_colors[line_colors_index] = (float)r; \
+ line_colors[line_colors_index + 1] = (float)g; \
+ line_colors[line_colors_index + 2] = (float)b; \
+ line_colors[line_colors_index + 3] = (float)a; \
+ line_colors_index += 4; \
+ \
+ vao1_count += 1; \
+}
+
+ExampleEntry example_entries[EXAMPLE_MAX_ENTRIES] = {NULL};
+size_t example_count = 0;
+size_t current_example = 0;
+
+void ExampleEntry_register(
+ char *name,
+ ExampleCallback setup,
+ ExampleCallback update
+) {
+ example_entries[example_count++] = (ExampleEntry){
+ .name=name,
+ .setup=setup,
+ .update=update
+ };
+}
+
+void ExampleContext_apply_settings(
+ ExampleContext *example,
+ ExampleSettings settings
+) {
+ example->window_width = settings.window_width;
+ example->window_height = settings.window_height;
+}
+
+void setup_ui(ExampleContext *example) {
+ example->ui_ctx = nk_sdl_init(example->window);
+
+ struct nk_color accent = nk_rgb(
+ (int)(example->theme.ui_accent.r * 255.0),
+ (int)(example->theme.ui_accent.g * 255.0),
+ (int)(example->theme.ui_accent.b * 255.0)
+ );
+ struct nk_color accent_light = nk_rgb(
+ (int)((example->theme.ui_accent.r + 0.1) * 255.0),
+ (int)((example->theme.ui_accent.g + 0.1) * 255.0),
+ (int)((example->theme.ui_accent.b + 0.1) * 255.0)
+ );
+ struct nk_color text = nk_rgb(
+ (int)(example->theme.ui_text.r * 255.0),
+ (int)(example->theme.ui_text.g * 255.0),
+ (int)(example->theme.ui_text.b * 255.0)
+ );
+
+ example->ui_ctx->style.window.fixed_background = nk_style_item_color(nk_rgba(17, 17, 20, 210));
+ example->ui_ctx->style.window.border = 0;
+ example->ui_ctx->style.window.header.active = nk_style_item_color(accent);
+ example->ui_ctx->style.window.header.normal = nk_style_item_color(accent);
+ example->ui_ctx->style.window.header.label_active = text;
+ example->ui_ctx->style.window.header.label_normal = text;
+ example->ui_ctx->style.window.header.label_padding = (struct nk_vec2){5.0, 2.0};
+ example->ui_ctx->style.window.header.minimize_button.text_active = text;
+ example->ui_ctx->style.window.header.minimize_button.text_normal = text;
+ example->ui_ctx->style.window.header.minimize_button.text_hover = text;
+ example->ui_ctx->style.window.header.minimize_button.active = nk_style_item_color(nk_rgba(255, 255, 255, 80));
+ example->ui_ctx->style.window.header.minimize_button.hover = nk_style_item_color(nk_rgba(255, 255, 255, 80));
+ example->ui_ctx->style.window.header.minimize_button.normal = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.window.header.padding = (struct nk_vec2){5.0, 2.0};
+ example->ui_ctx->style.window.padding = (struct nk_vec2){5.0, 6.0};
+ example->ui_ctx->style.text.color = text;
+
+ example->ui_ctx->style.button.rounding = 0;
+ example->ui_ctx->style.button.active = nk_style_item_color(accent);
+ example->ui_ctx->style.button.text_active = text;
+ example->ui_ctx->style.button.text_normal = text;
+ example->ui_ctx->style.button.text_hover = text;
+
+ example->ui_ctx->style.checkbox.text_active = text;
+ example->ui_ctx->style.checkbox.text_normal = text;
+ example->ui_ctx->style.checkbox.text_hover = text;
+ example->ui_ctx->style.checkbox.padding = (struct nk_vec2){3.0, 3.0};
+ example->ui_ctx->style.checkbox.active = nk_style_item_color(nk_rgb(37, 36, 38));
+ example->ui_ctx->style.checkbox.hover = nk_style_item_color(nk_rgb(55, 53, 56));
+ example->ui_ctx->style.checkbox.normal = nk_style_item_color(nk_rgb(37, 36, 38));
+ example->ui_ctx->style.checkbox.cursor_normal = nk_style_item_color(accent);
+ example->ui_ctx->style.checkbox.cursor_hover = nk_style_item_color(accent);
+
+ example->ui_ctx->style.option.text_active = text;
+ example->ui_ctx->style.option.text_normal = text;
+ example->ui_ctx->style.option.text_hover = text;
+ example->ui_ctx->style.option.active = nk_style_item_color(nk_rgb(37, 36, 38));
+ example->ui_ctx->style.option.hover = nk_style_item_color(nk_rgb(55, 53, 56));
+ example->ui_ctx->style.option.normal = nk_style_item_color(nk_rgb(37, 36, 38));
+ example->ui_ctx->style.option.cursor_normal = nk_style_item_color(accent);
+ example->ui_ctx->style.option.cursor_hover = nk_style_item_color(accent);
+
+ example->ui_ctx->style.slider.cursor_normal = nk_style_item_color(accent);
+ example->ui_ctx->style.slider.cursor_hover = nk_style_item_color(accent_light);
+ example->ui_ctx->style.slider.cursor_active = nk_style_item_color(accent_light);
+ example->ui_ctx->style.slider.bar_filled = accent;
+
+ example->ui_ctx->style.tab.node_maximize_button.active = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.tab.node_maximize_button.normal = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.tab.node_maximize_button.hover = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.tab.node_minimize_button.active = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.tab.node_minimize_button.normal = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.tab.node_minimize_button.hover = nk_style_item_color(nk_rgba(0, 0, 0, 0));
+ example->ui_ctx->style.tab.indent = 12.0;
+
+ struct nk_font_atlas *atlas;
+ nk_sdl_font_stash_begin(&atlas);
+ struct nk_font *font;
+
+ FILE *f = fopen("assets/FiraCode-Medium.ttf", "r");
+ if (f) {
+ fclose(f);
+ font = nk_font_atlas_add_from_file(atlas, "assets/FiraCode-Medium.ttf", 16, NULL);
+ }
+ else {
+ font = nk_font_atlas_add_default(atlas, 16, NULL);
+ printf("Couldn't access 'assets/FiraCode-Medium.ttf'");
+ }
+
+ nk_sdl_font_stash_end();
+
+ nk_style_set_font(example->ui_ctx, &font->handle);
+}
+
+// Transform (normalize) coordinate from screen space to opengl space [-1, 1]
+static inline nvVector2 normalize_coords(ExampleContext *example, nvVector2 v) {
+ return NV_VECTOR2(
+ (2.0 * v.x / example->window_width) - 1.0,
+ 1.0 - (2.0 * v.y / example->window_height)
+ );
+}
+
+// Transform coordinate from world space to screen space
+static inline nvVector2 world_to_screen(ExampleContext *example, nvVector2 world_pos) {
+ return nvVector2_mul(nvVector2_sub(world_pos, example->camera), example->zoom);
+}
+
+// Transform coordinate from screen space to world space
+static inline nvVector2 screen_to_world(ExampleContext *example, nvVector2 screen_pos) {
+ return nvVector2_add(nvVector2_div(screen_pos, example->zoom), example->camera);
+}
+
+
+int main(int argc, char *argv[]) {
+ srand((unsigned int)time(NULL));
+
+ ExampleSettings settings = {
+ .window_width = 1280,
+ .window_height = 720
+ };
+
+ ExampleContext example;
+ ExampleContext_apply_settings(&example, settings);
+
+ Clock *clock = Clock_new();
+
+ example.mouse.left = false;
+ example.mouse.right = false;
+ example.mouse.middle = false;
+ example.camera = nvVector2_zero;
+ example.zoom = 10.0;
+ example.fullscreen = false;
+
+ example.theme.dynamic_body = (FColor){1.0, 0.75, 0.29, 1.0};
+ example.theme.static_body = (FColor){0.78, 0.44, 0.23, 1.0};
+ example.theme.distance_constraint = (FColor){0.45, 0.87, 1.0, 1.0};
+ example.theme.hinge_constraint = (FColor){0.623, 0.47, 0.98, 1.0},
+ example.theme.spline_constraint = (FColor){0.76, 0.949, 0.247, 1.0};
+ example.theme.ui_accent = (FColor){0.486, 0.243, 0.968, 1.0};
+ example.theme.ui_text = (FColor){1.0, 1.0, 1.0, 1.0};
+
+ if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
+ fprintf(stderr, "SDL initialization error: %s\n", SDL_GetError());
+ exit(EXIT_FAILURE);
+ }
+
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
+
+ example.window = SDL_CreateWindow(
+ "Nova Examples",
+ SDL_WINDOWPOS_CENTERED,
+ SDL_WINDOWPOS_CENTERED,
+ example.window_width,
+ example.window_height,
+ SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI
+ );
+ if (!example.window) {
+ fprintf(stderr, SDL_GetError());
+ exit(EXIT_FAILURE);
+ }
+
+ example.gl_ctx = SDL_GL_CreateContext(example.window);
+ if (!example.gl_ctx) {
+ fprintf(stderr, SDL_GetError());
+ exit(EXIT_FAILURE);
+ }
+ SDL_GL_MakeCurrent(example.window, example.gl_ctx);
+
+ if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) {
+ fprintf(stderr, "Failed to initialize GLAD.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ SDL_Surface *window_icon = SDL_LoadBMP("assets/novaicon.bmp");
+ SDL_SetWindowIcon(example.window, window_icon);
+ SDL_FreeSurface(window_icon);
+
+ setup_ui(&example);
+
+ // Enable VSYNC
+ SDL_GL_SetSwapInterval(1);
+
+ const char *vertex_shader_src =
+"#version 330 core\n"
+"layout (location = 0) in vec2 in_pos;\n"
+"layout (location = 1) in vec4 in_color;\n"
+"out vec4 v_color;\n"
+"void main() {\n"
+" gl_Position = vec4(in_pos.x, in_pos.y, 0.0, 1.0);\n"
+" v_color = in_color;\n"
+"}\n";
+
+ const char *fragment_shader_src =
+"#version 330 core\n"
+"in vec4 v_color;\n"
+"out vec4 f_color;\n"
+"void main() {\n"
+" f_color = v_color;\n"
+"}\n";
+
+ nv_uint32 vertex_shader = ngl_load_shader(vertex_shader_src, GL_VERTEX_SHADER);
+ nv_uint32 fragment_shader = ngl_load_shader(fragment_shader_src, GL_FRAGMENT_SHADER);
+
+ nv_uint32 program = glCreateProgram();
+ glAttachShader(program, vertex_shader);
+ glAttachShader(program, fragment_shader);
+ glLinkProgram(program);
+ int success;
+ glGetProgramiv(program, GL_LINK_STATUS, &success);
+ if(!success) {
+ fprintf(stderr, "Shader program linking error.\n");
+ exit(EXIT_FAILURE);
+ }
+ glUseProgram(program);
+ glDeleteShader(vertex_shader);
+ glDeleteShader(fragment_shader);
+
+ glLineWidth(1.0);
+ glEnable(GL_LINE_SMOOTH);
+
+ size_t tri_vertices_size = sizeof(float) * EXAMPLE_MAX_TRI_VERTICES;
+ float *tri_vertices = NV_MALLOC(tri_vertices_size);
+ size_t tri_vertices_index = 0;
+
+ size_t tri_colors_size = sizeof(float) * EXAMPLE_MAX_TRI_COLORS;
+ float *tri_colors = NV_MALLOC(tri_colors_size);
+ size_t tri_colors_index = 0;
+
+ size_t line_vertices_size = sizeof(float) * EXAMPLE_MAX_LINE_VERTICES;
+ float *line_vertices = NV_MALLOC(line_vertices_size);
+ size_t line_vertices_index = 0;
+
+ size_t line_colors_size = sizeof(float) * EXAMPLE_MAX_LINE_COLORS;
+ float *line_colors = NV_MALLOC(line_colors_size);
+ size_t line_colors_index = 0;
+
+ nv_uint32 vbos[4];
+ vbos[0] = ngl_create_vbo();
+ vbos[1] = ngl_create_vbo();
+ vbos[2] = ngl_create_vbo();
+ vbos[3] = ngl_create_vbo();
+
+ nv_uint32 vaos[2];
+ vaos[0] = ngl_create_vao();
+ vaos[1] = ngl_create_vao();
+
+ nv_uint32 vertex_attr = 0;
+ nv_uint32 color_attr = 1;
+
+ glBindVertexArray(vaos[0]);
+ size_t vao0_count = 0;
+
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
+ glBufferData(GL_ARRAY_BUFFER, tri_vertices_size, tri_vertices, GL_DYNAMIC_DRAW);
+ glVertexAttribPointer(vertex_attr, 2, GL_FLOAT, GL_FALSE, 0, (void *)0);
+ glEnableVertexAttribArray(vertex_attr);
+
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[1]);
+ glBufferData(GL_ARRAY_BUFFER, tri_colors_size, tri_colors, GL_DYNAMIC_DRAW);
+ glVertexAttribPointer(color_attr, 4, GL_FLOAT, GL_FALSE, 0, (void *)0);
+ glEnableVertexAttribArray(color_attr);
+
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindVertexArray(0);
+
+ glBindVertexArray(vaos[1]);
+ size_t vao1_count = 0;
+
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[2]);
+ glBufferData(GL_ARRAY_BUFFER, line_vertices_size, line_vertices, GL_DYNAMIC_DRAW);
+ glVertexAttribPointer(vertex_attr, 2, GL_FLOAT, GL_FALSE, 0, (void *)0);
+ glEnableVertexAttribArray(vertex_attr);
+
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[3]);
+ glBufferData(GL_ARRAY_BUFFER, line_colors_size, line_colors, GL_DYNAMIC_DRAW);
+ glVertexAttribPointer(color_attr, 4, GL_FLOAT, GL_FALSE, 0, (void *)0);
+ glEnableVertexAttribArray(color_attr);
+
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindVertexArray(0);
+
+ nv_bool is_running = true;
+
+ nv_uint64 frame = 0;
+
+ example.space = nvSpace_new();
+ nvSpace_set_broadphase(example.space, nvBroadPhaseAlg_BVH);
+
+ int space_paused = 0;
+ nv_bool space_one_step = false;
+ nv_float space_dt = 1.0 / 60.0;
+ nv_float space_hertz = 60.0;
+
+ // UI settings
+ int draw_ui = 1;
+ int show_bytes = 0;
+ int draw_shapes = 1;
+ int draw_contacts = 0;
+ int draw_aabbs = 0;
+ int draw_constraints = 1;
+ int draw_positions = 0;
+ int draw_broadphase = 0;
+ int draw_normal_impulses = 0;
+ int draw_friction_impulses = 0;
+
+ nv_bool raycast = false;
+
+ nvPrecisionTimer render_timer;
+ double render_time = 0.0;
+ double old_render_time = 0.0;
+
+ int gl_major;
+ int gl_minor;
+ int gl_profile_mask;
+ SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &gl_major);
+ SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &gl_minor);
+ SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &gl_profile_mask);
+
+ char *gl_profile_mask_str;
+ switch (gl_profile_mask) {
+ case (SDL_GL_CONTEXT_PROFILE_CORE):
+ gl_profile_mask_str = "Core";
+ break;
+
+ case (SDL_GL_CONTEXT_PROFILE_COMPATIBILITY):
+ gl_profile_mask_str = "Compatibility";
+ break;
+
+ case (SDL_GL_CONTEXT_PROFILE_ES):
+ gl_profile_mask_str = "ES";
+ break;
+ }
+
+ printf("Nova Physics %s\n", NV_VERSION_STRING);
+ printf("SDL %d.%d.%d\n", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL);
+ printf("OpenGL %d.%d %s\n", gl_major, gl_minor, gl_profile_mask_str);
+ printf("\n");
+ printf("nv_float size: %llu bytes\n", (unsigned long long)sizeof(nv_float));
+ printf("Vendor: %s\n", glGetString(GL_VENDOR));
+ printf("Renderer: %s\n", glGetString(GL_RENDERER));
+
+ // Register all example demos
+
+ // General demos
+ ExampleEntry_register("Stack", Stack_setup, Stack_update);
+ ExampleEntry_register("Compound", Compound_setup, Compound_update);
+ ExampleEntry_register("Pyramid", Pyramid_setup, Pyramid_update);
+ ExampleEntry_register("Rocks", Rocks_setup, Rocks_update);
+ ExampleEntry_register("SoftBody", SoftBody_setup, SoftBody_update);
+ ExampleEntry_register("Contact Events", ContactEvent_setup, ContactEvent_update);
+
+ // Constraint demos
+ ExampleEntry_register("Distance", DistanceConstraint_setup, DistanceConstraint_update);
+ ExampleEntry_register("Hinge", HingeConstraint_setup, HingeConstraint_update);
+ ExampleEntry_register("Spline", SplineConstraint_setup, SplineConstraint_update);
+
+ // Material demos
+ ExampleEntry_register("Bouncing", Bouncing_setup, Bouncing_update);
+ ExampleEntry_register("Friction", Friction_setup, Friction_update);
+ ExampleEntry_register("Density", Density_setup, Density_update);
+ ExampleEntry_register("Damping", Damping_setup, Damping_update);
+
+ current_example = 2;
+
+ // TODO: OH MY GOD PLEASE FIND A MORE ELEGANT SOLUTION
+ int row_i = 0;
+ int row0[] = {row_i++, row_i++, row_i++, row_i++, row_i++, row_i++};
+ int row1[] = {row_i++, row_i++, row_i++};
+ int row2[] = {row_i++, row_i++, row_i++, row_i++};
+ #define CATEGORIES 3
+ int *categories[CATEGORIES];
+ size_t row_sizes[CATEGORIES] = {sizeof(row0)/sizeof(int), sizeof(row1)/sizeof(int), sizeof(row2)/sizeof(int)};
+ size_t demo_rows = CATEGORIES;
+ categories[0] = row0;
+ categories[1] = row1;
+ categories[2] = row2;
+ char *category_names[CATEGORIES] = {"General", "Constraints", "Material"};
+
+ example_entries[current_example].setup(&example);
+
+ nvConstraint *mouse_cons = NULL;
+ nvDistanceConstraintInitializer mouse_cons_init = nvDistanceConstraintInitializer_default;
+
+ while (is_running) {
+ Clock_tick(clock, 60.0);
+
+ old_render_time = render_time;
+ render_time = 0.0;
+
+ SDL_GetMouseState(&example.mouse.x, &example.mouse.y);
+ example.before_zoom = screen_to_world(&example, NV_VECTOR2((nv_float)example.mouse.x, (nv_float)example.mouse.y));
+
+ SDL_Event event;
+ nk_input_begin(example.ui_ctx);
+ while (SDL_PollEvent(&event) != 0) {
+ if (event.type == SDL_QUIT) {
+ is_running = false;
+ }
+
+ else if (event.type == SDL_MOUSEBUTTONDOWN) {
+ if (event.button.button == SDL_BUTTON_LEFT) {
+ example.mouse.left = true;
+
+ nvRigidBody *selected = NULL;
+ nvRigidBody *body;
+ size_t body_iter = 0;
+ while (nvSpace_iter_bodies(example.space, &body, &body_iter)) {
+ if (body->type == nvRigidBodyType_STATIC) continue;
+
+ nvTransform xform = (nvTransform){body->origin, body->angle};
+ nvAABB aabb = nvRigidBody_get_aabb(body);
+
+ if (nv_collide_aabb_x_point(aabb, example.before_zoom)) {
+
+ for (size_t j = 0; j < body->shapes->size; j++) {
+ nvShape *shape = body->shapes->data[j];
+ nvAABB saabb = nvShape_get_aabb(shape, xform);
+
+ if (nv_collide_aabb_x_point(saabb, example.before_zoom)) {
+ if (shape->type == nvShapeType_CIRCLE) {
+ if (nv_collide_circle_x_point(shape, xform, example.before_zoom)) {
+ selected = body;
+ break;
+ }
+ }
+ else if (shape->type == nvShapeType_POLYGON) {
+ if (nv_collide_polygon_x_point(shape, xform, example.before_zoom)) {
+ selected = body;
+ break;
+ }
+ }
+ }
+ }
+
+ if (selected) break;
+ }
+ }
+
+ if (selected) {
+ nvVector2 anchor = nvVector2_rotate(nvVector2_sub(example.before_zoom, nvRigidBody_get_position(selected)), -nvRigidBody_get_angle(selected));
+ mouse_cons_init.a = selected;
+ mouse_cons_init.b = NULL;
+ mouse_cons_init.length = 0.1;
+ mouse_cons_init.anchor_a = nvVector2_add(anchor, NV_VECTOR2(0.0, 0.01));
+ mouse_cons_init.anchor_b = example.before_zoom;
+ mouse_cons_init.spring = true;
+ mouse_cons_init.hertz = 1.0;
+ mouse_cons_init.damping = 0.5;
+ mouse_cons = nvDistanceConstraint_new(mouse_cons_init);
+ nvSpace_add_constraint(example.space, mouse_cons);
+ }
+ }
+
+ else if (event.button.button == SDL_BUTTON_MIDDLE) {
+ example.mouse.middle = true;
+ example.pan_start = NV_VECTOR2((nv_float)example.mouse.x, (nv_float)example.mouse.y);
+ }
+
+ else if (event.button.button == SDL_BUTTON_RIGHT) {
+ example.mouse.right = true;
+ }
+ }
+
+ else if (event.type == SDL_MOUSEBUTTONUP) {
+ if (event.button.button == SDL_BUTTON_LEFT) {
+ example.mouse.left = false;
+
+ if (mouse_cons) {
+ nvSpace_remove_constraint(example.space, mouse_cons);
+ nvConstraint_free(mouse_cons);
+ mouse_cons = NULL;
+ }
+ }
+
+ else if (event.button.button == SDL_BUTTON_MIDDLE) {
+ example.mouse.middle = false;
+ }
+
+ else if (event.button.button == SDL_BUTTON_RIGHT) {
+ example.mouse.right = false;
+ }
+ }
+
+ else if (event.type == SDL_MOUSEWHEEL) {
+ if (event.wheel.y > 0) {
+ example.zoom *= 1 + ZOOM_SCALE;
+ }
+
+ else if (event.wheel.y < 0) {
+ example.zoom *= 1 - ZOOM_SCALE;
+ }
+ }
+
+ else if (
+ event.type == SDL_WINDOWEVENT &&
+ event.window.event == SDL_WINDOWEVENT_RESIZED
+ ) {
+ example.window_width = event.window.data1;
+ example.window_height = event.window.data2;
+ }
+
+ else if (event.type == SDL_KEYDOWN) {
+ if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) {
+ is_running = false;
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_U) {
+ draw_ui = !draw_ui;
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_P) {
+ space_paused = !space_paused;
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_O) {
+ space_one_step = true;
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_DELETE) {
+ nvRigidBody *selected = NULL;
+ nvRigidBody *body;
+ size_t body_iter = 0;
+ while (nvSpace_iter_bodies(example.space, &body, &body_iter)) {
+ nvTransform xform = (nvTransform){body->origin, body->angle};
+ nvAABB aabb = nvRigidBody_get_aabb(body);
+
+ if (nv_collide_aabb_x_point(aabb, example.before_zoom)) {
+
+ for (size_t j = 0; j < body->shapes->size; j++) {
+ nvShape *shape = body->shapes->data[j];
+ nvAABB saabb = nvShape_get_aabb(shape, xform);
+
+ if (nv_collide_aabb_x_point(saabb, example.before_zoom)) {
+ if (shape->type == nvShapeType_CIRCLE) {
+ if (nv_collide_circle_x_point(shape, xform, example.before_zoom)) {
+ selected = body;
+ break;
+ }
+ }
+ else if (shape->type == nvShapeType_POLYGON) {
+ if (nv_collide_polygon_x_point(shape, xform, example.before_zoom)) {
+ selected = body;
+ break;
+ }
+ }
+ }
+ }
+
+ if (selected) break;
+ }
+ }
+
+ if (selected) {
+ nvSpace_remove_rigidbody(example.space, selected);
+ }
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_RETURN && event.key.keysym.mod == KMOD_LALT) {
+ example.fullscreen = !example.fullscreen;
+ if (example.fullscreen) {
+ SDL_SetWindowFullscreen(example.window, SDL_WINDOW_FULLSCREEN_DESKTOP);
+ }
+ else {
+ SDL_SetWindowFullscreen(example.window, 0);
+ }
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_F1) {
+ nvRigidBody *body;
+ size_t body_iter = 0;
+ while (nvSpace_iter_bodies(example.space, &body, &body_iter)) {
+ if (body->type == nvRigidBodyType_STATIC) continue;
+
+ nvVector2 pos = nvRigidBody_get_position(body);
+ pos.x += frand(-5.0, 5.0);
+ pos.y += frand(-5.0, 5.0);
+ nvRigidBody_set_position(body, pos);
+ }
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_F2) {
+ nvRigidBodyInitializer f2init = nvRigidBodyInitializer_default;
+ f2init.type = nvRigidBodyType_DYNAMIC;
+ f2init.position = example.before_zoom;
+ nvRigidBody *f2box = nvRigidBody_new(f2init);
+
+ nvShape *f2box_shape = nvRectShape_new(1.0, 1.0, nvVector2_zero);
+ nvRigidBody_add_shape(f2box, f2box_shape);
+
+ nvSpace_add_rigidbody(example.space, f2box);
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_F3) {
+ nvRigidBodyInitializer f2init = nvRigidBodyInitializer_default;
+ f2init.type = nvRigidBodyType_DYNAMIC;
+ f2init.position = example.before_zoom;
+ nvRigidBody *f2box = nvRigidBody_new(f2init);
+
+ nvShape *f2box_shape = nvCircleShape_new(nvVector2_zero, 1.0);
+ nvRigidBody_add_shape(f2box, f2box_shape);
+
+ nvSpace_add_rigidbody(example.space, f2box);
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_F4) {
+ create_circle_softbody(&example, example.before_zoom, 12, 2.5, 0.6);
+ }
+
+ else if (event.key.keysym.scancode == SDL_SCANCODE_F5) {
+ raycast = !raycast;
+ }
+ }
+
+ nk_sdl_handle_event(&event);
+ }
+ nk_sdl_handle_grab();
+ nk_input_end(example.ui_ctx);
+
+ example.after_zoom = screen_to_world(&example, NV_VECTOR2((nv_float)example.mouse.x, (nv_float)example.mouse.y));
+
+ if (example.mouse.middle) {
+ example.camera = nvVector2_sub(example.camera, nvVector2_div(nvVector2_sub(NV_VECTOR2((nv_float)example.mouse.x, (nv_float)example.mouse.y), example.pan_start), example.zoom));
+ example.pan_start = NV_VECTOR2((nv_float)example.mouse.x, (nv_float)example.mouse.y);
+ }
+ example.camera = nvVector2_add(example.camera, nvVector2_sub(example.before_zoom, example.after_zoom));
+
+ if (mouse_cons) {
+ nvDistanceConstraint_set_anchor_b(mouse_cons, example.before_zoom);
+ }
+
+ if (draw_ui) {
+ if (nk_begin(example.ui_ctx, "Simulation", nk_rect(0.0f, 0.0f, 300.0f, (float)example.window_height), NK_WINDOW_TITLE)) {
+ char display_buf[16];
+ const float ratio[] = {0.40f, 0.47f, 0.13f};
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Space Settings", NK_MAXIMIZED)) {
+ nvSpaceSettings *settings = &example.space->settings;
+ {
+ nk_layout_row(example.ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example.ui_ctx, "Gravity", NK_TEXT_LEFT);
+
+ nk_slider_float(example.ui_ctx, 0.0f, (float *)&example.space->gravity.y, 50.0f, 0.005f);
+
+ sprintf(display_buf, "%3.2f", example.space->gravity.y);
+ nk_label(example.ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example.ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example.ui_ctx, "Baumgarte", NK_TEXT_LEFT);
+
+ nk_slider_float(example.ui_ctx, 0.0f, (float *)&settings->baumgarte, 1.0f, 0.005f);
+
+ sprintf(display_buf, "%3.2f", settings->baumgarte);
+ nk_label(example.ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example.ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example.ui_ctx, "Velocity Iters", NK_TEXT_LEFT);
+
+ nk_slider_int(example.ui_ctx, 0, (int *)&settings->velocity_iterations, 30, 1);
+
+ sprintf(display_buf, "%u", settings->velocity_iterations);
+ nk_label(example.ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example.ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example.ui_ctx, "Hertz", NK_TEXT_LEFT);
+
+ if (nk_slider_float(example.ui_ctx, 7.5f, (float *)&space_hertz, 180.0f, 0.005f))
+ space_dt = 1.0 / space_hertz;
+
+ sprintf(display_buf, "%f", space_hertz);
+ nk_label(example.ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+ {
+ nk_layout_row(example.ui_ctx, NK_DYNAMIC, 16, 3, ratio);
+
+ nk_label(example.ui_ctx, "Substeps", NK_TEXT_LEFT);
+
+ nk_slider_int(example.ui_ctx, 1, (int *)&settings->substeps, 5, 1);
+
+ sprintf(display_buf, "%u", settings->substeps);
+ nk_label(example.ui_ctx, display_buf, NK_TEXT_LEFT);
+ }
+
+ nk_layout_row_dynamic(example.ui_ctx, 20, 1);
+ nk_checkbox_label(example.ui_ctx, "Warmstarting", &settings->warmstarting);
+
+ nk_layout_row_static(example.ui_ctx, 25, 120, 1);
+ nk_checkbox_label(example.ui_ctx, "Paused", &space_paused);
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_NODE, "Broadphase", NK_MAXIMIZED)) {
+ nk_layout_row_dynamic(example.ui_ctx, 16, 1);
+ if (nk_option_label(example.ui_ctx, "Bruteforce", nvSpace_get_broadphase(example.space) == nvBroadPhaseAlg_BRUTE_FORCE))
+ nvSpace_set_broadphase(example.space, nvBroadPhaseAlg_BRUTE_FORCE);
+ if (nk_option_label(example.ui_ctx, "BVH", nvSpace_get_broadphase(example.space) == nvBroadPhaseAlg_BVH))
+ nvSpace_set_broadphase(example.space, nvBroadPhaseAlg_BVH);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+
+ nk_layout_row_dynamic(example.ui_ctx, 8, 1);
+ nk_spacer(example.ui_ctx);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Drawing", NK_MINIMIZED)) {
+ nk_layout_row_dynamic(example.ui_ctx, 16, 1);
+
+ nk_checkbox_label(example.ui_ctx, "Shapes", &draw_shapes);
+ nk_checkbox_label(example.ui_ctx, "AABBs", &draw_aabbs);
+ nk_checkbox_label(example.ui_ctx, "Broadphase", &draw_broadphase);
+ nk_checkbox_label(example.ui_ctx, "Contacts", &draw_contacts);
+ nk_checkbox_label(example.ui_ctx, "Constraints", &draw_constraints);
+ nk_checkbox_label(example.ui_ctx, "Positions", &draw_positions);
+ nk_checkbox_label(example.ui_ctx, "Velocities", &space_paused);
+ nk_checkbox_label(example.ui_ctx, "Normal impulses", &draw_normal_impulses);
+ nk_checkbox_label(example.ui_ctx, "Friction impulses", &draw_friction_impulses);
+
+ nk_layout_row_dynamic(example.ui_ctx, 8, 1);
+ nk_spacer(example.ui_ctx);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Demos", NK_MINIMIZED)) {
+ for (size_t row = 0; row < demo_rows; row++) {
+ char *title = category_names[row];
+
+ if (nk_tree_push_id(example.ui_ctx, NK_TREE_TAB, title, NK_MINIMIZED, row)) {
+ size_t row_size = row_sizes[row];
+ for (size_t demo_i = 0; demo_i < row_size; demo_i++) {
+ size_t demo = categories[row][demo_i];
+ nk_layout_row_dynamic(example.ui_ctx, 22, 1);
+ if (nk_button_label(example.ui_ctx, example_entries[demo].name)) {
+ current_example = demo;
+ nvSpace_clear(example.space, true);
+ nvSpace_set_gravity(example.space, NV_VECTOR2(0.0, 9.81));
+ mouse_cons = NULL;
+ NV_FREE(example.space->listener);
+ example.space->listener = NULL;
+ example_entries[current_example].setup(&example);
+ }
+ }
+
+ nk_layout_row_dynamic(example.ui_ctx, 8, 1);
+ nk_spacer(example.ui_ctx);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+ }
+
+ nk_tree_pop(example.ui_ctx);
+ }
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Controls", NK_MINIMIZED)) {
+ nk_layout_row_dynamic(example.ui_ctx, 16, 1);
+
+ nk_label(example.ui_ctx, "[LMB] to drag objects.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[MWHEEL] to move & zoom camera.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[ESC] to exit.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[P] to pause simulation.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[U] to toggle UI.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[ALT+ENTER] to toggle fullscreen.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[DEL] to remove bodies.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[F1] to teleport everything.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[F2] to create box.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[F3] to create ball.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[F4] to create soft-body.", NK_TEXT_LEFT);
+ nk_label(example.ui_ctx, "[F5] to cast ray.", NK_TEXT_LEFT);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+ }
+ nk_end(example.ui_ctx);
+
+ if (
+ nk_begin(
+ example.ui_ctx,
+ "Profile",
+ nk_rect((float)example.window_width - 250.0f, 0.0f, 250.0f, 400.0f),
+ NK_WINDOW_TITLE | NK_WINDOW_MINIMIZABLE
+ )
+ ) {
+ char fmt_buffer[32];
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Overview", NK_MAXIMIZED)) {
+ nk_layout_row_dynamic(example.ui_ctx, 16, 1);
+
+ sprintf(fmt_buffer, "FPS: %.1f", clock->fps);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Physics: %.3fms", example.space->profiler.step * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Render: %.3fms", old_render_time);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Frame: %llu", (unsigned long long)frame);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Physics", NK_MINIMIZED)) {
+ nk_layout_row_dynamic(example.ui_ctx, 16, 1);
+
+ sprintf(fmt_buffer, "Step: %.3fms", example.space->profiler.step * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Broadphase: %.3fms", example.space->profiler.broadphase * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "BPh finalize: %.3fms", example.space->profiler.broadphase_finalize * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "BVH build: %.3fms", example.space->profiler.bvh_build * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "BVH traverse: %.3fms", example.space->profiler.bvh_traverse * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "BVH NV_FREE: %.3fms", example.space->profiler.bvh_free * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Narrowphase: %.3fms", example.space->profiler.narrowphase * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Presolve: %.3fms", example.space->profiler.presolve * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Warmstart: %.3fms", example.space->profiler.warmstart * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Solve velocity: %.3fms", example.space->profiler.solve_velocities * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Solve position: %.3fms", example.space->profiler.solve_positions * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Integrate vels.: %.3fms", example.space->profiler.integrate_velocities * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ sprintf(fmt_buffer, "Integrate accels.: %.3fms", example.space->profiler.integrate_velocities * 1000.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ nk_tree_pop(example.ui_ctx);
+ }
+
+ if (nk_tree_push(example.ui_ctx, NK_TREE_TAB, "Memory", NK_MINIMIZED)) {
+ nk_layout_row_dynamic(example.ui_ctx, 16, 1);
+
+ size_t process_mem = get_current_memory_usage();
+ sprintf(fmt_buffer, "Process: %1.f MB", (double)process_mem / 1048576.0);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+
+ nk_checkbox_label(example.ui_ctx, "Show in bytes", &show_bytes);
+ char *unit;
+ if (show_bytes) unit = "B";
+ else unit = "KB";
+
+ double unit_size;
+ if (show_bytes) unit_size = 1.0;
+ else unit_size = 1024.0;
+
+ size_t num_shapes = 0;
+ size_t bodies_bytes = 0;
+
+ nvRigidBody *body;
+ size_t body_iter = 0;
+ while (nvSpace_iter_bodies(example.space, &body, &body_iter)) {
+ bodies_bytes += sizeof(nvArray); // Shape array
+ num_shapes += body->shapes->size;
+ }
+
+ size_t shapes_bytes = num_shapes * sizeof(nvShape);
+ double shapes_s = (double)(shapes_bytes) / unit_size;
+
+ size_t num_bodies = example.space->bodies->size;
+ bodies_bytes += num_bodies * sizeof(nvRigidBody);
+ double bodies_s = (double)(bodies_bytes) / unit_size;
+
+ size_t num_cons = example.space->constraints->size;
+ size_t cons_bytes = num_cons * sizeof(nvConstraint);
+ double cons_s = (double)(cons_bytes) / unit_size;
+
+ size_t num_contacts = example.space->contacts->count;
+ size_t contacts_bytes = num_contacts * sizeof(nvPersistentContactPair);
+ double contacts_s = (double)(contacts_bytes) / unit_size;
+
+ size_t pairs_bytes = example.space->broadphase_pairs->pool_size;
+ double pairs_s = (double)(pairs_bytes) / unit_size;
+
+ size_t space_bytes =
+ sizeof(nvSpace) +
+ bodies_bytes + sizeof(nvArray) +
+ cons_bytes + sizeof(nvArray) +
+ pairs_bytes + sizeof(nvMemoryPool) +
+ contacts_bytes + sizeof(nvHashMap);
+ double space_s = (double)space_bytes / unit_size;
+
+ if (!show_bytes && space_s > 1024.0) {
+ space_s /= 1024.0;
+ unit = "MB";
+ }
+ sprintf(fmt_buffer, "Space: %.1f %s", space_s, unit);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+ unit = "KB";
+
+ if (!show_bytes && bodies_s > 1024.0) {
+ bodies_s /= 1024.0;
+ unit = "MB";
+ }
+ sprintf(fmt_buffer, "Bodies: %llu (%.1f %s)", (unsigned long long)num_bodies, bodies_s, unit);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+ unit = "KB";
+
+ if (!show_bytes && shapes_s > 1024.0) {
+ shapes_s /= 1024.0;
+ unit = "MB";
+ }
+ sprintf(fmt_buffer, "Shapes: %llu (%.1f %s)", (unsigned long long)num_shapes, shapes_s, unit);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+ unit = "KB";
+
+ if (!show_bytes && cons_s > 1024.0) {
+ cons_s /= 1024.0;
+ unit = "MB";
+ }
+ sprintf(fmt_buffer, "Constraints: %llu (%.1f %s)", (unsigned long long)num_cons, cons_s, unit);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+ unit = "KB";
+
+ if (!show_bytes && pairs_s > 1024.0) {
+ pairs_s /= 1024.0;
+ unit = "MB";
+ }
+ unsigned long long pairs_n = example.space->broadphase_pairs->pool_size / example.space->broadphase_pairs->chunk_size;
+ sprintf(fmt_buffer, "BPh: %llu/%llu (%.1f %s)", (unsigned long long)example.space->broadphase_pairs->current_size, pairs_n, pairs_s, unit);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+ unit = "KB";
+
+ if (!show_bytes && contacts_s > 1024.0) {
+ contacts_s /= 1024.0;
+ unit = "MB";
+ }
+ sprintf(fmt_buffer, "Contacts: %llu (%.1f %s)", (unsigned long long)num_contacts, contacts_s, unit);
+ nk_label(example.ui_ctx, fmt_buffer, NK_TEXT_LEFT);
+ unit = "KB";
+
+ nk_tree_pop(example.ui_ctx);
+ }
+ }
+ nk_end(example.ui_ctx);
+
+ if (
+ nk_begin(
+ example.ui_ctx,
+ example_entries[current_example].name,
+ nk_rect((float)example.window_width - 250.0f, example.window_height - 300.0f, 250.0f, 300.0f),
+ NK_WINDOW_TITLE | NK_WINDOW_MOVABLE | NK_WINDOW_MINIMIZABLE
+ )
+ ) {
+ example_entries[current_example].update(&example);
+ }
+ nk_end(example.ui_ctx);
+ }
+
+ if (!space_paused || (space_paused && space_one_step)) {
+ nvSpace_step(example.space, space_dt);
+ space_one_step = false;
+ }
+
+ nvPrecisionTimer_start(&render_timer);
+
+ tri_vertices_index = 0;
+ tri_colors_index = 0;
+ vao0_count = 0;
+ line_vertices_index = 0;
+ line_colors_index = 0;
+ vao1_count = 0;
+
+ if (raycast) {
+ nvRayCastResult results[256];
+ size_t num_results;
+ nvSpace_cast_ray(
+ example.space,
+ NV_VECTOR2(64.0, 36.0),
+ example.before_zoom,
+ results,
+ &num_results,
+ 256
+ );
+
+ nvVector2 p0 = NV_VECTOR2(64.0, 36.0);
+ nvVector2 p1 = example.before_zoom;
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+
+ ADD_LINE(p0.x, p0.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(p0.x, p0.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p1.x, p1.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p1.x, p1.y, 0.0, 0.0, 0.0, 0.0);
+
+ for (size_t i = 0; i < num_results; i++) {
+ nvRayCastResult result = results[i];
+
+ nvVector2 p0 = result.position;
+ nvVector2 p1 = nvVector2_add(p0, result.normal);
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+
+ ADD_LINE(p0.x, p0.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(p0.x, p0.y, 1.0, 0.0, 0.0, 1.0);
+ ADD_LINE(p1.x, p1.y, 1.0, 0.0, 0.0, 1.0);
+ ADD_LINE(p1.x, p1.y, 0.0, 0.0, 0.0, 0.0);
+ }
+ }
+
+ if (draw_shapes) {
+ nvRigidBody *body;
+ size_t body_iter = 0;
+ while (nvSpace_iter_bodies(example.space, &body, &body_iter)) {
+ double r, g, b;
+ if (body->type == nvRigidBodyType_DYNAMIC) {
+ r = example.theme.dynamic_body.r;
+ g = example.theme.dynamic_body.g;
+ b = example.theme.dynamic_body.b;
+ }
+ else {
+ r = example.theme.static_body.r;
+ g = example.theme.static_body.g;
+ b = example.theme.static_body.b;
+ }
+
+ nvShape *shape;
+ size_t shape_iter = 0;
+ while (nvRigidBody_iter_shapes(body, &shape, &shape_iter)) {
+
+ if (shape->type == nvShapeType_POLYGON) {
+ nvPolygon_transform(shape, (nvTransform){body->origin, nvRigidBody_get_angle(body)});
+ nvPolygon polygon = shape->polygon;
+ nvVector2 v0 = polygon.xvertices[0];
+ nvVector2 v0t = world_to_screen(&example, v0);
+ v0t = normalize_coords(&example, v0t);
+
+ for (size_t j = 0; j < polygon.num_vertices - 2; j++) {
+ nvVector2 v1 = polygon.xvertices[j + 1];
+ nvVector2 v2 = polygon.xvertices[j + 2];
+
+ nvVector2 v1t = world_to_screen(&example, v1);
+ nvVector2 v2t = world_to_screen(&example, v2);
+
+ v1t = normalize_coords(&example, v1t);
+ v2t = normalize_coords(&example, v2t);
+
+ ADD_TRIANGLE(
+ v0t.x, v0t.y,
+ v1t.x, v1t.y,
+ v2t.x, v2t.y,
+ r,
+ g,
+ b,
+ 0.1
+ );
+ }
+
+ ADD_LINE(v0t.x, v0t.y, 0.0, 0.0, 0.0, 0.0);
+
+ for (size_t j = 0; j < polygon.num_vertices; j++) {
+ nvVector2 va = polygon.xvertices[j];
+ nvVector2 vat = world_to_screen(&example, va);
+ vat = normalize_coords(&example, vat);
+
+ ADD_LINE(vat.x, vat.y, r, g, b, 1.0;)
+ }
+
+ // The reason we add 2 more extra vertices per object is to
+ // basically a transparent line between objects. I currently
+ // have no idea how to remove the linked lines in GL_LINE_STRIP
+ // drawing mode but I believe this is efficient enough.
+ ADD_LINE(v0t.x, v0t.y, r, g, b, 1.0);
+ ADD_LINE(v0t.x, v0t.y, 0.0, 0.0, 0.0, 0.0);
+ }
+ else if (shape->type == nvShapeType_CIRCLE) {
+ nvVector2 c = nvVector2_add(nvVector2_rotate(shape->circle.center, body->angle), body->origin);
+
+ nvVector2 vertices[CIRCLE_VERTICES];
+ nvVector2 arm = NV_VECTOR2(shape->circle.radius, 0.0);
+
+ for (size_t i = 0; i < CIRCLE_VERTICES; i++) {
+ vertices[i] = nvVector2_add(c, arm);
+ arm = nvVector2_rotate(arm, 2.0 * NV_PI / (nv_float)CIRCLE_VERTICES);
+ }
+
+ nvVector2 v0 = vertices[0];
+ nvVector2 v0t = world_to_screen(&example, v0);
+ v0t = normalize_coords(&example, v0t);
+
+ for (size_t j = 0; j < CIRCLE_VERTICES - 2; j++) {
+ nvVector2 v1 = vertices[j + 1];
+ nvVector2 v2 = vertices[j + 2];
+
+ nvVector2 v1t = world_to_screen(&example, v1);
+ nvVector2 v2t = world_to_screen(&example, v2);
+
+ v1t = normalize_coords(&example, v1t);
+ v2t = normalize_coords(&example, v2t);
+
+ ADD_TRIANGLE(
+ v0t.x, v0t.y,
+ v1t.x, v1t.y,
+ v2t.x, v2t.y,
+ r,
+ g,
+ b,
+ 0.1
+ );
+ }
+
+ ADD_LINE(v0t.x, v0t.y, 0.0, 0.0, 0.0, 0.0);
+
+ for (size_t j = 0; j < CIRCLE_VERTICES; j++) {
+ nvVector2 va = vertices[j];
+ nvVector2 vat = world_to_screen(&example, va);
+ vat = normalize_coords(&example, vat);
+
+ ADD_LINE(vat.x, vat.y, r, g, b, 1.0;)
+ }
+
+ ADD_LINE(v0t.x, v0t.y, r, g, b, 1.0);
+ ADD_LINE(v0t.x, v0t.y, 0.0, 0.0, 0.0, 0.0);
+ }
+
+ if (draw_aabbs) {
+ nvAABB saabb = nvShape_get_aabb(shape, (nvTransform){body->origin, body->angle});
+ nvVector2 p0 = NV_VECTOR2(saabb.min_x, saabb.min_y);
+ nvVector2 p1 = NV_VECTOR2(saabb.max_x, saabb.min_y);
+ nvVector2 p2 = NV_VECTOR2(saabb.max_x, saabb.max_y);
+ nvVector2 p3 = NV_VECTOR2(saabb.min_x, saabb.max_y);
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+ p2 = world_to_screen(&example, p2);
+ p2 = normalize_coords(&example, p2);
+ p3 = world_to_screen(&example, p3);
+ p3 = normalize_coords(&example, p3);
+
+ ADD_LINE(p0.x, p0.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(p0.x, p0.y, 0.0, 1.0, 0.0, 0.4);
+ ADD_LINE(p1.x, p1.y, 0.0, 1.0, 0.0, 0.4);
+ ADD_LINE(p2.x, p2.y, 0.0, 1.0, 0.0, 0.4);
+ ADD_LINE(p3.x, p3.y, 0.0, 1.0, 0.0, 0.4);
+ ADD_LINE(p0.x, p0.y, 0.0, 1.0, 0.0, 0.4);
+ ADD_LINE(p0.x, p0.y, 0.0, 0.0, 0.0, 0.0);
+ }
+ }
+
+ if (draw_aabbs) {
+ nvAABB aabb = nvRigidBody_get_aabb(body);
+ nvVector2 p0 = NV_VECTOR2(aabb.min_x, aabb.min_y);
+ nvVector2 p1 = NV_VECTOR2(aabb.max_x, aabb.min_y);
+ nvVector2 p2 = NV_VECTOR2(aabb.max_x, aabb.max_y);
+ nvVector2 p3 = NV_VECTOR2(aabb.min_x, aabb.max_y);
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+ p2 = world_to_screen(&example, p2);
+ p2 = normalize_coords(&example, p2);
+ p3 = world_to_screen(&example, p3);
+ p3 = normalize_coords(&example, p3);
+
+ ADD_LINE(p0.x, p0.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(p0.x, p0.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p1.x, p1.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p2.x, p2.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p3.x, p3.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p0.x, p0.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(p0.x, p0.y, 0.0, 0.0, 0.0, 0.0);
+ }
+
+ if (draw_positions) {
+ nvVector2 com = nvRigidBody_get_position(body);
+ nvVector2 arm0 = nvVector2_rotate(NV_VECTOR2(0.5, 0.0), nvRigidBody_get_angle(body));
+ nvVector2 arm1 = nvVector2_perpr(arm0);
+ arm0 = nvVector2_add(arm0, com);
+ arm1 = nvVector2_add(arm1, com);
+
+ com = world_to_screen(&example, com);
+ com = normalize_coords(&example, com);
+ arm0 = world_to_screen(&example, arm0);
+ arm0 = normalize_coords(&example, arm0);
+ arm1 = world_to_screen(&example, arm1);
+ arm1 = normalize_coords(&example, arm1);
+
+ ADD_LINE(arm0.x, arm0.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(arm0.x, arm0.y, 1.0, 0.0, 0.0, 1.0);
+ ADD_LINE(com.x, com.y, 1.0, 0.0, 0.0, 1.0);
+ ADD_LINE(com.x, com.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(arm1.x, arm1.y, 0.0, 1.0, 0.0, 1.0);
+ ADD_LINE(arm1.x, arm1.y, 0.0, 1.0, 0.0, 0.0);
+ }
+
+ }
+ }
+
+ if (draw_constraints) {
+ nvConstraint *cons;
+ size_t cons_iter = 0;
+ while (nvSpace_iter_constraints(example.space, &cons, &cons_iter)) {
+ switch (cons->type) {
+ case nvConstraintType_DISTANCE: {
+ nvVector2 a = nvDistanceConstraint_get_anchor_a(cons);
+ nvVector2 b = nvDistanceConstraint_get_anchor_b(cons);
+
+ if (cons->a) a = nvVector2_add(nvVector2_rotate(a, nvRigidBody_get_angle(cons->a)), nvRigidBody_get_position(cons->a));
+ if (cons->b) b = nvVector2_add(nvVector2_rotate(b, nvRigidBody_get_angle(cons->b)), nvRigidBody_get_position(cons->b));
+
+ a = world_to_screen(&example, a);
+ b = world_to_screen(&example, b);
+ a = normalize_coords(&example, a);
+ b = normalize_coords(&example, b);
+
+ ADD_LINE(a.x, a.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(
+ a.x, a.y,
+ example.theme.distance_constraint.r,
+ example.theme.distance_constraint.g,
+ example.theme.distance_constraint.b,
+ 1.0
+ );
+ ADD_LINE(
+ b.x, b.y,
+ example.theme.distance_constraint.r,
+ example.theme.distance_constraint.g,
+ example.theme.distance_constraint.b,
+ 1.0
+ );
+ ADD_LINE(b.x, b.y, 0.0, 0.0, 0.0, 0.0);
+
+ break;
+ }
+ case nvConstraintType_HINGE: {
+ nvHingeConstraint *hinge_cons = cons->def;
+
+ nvVector2 pa, pb;
+ nvVector2 p;
+
+ if (cons->a) {
+ p = nvRigidBody_get_position(cons->a);
+ pa = nvVector2_add(p, hinge_cons->xanchor_a);
+ }
+ else {
+ p = hinge_cons->anchor;
+ pa = hinge_cons->anchor;
+ }
+ p = world_to_screen(&example, p);
+ p = normalize_coords(&example, p);
+ pa = world_to_screen(&example, pa);
+ pa = normalize_coords(&example, pa);
+
+ ADD_LINE(p.x, p.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(
+ p.x, p.y,
+ example.theme.hinge_constraint.r,
+ example.theme.hinge_constraint.g,
+ example.theme.hinge_constraint.b,
+ 1.0
+ );
+ ADD_LINE(
+ pa.x, pa.y,
+ example.theme.hinge_constraint.r,
+ example.theme.hinge_constraint.g,
+ example.theme.hinge_constraint.b,
+ 1.0
+ );
+ ADD_LINE(pa.x, pa.y, 0.0, 0.0, 0.0, 0.0);
+
+ if (cons->b) {
+ p = nvRigidBody_get_position(cons->b);
+ pb = nvVector2_add(p, hinge_cons->xanchor_b);
+ }
+ else {
+ p = hinge_cons->anchor;
+ pb = hinge_cons->anchor;
+ }
+ p = world_to_screen(&example, p);
+ p = normalize_coords(&example, p);
+ pb = world_to_screen(&example, pb);
+ pb = normalize_coords(&example, pb);
+
+ ADD_LINE(p.x, p.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(
+ p.x, p.y,
+ example.theme.hinge_constraint.r,
+ example.theme.hinge_constraint.g,
+ example.theme.hinge_constraint.b,
+ 1.0
+ );
+ ADD_LINE(
+ pb.x, pb.y,
+ example.theme.hinge_constraint.r,
+ example.theme.hinge_constraint.g,
+ example.theme.hinge_constraint.b,
+ 1.0
+ );
+ ADD_LINE(pb.x, pb.y, 0.0, 0.0, 0.0, 0.0);
+
+ nvVector2 r = nvVector2_mul(nvVector2_add(pa, pb), 0.5);
+ float ar = (float)example.window_height / (float)example.window_width;
+
+ nvVector2 radius = NV_VECTOR2(0.025, 0.0);
+ ADD_LINE(
+ r.x + radius.x * ar,
+ r.y + radius.y,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0
+ );
+ for (size_t i = 0; i < 13; i++) {
+ radius = nvVector2_rotate(radius, 2.0 * NV_PI / 12.0);
+ ADD_LINE(
+ r.x + radius.x * ar,
+ r.y + radius.y,
+ example.theme.hinge_constraint.r * 2.0,
+ example.theme.hinge_constraint.g * 2.0,
+ example.theme.hinge_constraint.b * 2.0,
+ 1.0
+ );
+ }
+ ADD_LINE(
+ r.x + radius.x * ar,
+ r.y + radius.y,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0
+ );
+
+ if (hinge_cons->enable_limits) {
+ nvVector2 upper = nvVector2_rotate(NV_VECTOR2(0.025 * 1.5, 0.0), -hinge_cons->upper_limit + NV_PI);
+ nvVector2 lower = nvVector2_rotate(NV_VECTOR2(0.025 * 1.5, 0.0), -hinge_cons->lower_limit + NV_PI);
+ upper.x *= ar;
+ lower.x *= ar;
+ upper = nvVector2_add(r, upper);
+ lower = nvVector2_add(r, lower);
+
+ ADD_LINE(upper.x, upper.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(upper.x, upper.y, 1.0, 0.376, 0.25, 1.0);
+ ADD_LINE(r.x, r.y, 1.0, 0.376, 0.25, 1.0);
+ ADD_LINE(r.x, r.y, 0.325, 0.615, 0.988, 1.0);
+ ADD_LINE(lower.x, lower.y, 0.325, 0.615, 0.988, 1.0);
+ ADD_LINE(lower.x, lower.y, 0.0, 0.0, 0.0, 0.0);
+ }
+
+ break;
+ }
+ case nvConstraintType_SPLINE: {
+ nvSplineConstraint *spline_cons = cons->def;
+
+ nvVector2 va = spline_cons->controls[0];
+ nvVector2 vb = spline_cons->controls[1];
+
+ va = world_to_screen(&example, va);
+ va = normalize_coords(&example, va);
+ vb = world_to_screen(&example, vb);
+ vb = normalize_coords(&example, vb);
+
+ ADD_LINE(va.x, va.y, 0.0, 0.0, 0.0, 0.0);
+
+ for (int i = 0; i < spline_cons->num_controls; i++) {
+ va = spline_cons->controls[i];
+
+ nv_float s = 3.0 / example.zoom;
+ nvVector2 p0 = nvVector2_add(va, NV_VECTOR2(-s, -s));
+ nvVector2 p1 = nvVector2_add(va, NV_VECTOR2(-s, s));
+ nvVector2 p2 = nvVector2_add(va, NV_VECTOR2(s, s));
+ nvVector2 p3 = nvVector2_add(va, NV_VECTOR2(s, -s));
+
+ va = world_to_screen(&example, va);
+ va = normalize_coords(&example, va);
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+ p2 = world_to_screen(&example, p2);
+ p2 = normalize_coords(&example, p2);
+ p3 = world_to_screen(&example, p3);
+ p3 = normalize_coords(&example, p3);
+
+ ADD_LINE(
+ va.x, va.y,
+ example.theme.spline_constraint.r,
+ example.theme.spline_constraint.g,
+ example.theme.spline_constraint.b,
+ 0.19
+ );
+
+ ADD_TRIANGLE(
+ p0.x, p0.y,
+ p1.x, p1.y,
+ p2.x, p2.y,
+ example.theme.spline_constraint.r,
+ example.theme.spline_constraint.g,
+ example.theme.spline_constraint.b,
+ 1.0
+ );
+
+ ADD_TRIANGLE(
+ p0.x, p0.y,
+ p2.x, p2.y,
+ p3.x, p3.y,
+ example.theme.spline_constraint.r,
+ example.theme.spline_constraint.g,
+ example.theme.spline_constraint.b,
+ 1.0
+ );
+ }
+
+ ADD_LINE(va.x, va.y, 0.0, 0.0, 0.0, 0.0);
+
+ #define SPLINE_SAMPLES 200
+ nvVector2 sampled[SPLINE_SAMPLES];
+ sample_spline(spline_cons, sampled, SPLINE_SAMPLES);
+
+ va = sampled[0];
+ va = world_to_screen(&example, va);
+ va = normalize_coords(&example, va);
+ ADD_LINE(va.x, va.y, 0.0, 0.0, 0.0, 0.0);
+
+ for (size_t i = 0; i < SPLINE_SAMPLES; i++) {
+ va = sampled[i];
+
+ va = world_to_screen(&example, va);
+ va = normalize_coords(&example, va);
+
+ ADD_LINE(va.x, va.y, 1.0, 1.0, 1.0, 1.0);
+ }
+
+ ADD_LINE(va.x, va.y, 0.0, 0.0, 0.0, 0.0);
+
+ break;
+ }
+ }
+ }
+ }
+
+ if (draw_contacts) {
+ void *map_val;
+ size_t l = 0;
+ while (nvHashMap_iter(example.space->contacts, &l, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
+ for (size_t c = 0; c < pcp->contact_count; c++) {
+ nvContact contact = pcp->contacts[c];
+
+ FColor color;
+ if (contact.separation > 0) {
+ color = (FColor){1.0, 0.2, 0.0, 0.1};
+ }
+ else {
+ color = (FColor){1.0, 0.2, 0.0, 1.0};
+ }
+
+ nvVector2 pa = pcp->body_b->position;
+ nvVector2 p = nvVector2_add(pa, contact.anchor_b);
+
+ if (example.mouse.right && nvVector2_len(nvVector2_sub(p, example.before_zoom)) < 0.1) {
+ printf(
+ "Contact %llu\n"
+ " Shape A: %u\n"
+ " Shape B: %u\n"
+ " Body A: %llu\n"
+ " Body B: %llu\n"
+ " Depth: %f\n",
+ (unsigned long long)contact.id,
+ (unsigned int)pcp->shape_a->id,
+ (unsigned int)pcp->shape_b->id,
+ (unsigned long long)pcp->body_a->id,
+ (unsigned long long)pcp->body_b->id,
+ contact.separation
+ );
+ }
+
+ nv_float w = 3.2 / example.zoom;
+ nv_float h = w * 2.5;
+ nv_float a = nv_atan2(pcp->normal.y, pcp->normal.x);
+ nvVector2 r0 = nvVector2_rotate(NV_VECTOR2(0.0, w), a);
+ nvVector2 r1 = nvVector2_rotate(NV_VECTOR2(h, 0.0), a);
+ nvVector2 r2 = nvVector2_rotate(NV_VECTOR2(0.0, -w), a);
+ nvVector2 r3 = nvVector2_rotate(NV_VECTOR2(-h, 0.0), a);
+ nvVector2 p0 = nvVector2_add(p, r0);
+ nvVector2 p1 = nvVector2_add(p, r1);
+ nvVector2 p2 = nvVector2_add(p, r2);
+ nvVector2 p3 = nvVector2_add(p, r3);
+
+ // Draw either penetration depth or normal impulse
+ nv_float normal_mag;
+ if (draw_normal_impulses)
+ normal_mag = contact.solver_info.normal_impulse;
+ else
+ normal_mag = -contact.separation;
+
+ nvVector2 pn = nvVector2_add(p, nvVector2_mul(pcp->normal, normal_mag));
+
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+ p2 = world_to_screen(&example, p2);
+ p2 = normalize_coords(&example, p2);
+ p3 = world_to_screen(&example, p3);
+ p3 = normalize_coords(&example, p3);
+ pn = world_to_screen(&example, pn);
+ pn = normalize_coords(&example, pn);
+ p = world_to_screen(&example, p);
+ p = normalize_coords(&example, p);
+
+ ADD_LINE(p.x, p.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(
+ p.x, p.y,
+ 1.0,
+ 0.7,
+ 0.7,
+ color.a
+ );
+ ADD_LINE(
+ pn.x, pn.y,
+ 1.0,
+ 0.7,
+ 0.7,
+ color.a
+ );
+ ADD_LINE(p.x, p.y, 0.0, 0.0, 0.0, 0.0);
+
+ // Draw friction impulses
+ if (draw_friction_impulses) {
+ nv_float tangent_mag = contact.solver_info.tangent_impulse;
+ nvVector2 pt = nvVector2_add(
+ nvVector2_add(pa, contact.anchor_b), nvVector2_mul(nvVector2_perpr(pcp->normal), tangent_mag));
+ pt = world_to_screen(&example, pt);
+ pt = normalize_coords(&example, pt);
+
+ ADD_LINE(p.x, p.y, 0.0, 0.0, 0.0, 0.0);
+ ADD_LINE(
+ p.x, p.y,
+ 1.0,
+ 0.8,
+ 0.7,
+ color.a
+ );
+ ADD_LINE(
+ pt.x, pt.y,
+ 1.0,
+ 0.8,
+ 0.7,
+ color.a
+ );
+ ADD_LINE(p.x, p.y, 0.0, 0.0, 0.0, 0.0);
+ }
+
+ ADD_TRIANGLE(
+ p0.x, p0.y,
+ p1.x, p1.y,
+ p2.x, p2.y,
+ color.r,
+ color.g,
+ color.b,
+ color.a
+ );
+
+ ADD_TRIANGLE(
+ p0.x, p0.y,
+ p2.x, p2.y,
+ p3.x, p3.y,
+ color.r,
+ color.g,
+ color.b,
+ color.a
+ );
+ }
+ }
+ }
+
+ if (draw_broadphase) {
+ if (nvSpace_get_broadphase(example.space) == nvBroadPhaseAlg_BVH) {
+ nvBVHNode *bvh = nvBVHTree_new(example.space->bodies);
+ bvh_calc_depth(bvh, 0);
+ nv_int64 max_depth = bvh_max_depth(bvh);
+
+ nvArray *stack = nvArray_new();
+ nvBVHNode *current = bvh;
+
+ while (stack->size != 0 || current) {
+ while (current) {
+ nvArray_add(stack, current);
+ current = current->left;
+ }
+ // Current node is NULL at this point
+ // continue from stack
+
+ current = nvArray_pop(stack, stack->size - 1);
+
+ nvAABB saabb = current->aabb;
+ nvVector2 p0 = NV_VECTOR2(saabb.min_x, saabb.min_y);
+ nvVector2 p1 = NV_VECTOR2(saabb.max_x, saabb.min_y);
+ nvVector2 p2 = NV_VECTOR2(saabb.max_x, saabb.max_y);
+ nvVector2 p3 = NV_VECTOR2(saabb.min_x, saabb.max_y);
+ p0 = world_to_screen(&example, p0);
+ p0 = normalize_coords(&example, p0);
+ p1 = world_to_screen(&example, p1);
+ p1 = normalize_coords(&example, p1);
+ p2 = world_to_screen(&example, p2);
+ p2 = normalize_coords(&example, p2);
+ p3 = world_to_screen(&example, p3);
+ p3 = normalize_coords(&example, p3);
+
+ double t = (double)current->depth / (double)max_depth;
+
+ FColor color = FColor_lerp((FColor){0.0, 0.0, 1.0, 1.0}, (FColor){1.0, 0.0, 0.0, 1.0}, t);
+
+ ADD_TRIANGLE(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y, color.r, color.g, color.b, 0.1);
+ ADD_TRIANGLE(p0.x, p0.y, p3.x, p3.y, p2.x, p2.y, color.r, color.g, color.b, 0.1);
+
+ ADD_LINE(p0.x, p0.y, color.r, color.g, color.b, 0.0);
+ ADD_LINE(p0.x, p0.y, color.r, color.g, color.b, 0.7);
+ ADD_LINE(p1.x, p1.y, color.r, color.g, color.b, 0.7);
+ ADD_LINE(p2.x, p2.y, color.r, color.g, color.b, 0.7);
+ ADD_LINE(p3.x, p3.y, color.r, color.g, color.b, 0.7);
+ ADD_LINE(p0.x, p0.y, color.r, color.g, color.b, 0.7);
+ ADD_LINE(p0.x, p0.y, color.r, color.g, color.b, 0.0);
+
+ current = current->right;
+ }
+
+ nvArray_free(stack);
+ nvBVHTree_free(bvh);
+ }
+ }
+
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, (tri_vertices_index) * sizeof(float), tri_vertices);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[1]);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, (tri_colors_index) * sizeof(float), tri_colors);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[2]);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, (line_vertices_index) * sizeof(float), line_vertices);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, vbos[3]);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, (line_colors_index) * sizeof(float), line_colors);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+ nvPrecisionTimer_stop(&render_timer);
+ render_time += render_timer.elapsed,
+
+ nvPrecisionTimer_start(&render_timer);
+ ngl_clear(30.0f/255.0f, 27.0f/255.0f, 36.0f/255.0f, 1.0f);
+
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glEnable(GL_BLEND);
+
+ glUseProgram(program);
+ ngl_vao_render(vaos[0], GL_TRIANGLES, vao0_count);
+ ngl_vao_render(vaos[1], GL_LINE_STRIP, vao1_count);
+ glUseProgram(0);
+
+ nk_sdl_render(
+ NK_ANTI_ALIASING_ON,
+ NUKLEAR_MAX_VERTEX_MEMORY,
+ NUKLEAR_MAX_ELEMENT_MEMORY
+ );
+
+ SDL_GL_SwapWindow(example.window);
+ nvPrecisionTimer_stop(&render_timer);
+ render_time += render_timer.elapsed,
+
+ frame++;
+ }
+
+ nvSpace_free(example.space);
+
+ nk_sdl_shutdown();
+
+ NV_FREE(tri_vertices);
+ NV_FREE(tri_colors);
+ NV_FREE(line_vertices);
+ NV_FREE(line_colors);
+
+ glDeleteVertexArrays(2, vaos);
+ glDeleteBuffers(4, vbos);
+ glDeleteProgram(program);
+
+ SDL_GL_DeleteContext(example.gl_ctx);
+ SDL_DestroyWindow(example.window);
+ SDL_Quit();
+
+ return EXIT_SUCCESS;
+}
\ No newline at end of file
diff --git a/examples/newtons_cradle.h b/examples/newtons_cradle.h
deleted file mode 100644
index 6fb0a57..0000000
--- a/examples/newtons_cradle.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void NewtonsCradleExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- int n = 7; // Amount of balls
- nv_float radius = 4.2; // Radius of balls
- nv_float width = (radius + 0.01) * 2.0 * n; // Size of the cradle
- nv_float length = 30.0; // Length of the cradle links
-
- nvMaterial ball_material = (nvMaterial){
- .density = 1.0,
- .restitution = 1.0,
- .friction = 0.1
- };
-
- for (size_t i = 0; i < n; i++) {
- nvBody *ball;
- if (i == 0) {
- ball = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(radius),
- NV_VEC2(
- 1280.0 / 20.0 - width / 2.0 + i * radius * 2.0001 + radius - length/2.0,
- 16.0 + length + 1.1 + radius - length/2.0
- ),
- 0.0,
- ball_material
- );
- }
- else {
- ball = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(radius),
- NV_VEC2(
- 1280.0 / 20.0 - width / 2.0 + i * radius * 2.0001 + radius,
- 16.0 + length + 1.1 + radius
- ),
- 0.0,
- ball_material
- );
- }
-
- nvSpace_add(space, ball);
-
- nvVector2 connection_pos = {
- 1280.0 / 20.0 - width / 2.0 + i * radius * 2.0001 + radius,
- 16.0
- };
-
- nvConstraint *dist_joint = nvDistanceJoint_new(
- NULL, ball,
- connection_pos, nvVector2_zero,
- length
- );
-
- nvSpace_add_constraint(space, dist_joint);
- }
-}
\ No newline at end of file
diff --git a/examples/ngl.h b/examples/ngl.h
new file mode 100644
index 0000000..f12f2e9
--- /dev/null
+++ b/examples/ngl.h
@@ -0,0 +1,62 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_EXAMPLE_GL_HELPER_H
+#define NOVAPHYSICS_EXAMPLE_GL_HELPER_H
+
+#include
+#include
+
+#include
+#include
+
+#include "common.h"
+
+
+nv_uint32 ngl_load_shader(const char *source, int shader_type) {
+ nv_uint32 shader_id = glCreateShader(shader_type);
+ glShaderSource(shader_id, 1, &source, NULL);
+ glCompileShader(shader_id);
+
+ int success;
+ glGetShaderiv(shader_id, GL_COMPILE_STATUS, &success);
+ if (!success) {
+ fprintf(stderr, "Shader compilation error.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ return shader_id;
+}
+
+nv_uint32 ngl_create_vbo() {
+ nv_uint32 vbo_id;
+ glGenBuffers(1, &vbo_id);
+ return vbo_id;
+}
+
+nv_uint32 ngl_create_vao() {
+ nv_uint32 vao_id;
+ glGenVertexArrays(1, &vao_id);
+ return vao_id;
+}
+
+void ngl_clear(float red, float green, float blue, float alpha) {
+ glClearColor(red, green, blue, alpha);
+ glClear(GL_COLOR_BUFFER_BIT);
+}
+
+void ngl_vao_render(nv_uint32 vao_id, nv_uint32 mode, size_t count) {
+ glBindVertexArray(vao_id);
+ glDrawArrays(mode, 0, (int)count);
+ glBindVertexArray(0);
+}
+
+
+#endif
\ No newline at end of file
diff --git a/examples/orbit.h b/examples/orbit.h
deleted file mode 100644
index 55b15e9..0000000
--- a/examples/orbit.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void OrbitExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- space->gravity = nvVector2_zero;
-
- nvMaterial star_material = (nvMaterial){
- .density = 15.0,
- .restitution = 0.5,
- .friction = 0.0
- };
-
- nvMaterial planet_material = (nvMaterial){
- .density = 2.0,
- .restitution = 0.5,
- .friction = 0.0
- };
-
- nvBody *star = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(3.0),
- NV_VEC2(64.0, 36.0),
- 0.0,
- star_material
- );
-
- nvSpace_add(space, star);
-
- nvBody_set_is_attractor(star, true);
-
- for (nv_float angle = 0.0; angle < 2.0 * NV_PI; angle += 0.1) {
- nv_float dist = frand(25.0, 40.0);
- nvVector2 delta = nvVector2_rotate(NV_VEC2(dist, 0.0), angle);
- nvVector2 pos = nvVector2_add(star->position, delta);
-
- nvBody *planet = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(0.7),
- pos,
- 0.0,
- planet_material
- );
-
- nvSpace_add(space, planet);
-
- nv_float strength = 1.5e2 / ((dist - 25.0) / 5.0 + 1.0); // / ((dist - 20.0) * 0.5);
- nvBody_apply_force(planet, nvVector2_mul(nvVector2_perp(delta), strength));
- }
-}
\ No newline at end of file
diff --git a/examples/pool.h b/examples/pool.h
deleted file mode 100644
index 23e9357..0000000
--- a/examples/pool.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void PoolExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create borders of the pool
-
- nvBody *wall_bottom = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(60.0, 5.0),
- NV_VEC2(64.0, 62.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, wall_bottom);
-
- nvBody *wall_left = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 40.0),
- NV_VEC2(24.0, 47.5),
- -NV_PI / 5.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, wall_left);
-
- nvBody *wall_right = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(5.0, 40.0),
- NV_VEC2(104.0, 47.5),
- NV_PI / 5.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, wall_right);
-
-
- // Add balls
-
- double radius = 0.7;
-
- nvMaterial ball_material = {
- .density = 1.0,
- .restitution = 0.0,
- .friction = 0.0
- };
-
- for (size_t y = 0; y < 18; y++) {
- for (size_t x = 0; x < 30; x++) {
-
- nvBody *ball = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(radius),
- NV_VEC2(33.0 + x * (radius * 2.0), 25.8 + y * (radius * 2.0)),
- 0.0,
- ball_material
- );
-
- nvSpace_add(space, ball);
- }
- }
-
-
- // Add ship
-
- // Vertices array will get free'd along with bodies
- // once nvSpace_free is called (or Example_free in this case)
- nvArray *ship_vertices = nvArray_new();
- nvArray_add(ship_vertices, NV_VEC2_NEW(-5.0, -2.0));
- nvArray_add(ship_vertices, NV_VEC2_NEW(5.0, -2.0));
- nvArray_add(ship_vertices, NV_VEC2_NEW(3.0, 2.0));
- nvArray_add(ship_vertices, NV_VEC2_NEW(-3.0, 2.0));
-
- nvBody *ship = nvBody_new(
- nvBodyType_DYNAMIC,
- nvPolygonShape_new(ship_vertices),
- NV_VEC2(44.0, 15.0),
- 0.0,
- nvMaterial_GLASS
- );
-
- nvSpace_add(space, ship);
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID)
- nvSpace_set_SHG(space, space->shg->bounds, 1.4, 1.4);
-}
\ No newline at end of file
diff --git a/examples/pyramid.h b/examples/pyramid.h
deleted file mode 100644
index 671eb81..0000000
--- a/examples/pyramid.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void PyramidExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create ground
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(200.0, 5.0),
- NV_VEC2(64.0, 62.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
-
- // Create bricks of the pyramid
-
- size_t base = get_slider_setting("Pyramid base");
- nv_float size = get_slider_setting("Box size");
- nv_float s2 = size / 2.0;
- nv_float y_gap = get_slider_setting("Air gap");
-
- for (size_t y = 0; y < base; y++) {
- for (size_t x = 0; x < base - y; x++) {
-
- nvBody *brick = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(size, size),
- NV_VEC2(
- 128.0 / 2.0 - (base * s2 - s2) + x * size + y * s2,
- 62.5 - 2.5 - s2 - y * (size + y_gap)
- ),
- 0.0,
- nvMaterial_BASIC
- );
-
- nvSpace_add(space, brick);
- }
- }
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID)
- nvSpace_set_SHG(space, space->shg->bounds, size + (size * 0.2), size + (size * 0.2));
-}
-
-
-void PyramidExample_init(ExampleEntry *entry) {
- add_slider_setting(entry, "Pyramid base", SliderType_INTEGER, 32, 3, 100);
- add_slider_setting(entry, "Box size", SliderType_FLOAT, 1.5, 0.5, 3.0);
- add_slider_setting(entry, "Air gap", SliderType_FLOAT, 0.0, 0.0, 1.5);
-}
\ No newline at end of file
diff --git a/examples/ragdolls.h b/examples/ragdolls.h
deleted file mode 100644
index ad47dd2..0000000
--- a/examples/ragdolls.h
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void create_ragdoll(nvSpace *space, nvVector2 position, nv_float scale, nv_uint32 group) {
- nvBody *torso = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((1.5 * scale) * 2.0, (2.0 * scale) * 2.0),
- position,
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, torso);
- torso->collision_group = group;
-
- nvBody *head = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.0 * scale),
- NV_VEC2(position.x, position.y - 2.0 * scale - 1.0 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, head);
- head->collision_group = group;
-
- nvConstraint *head_link = nvHingeJoint_new(torso, head, NV_VEC2(position.x, position.y - 2.0 * scale));
- nvHingeJoint *head_link_def = (nvHingeJoint *)head_link->def;
- nvSpace_add_constraint(space, head_link);
- head_link_def->enable_limits = true;
- head_link_def->lower_limit = -NV_PI / 4.0;
- head_link_def->upper_limit = NV_PI / 4.0;
-
- nvBody *larm1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((1.5 * scale) * 2.0, (0.5 * scale) * 2.0),
- NV_VEC2(position.x - 1.5 * scale - 1.0 * scale, position.y - 2.0 * scale + 0.5 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, larm1);
- larm1->collision_group = group;
-
- nvConstraint *larm1_link = nvHingeJoint_new(torso, larm1, NV_VEC2(position.x - 1.5 * scale, position.y - 2.0 * scale + 0.5 * scale));
- nvHingeJoint *larm1_link_def = (nvHingeJoint *)larm1_link->def;
- nvSpace_add_constraint(space, larm1_link);
- larm1_link_def->enable_limits = true;
- larm1_link_def->lower_limit = -NV_PI / 2.0;
- larm1_link_def->upper_limit = NV_PI / 2.0;
-
- nvBody *larm2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((1.5 * scale) * 2.0, (0.5 * scale) * 2.0),
- NV_VEC2(position.x - 1.5 * scale - 2.0 * scale - 1.0 * scale, position.y - 2.0 * scale + 0.5 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, larm2);
- larm2->collision_group = group;
-
- nvConstraint *larm2_link = nvHingeJoint_new(larm1, larm2, NV_VEC2(position.x - 1.5 * scale - 2.0 * scale, position.y - 2.0 * scale + 0.5 * scale));
- nvHingeJoint *larm2_link_def = (nvHingeJoint *)larm2_link->def;
- nvSpace_add_constraint(space, larm2_link);
- larm2_link_def->enable_limits = true;
- larm2_link_def->lower_limit = -NV_PI / 2.0;
- larm2_link_def->upper_limit = NV_PI / 2.0;
-
- nvBody *rarm1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((1.5 * scale) * 2.0, (0.5 * scale) * 2.0),
- NV_VEC2(position.x + 1.5 * scale + 1.0 * scale, position.y - 2.0 * scale + 0.5 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, rarm1);
- rarm1->collision_group = group;
-
- nvConstraint *rarm1_link = nvHingeJoint_new(torso, rarm1, NV_VEC2(position.x + 1.5 * scale, position.y - 2.0 * scale + 0.5 * scale));
- nvHingeJoint *rarm1_link_def = (nvHingeJoint *)rarm1_link->def;
- nvSpace_add_constraint(space, rarm1_link);
- rarm1_link_def->enable_limits = true;
- rarm1_link_def->lower_limit = -NV_PI / 2.0;
- rarm1_link_def->upper_limit = NV_PI / 2.0;
-
- nvBody *rarm2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((1.5 * scale) * 2.0, (0.5 * scale) * 2.0),
- NV_VEC2(position.x + 1.5 * scale + 2.0 * scale + 1.0 * scale, position.y - 2.0 * scale + 0.5 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, rarm2);
- rarm2->collision_group = group;
-
- nvConstraint *rarm2_link = nvHingeJoint_new(rarm1, rarm2, NV_VEC2(position.x + 1.5 * scale + 2.0 * scale, position.y - 2.0 * scale + 0.5 * scale));
- nvHingeJoint *rarm2_link_def = (nvHingeJoint *)rarm2_link->def;
- nvSpace_add_constraint(space, rarm2_link);
- rarm2_link_def->enable_limits = true;
- rarm2_link_def->lower_limit = -NV_PI / 2.0;
- rarm2_link_def->upper_limit = NV_PI / 2.0;
-
- nvBody *lleg1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((0.5 * scale) * 2.0, (1.5 * scale) * 2.0),
- NV_VEC2(position.x - 1.5 * scale + 0.5 * scale, position.y + 2.0 * scale + 1.0 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, lleg1);
- lleg1->collision_group = group;
-
- nvConstraint *lleg1_link = nvHingeJoint_new(torso, lleg1, NV_VEC2(position.x - 1.5 * scale + 0.5 * scale, position.y + 2.0 * scale));
- nvHingeJoint *lleg1_link_def = (nvHingeJoint *)lleg1_link->def;
- nvSpace_add_constraint(space, lleg1_link);
- lleg1_link_def->enable_limits = true;
- lleg1_link_def->lower_limit = -NV_PI / 2.0 + 0.3;
- lleg1_link_def->upper_limit = NV_PI / 2.0 - 0.3;
-
- nvBody *lleg2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((0.5 * scale) * 2.0, (1.5 * scale) * 2.0),
- NV_VEC2(position.x - 1.5 * scale + 0.5 * scale, position.y + 2.0 * scale + 2.0 * scale + 1.0 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, lleg2);
- lleg2->collision_group = group;
-
- nvConstraint *lleg2_link = nvHingeJoint_new(lleg1, lleg2, NV_VEC2(position.x - 1.5 * scale + 0.5 * scale, position.y + 2.0 * scale + 2.0 * scale));
- nvHingeJoint *lleg2_link_def = (nvHingeJoint *)lleg2_link->def;
- nvSpace_add_constraint(space, lleg2_link);
- lleg2_link_def->enable_limits = true;
- lleg2_link_def->lower_limit = -NV_PI / 2.0 + 0.0;
- lleg2_link_def->upper_limit = 0.0;
-
- nvBody *rleg1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((0.5 * scale) * 2.0, (1.5 * scale) * 2.0),
- NV_VEC2(position.x + 1.5 * scale - 0.5 * scale, position.y + 2.0 * scale + 1.0 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, rleg1);
- rleg1->collision_group = group;
-
- nvConstraint *rleg1_link = nvHingeJoint_new(torso, rleg1, NV_VEC2(position.x + 1.5 * scale - 0.5 * scale, position.y + 2.0 * scale));
- nvHingeJoint *rleg1_link_def = (nvHingeJoint *)rleg1_link->def;
- nvSpace_add_constraint(space, rleg1_link);
- rleg1_link_def->enable_limits = true;
- rleg1_link_def->lower_limit = -NV_PI / 2.0 + 0.3;
- rleg1_link_def->upper_limit = NV_PI / 2.0 - 0.3;
-
- nvBody *rleg2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new((0.5 * scale) * 2.0, (1.5 * scale) * 2.0),
- NV_VEC2(position.x + 1.5 * scale - 0.5 * scale, position.y + 2.0 * scale + 2.0 * scale + 1.0 * scale),
- 0.0,
- nvMaterial_BASIC
- );
- nvSpace_add(space, rleg2);
- rleg2->collision_group = group;
-
- nvConstraint *rleg2_link = nvHingeJoint_new(rleg1, rleg2, NV_VEC2(position.x + 1.5 * scale - 0.5 * scale, position.y + 2.0 * scale + 2.0 * scale));
- nvHingeJoint *rleg2_link_def = (nvHingeJoint *)rleg2_link->def;
- nvSpace_add_constraint(space, rleg2_link);
- rleg2_link_def->enable_limits = true;
- rleg2_link_def->lower_limit = 0.0;
- rleg2_link_def->upper_limit = NV_PI / 2.0 - 0.3;
-}
-
-
-void RagdollsExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 72.0 - 2.5),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
- for (size_t i = 0; i < 100; i++) {
- create_ragdoll(example->space, NV_VEC2(64.0 + frand(-30.0, 30.0), 36.0 + frand(-130.0, 15.0)), 1.0, i + 0.6);
- }
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SHG)
- nvSpace_set_SHG(space, space->shg->bounds, 2.0, 2.0);
-}
\ No newline at end of file
diff --git a/examples/spring_car.h b/examples/spring_car.h
deleted file mode 100644
index 6065823..0000000
--- a/examples/spring_car.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void SpringCarExample_update(Example *example) {
- nvSpace *space = example->space;
-
- if (example->keys[SDL_SCANCODE_LEFT] || example->keys[SDL_SCANCODE_RIGHT]) {
- nvBody *wheel1 = (nvBody *)space->bodies->data[5];
-
- double strength = 18.0 * 1e2;
- double limit = 30.0;
-
- if (example->keys[SDL_SCANCODE_LEFT]) {
- if (wheel1->angular_velocity > -limit)
- wheel1->torque -= strength;
- }
- else {
- if (wheel1->angular_velocity < limit)
- wheel1->torque += strength;
- }
- }
-}
-
-
-void SpringCarExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create ground
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 22.0),
- NV_VEC2(64.0, 36.0 + 25.0),
- 0.0,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground);
-
- nvBody *ground2 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(15.0, 3.0),
- NV_VEC2(75.0, 50.0),
- -0.3,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground2);
-
- nvBody *ground3 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(15.0, 3.0),
- NV_VEC2(86.0, 43.0),
- -0.8,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground3);
-
- nvBody *ground4 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(7.0, 3.0),
- NV_VEC2(92.0, 35.5),
- -1.1,
- nvMaterial_CONCRETE
- );
-
- nvSpace_add(space, ground4);
-
-
- // Create wheels
-
- nvMaterial wheel_mat = (nvMaterial){1.5, 0.3, 3.0};
-
- nvBody *wheel1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.8),
- NV_VEC2(53.0, 32.0),
- 0.0,
- wheel_mat
- );
- wheel1->collision_group = 1;
- nvSpace_add(space, wheel1);
-
- nvBody *wheel2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(1.8),
- NV_VEC2(57.0, 32.0),
- 0.0,
- wheel_mat
- );
- wheel2->collision_group = 1;
- nvSpace_add(space, wheel2);
-
-
- // Create car body
- nvArray *car_body_vertices = nvArray_new();
- nvArray_add(car_body_vertices, NV_VEC2_NEW(-5.0, 2.5));
- nvArray_add(car_body_vertices, NV_VEC2_NEW(-5.0, 0.0));
- nvArray_add(car_body_vertices, NV_VEC2_NEW(-3.0, -2.5));
- nvArray_add(car_body_vertices, NV_VEC2_NEW(1.0, -2.5));
- nvArray_add(car_body_vertices, NV_VEC2_NEW(5.0, 0.0));
- nvArray_add(car_body_vertices, NV_VEC2_NEW(5.0, 2.5));
-
- // Fix the centroid of the polygon shape
- nvVector2 centroid = nv_polygon_centroid(car_body_vertices);
- for (size_t i = 0; i < car_body_vertices->size; i++) {
- nvVector2 vert = NV_TO_VEC2(car_body_vertices->data[i]);
-
- vert = nvVector2_sub(vert, centroid);
-
- NV_TO_VEC2P(car_body_vertices->data[i])->x = vert.x;
- NV_TO_VEC2P(car_body_vertices->data[i])->y = vert.y;
- }
-
- nvBody *car_body = nvBody_new(
- nvBodyType_DYNAMIC,
- nvPolygonShape_new(car_body_vertices),
- NV_VEC2(55.0, 30.0),
- 0.0,
- (nvMaterial){4.0, 0.3, 0.5}
- );
- car_body->collision_group = 1;
- nvSpace_add(space, car_body);
-
-
- // Create spring constraints
-
- double suspension_length = 2.3;
- double suspension_strength = 2500.0;
- double suspension_damping = 150.00;
-
- nvConstraint *spring1 = nvSpring_new(
- wheel1, car_body,
- NV_VEC2(0.0, 0.0), NV_VEC2(-3.5, 0.4),
- suspension_length,
- suspension_strength,
- suspension_damping
- );
-
- nvSpace_add_constraint(space, spring1);
-
- nvConstraint *spring2 = nvSpring_new(
- wheel1, car_body,
- NV_VEC2(0.0, 0.0), NV_VEC2(-1.0, 0.4),
- suspension_length,
- suspension_strength * 6.0,
- suspension_damping * 2.0
- );
-
-
- nvSpace_add_constraint(space, spring2);
-
- nvConstraint *spring3 = nvSpring_new(
- wheel2, car_body,
- NV_VEC2(0.0, 0.0), NV_VEC2(4.0, 0.4),
- suspension_length,
- suspension_strength,
- suspension_damping
- );
-
- nvSpace_add_constraint(space, spring3);
-
- nvConstraint *spring4 = nvSpring_new(
- wheel2, car_body,
- NV_VEC2(0.0, 0.0), NV_VEC2(1.5, 0.4),
- suspension_length,
- suspension_strength * 6.0,
- suspension_damping * 2.0
- );
-
- nvSpace_add_constraint(space, spring4);
-}
\ No newline at end of file
diff --git a/examples/stack.h b/examples/stack.h
deleted file mode 100644
index 637c7b5..0000000
--- a/examples/stack.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void StackExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- // Create ground & walls
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(128.0, 5.0),
- NV_VEC2(64.0, 70.0),
- 0.0,
- (nvMaterial){1.0, 0.1, 0.65}
- );
-
- nvSpace_add(space, ground);
-
- nv_float offsets[20] = {
- -0.3, 0.1, 0.0, 0.2, -0.15,
- 0.05, -0.09, 0.04, -0.1, 0.3,
- 0.2, 0.24, -0.017, 0.17, 0.03,
- 0.3, 0.0, -0.06, 0.25, 0.08
- };
-
- // Create stacked boxes
-
- int cols = 12;
- int rows = 20;
- nv_float size = 3.0;
- nv_float s2 = size / 2.0;
- nv_float gap = 0.0;
-
- size_t x = 0;
- size_t y = 0;
-
- nv_float horizontal_offset = 0.0;
-
- for (y = 0; y < rows; y++) {
- for (x = 0; x < cols; x ++) {
- if (y > x + 8) continue;
-
- nv_float offset = offsets[(x + y) % 20] * horizontal_offset;
-
- nvBody *box = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(size, size),
- NV_VEC2(
- 128.0 / 2.0 - 25.0 - ((nv_float)cols * size) / 2.0 + s2 + size * x + offset + (x * 4.5),
- 70 - 2.5 - s2 - y * (size + gap)
- ),
- 0.0,
- (nvMaterial){1.0, 0.0, 0.5}
- );
-
- nvSpace_add(space, box);
- }
- }
-
-
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SPATIAL_HASH_GRID)
- nvSpace_set_SHG(space, space->shg->bounds, 3.8, 3.8);
-}
\ No newline at end of file
diff --git a/examples/varying_bounce.h b/examples/varying_bounce.h
deleted file mode 100644
index 54ce1b4..0000000
--- a/examples/varying_bounce.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void VaryingBounceExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- nvMaterial ground_mat = {
- .density = 1.0,
- .restitution = 1.0,
- .friction = 0.0
- };
-
- // Create ground
- nvBody *ground = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(185.0, 5.0),
- NV_VEC2(64.0, 62.5),
- 0.0,
- ground_mat
- );
-
- nvSpace_add(space, ground);
-
- for (size_t i = 0; i < 5; i++) {
-
- nvMaterial material = {
- .density = 1.0,
- .restitution = (nv_float)i / 4.0,
- .friction = 0.0
- };
-
- nvBody *ball = nvBody_new(
- nvBodyType_DYNAMIC,
- nvCircleShape_new(4.0),
- NV_VEC2(45.0 + (i * (8.0 + 1.0)), 20.0),
- 0.0,
- material
- );
-
- nvSpace_add(space, ball);
- }
-}
\ No newline at end of file
diff --git a/examples/varying_friction.h b/examples/varying_friction.h
deleted file mode 100644
index ef63e45..0000000
--- a/examples/varying_friction.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "example.h"
-
-
-void VaryingFrictionExample_setup(Example *example) {
- nvSpace *space = example->space;
-
- nvMaterial platform_mat = {
- .density = 1.0,
- .restitution = 0.0,
- .friction = 0.5
- };
-
- nv_float platform_angle = 0.6;
- nv_float box_angle = 0.0;
-
- // Create platforms
- nvBody *platform0 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(100.0, 2.0),
- NV_VEC2(64.0, 18.0 + 15.0),
- platform_angle,
- platform_mat
- );
-
- nvSpace_add(space, platform0);
-
- nvBody *platform1 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(100.0, 2.0),
- NV_VEC2(64.0, 36.0 + 15.0),
- platform_angle,
- platform_mat
- );
-
- nvSpace_add(space, platform1);
-
- nvBody *platform2 = nvBody_new(
- nvBodyType_STATIC,
- nvRectShape_new(100.0, 2.0),
- NV_VEC2(64.0, 54.0 + 15.0),
- platform_angle,
- platform_mat
- );
-
- nvSpace_add(space, platform2);
-
- // Create boxes
- nvBody *box0 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(3.0, 3.0),
- NV_VEC2(50.0, 18.0),
- box_angle,
- (nvMaterial){
- .density = 1.0,
- .restitution = 0.0,
- .friction = 0.0
- }
- );
-
- nvSpace_add(space, box0);
-
- nvBody *box1 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(3.0, 3.0),
- NV_VEC2(50.0, 36.0),
- box_angle,
- (nvMaterial){
- .density = 1.0,
- .restitution = 0.0,
- .friction = 0.35
- }
- );
-
- nvSpace_add(space, box1);
-
- nvBody *box2 = nvBody_new(
- nvBodyType_DYNAMIC,
- nvRectShape_new(3.0, 3.0),
- NV_VEC2(50.0, 54.0),
- box_angle,
- (nvMaterial){
- .density = 1.0,
- .restitution = 0.0,
- .friction = 0.8
- }
- );
-
- nvSpace_add(space, box2);
-}
\ No newline at end of file
diff --git a/external/glad/glad.c b/external/glad/glad.c
new file mode 100644
index 0000000..426cc11
--- /dev/null
+++ b/external/glad/glad.c
@@ -0,0 +1,2532 @@
+/*
+
+ OpenGL loader generated by glad 0.1.36 on Mon Mar 4 16:26:18 2024.
+
+ Language/Generator: C/C++
+ Specification: gl
+ APIs: gl=4.6
+ Profile: compatibility
+ Extensions:
+
+ Loader: True
+ Local files: False
+ Omit khrplatform: False
+ Reproducible: False
+
+ Commandline:
+ --profile="compatibility" --api="gl=4.6" --generator="c" --spec="gl" --extensions=""
+ Online:
+ https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.6
+*/
+
+#include
+#include
+#include
+#include
+
+static void* get_proc(const char *namez);
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+#ifndef _WINDOWS_
+#undef APIENTRY
+#endif
+#include
+static HMODULE libGL;
+
+typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*);
+static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr;
+
+#ifdef _MSC_VER
+#ifdef __has_include
+ #if __has_include()
+ #define HAVE_WINAPIFAMILY 1
+ #endif
+#elif _MSC_VER >= 1700 && !_USING_V110_SDK71_
+ #define HAVE_WINAPIFAMILY 1
+#endif
+#endif
+
+#ifdef HAVE_WINAPIFAMILY
+ #include
+ #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+ #define IS_UWP 1
+ #endif
+#endif
+
+static
+int open_gl(void) {
+#ifndef IS_UWP
+ libGL = LoadLibraryW(L"opengl32.dll");
+ if(libGL != NULL) {
+ void (* tmp)(void);
+ tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress");
+ gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp;
+ return gladGetProcAddressPtr != NULL;
+ }
+#endif
+
+ return 0;
+}
+
+static
+void close_gl(void) {
+ if(libGL != NULL) {
+ FreeLibrary((HMODULE) libGL);
+ libGL = NULL;
+ }
+}
+#else
+#include
+static void* libGL;
+
+#if !defined(__APPLE__) && !defined(__HAIKU__)
+typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*);
+static 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) {
+#if defined(__APPLE__) || defined(__HAIKU__)
+ return 1;
+#else
+ gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL,
+ "glXGetProcAddressARB");
+ return gladGetProcAddressPtr != NULL;
+#endif
+ }
+ }
+
+ return 0;
+}
+
+static
+void close_gl(void) {
+ if(libGL != NULL) {
+ dlclose(libGL);
+ libGL = NULL;
+ }
+}
+#endif
+
+static
+void* get_proc(const char *namez) {
+ void* result = NULL;
+ if(libGL == NULL) return NULL;
+
+#if !defined(__APPLE__) && !defined(__HAIKU__)
+ if(gladGetProcAddressPtr != NULL) {
+ result = gladGetProcAddressPtr(namez);
+ }
+#endif
+ if(result == NULL) {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ result = (void*)GetProcAddress((HMODULE) 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 = { 0, 0 };
+
+#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 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 {
+ unsigned int index;
+
+ num_exts_i = 0;
+ glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i);
+ if (num_exts_i > 0) {
+ exts_i = (char **)malloc((size_t)num_exts_i * (sizeof *exts_i));
+ }
+
+ if (exts_i == NULL) {
+ return 0;
+ }
+
+ for(index = 0; index < (unsigned)num_exts_i; index++) {
+ const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index);
+ size_t len = strlen(gl_str_tmp);
+
+ char *local_str = (char*)malloc((len+1) * sizeof(char));
+ if(local_str != NULL) {
+ memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char));
+ }
+ exts_i[index] = local_str;
+ }
+ }
+#endif
+ return 1;
+}
+
+static void free_exts(void) {
+ if (exts_i != NULL) {
+ int index;
+ for(index = 0; index < num_exts_i; index++) {
+ free((char *)exts_i[index]);
+ }
+ free((void *)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;
+ if(exts_i == NULL) return 0;
+ for(index = 0; index < num_exts_i; index++) {
+ const char *e = exts_i[index];
+
+ if(exts_i[index] != NULL && strcmp(e, ext) == 0) {
+ return 1;
+ }
+ }
+ }
+#endif
+
+ return 0;
+}
+int GLAD_GL_VERSION_1_0 = 0;
+int GLAD_GL_VERSION_1_1 = 0;
+int GLAD_GL_VERSION_1_2 = 0;
+int GLAD_GL_VERSION_1_3 = 0;
+int GLAD_GL_VERSION_1_4 = 0;
+int GLAD_GL_VERSION_1_5 = 0;
+int GLAD_GL_VERSION_2_0 = 0;
+int GLAD_GL_VERSION_2_1 = 0;
+int GLAD_GL_VERSION_3_0 = 0;
+int GLAD_GL_VERSION_3_1 = 0;
+int GLAD_GL_VERSION_3_2 = 0;
+int GLAD_GL_VERSION_3_3 = 0;
+int GLAD_GL_VERSION_4_0 = 0;
+int GLAD_GL_VERSION_4_1 = 0;
+int GLAD_GL_VERSION_4_2 = 0;
+int GLAD_GL_VERSION_4_3 = 0;
+int GLAD_GL_VERSION_4_4 = 0;
+int GLAD_GL_VERSION_4_5 = 0;
+int GLAD_GL_VERSION_4_6 = 0;
+PFNGLACCUMPROC glad_glAccum = NULL;
+PFNGLACTIVESHADERPROGRAMPROC glad_glActiveShaderProgram = NULL;
+PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL;
+PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL;
+PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL;
+PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL;
+PFNGLATTACHSHADERPROC glad_glAttachShader = NULL;
+PFNGLBEGINPROC glad_glBegin = NULL;
+PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL;
+PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL;
+PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed = NULL;
+PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL;
+PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL;
+PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL;
+PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL;
+PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL;
+PFNGLBINDBUFFERSBASEPROC glad_glBindBuffersBase = NULL;
+PFNGLBINDBUFFERSRANGEPROC glad_glBindBuffersRange = NULL;
+PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL;
+PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL;
+PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL;
+PFNGLBINDIMAGETEXTUREPROC glad_glBindImageTexture = NULL;
+PFNGLBINDIMAGETEXTURESPROC glad_glBindImageTextures = NULL;
+PFNGLBINDPROGRAMPIPELINEPROC glad_glBindProgramPipeline = NULL;
+PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL;
+PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL;
+PFNGLBINDSAMPLERSPROC glad_glBindSamplers = NULL;
+PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL;
+PFNGLBINDTEXTUREUNITPROC glad_glBindTextureUnit = NULL;
+PFNGLBINDTEXTURESPROC glad_glBindTextures = NULL;
+PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback = NULL;
+PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL;
+PFNGLBINDVERTEXBUFFERPROC glad_glBindVertexBuffer = NULL;
+PFNGLBINDVERTEXBUFFERSPROC glad_glBindVertexBuffers = NULL;
+PFNGLBITMAPPROC glad_glBitmap = NULL;
+PFNGLBLENDCOLORPROC glad_glBlendColor = NULL;
+PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL;
+PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL;
+PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei = NULL;
+PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi = NULL;
+PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL;
+PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL;
+PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei = NULL;
+PFNGLBLENDFUNCIPROC glad_glBlendFunci = NULL;
+PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL;
+PFNGLBLITNAMEDFRAMEBUFFERPROC glad_glBlitNamedFramebuffer = NULL;
+PFNGLBUFFERDATAPROC glad_glBufferData = NULL;
+PFNGLBUFFERSTORAGEPROC glad_glBufferStorage = NULL;
+PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL;
+PFNGLCALLLISTPROC glad_glCallList = NULL;
+PFNGLCALLLISTSPROC glad_glCallLists = NULL;
+PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL;
+PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glad_glCheckNamedFramebufferStatus = NULL;
+PFNGLCLAMPCOLORPROC glad_glClampColor = NULL;
+PFNGLCLEARPROC glad_glClear = NULL;
+PFNGLCLEARACCUMPROC glad_glClearAccum = NULL;
+PFNGLCLEARBUFFERDATAPROC glad_glClearBufferData = NULL;
+PFNGLCLEARBUFFERSUBDATAPROC glad_glClearBufferSubData = NULL;
+PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL;
+PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL;
+PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL;
+PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL;
+PFNGLCLEARCOLORPROC glad_glClearColor = NULL;
+PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL;
+PFNGLCLEARDEPTHFPROC glad_glClearDepthf = NULL;
+PFNGLCLEARINDEXPROC glad_glClearIndex = NULL;
+PFNGLCLEARNAMEDBUFFERDATAPROC glad_glClearNamedBufferData = NULL;
+PFNGLCLEARNAMEDBUFFERSUBDATAPROC glad_glClearNamedBufferSubData = NULL;
+PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glad_glClearNamedFramebufferfi = NULL;
+PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glad_glClearNamedFramebufferfv = NULL;
+PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glad_glClearNamedFramebufferiv = NULL;
+PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glad_glClearNamedFramebufferuiv = NULL;
+PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL;
+PFNGLCLEARTEXIMAGEPROC glad_glClearTexImage = NULL;
+PFNGLCLEARTEXSUBIMAGEPROC glad_glClearTexSubImage = NULL;
+PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL;
+PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL;
+PFNGLCLIPCONTROLPROC glad_glClipControl = NULL;
+PFNGLCLIPPLANEPROC glad_glClipPlane = NULL;
+PFNGLCOLOR3BPROC glad_glColor3b = NULL;
+PFNGLCOLOR3BVPROC glad_glColor3bv = NULL;
+PFNGLCOLOR3DPROC glad_glColor3d = NULL;
+PFNGLCOLOR3DVPROC glad_glColor3dv = NULL;
+PFNGLCOLOR3FPROC glad_glColor3f = NULL;
+PFNGLCOLOR3FVPROC glad_glColor3fv = NULL;
+PFNGLCOLOR3IPROC glad_glColor3i = NULL;
+PFNGLCOLOR3IVPROC glad_glColor3iv = NULL;
+PFNGLCOLOR3SPROC glad_glColor3s = NULL;
+PFNGLCOLOR3SVPROC glad_glColor3sv = NULL;
+PFNGLCOLOR3UBPROC glad_glColor3ub = NULL;
+PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL;
+PFNGLCOLOR3UIPROC glad_glColor3ui = NULL;
+PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL;
+PFNGLCOLOR3USPROC glad_glColor3us = NULL;
+PFNGLCOLOR3USVPROC glad_glColor3usv = NULL;
+PFNGLCOLOR4BPROC glad_glColor4b = NULL;
+PFNGLCOLOR4BVPROC glad_glColor4bv = NULL;
+PFNGLCOLOR4DPROC glad_glColor4d = NULL;
+PFNGLCOLOR4DVPROC glad_glColor4dv = NULL;
+PFNGLCOLOR4FPROC glad_glColor4f = NULL;
+PFNGLCOLOR4FVPROC glad_glColor4fv = NULL;
+PFNGLCOLOR4IPROC glad_glColor4i = NULL;
+PFNGLCOLOR4IVPROC glad_glColor4iv = NULL;
+PFNGLCOLOR4SPROC glad_glColor4s = NULL;
+PFNGLCOLOR4SVPROC glad_glColor4sv = NULL;
+PFNGLCOLOR4UBPROC glad_glColor4ub = NULL;
+PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL;
+PFNGLCOLOR4UIPROC glad_glColor4ui = NULL;
+PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL;
+PFNGLCOLOR4USPROC glad_glColor4us = NULL;
+PFNGLCOLOR4USVPROC glad_glColor4usv = NULL;
+PFNGLCOLORMASKPROC glad_glColorMask = NULL;
+PFNGLCOLORMASKIPROC glad_glColorMaski = NULL;
+PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL;
+PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL;
+PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL;
+PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL;
+PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL;
+PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL;
+PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL;
+PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL;
+PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL;
+PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL;
+PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL;
+PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL;
+PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL;
+PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glad_glCompressedTextureSubImage1D = NULL;
+PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glad_glCompressedTextureSubImage2D = NULL;
+PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glad_glCompressedTextureSubImage3D = NULL;
+PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL;
+PFNGLCOPYIMAGESUBDATAPROC glad_glCopyImageSubData = NULL;
+PFNGLCOPYNAMEDBUFFERSUBDATAPROC glad_glCopyNamedBufferSubData = NULL;
+PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL;
+PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL;
+PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL;
+PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL;
+PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL;
+PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL;
+PFNGLCOPYTEXTURESUBIMAGE1DPROC glad_glCopyTextureSubImage1D = NULL;
+PFNGLCOPYTEXTURESUBIMAGE2DPROC glad_glCopyTextureSubImage2D = NULL;
+PFNGLCOPYTEXTURESUBIMAGE3DPROC glad_glCopyTextureSubImage3D = NULL;
+PFNGLCREATEBUFFERSPROC glad_glCreateBuffers = NULL;
+PFNGLCREATEFRAMEBUFFERSPROC glad_glCreateFramebuffers = NULL;
+PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL;
+PFNGLCREATEPROGRAMPIPELINESPROC glad_glCreateProgramPipelines = NULL;
+PFNGLCREATEQUERIESPROC glad_glCreateQueries = NULL;
+PFNGLCREATERENDERBUFFERSPROC glad_glCreateRenderbuffers = NULL;
+PFNGLCREATESAMPLERSPROC glad_glCreateSamplers = NULL;
+PFNGLCREATESHADERPROC glad_glCreateShader = NULL;
+PFNGLCREATESHADERPROGRAMVPROC glad_glCreateShaderProgramv = NULL;
+PFNGLCREATETEXTURESPROC glad_glCreateTextures = NULL;
+PFNGLCREATETRANSFORMFEEDBACKSPROC glad_glCreateTransformFeedbacks = NULL;
+PFNGLCREATEVERTEXARRAYSPROC glad_glCreateVertexArrays = NULL;
+PFNGLCULLFACEPROC glad_glCullFace = NULL;
+PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback = NULL;
+PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl = NULL;
+PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert = NULL;
+PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL;
+PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL;
+PFNGLDELETELISTSPROC glad_glDeleteLists = NULL;
+PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL;
+PFNGLDELETEPROGRAMPIPELINESPROC glad_glDeleteProgramPipelines = NULL;
+PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL;
+PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL;
+PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL;
+PFNGLDELETESHADERPROC glad_glDeleteShader = NULL;
+PFNGLDELETESYNCPROC glad_glDeleteSync = NULL;
+PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL;
+PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks = NULL;
+PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL;
+PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL;
+PFNGLDEPTHMASKPROC glad_glDepthMask = NULL;
+PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL;
+PFNGLDEPTHRANGEARRAYVPROC glad_glDepthRangeArrayv = NULL;
+PFNGLDEPTHRANGEINDEXEDPROC glad_glDepthRangeIndexed = NULL;
+PFNGLDEPTHRANGEFPROC glad_glDepthRangef = NULL;
+PFNGLDETACHSHADERPROC glad_glDetachShader = NULL;
+PFNGLDISABLEPROC glad_glDisable = NULL;
+PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL;
+PFNGLDISABLEVERTEXARRAYATTRIBPROC glad_glDisableVertexArrayAttrib = NULL;
+PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL;
+PFNGLDISABLEIPROC glad_glDisablei = NULL;
+PFNGLDISPATCHCOMPUTEPROC glad_glDispatchCompute = NULL;
+PFNGLDISPATCHCOMPUTEINDIRECTPROC glad_glDispatchComputeIndirect = NULL;
+PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL;
+PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect = NULL;
+PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL;
+PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance = NULL;
+PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL;
+PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL;
+PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL;
+PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL;
+PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect = NULL;
+PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL;
+PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance = NULL;
+PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL;
+PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance = NULL;
+PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL;
+PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL;
+PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glad_glDrawTransformFeedbackInstanced = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glad_glDrawTransformFeedbackStreamInstanced = NULL;
+PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL;
+PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL;
+PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL;
+PFNGLENABLEPROC glad_glEnable = NULL;
+PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL;
+PFNGLENABLEVERTEXARRAYATTRIBPROC glad_glEnableVertexArrayAttrib = NULL;
+PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL;
+PFNGLENABLEIPROC glad_glEnablei = NULL;
+PFNGLENDPROC glad_glEnd = NULL;
+PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL;
+PFNGLENDLISTPROC glad_glEndList = NULL;
+PFNGLENDQUERYPROC glad_glEndQuery = NULL;
+PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed = NULL;
+PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL;
+PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL;
+PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL;
+PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL;
+PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL;
+PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL;
+PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL;
+PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL;
+PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL;
+PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL;
+PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL;
+PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL;
+PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL;
+PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL;
+PFNGLFENCESYNCPROC glad_glFenceSync = NULL;
+PFNGLFINISHPROC glad_glFinish = NULL;
+PFNGLFLUSHPROC glad_glFlush = NULL;
+PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL;
+PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glad_glFlushMappedNamedBufferRange = NULL;
+PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL;
+PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL;
+PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL;
+PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL;
+PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL;
+PFNGLFOGFPROC glad_glFogf = NULL;
+PFNGLFOGFVPROC glad_glFogfv = NULL;
+PFNGLFOGIPROC glad_glFogi = NULL;
+PFNGLFOGIVPROC glad_glFogiv = NULL;
+PFNGLFRAMEBUFFERPARAMETERIPROC glad_glFramebufferParameteri = NULL;
+PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL;
+PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL;
+PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL;
+PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL;
+PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL;
+PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL;
+PFNGLFRONTFACEPROC glad_glFrontFace = NULL;
+PFNGLFRUSTUMPROC glad_glFrustum = NULL;
+PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL;
+PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL;
+PFNGLGENLISTSPROC glad_glGenLists = NULL;
+PFNGLGENPROGRAMPIPELINESPROC glad_glGenProgramPipelines = NULL;
+PFNGLGENQUERIESPROC glad_glGenQueries = NULL;
+PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL;
+PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL;
+PFNGLGENTEXTURESPROC glad_glGenTextures = NULL;
+PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks = NULL;
+PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL;
+PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL;
+PFNGLGENERATETEXTUREMIPMAPPROC glad_glGenerateTextureMipmap = NULL;
+PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glad_glGetActiveAtomicCounterBufferiv = NULL;
+PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL;
+PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName = NULL;
+PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName = NULL;
+PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv = NULL;
+PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL;
+PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL;
+PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL;
+PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL;
+PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL;
+PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL;
+PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL;
+PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL;
+PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL;
+PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL;
+PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL;
+PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL;
+PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL;
+PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL;
+PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL;
+PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glad_glGetCompressedTextureImage = NULL;
+PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glad_glGetCompressedTextureSubImage = NULL;
+PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog = NULL;
+PFNGLGETDOUBLEI_VPROC glad_glGetDoublei_v = NULL;
+PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL;
+PFNGLGETERRORPROC glad_glGetError = NULL;
+PFNGLGETFLOATI_VPROC glad_glGetFloati_v = NULL;
+PFNGLGETFLOATVPROC glad_glGetFloatv = NULL;
+PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL;
+PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL;
+PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL;
+PFNGLGETFRAMEBUFFERPARAMETERIVPROC glad_glGetFramebufferParameteriv = NULL;
+PFNGLGETGRAPHICSRESETSTATUSPROC glad_glGetGraphicsResetStatus = NULL;
+PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL;
+PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL;
+PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL;
+PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL;
+PFNGLGETINTERNALFORMATI64VPROC glad_glGetInternalformati64v = NULL;
+PFNGLGETINTERNALFORMATIVPROC glad_glGetInternalformativ = NULL;
+PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL;
+PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL;
+PFNGLGETMAPDVPROC glad_glGetMapdv = NULL;
+PFNGLGETMAPFVPROC glad_glGetMapfv = NULL;
+PFNGLGETMAPIVPROC glad_glGetMapiv = NULL;
+PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL;
+PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL;
+PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL;
+PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glad_glGetNamedBufferParameteri64v = NULL;
+PFNGLGETNAMEDBUFFERPARAMETERIVPROC glad_glGetNamedBufferParameteriv = NULL;
+PFNGLGETNAMEDBUFFERPOINTERVPROC glad_glGetNamedBufferPointerv = NULL;
+PFNGLGETNAMEDBUFFERSUBDATAPROC glad_glGetNamedBufferSubData = NULL;
+PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetNamedFramebufferAttachmentParameteriv = NULL;
+PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glad_glGetNamedFramebufferParameteriv = NULL;
+PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glad_glGetNamedRenderbufferParameteriv = NULL;
+PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel = NULL;
+PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel = NULL;
+PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL;
+PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL;
+PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL;
+PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL;
+PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL;
+PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary = NULL;
+PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL;
+PFNGLGETPROGRAMINTERFACEIVPROC glad_glGetProgramInterfaceiv = NULL;
+PFNGLGETPROGRAMPIPELINEINFOLOGPROC glad_glGetProgramPipelineInfoLog = NULL;
+PFNGLGETPROGRAMPIPELINEIVPROC glad_glGetProgramPipelineiv = NULL;
+PFNGLGETPROGRAMRESOURCEINDEXPROC glad_glGetProgramResourceIndex = NULL;
+PFNGLGETPROGRAMRESOURCELOCATIONPROC glad_glGetProgramResourceLocation = NULL;
+PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glad_glGetProgramResourceLocationIndex = NULL;
+PFNGLGETPROGRAMRESOURCENAMEPROC glad_glGetProgramResourceName = NULL;
+PFNGLGETPROGRAMRESOURCEIVPROC glad_glGetProgramResourceiv = NULL;
+PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv = NULL;
+PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL;
+PFNGLGETQUERYBUFFEROBJECTI64VPROC glad_glGetQueryBufferObjecti64v = NULL;
+PFNGLGETQUERYBUFFEROBJECTIVPROC glad_glGetQueryBufferObjectiv = NULL;
+PFNGLGETQUERYBUFFEROBJECTUI64VPROC glad_glGetQueryBufferObjectui64v = NULL;
+PFNGLGETQUERYBUFFEROBJECTUIVPROC glad_glGetQueryBufferObjectuiv = NULL;
+PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv = NULL;
+PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL;
+PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL;
+PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL;
+PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL;
+PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL;
+PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL;
+PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL;
+PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL;
+PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL;
+PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL;
+PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL;
+PFNGLGETSHADERPRECISIONFORMATPROC glad_glGetShaderPrecisionFormat = NULL;
+PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL;
+PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL;
+PFNGLGETSTRINGPROC glad_glGetString = NULL;
+PFNGLGETSTRINGIPROC glad_glGetStringi = NULL;
+PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex = NULL;
+PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation = NULL;
+PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL;
+PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL;
+PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL;
+PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL;
+PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL;
+PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL;
+PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL;
+PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL;
+PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL;
+PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL;
+PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL;
+PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL;
+PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL;
+PFNGLGETTEXTUREIMAGEPROC glad_glGetTextureImage = NULL;
+PFNGLGETTEXTURELEVELPARAMETERFVPROC glad_glGetTextureLevelParameterfv = NULL;
+PFNGLGETTEXTURELEVELPARAMETERIVPROC glad_glGetTextureLevelParameteriv = NULL;
+PFNGLGETTEXTUREPARAMETERIIVPROC glad_glGetTextureParameterIiv = NULL;
+PFNGLGETTEXTUREPARAMETERIUIVPROC glad_glGetTextureParameterIuiv = NULL;
+PFNGLGETTEXTUREPARAMETERFVPROC glad_glGetTextureParameterfv = NULL;
+PFNGLGETTEXTUREPARAMETERIVPROC glad_glGetTextureParameteriv = NULL;
+PFNGLGETTEXTURESUBIMAGEPROC glad_glGetTextureSubImage = NULL;
+PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL;
+PFNGLGETTRANSFORMFEEDBACKI64_VPROC glad_glGetTransformFeedbacki64_v = NULL;
+PFNGLGETTRANSFORMFEEDBACKI_VPROC glad_glGetTransformFeedbacki_v = NULL;
+PFNGLGETTRANSFORMFEEDBACKIVPROC glad_glGetTransformFeedbackiv = NULL;
+PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL;
+PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL;
+PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL;
+PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv = NULL;
+PFNGLGETUNIFORMDVPROC glad_glGetUniformdv = NULL;
+PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL;
+PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL;
+PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL;
+PFNGLGETVERTEXARRAYINDEXED64IVPROC glad_glGetVertexArrayIndexed64iv = NULL;
+PFNGLGETVERTEXARRAYINDEXEDIVPROC glad_glGetVertexArrayIndexediv = NULL;
+PFNGLGETVERTEXARRAYIVPROC glad_glGetVertexArrayiv = NULL;
+PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL;
+PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL;
+PFNGLGETVERTEXATTRIBLDVPROC glad_glGetVertexAttribLdv = NULL;
+PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL;
+PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL;
+PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL;
+PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL;
+PFNGLGETNCOLORTABLEPROC glad_glGetnColorTable = NULL;
+PFNGLGETNCOMPRESSEDTEXIMAGEPROC glad_glGetnCompressedTexImage = NULL;
+PFNGLGETNCONVOLUTIONFILTERPROC glad_glGetnConvolutionFilter = NULL;
+PFNGLGETNHISTOGRAMPROC glad_glGetnHistogram = NULL;
+PFNGLGETNMAPDVPROC glad_glGetnMapdv = NULL;
+PFNGLGETNMAPFVPROC glad_glGetnMapfv = NULL;
+PFNGLGETNMAPIVPROC glad_glGetnMapiv = NULL;
+PFNGLGETNMINMAXPROC glad_glGetnMinmax = NULL;
+PFNGLGETNPIXELMAPFVPROC glad_glGetnPixelMapfv = NULL;
+PFNGLGETNPIXELMAPUIVPROC glad_glGetnPixelMapuiv = NULL;
+PFNGLGETNPIXELMAPUSVPROC glad_glGetnPixelMapusv = NULL;
+PFNGLGETNPOLYGONSTIPPLEPROC glad_glGetnPolygonStipple = NULL;
+PFNGLGETNSEPARABLEFILTERPROC glad_glGetnSeparableFilter = NULL;
+PFNGLGETNTEXIMAGEPROC glad_glGetnTexImage = NULL;
+PFNGLGETNUNIFORMDVPROC glad_glGetnUniformdv = NULL;
+PFNGLGETNUNIFORMFVPROC glad_glGetnUniformfv = NULL;
+PFNGLGETNUNIFORMIVPROC glad_glGetnUniformiv = NULL;
+PFNGLGETNUNIFORMUIVPROC glad_glGetnUniformuiv = NULL;
+PFNGLHINTPROC glad_glHint = NULL;
+PFNGLINDEXMASKPROC glad_glIndexMask = NULL;
+PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL;
+PFNGLINDEXDPROC glad_glIndexd = NULL;
+PFNGLINDEXDVPROC glad_glIndexdv = NULL;
+PFNGLINDEXFPROC glad_glIndexf = NULL;
+PFNGLINDEXFVPROC glad_glIndexfv = NULL;
+PFNGLINDEXIPROC glad_glIndexi = NULL;
+PFNGLINDEXIVPROC glad_glIndexiv = NULL;
+PFNGLINDEXSPROC glad_glIndexs = NULL;
+PFNGLINDEXSVPROC glad_glIndexsv = NULL;
+PFNGLINDEXUBPROC glad_glIndexub = NULL;
+PFNGLINDEXUBVPROC glad_glIndexubv = NULL;
+PFNGLINITNAMESPROC glad_glInitNames = NULL;
+PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL;
+PFNGLINVALIDATEBUFFERDATAPROC glad_glInvalidateBufferData = NULL;
+PFNGLINVALIDATEBUFFERSUBDATAPROC glad_glInvalidateBufferSubData = NULL;
+PFNGLINVALIDATEFRAMEBUFFERPROC glad_glInvalidateFramebuffer = NULL;
+PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glad_glInvalidateNamedFramebufferData = NULL;
+PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glad_glInvalidateNamedFramebufferSubData = NULL;
+PFNGLINVALIDATESUBFRAMEBUFFERPROC glad_glInvalidateSubFramebuffer = NULL;
+PFNGLINVALIDATETEXIMAGEPROC glad_glInvalidateTexImage = NULL;
+PFNGLINVALIDATETEXSUBIMAGEPROC glad_glInvalidateTexSubImage = NULL;
+PFNGLISBUFFERPROC glad_glIsBuffer = NULL;
+PFNGLISENABLEDPROC glad_glIsEnabled = NULL;
+PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL;
+PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL;
+PFNGLISLISTPROC glad_glIsList = NULL;
+PFNGLISPROGRAMPROC glad_glIsProgram = NULL;
+PFNGLISPROGRAMPIPELINEPROC glad_glIsProgramPipeline = NULL;
+PFNGLISQUERYPROC glad_glIsQuery = NULL;
+PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL;
+PFNGLISSAMPLERPROC glad_glIsSampler = NULL;
+PFNGLISSHADERPROC glad_glIsShader = NULL;
+PFNGLISSYNCPROC glad_glIsSync = NULL;
+PFNGLISTEXTUREPROC glad_glIsTexture = NULL;
+PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback = NULL;
+PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL;
+PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL;
+PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL;
+PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL;
+PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL;
+PFNGLLIGHTFPROC glad_glLightf = NULL;
+PFNGLLIGHTFVPROC glad_glLightfv = NULL;
+PFNGLLIGHTIPROC glad_glLighti = NULL;
+PFNGLLIGHTIVPROC glad_glLightiv = NULL;
+PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL;
+PFNGLLINEWIDTHPROC glad_glLineWidth = NULL;
+PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL;
+PFNGLLISTBASEPROC glad_glListBase = NULL;
+PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL;
+PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL;
+PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL;
+PFNGLLOADNAMEPROC glad_glLoadName = NULL;
+PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL;
+PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL;
+PFNGLLOGICOPPROC glad_glLogicOp = NULL;
+PFNGLMAP1DPROC glad_glMap1d = NULL;
+PFNGLMAP1FPROC glad_glMap1f = NULL;
+PFNGLMAP2DPROC glad_glMap2d = NULL;
+PFNGLMAP2FPROC glad_glMap2f = NULL;
+PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL;
+PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL;
+PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL;
+PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL;
+PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL;
+PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL;
+PFNGLMAPNAMEDBUFFERPROC glad_glMapNamedBuffer = NULL;
+PFNGLMAPNAMEDBUFFERRANGEPROC glad_glMapNamedBufferRange = NULL;
+PFNGLMATERIALFPROC glad_glMaterialf = NULL;
+PFNGLMATERIALFVPROC glad_glMaterialfv = NULL;
+PFNGLMATERIALIPROC glad_glMateriali = NULL;
+PFNGLMATERIALIVPROC glad_glMaterialiv = NULL;
+PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL;
+PFNGLMEMORYBARRIERPROC glad_glMemoryBarrier = NULL;
+PFNGLMEMORYBARRIERBYREGIONPROC glad_glMemoryBarrierByRegion = NULL;
+PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading = NULL;
+PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL;
+PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL;
+PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL;
+PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL;
+PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL;
+PFNGLMULTIDRAWARRAYSINDIRECTPROC glad_glMultiDrawArraysIndirect = NULL;
+PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC glad_glMultiDrawArraysIndirectCount = NULL;
+PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL;
+PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL;
+PFNGLMULTIDRAWELEMENTSINDIRECTPROC glad_glMultiDrawElementsIndirect = NULL;
+PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC glad_glMultiDrawElementsIndirectCount = NULL;
+PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL;
+PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL;
+PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL;
+PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL;
+PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL;
+PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL;
+PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL;
+PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL;
+PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL;
+PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL;
+PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL;
+PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL;
+PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL;
+PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL;
+PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL;
+PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL;
+PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL;
+PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL;
+PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL;
+PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL;
+PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL;
+PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL;
+PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL;
+PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL;
+PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL;
+PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL;
+PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL;
+PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL;
+PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL;
+PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL;
+PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL;
+PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL;
+PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL;
+PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL;
+PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL;
+PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL;
+PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL;
+PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL;
+PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL;
+PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL;
+PFNGLNAMEDBUFFERDATAPROC glad_glNamedBufferData = NULL;
+PFNGLNAMEDBUFFERSTORAGEPROC glad_glNamedBufferStorage = NULL;
+PFNGLNAMEDBUFFERSUBDATAPROC glad_glNamedBufferSubData = NULL;
+PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glad_glNamedFramebufferDrawBuffer = NULL;
+PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glad_glNamedFramebufferDrawBuffers = NULL;
+PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glad_glNamedFramebufferParameteri = NULL;
+PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glad_glNamedFramebufferReadBuffer = NULL;
+PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glad_glNamedFramebufferRenderbuffer = NULL;
+PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glad_glNamedFramebufferTexture = NULL;
+PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glad_glNamedFramebufferTextureLayer = NULL;
+PFNGLNAMEDRENDERBUFFERSTORAGEPROC glad_glNamedRenderbufferStorage = NULL;
+PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glNamedRenderbufferStorageMultisample = NULL;
+PFNGLNEWLISTPROC glad_glNewList = NULL;
+PFNGLNORMAL3BPROC glad_glNormal3b = NULL;
+PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL;
+PFNGLNORMAL3DPROC glad_glNormal3d = NULL;
+PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL;
+PFNGLNORMAL3FPROC glad_glNormal3f = NULL;
+PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL;
+PFNGLNORMAL3IPROC glad_glNormal3i = NULL;
+PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL;
+PFNGLNORMAL3SPROC glad_glNormal3s = NULL;
+PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL;
+PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL;
+PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL;
+PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL;
+PFNGLOBJECTLABELPROC glad_glObjectLabel = NULL;
+PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel = NULL;
+PFNGLORTHOPROC glad_glOrtho = NULL;
+PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL;
+PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv = NULL;
+PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri = NULL;
+PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback = NULL;
+PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL;
+PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL;
+PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL;
+PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL;
+PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL;
+PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL;
+PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL;
+PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL;
+PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL;
+PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL;
+PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL;
+PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL;
+PFNGLPOINTSIZEPROC glad_glPointSize = NULL;
+PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL;
+PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL;
+PFNGLPOLYGONOFFSETCLAMPPROC glad_glPolygonOffsetClamp = NULL;
+PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL;
+PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL;
+PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL;
+PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup = NULL;
+PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL;
+PFNGLPOPNAMEPROC glad_glPopName = NULL;
+PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL;
+PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL;
+PFNGLPROGRAMBINARYPROC glad_glProgramBinary = NULL;
+PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri = NULL;
+PFNGLPROGRAMUNIFORM1DPROC glad_glProgramUniform1d = NULL;
+PFNGLPROGRAMUNIFORM1DVPROC glad_glProgramUniform1dv = NULL;
+PFNGLPROGRAMUNIFORM1FPROC glad_glProgramUniform1f = NULL;
+PFNGLPROGRAMUNIFORM1FVPROC glad_glProgramUniform1fv = NULL;
+PFNGLPROGRAMUNIFORM1IPROC glad_glProgramUniform1i = NULL;
+PFNGLPROGRAMUNIFORM1IVPROC glad_glProgramUniform1iv = NULL;
+PFNGLPROGRAMUNIFORM1UIPROC glad_glProgramUniform1ui = NULL;
+PFNGLPROGRAMUNIFORM1UIVPROC glad_glProgramUniform1uiv = NULL;
+PFNGLPROGRAMUNIFORM2DPROC glad_glProgramUniform2d = NULL;
+PFNGLPROGRAMUNIFORM2DVPROC glad_glProgramUniform2dv = NULL;
+PFNGLPROGRAMUNIFORM2FPROC glad_glProgramUniform2f = NULL;
+PFNGLPROGRAMUNIFORM2FVPROC glad_glProgramUniform2fv = NULL;
+PFNGLPROGRAMUNIFORM2IPROC glad_glProgramUniform2i = NULL;
+PFNGLPROGRAMUNIFORM2IVPROC glad_glProgramUniform2iv = NULL;
+PFNGLPROGRAMUNIFORM2UIPROC glad_glProgramUniform2ui = NULL;
+PFNGLPROGRAMUNIFORM2UIVPROC glad_glProgramUniform2uiv = NULL;
+PFNGLPROGRAMUNIFORM3DPROC glad_glProgramUniform3d = NULL;
+PFNGLPROGRAMUNIFORM3DVPROC glad_glProgramUniform3dv = NULL;
+PFNGLPROGRAMUNIFORM3FPROC glad_glProgramUniform3f = NULL;
+PFNGLPROGRAMUNIFORM3FVPROC glad_glProgramUniform3fv = NULL;
+PFNGLPROGRAMUNIFORM3IPROC glad_glProgramUniform3i = NULL;
+PFNGLPROGRAMUNIFORM3IVPROC glad_glProgramUniform3iv = NULL;
+PFNGLPROGRAMUNIFORM3UIPROC glad_glProgramUniform3ui = NULL;
+PFNGLPROGRAMUNIFORM3UIVPROC glad_glProgramUniform3uiv = NULL;
+PFNGLPROGRAMUNIFORM4DPROC glad_glProgramUniform4d = NULL;
+PFNGLPROGRAMUNIFORM4DVPROC glad_glProgramUniform4dv = NULL;
+PFNGLPROGRAMUNIFORM4FPROC glad_glProgramUniform4f = NULL;
+PFNGLPROGRAMUNIFORM4FVPROC glad_glProgramUniform4fv = NULL;
+PFNGLPROGRAMUNIFORM4IPROC glad_glProgramUniform4i = NULL;
+PFNGLPROGRAMUNIFORM4IVPROC glad_glProgramUniform4iv = NULL;
+PFNGLPROGRAMUNIFORM4UIPROC glad_glProgramUniform4ui = NULL;
+PFNGLPROGRAMUNIFORM4UIVPROC glad_glProgramUniform4uiv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX2DVPROC glad_glProgramUniformMatrix2dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX2FVPROC glad_glProgramUniformMatrix2fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glad_glProgramUniformMatrix2x3dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glad_glProgramUniformMatrix2x3fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glad_glProgramUniformMatrix2x4dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glad_glProgramUniformMatrix2x4fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX3DVPROC glad_glProgramUniformMatrix3dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX3FVPROC glad_glProgramUniformMatrix3fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glad_glProgramUniformMatrix3x2dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glad_glProgramUniformMatrix3x2fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glad_glProgramUniformMatrix3x4dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glad_glProgramUniformMatrix3x4fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX4DVPROC glad_glProgramUniformMatrix4dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX4FVPROC glad_glProgramUniformMatrix4fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glad_glProgramUniformMatrix4x2dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glad_glProgramUniformMatrix4x2fv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glad_glProgramUniformMatrix4x3dv = NULL;
+PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glad_glProgramUniformMatrix4x3fv = NULL;
+PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL;
+PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL;
+PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL;
+PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup = NULL;
+PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL;
+PFNGLPUSHNAMEPROC glad_glPushName = NULL;
+PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL;
+PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL;
+PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL;
+PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL;
+PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL;
+PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL;
+PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL;
+PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL;
+PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL;
+PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL;
+PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL;
+PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL;
+PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL;
+PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL;
+PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL;
+PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL;
+PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL;
+PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL;
+PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL;
+PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL;
+PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL;
+PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL;
+PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL;
+PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL;
+PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL;
+PFNGLREADBUFFERPROC glad_glReadBuffer = NULL;
+PFNGLREADPIXELSPROC glad_glReadPixels = NULL;
+PFNGLREADNPIXELSPROC glad_glReadnPixels = NULL;
+PFNGLRECTDPROC glad_glRectd = NULL;
+PFNGLRECTDVPROC glad_glRectdv = NULL;
+PFNGLRECTFPROC glad_glRectf = NULL;
+PFNGLRECTFVPROC glad_glRectfv = NULL;
+PFNGLRECTIPROC glad_glRecti = NULL;
+PFNGLRECTIVPROC glad_glRectiv = NULL;
+PFNGLRECTSPROC glad_glRects = NULL;
+PFNGLRECTSVPROC glad_glRectsv = NULL;
+PFNGLRELEASESHADERCOMPILERPROC glad_glReleaseShaderCompiler = NULL;
+PFNGLRENDERMODEPROC glad_glRenderMode = NULL;
+PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL;
+PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL;
+PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback = NULL;
+PFNGLROTATEDPROC glad_glRotated = NULL;
+PFNGLROTATEFPROC glad_glRotatef = NULL;
+PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL;
+PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL;
+PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL;
+PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL;
+PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL;
+PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL;
+PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL;
+PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL;
+PFNGLSCALEDPROC glad_glScaled = NULL;
+PFNGLSCALEFPROC glad_glScalef = NULL;
+PFNGLSCISSORPROC glad_glScissor = NULL;
+PFNGLSCISSORARRAYVPROC glad_glScissorArrayv = NULL;
+PFNGLSCISSORINDEXEDPROC glad_glScissorIndexed = NULL;
+PFNGLSCISSORINDEXEDVPROC glad_glScissorIndexedv = NULL;
+PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL;
+PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL;
+PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL;
+PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL;
+PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL;
+PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL;
+PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL;
+PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL;
+PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL;
+PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL;
+PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL;
+PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL;
+PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL;
+PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL;
+PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL;
+PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL;
+PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL;
+PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL;
+PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL;
+PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL;
+PFNGLSHADEMODELPROC glad_glShadeModel = NULL;
+PFNGLSHADERBINARYPROC glad_glShaderBinary = NULL;
+PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL;
+PFNGLSHADERSTORAGEBLOCKBINDINGPROC glad_glShaderStorageBlockBinding = NULL;
+PFNGLSPECIALIZESHADERPROC glad_glSpecializeShader = NULL;
+PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL;
+PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL;
+PFNGLSTENCILMASKPROC glad_glStencilMask = NULL;
+PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL;
+PFNGLSTENCILOPPROC glad_glStencilOp = NULL;
+PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL;
+PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL;
+PFNGLTEXBUFFERRANGEPROC glad_glTexBufferRange = NULL;
+PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL;
+PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL;
+PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL;
+PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL;
+PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL;
+PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL;
+PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL;
+PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL;
+PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL;
+PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL;
+PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL;
+PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL;
+PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL;
+PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL;
+PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL;
+PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL;
+PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL;
+PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL;
+PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL;
+PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL;
+PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL;
+PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL;
+PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL;
+PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL;
+PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL;
+PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL;
+PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL;
+PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL;
+PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL;
+PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL;
+PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL;
+PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL;
+PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL;
+PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL;
+PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL;
+PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL;
+PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL;
+PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL;
+PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL;
+PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL;
+PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL;
+PFNGLTEXENVFPROC glad_glTexEnvf = NULL;
+PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL;
+PFNGLTEXENVIPROC glad_glTexEnvi = NULL;
+PFNGLTEXENVIVPROC glad_glTexEnviv = NULL;
+PFNGLTEXGENDPROC glad_glTexGend = NULL;
+PFNGLTEXGENDVPROC glad_glTexGendv = NULL;
+PFNGLTEXGENFPROC glad_glTexGenf = NULL;
+PFNGLTEXGENFVPROC glad_glTexGenfv = NULL;
+PFNGLTEXGENIPROC glad_glTexGeni = NULL;
+PFNGLTEXGENIVPROC glad_glTexGeniv = NULL;
+PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL;
+PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL;
+PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL;
+PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL;
+PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL;
+PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL;
+PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL;
+PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL;
+PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL;
+PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL;
+PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL;
+PFNGLTEXSTORAGE1DPROC glad_glTexStorage1D = NULL;
+PFNGLTEXSTORAGE2DPROC glad_glTexStorage2D = NULL;
+PFNGLTEXSTORAGE2DMULTISAMPLEPROC glad_glTexStorage2DMultisample = NULL;
+PFNGLTEXSTORAGE3DPROC glad_glTexStorage3D = NULL;
+PFNGLTEXSTORAGE3DMULTISAMPLEPROC glad_glTexStorage3DMultisample = NULL;
+PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL;
+PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL;
+PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL;
+PFNGLTEXTUREBARRIERPROC glad_glTextureBarrier = NULL;
+PFNGLTEXTUREBUFFERPROC glad_glTextureBuffer = NULL;
+PFNGLTEXTUREBUFFERRANGEPROC glad_glTextureBufferRange = NULL;
+PFNGLTEXTUREPARAMETERIIVPROC glad_glTextureParameterIiv = NULL;
+PFNGLTEXTUREPARAMETERIUIVPROC glad_glTextureParameterIuiv = NULL;
+PFNGLTEXTUREPARAMETERFPROC glad_glTextureParameterf = NULL;
+PFNGLTEXTUREPARAMETERFVPROC glad_glTextureParameterfv = NULL;
+PFNGLTEXTUREPARAMETERIPROC glad_glTextureParameteri = NULL;
+PFNGLTEXTUREPARAMETERIVPROC glad_glTextureParameteriv = NULL;
+PFNGLTEXTURESTORAGE1DPROC glad_glTextureStorage1D = NULL;
+PFNGLTEXTURESTORAGE2DPROC glad_glTextureStorage2D = NULL;
+PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glad_glTextureStorage2DMultisample = NULL;
+PFNGLTEXTURESTORAGE3DPROC glad_glTextureStorage3D = NULL;
+PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glad_glTextureStorage3DMultisample = NULL;
+PFNGLTEXTURESUBIMAGE1DPROC glad_glTextureSubImage1D = NULL;
+PFNGLTEXTURESUBIMAGE2DPROC glad_glTextureSubImage2D = NULL;
+PFNGLTEXTURESUBIMAGE3DPROC glad_glTextureSubImage3D = NULL;
+PFNGLTEXTUREVIEWPROC glad_glTextureView = NULL;
+PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glad_glTransformFeedbackBufferBase = NULL;
+PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glad_glTransformFeedbackBufferRange = NULL;
+PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL;
+PFNGLTRANSLATEDPROC glad_glTranslated = NULL;
+PFNGLTRANSLATEFPROC glad_glTranslatef = NULL;
+PFNGLUNIFORM1DPROC glad_glUniform1d = NULL;
+PFNGLUNIFORM1DVPROC glad_glUniform1dv = NULL;
+PFNGLUNIFORM1FPROC glad_glUniform1f = NULL;
+PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL;
+PFNGLUNIFORM1IPROC glad_glUniform1i = NULL;
+PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL;
+PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL;
+PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL;
+PFNGLUNIFORM2DPROC glad_glUniform2d = NULL;
+PFNGLUNIFORM2DVPROC glad_glUniform2dv = NULL;
+PFNGLUNIFORM2FPROC glad_glUniform2f = NULL;
+PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL;
+PFNGLUNIFORM2IPROC glad_glUniform2i = NULL;
+PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL;
+PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL;
+PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL;
+PFNGLUNIFORM3DPROC glad_glUniform3d = NULL;
+PFNGLUNIFORM3DVPROC glad_glUniform3dv = NULL;
+PFNGLUNIFORM3FPROC glad_glUniform3f = NULL;
+PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL;
+PFNGLUNIFORM3IPROC glad_glUniform3i = NULL;
+PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL;
+PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL;
+PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL;
+PFNGLUNIFORM4DPROC glad_glUniform4d = NULL;
+PFNGLUNIFORM4DVPROC glad_glUniform4dv = NULL;
+PFNGLUNIFORM4FPROC glad_glUniform4f = NULL;
+PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL;
+PFNGLUNIFORM4IPROC glad_glUniform4i = NULL;
+PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL;
+PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL;
+PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL;
+PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL;
+PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv = NULL;
+PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL;
+PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv = NULL;
+PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL;
+PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv = NULL;
+PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL;
+PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv = NULL;
+PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL;
+PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv = NULL;
+PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL;
+PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv = NULL;
+PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL;
+PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv = NULL;
+PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL;
+PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv = NULL;
+PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL;
+PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv = NULL;
+PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL;
+PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv = NULL;
+PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL;
+PFNGLUNMAPNAMEDBUFFERPROC glad_glUnmapNamedBuffer = NULL;
+PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL;
+PFNGLUSEPROGRAMSTAGESPROC glad_glUseProgramStages = NULL;
+PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL;
+PFNGLVALIDATEPROGRAMPIPELINEPROC glad_glValidateProgramPipeline = NULL;
+PFNGLVERTEX2DPROC glad_glVertex2d = NULL;
+PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL;
+PFNGLVERTEX2FPROC glad_glVertex2f = NULL;
+PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL;
+PFNGLVERTEX2IPROC glad_glVertex2i = NULL;
+PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL;
+PFNGLVERTEX2SPROC glad_glVertex2s = NULL;
+PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL;
+PFNGLVERTEX3DPROC glad_glVertex3d = NULL;
+PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL;
+PFNGLVERTEX3FPROC glad_glVertex3f = NULL;
+PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL;
+PFNGLVERTEX3IPROC glad_glVertex3i = NULL;
+PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL;
+PFNGLVERTEX3SPROC glad_glVertex3s = NULL;
+PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL;
+PFNGLVERTEX4DPROC glad_glVertex4d = NULL;
+PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL;
+PFNGLVERTEX4FPROC glad_glVertex4f = NULL;
+PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL;
+PFNGLVERTEX4IPROC glad_glVertex4i = NULL;
+PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL;
+PFNGLVERTEX4SPROC glad_glVertex4s = NULL;
+PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL;
+PFNGLVERTEXARRAYATTRIBBINDINGPROC glad_glVertexArrayAttribBinding = NULL;
+PFNGLVERTEXARRAYATTRIBFORMATPROC glad_glVertexArrayAttribFormat = NULL;
+PFNGLVERTEXARRAYATTRIBIFORMATPROC glad_glVertexArrayAttribIFormat = NULL;
+PFNGLVERTEXARRAYATTRIBLFORMATPROC glad_glVertexArrayAttribLFormat = NULL;
+PFNGLVERTEXARRAYBINDINGDIVISORPROC glad_glVertexArrayBindingDivisor = NULL;
+PFNGLVERTEXARRAYELEMENTBUFFERPROC glad_glVertexArrayElementBuffer = NULL;
+PFNGLVERTEXARRAYVERTEXBUFFERPROC glad_glVertexArrayVertexBuffer = NULL;
+PFNGLVERTEXARRAYVERTEXBUFFERSPROC glad_glVertexArrayVertexBuffers = NULL;
+PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL;
+PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL;
+PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL;
+PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL;
+PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL;
+PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL;
+PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL;
+PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL;
+PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL;
+PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL;
+PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL;
+PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL;
+PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL;
+PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL;
+PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL;
+PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL;
+PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL;
+PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL;
+PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL;
+PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL;
+PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL;
+PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL;
+PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL;
+PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL;
+PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL;
+PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL;
+PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL;
+PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL;
+PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL;
+PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL;
+PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL;
+PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL;
+PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL;
+PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL;
+PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL;
+PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL;
+PFNGLVERTEXATTRIBBINDINGPROC glad_glVertexAttribBinding = NULL;
+PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL;
+PFNGLVERTEXATTRIBFORMATPROC glad_glVertexAttribFormat = NULL;
+PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL;
+PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL;
+PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL;
+PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL;
+PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL;
+PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL;
+PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL;
+PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL;
+PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL;
+PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL;
+PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL;
+PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL;
+PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL;
+PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL;
+PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL;
+PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL;
+PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL;
+PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL;
+PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL;
+PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL;
+PFNGLVERTEXATTRIBIFORMATPROC glad_glVertexAttribIFormat = NULL;
+PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL;
+PFNGLVERTEXATTRIBL1DPROC glad_glVertexAttribL1d = NULL;
+PFNGLVERTEXATTRIBL1DVPROC glad_glVertexAttribL1dv = NULL;
+PFNGLVERTEXATTRIBL2DPROC glad_glVertexAttribL2d = NULL;
+PFNGLVERTEXATTRIBL2DVPROC glad_glVertexAttribL2dv = NULL;
+PFNGLVERTEXATTRIBL3DPROC glad_glVertexAttribL3d = NULL;
+PFNGLVERTEXATTRIBL3DVPROC glad_glVertexAttribL3dv = NULL;
+PFNGLVERTEXATTRIBL4DPROC glad_glVertexAttribL4d = NULL;
+PFNGLVERTEXATTRIBL4DVPROC glad_glVertexAttribL4dv = NULL;
+PFNGLVERTEXATTRIBLFORMATPROC glad_glVertexAttribLFormat = NULL;
+PFNGLVERTEXATTRIBLPOINTERPROC glad_glVertexAttribLPointer = NULL;
+PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL;
+PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL;
+PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL;
+PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL;
+PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL;
+PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL;
+PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL;
+PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL;
+PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL;
+PFNGLVERTEXBINDINGDIVISORPROC glad_glVertexBindingDivisor = NULL;
+PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL;
+PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL;
+PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL;
+PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL;
+PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL;
+PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL;
+PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL;
+PFNGLVIEWPORTPROC glad_glViewport = NULL;
+PFNGLVIEWPORTARRAYVPROC glad_glViewportArrayv = NULL;
+PFNGLVIEWPORTINDEXEDFPROC glad_glViewportIndexedf = NULL;
+PFNGLVIEWPORTINDEXEDFVPROC glad_glViewportIndexedfv = NULL;
+PFNGLWAITSYNCPROC glad_glWaitSync = NULL;
+PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL;
+PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL;
+PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL;
+PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL;
+PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL;
+PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL;
+PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL;
+PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL;
+PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL;
+PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL;
+PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL;
+PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL;
+PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL;
+PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL;
+PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL;
+PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL;
+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");
+ glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList");
+ glad_glEndList = (PFNGLENDLISTPROC)load("glEndList");
+ glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList");
+ glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists");
+ glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists");
+ glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists");
+ glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase");
+ glad_glBegin = (PFNGLBEGINPROC)load("glBegin");
+ glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap");
+ glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b");
+ glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv");
+ glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d");
+ glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv");
+ glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f");
+ glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv");
+ glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i");
+ glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv");
+ glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s");
+ glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv");
+ glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub");
+ glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv");
+ glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui");
+ glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv");
+ glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us");
+ glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv");
+ glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b");
+ glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv");
+ glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d");
+ glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv");
+ glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f");
+ glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv");
+ glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i");
+ glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv");
+ glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s");
+ glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv");
+ glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub");
+ glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv");
+ glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui");
+ glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv");
+ glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us");
+ glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv");
+ glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag");
+ glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv");
+ glad_glEnd = (PFNGLENDPROC)load("glEnd");
+ glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd");
+ glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv");
+ glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf");
+ glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv");
+ glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi");
+ glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv");
+ glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs");
+ glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv");
+ glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b");
+ glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv");
+ glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d");
+ glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv");
+ glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f");
+ glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv");
+ glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i");
+ glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv");
+ glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s");
+ glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv");
+ glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d");
+ glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv");
+ glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f");
+ glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv");
+ glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i");
+ glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv");
+ glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s");
+ glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv");
+ glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d");
+ glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv");
+ glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f");
+ glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv");
+ glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i");
+ glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv");
+ glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s");
+ glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv");
+ glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d");
+ glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv");
+ glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f");
+ glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv");
+ glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i");
+ glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv");
+ glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s");
+ glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv");
+ glad_glRectd = (PFNGLRECTDPROC)load("glRectd");
+ glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv");
+ glad_glRectf = (PFNGLRECTFPROC)load("glRectf");
+ glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv");
+ glad_glRecti = (PFNGLRECTIPROC)load("glRecti");
+ glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv");
+ glad_glRects = (PFNGLRECTSPROC)load("glRects");
+ glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv");
+ glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d");
+ glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv");
+ glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f");
+ glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv");
+ glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i");
+ glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv");
+ glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s");
+ glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv");
+ glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d");
+ glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv");
+ glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f");
+ glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv");
+ glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i");
+ glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv");
+ glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s");
+ glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv");
+ glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d");
+ glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv");
+ glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f");
+ glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv");
+ glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i");
+ glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv");
+ glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s");
+ glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv");
+ glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d");
+ glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv");
+ glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f");
+ glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv");
+ glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i");
+ glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv");
+ glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s");
+ glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv");
+ glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d");
+ glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv");
+ glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f");
+ glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv");
+ glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i");
+ glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv");
+ glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s");
+ glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv");
+ glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d");
+ glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv");
+ glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f");
+ glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv");
+ glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i");
+ glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv");
+ glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s");
+ glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv");
+ glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d");
+ glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv");
+ glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f");
+ glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv");
+ glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i");
+ glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv");
+ glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s");
+ glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv");
+ glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane");
+ glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial");
+ glad_glFogf = (PFNGLFOGFPROC)load("glFogf");
+ glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv");
+ glad_glFogi = (PFNGLFOGIPROC)load("glFogi");
+ glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv");
+ glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf");
+ glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv");
+ glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti");
+ glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv");
+ glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf");
+ glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv");
+ glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli");
+ glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv");
+ glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple");
+ glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf");
+ glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv");
+ glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali");
+ glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv");
+ glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple");
+ glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel");
+ glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf");
+ glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv");
+ glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi");
+ glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv");
+ glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend");
+ glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv");
+ glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf");
+ glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv");
+ glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni");
+ glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv");
+ glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer");
+ glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer");
+ glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode");
+ glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames");
+ glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName");
+ glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough");
+ glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName");
+ glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName");
+ glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum");
+ glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex");
+ glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask");
+ glad_glAccum = (PFNGLACCUMPROC)load("glAccum");
+ glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib");
+ glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib");
+ glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d");
+ glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f");
+ glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d");
+ glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f");
+ glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d");
+ glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f");
+ glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d");
+ glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f");
+ glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d");
+ glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv");
+ glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f");
+ glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv");
+ glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d");
+ glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv");
+ glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f");
+ glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv");
+ glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1");
+ glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1");
+ glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2");
+ glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2");
+ glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc");
+ glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom");
+ glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf");
+ glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi");
+ glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv");
+ glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv");
+ glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv");
+ glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels");
+ glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels");
+ glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane");
+ glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv");
+ glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv");
+ glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv");
+ glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv");
+ glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv");
+ glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv");
+ glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv");
+ glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv");
+ glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv");
+ glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv");
+ glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple");
+ glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv");
+ glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv");
+ glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv");
+ glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv");
+ glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv");
+ glad_glIsList = (PFNGLISLISTPROC)load("glIsList");
+ glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum");
+ glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity");
+ glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf");
+ glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd");
+ glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode");
+ glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf");
+ glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd");
+ glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho");
+ glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix");
+ glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix");
+ glad_glRotated = (PFNGLROTATEDPROC)load("glRotated");
+ glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef");
+ glad_glScaled = (PFNGLSCALEDPROC)load("glScaled");
+ glad_glScalef = (PFNGLSCALEFPROC)load("glScalef");
+ glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated");
+ glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef");
+}
+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_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv");
+ 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");
+ glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement");
+ glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer");
+ glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState");
+ glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer");
+ glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState");
+ glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer");
+ glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays");
+ glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer");
+ glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer");
+ glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer");
+ glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident");
+ glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures");
+ glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub");
+ glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv");
+ glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib");
+ glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib");
+}
+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");
+ glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture");
+ glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d");
+ glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv");
+ glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f");
+ glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv");
+ glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i");
+ glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv");
+ glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s");
+ glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv");
+ glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d");
+ glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv");
+ glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f");
+ glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv");
+ glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i");
+ glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv");
+ glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s");
+ glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv");
+ glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d");
+ glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv");
+ glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f");
+ glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv");
+ glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i");
+ glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv");
+ glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s");
+ glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv");
+ glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d");
+ glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv");
+ glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f");
+ glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv");
+ glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i");
+ glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv");
+ glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s");
+ glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv");
+ glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf");
+ glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd");
+ glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf");
+ glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd");
+}
+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_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf");
+ glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv");
+ glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd");
+ glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv");
+ glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer");
+ glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b");
+ glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv");
+ glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d");
+ glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv");
+ glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f");
+ glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv");
+ glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i");
+ glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv");
+ glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s");
+ glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv");
+ glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub");
+ glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv");
+ glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui");
+ glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv");
+ glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us");
+ glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv");
+ glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer");
+ glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d");
+ glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv");
+ glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f");
+ glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv");
+ glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i");
+ glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv");
+ glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s");
+ glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv");
+ glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d");
+ glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv");
+ glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f");
+ glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv");
+ glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i");
+ glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv");
+ glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s");
+ glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv");
+ 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_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)load("glProgramParameteri");
+ 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");
+ glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv");
+}
+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 void load_GL_VERSION_4_6(GLADloadproc load) {
+ if(!GLAD_GL_VERSION_4_6) return;
+ glad_glSpecializeShader = (PFNGLSPECIALIZESHADERPROC)load("glSpecializeShader");
+ glad_glMultiDrawArraysIndirectCount = (PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC)load("glMultiDrawArraysIndirectCount");
+ glad_glMultiDrawElementsIndirectCount = (PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC)load("glMultiDrawElementsIndirectCount");
+ glad_glPolygonOffsetClamp = (PFNGLPOLYGONOFFSETCLAMPPROC)load("glPolygonOffsetClamp");
+}
+static int find_extensionsGL(void) {
+ if (!get_exts()) return 0;
+ (void)&has_ext;
+ 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;
+ GLAD_GL_VERSION_4_6 = (major == 4 && minor >= 6) || major > 4;
+ if (GLVersion.major > 4 || (GLVersion.major >= 4 && GLVersion.minor >= 6)) {
+ max_loaded_major = 4;
+ max_loaded_minor = 6;
+ }
+}
+
+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);
+ load_GL_VERSION_4_6(load);
+
+ if (!find_extensionsGL()) return 0;
+ return GLVersion.major != 0 || GLVersion.minor != 0;
+}
+
diff --git a/external/glad/glad.h b/external/glad/glad.h
new file mode 100644
index 0000000..f70fb14
--- /dev/null
+++ b/external/glad/glad.h
@@ -0,0 +1,5169 @@
+/*
+
+ OpenGL loader generated by glad 0.1.36 on Mon Mar 4 16:26:18 2024.
+
+ Language/Generator: C/C++
+ Specification: gl
+ APIs: gl=4.6
+ Profile: compatibility
+ Extensions:
+
+ Loader: True
+ Local files: False
+ Omit khrplatform: False
+ Reproducible: False
+
+ Commandline:
+ --profile="compatibility" --api="gl=4.6" --generator="c" --spec="gl" --extensions=""
+ Online:
+ https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.6
+*/
+
+
+#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__)
+#define APIENTRY __stdcall
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+
+#ifndef GLAPIENTRY
+#define GLAPIENTRY 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
+typedef unsigned int GLenum;
+typedef unsigned char GLboolean;
+typedef unsigned int GLbitfield;
+typedef void GLvoid;
+typedef khronos_int8_t GLbyte;
+typedef khronos_uint8_t GLubyte;
+typedef khronos_int16_t GLshort;
+typedef khronos_uint16_t GLushort;
+typedef int GLint;
+typedef unsigned int GLuint;
+typedef khronos_int32_t GLclampx;
+typedef int GLsizei;
+typedef khronos_float_t GLfloat;
+typedef khronos_float_t GLclampf;
+typedef double GLdouble;
+typedef double GLclampd;
+typedef void *GLeglClientBufferEXT;
+typedef void *GLeglImageOES;
+typedef char GLchar;
+typedef char GLcharARB;
+#ifdef __APPLE__
+typedef void *GLhandleARB;
+#else
+typedef unsigned int GLhandleARB;
+#endif
+typedef khronos_uint16_t GLhalf;
+typedef khronos_uint16_t GLhalfARB;
+typedef khronos_int32_t GLfixed;
+typedef khronos_intptr_t GLintptr;
+typedef khronos_intptr_t GLintptrARB;
+typedef khronos_ssize_t GLsizeiptr;
+typedef khronos_ssize_t GLsizeiptrARB;
+typedef khronos_int64_t GLint64;
+typedef khronos_int64_t GLint64EXT;
+typedef khronos_uint64_t GLuint64;
+typedef khronos_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;
+typedef void (APIENTRY *GLVULKANPROCNV)(void);
+#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_QUADS 0x0007
+#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_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_TEXTURE_WIDTH 0x1000
+#define GL_TEXTURE_HEIGHT 0x1001
+#define GL_TEXTURE_BORDER_COLOR 0x1004
+#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_STACK_OVERFLOW 0x0503
+#define GL_STACK_UNDERFLOW 0x0504
+#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_REPEAT 0x2901
+#define GL_CURRENT_BIT 0x00000001
+#define GL_POINT_BIT 0x00000002
+#define GL_LINE_BIT 0x00000004
+#define GL_POLYGON_BIT 0x00000008
+#define GL_POLYGON_STIPPLE_BIT 0x00000010
+#define GL_PIXEL_MODE_BIT 0x00000020
+#define GL_LIGHTING_BIT 0x00000040
+#define GL_FOG_BIT 0x00000080
+#define GL_ACCUM_BUFFER_BIT 0x00000200
+#define GL_VIEWPORT_BIT 0x00000800
+#define GL_TRANSFORM_BIT 0x00001000
+#define GL_ENABLE_BIT 0x00002000
+#define GL_HINT_BIT 0x00008000
+#define GL_EVAL_BIT 0x00010000
+#define GL_LIST_BIT 0x00020000
+#define GL_TEXTURE_BIT 0x00040000
+#define GL_SCISSOR_BIT 0x00080000
+#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF
+#define GL_QUAD_STRIP 0x0008
+#define GL_POLYGON 0x0009
+#define GL_ACCUM 0x0100
+#define GL_LOAD 0x0101
+#define GL_RETURN 0x0102
+#define GL_MULT 0x0103
+#define GL_ADD 0x0104
+#define GL_AUX0 0x0409
+#define GL_AUX1 0x040A
+#define GL_AUX2 0x040B
+#define GL_AUX3 0x040C
+#define GL_2D 0x0600
+#define GL_3D 0x0601
+#define GL_3D_COLOR 0x0602
+#define GL_3D_COLOR_TEXTURE 0x0603
+#define GL_4D_COLOR_TEXTURE 0x0604
+#define GL_PASS_THROUGH_TOKEN 0x0700
+#define GL_POINT_TOKEN 0x0701
+#define GL_LINE_TOKEN 0x0702
+#define GL_POLYGON_TOKEN 0x0703
+#define GL_BITMAP_TOKEN 0x0704
+#define GL_DRAW_PIXEL_TOKEN 0x0705
+#define GL_COPY_PIXEL_TOKEN 0x0706
+#define GL_LINE_RESET_TOKEN 0x0707
+#define GL_EXP 0x0800
+#define GL_EXP2 0x0801
+#define GL_COEFF 0x0A00
+#define GL_ORDER 0x0A01
+#define GL_DOMAIN 0x0A02
+#define GL_PIXEL_MAP_I_TO_I 0x0C70
+#define GL_PIXEL_MAP_S_TO_S 0x0C71
+#define GL_PIXEL_MAP_I_TO_R 0x0C72
+#define GL_PIXEL_MAP_I_TO_G 0x0C73
+#define GL_PIXEL_MAP_I_TO_B 0x0C74
+#define GL_PIXEL_MAP_I_TO_A 0x0C75
+#define GL_PIXEL_MAP_R_TO_R 0x0C76
+#define GL_PIXEL_MAP_G_TO_G 0x0C77
+#define GL_PIXEL_MAP_B_TO_B 0x0C78
+#define GL_PIXEL_MAP_A_TO_A 0x0C79
+#define GL_CURRENT_COLOR 0x0B00
+#define GL_CURRENT_INDEX 0x0B01
+#define GL_CURRENT_NORMAL 0x0B02
+#define GL_CURRENT_TEXTURE_COORDS 0x0B03
+#define GL_CURRENT_RASTER_COLOR 0x0B04
+#define GL_CURRENT_RASTER_INDEX 0x0B05
+#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06
+#define GL_CURRENT_RASTER_POSITION 0x0B07
+#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08
+#define GL_CURRENT_RASTER_DISTANCE 0x0B09
+#define GL_POINT_SMOOTH 0x0B10
+#define GL_LINE_STIPPLE 0x0B24
+#define GL_LINE_STIPPLE_PATTERN 0x0B25
+#define GL_LINE_STIPPLE_REPEAT 0x0B26
+#define GL_LIST_MODE 0x0B30
+#define GL_MAX_LIST_NESTING 0x0B31
+#define GL_LIST_BASE 0x0B32
+#define GL_LIST_INDEX 0x0B33
+#define GL_POLYGON_STIPPLE 0x0B42
+#define GL_EDGE_FLAG 0x0B43
+#define GL_LIGHTING 0x0B50
+#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51
+#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52
+#define GL_LIGHT_MODEL_AMBIENT 0x0B53
+#define GL_SHADE_MODEL 0x0B54
+#define GL_COLOR_MATERIAL_FACE 0x0B55
+#define GL_COLOR_MATERIAL_PARAMETER 0x0B56
+#define GL_COLOR_MATERIAL 0x0B57
+#define GL_FOG 0x0B60
+#define GL_FOG_INDEX 0x0B61
+#define GL_FOG_DENSITY 0x0B62
+#define GL_FOG_START 0x0B63
+#define GL_FOG_END 0x0B64
+#define GL_FOG_MODE 0x0B65
+#define GL_FOG_COLOR 0x0B66
+#define GL_ACCUM_CLEAR_VALUE 0x0B80
+#define GL_MATRIX_MODE 0x0BA0
+#define GL_NORMALIZE 0x0BA1
+#define GL_MODELVIEW_STACK_DEPTH 0x0BA3
+#define GL_PROJECTION_STACK_DEPTH 0x0BA4
+#define GL_TEXTURE_STACK_DEPTH 0x0BA5
+#define GL_MODELVIEW_MATRIX 0x0BA6
+#define GL_PROJECTION_MATRIX 0x0BA7
+#define GL_TEXTURE_MATRIX 0x0BA8
+#define GL_ATTRIB_STACK_DEPTH 0x0BB0
+#define GL_ALPHA_TEST 0x0BC0
+#define GL_ALPHA_TEST_FUNC 0x0BC1
+#define GL_ALPHA_TEST_REF 0x0BC2
+#define GL_LOGIC_OP 0x0BF1
+#define GL_AUX_BUFFERS 0x0C00
+#define GL_INDEX_CLEAR_VALUE 0x0C20
+#define GL_INDEX_WRITEMASK 0x0C21
+#define GL_INDEX_MODE 0x0C30
+#define GL_RGBA_MODE 0x0C31
+#define GL_RENDER_MODE 0x0C40
+#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50
+#define GL_POINT_SMOOTH_HINT 0x0C51
+#define GL_FOG_HINT 0x0C54
+#define GL_TEXTURE_GEN_S 0x0C60
+#define GL_TEXTURE_GEN_T 0x0C61
+#define GL_TEXTURE_GEN_R 0x0C62
+#define GL_TEXTURE_GEN_Q 0x0C63
+#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0
+#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1
+#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2
+#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3
+#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4
+#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5
+#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6
+#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7
+#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8
+#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9
+#define GL_MAP_COLOR 0x0D10
+#define GL_MAP_STENCIL 0x0D11
+#define GL_INDEX_SHIFT 0x0D12
+#define GL_INDEX_OFFSET 0x0D13
+#define GL_RED_SCALE 0x0D14
+#define GL_RED_BIAS 0x0D15
+#define GL_ZOOM_X 0x0D16
+#define GL_ZOOM_Y 0x0D17
+#define GL_GREEN_SCALE 0x0D18
+#define GL_GREEN_BIAS 0x0D19
+#define GL_BLUE_SCALE 0x0D1A
+#define GL_BLUE_BIAS 0x0D1B
+#define GL_ALPHA_SCALE 0x0D1C
+#define GL_ALPHA_BIAS 0x0D1D
+#define GL_DEPTH_SCALE 0x0D1E
+#define GL_DEPTH_BIAS 0x0D1F
+#define GL_MAX_EVAL_ORDER 0x0D30
+#define GL_MAX_LIGHTS 0x0D31
+#define GL_MAX_CLIP_PLANES 0x0D32
+#define GL_MAX_PIXEL_MAP_TABLE 0x0D34
+#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35
+#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36
+#define GL_MAX_NAME_STACK_DEPTH 0x0D37
+#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38
+#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39
+#define GL_INDEX_BITS 0x0D51
+#define GL_RED_BITS 0x0D52
+#define GL_GREEN_BITS 0x0D53
+#define GL_BLUE_BITS 0x0D54
+#define GL_ALPHA_BITS 0x0D55
+#define GL_DEPTH_BITS 0x0D56
+#define GL_STENCIL_BITS 0x0D57
+#define GL_ACCUM_RED_BITS 0x0D58
+#define GL_ACCUM_GREEN_BITS 0x0D59
+#define GL_ACCUM_BLUE_BITS 0x0D5A
+#define GL_ACCUM_ALPHA_BITS 0x0D5B
+#define GL_NAME_STACK_DEPTH 0x0D70
+#define GL_AUTO_NORMAL 0x0D80
+#define GL_MAP1_COLOR_4 0x0D90
+#define GL_MAP1_INDEX 0x0D91
+#define GL_MAP1_NORMAL 0x0D92
+#define GL_MAP1_TEXTURE_COORD_1 0x0D93
+#define GL_MAP1_TEXTURE_COORD_2 0x0D94
+#define GL_MAP1_TEXTURE_COORD_3 0x0D95
+#define GL_MAP1_TEXTURE_COORD_4 0x0D96
+#define GL_MAP1_VERTEX_3 0x0D97
+#define GL_MAP1_VERTEX_4 0x0D98
+#define GL_MAP2_COLOR_4 0x0DB0
+#define GL_MAP2_INDEX 0x0DB1
+#define GL_MAP2_NORMAL 0x0DB2
+#define GL_MAP2_TEXTURE_COORD_1 0x0DB3
+#define GL_MAP2_TEXTURE_COORD_2 0x0DB4
+#define GL_MAP2_TEXTURE_COORD_3 0x0DB5
+#define GL_MAP2_TEXTURE_COORD_4 0x0DB6
+#define GL_MAP2_VERTEX_3 0x0DB7
+#define GL_MAP2_VERTEX_4 0x0DB8
+#define GL_MAP1_GRID_DOMAIN 0x0DD0
+#define GL_MAP1_GRID_SEGMENTS 0x0DD1
+#define GL_MAP2_GRID_DOMAIN 0x0DD2
+#define GL_MAP2_GRID_SEGMENTS 0x0DD3
+#define GL_TEXTURE_COMPONENTS 0x1003
+#define GL_TEXTURE_BORDER 0x1005
+#define GL_AMBIENT 0x1200
+#define GL_DIFFUSE 0x1201
+#define GL_SPECULAR 0x1202
+#define GL_POSITION 0x1203
+#define GL_SPOT_DIRECTION 0x1204
+#define GL_SPOT_EXPONENT 0x1205
+#define GL_SPOT_CUTOFF 0x1206
+#define GL_CONSTANT_ATTENUATION 0x1207
+#define GL_LINEAR_ATTENUATION 0x1208
+#define GL_QUADRATIC_ATTENUATION 0x1209
+#define GL_COMPILE 0x1300
+#define GL_COMPILE_AND_EXECUTE 0x1301
+#define GL_2_BYTES 0x1407
+#define GL_3_BYTES 0x1408
+#define GL_4_BYTES 0x1409
+#define GL_EMISSION 0x1600
+#define GL_SHININESS 0x1601
+#define GL_AMBIENT_AND_DIFFUSE 0x1602
+#define GL_COLOR_INDEXES 0x1603
+#define GL_MODELVIEW 0x1700
+#define GL_PROJECTION 0x1701
+#define GL_COLOR_INDEX 0x1900
+#define GL_LUMINANCE 0x1909
+#define GL_LUMINANCE_ALPHA 0x190A
+#define GL_BITMAP 0x1A00
+#define GL_RENDER 0x1C00
+#define GL_FEEDBACK 0x1C01
+#define GL_SELECT 0x1C02
+#define GL_FLAT 0x1D00
+#define GL_SMOOTH 0x1D01
+#define GL_S 0x2000
+#define GL_T 0x2001
+#define GL_R 0x2002
+#define GL_Q 0x2003
+#define GL_MODULATE 0x2100
+#define GL_DECAL 0x2101
+#define GL_TEXTURE_ENV_MODE 0x2200
+#define GL_TEXTURE_ENV_COLOR 0x2201
+#define GL_TEXTURE_ENV 0x2300
+#define GL_EYE_LINEAR 0x2400
+#define GL_OBJECT_LINEAR 0x2401
+#define GL_SPHERE_MAP 0x2402
+#define GL_TEXTURE_GEN_MODE 0x2500
+#define GL_OBJECT_PLANE 0x2501
+#define GL_EYE_PLANE 0x2502
+#define GL_CLAMP 0x2900
+#define GL_CLIP_PLANE0 0x3000
+#define GL_CLIP_PLANE1 0x3001
+#define GL_CLIP_PLANE2 0x3002
+#define GL_CLIP_PLANE3 0x3003
+#define GL_CLIP_PLANE4 0x3004
+#define GL_CLIP_PLANE5 0x3005
+#define GL_LIGHT0 0x4000
+#define GL_LIGHT1 0x4001
+#define GL_LIGHT2 0x4002
+#define GL_LIGHT3 0x4003
+#define GL_LIGHT4 0x4004
+#define GL_LIGHT5 0x4005
+#define GL_LIGHT6 0x4006
+#define GL_LIGHT7 0x4007
+#define GL_COLOR_LOGIC_OP 0x0BF2
+#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_INTERNAL_FORMAT 0x1003
+#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_DOUBLE 0x140A
+#define GL_PROXY_TEXTURE_1D 0x8063
+#define GL_PROXY_TEXTURE_2D 0x8064
+#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_CLIENT_PIXEL_STORE_BIT 0x00000001
+#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002
+#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF
+#define GL_VERTEX_ARRAY_POINTER 0x808E
+#define GL_NORMAL_ARRAY_POINTER 0x808F
+#define GL_COLOR_ARRAY_POINTER 0x8090
+#define GL_INDEX_ARRAY_POINTER 0x8091
+#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092
+#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093
+#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0
+#define GL_SELECTION_BUFFER_POINTER 0x0DF3
+#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1
+#define GL_INDEX_LOGIC_OP 0x0BF1
+#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B
+#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1
+#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2
+#define GL_SELECTION_BUFFER_SIZE 0x0DF4
+#define GL_VERTEX_ARRAY 0x8074
+#define GL_NORMAL_ARRAY 0x8075
+#define GL_COLOR_ARRAY 0x8076
+#define GL_INDEX_ARRAY 0x8077
+#define GL_TEXTURE_COORD_ARRAY 0x8078
+#define GL_EDGE_FLAG_ARRAY 0x8079
+#define GL_VERTEX_ARRAY_SIZE 0x807A
+#define GL_VERTEX_ARRAY_TYPE 0x807B
+#define GL_VERTEX_ARRAY_STRIDE 0x807C
+#define GL_NORMAL_ARRAY_TYPE 0x807E
+#define GL_NORMAL_ARRAY_STRIDE 0x807F
+#define GL_COLOR_ARRAY_SIZE 0x8081
+#define GL_COLOR_ARRAY_TYPE 0x8082
+#define GL_COLOR_ARRAY_STRIDE 0x8083
+#define GL_INDEX_ARRAY_TYPE 0x8085
+#define GL_INDEX_ARRAY_STRIDE 0x8086
+#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088
+#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089
+#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A
+#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C
+#define GL_TEXTURE_LUMINANCE_SIZE 0x8060
+#define GL_TEXTURE_INTENSITY_SIZE 0x8061
+#define GL_TEXTURE_PRIORITY 0x8066
+#define GL_TEXTURE_RESIDENT 0x8067
+#define GL_ALPHA4 0x803B
+#define GL_ALPHA8 0x803C
+#define GL_ALPHA12 0x803D
+#define GL_ALPHA16 0x803E
+#define GL_LUMINANCE4 0x803F
+#define GL_LUMINANCE8 0x8040
+#define GL_LUMINANCE12 0x8041
+#define GL_LUMINANCE16 0x8042
+#define GL_LUMINANCE4_ALPHA4 0x8043
+#define GL_LUMINANCE6_ALPHA2 0x8044
+#define GL_LUMINANCE8_ALPHA8 0x8045
+#define GL_LUMINANCE12_ALPHA4 0x8046
+#define GL_LUMINANCE12_ALPHA12 0x8047
+#define GL_LUMINANCE16_ALPHA16 0x8048
+#define GL_INTENSITY 0x8049
+#define GL_INTENSITY4 0x804A
+#define GL_INTENSITY8 0x804B
+#define GL_INTENSITY12 0x804C
+#define GL_INTENSITY16 0x804D
+#define GL_V2F 0x2A20
+#define GL_V3F 0x2A21
+#define GL_C4UB_V2F 0x2A22
+#define GL_C4UB_V3F 0x2A23
+#define GL_C3F_V3F 0x2A24
+#define GL_N3F_V3F 0x2A25
+#define GL_C4F_N3F_V3F 0x2A26
+#define GL_T2F_V3F 0x2A27
+#define GL_T4F_V4F 0x2A28
+#define GL_T2F_C4UB_V3F 0x2A29
+#define GL_T2F_C3F_V3F 0x2A2A
+#define GL_T2F_N3F_V3F 0x2A2B
+#define GL_T2F_C4F_N3F_V3F 0x2A2C
+#define GL_T4F_C4F_N3F_V4F 0x2A2D
+#define GL_UNSIGNED_BYTE_3_3_2 0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
+#define GL_UNSIGNED_INT_8_8_8_8 0x8035
+#define GL_UNSIGNED_INT_10_10_10_2 0x8036
+#define GL_TEXTURE_BINDING_3D 0x806A
+#define GL_PACK_SKIP_IMAGES 0x806B
+#define GL_PACK_IMAGE_HEIGHT 0x806C
+#define GL_UNPACK_SKIP_IMAGES 0x806D
+#define GL_UNPACK_IMAGE_HEIGHT 0x806E
+#define GL_TEXTURE_3D 0x806F
+#define GL_PROXY_TEXTURE_3D 0x8070
+#define GL_TEXTURE_DEPTH 0x8071
+#define GL_TEXTURE_WRAP_R 0x8072
+#define GL_MAX_3D_TEXTURE_SIZE 0x8073
+#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362
+#define GL_UNSIGNED_SHORT_5_6_5 0x8363
+#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366
+#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
+#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
+#define GL_BGR 0x80E0
+#define GL_BGRA 0x80E1
+#define GL_MAX_ELEMENTS_VERTICES 0x80E8
+#define GL_MAX_ELEMENTS_INDICES 0x80E9
+#define GL_CLAMP_TO_EDGE 0x812F
+#define GL_TEXTURE_MIN_LOD 0x813A
+#define GL_TEXTURE_MAX_LOD 0x813B
+#define GL_TEXTURE_BASE_LEVEL 0x813C
+#define GL_TEXTURE_MAX_LEVEL 0x813D
+#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12
+#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13
+#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22
+#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23
+#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
+#define GL_RESCALE_NORMAL 0x803A
+#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8
+#define GL_SINGLE_COLOR 0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR 0x81FA
+#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
+#define GL_TEXTURE0 0x84C0
+#define GL_TEXTURE1 0x84C1
+#define GL_TEXTURE2 0x84C2
+#define GL_TEXTURE3 0x84C3
+#define GL_TEXTURE4 0x84C4
+#define GL_TEXTURE5 0x84C5
+#define GL_TEXTURE6 0x84C6
+#define GL_TEXTURE7 0x84C7
+#define GL_TEXTURE8 0x84C8
+#define GL_TEXTURE9 0x84C9
+#define GL_TEXTURE10 0x84CA
+#define GL_TEXTURE11 0x84CB
+#define GL_TEXTURE12 0x84CC
+#define GL_TEXTURE13 0x84CD
+#define GL_TEXTURE14 0x84CE
+#define GL_TEXTURE15 0x84CF
+#define GL_TEXTURE16 0x84D0
+#define GL_TEXTURE17 0x84D1
+#define GL_TEXTURE18 0x84D2
+#define GL_TEXTURE19 0x84D3
+#define GL_TEXTURE20 0x84D4
+#define GL_TEXTURE21 0x84D5
+#define GL_TEXTURE22 0x84D6
+#define GL_TEXTURE23 0x84D7
+#define GL_TEXTURE24 0x84D8
+#define GL_TEXTURE25 0x84D9
+#define GL_TEXTURE26 0x84DA
+#define GL_TEXTURE27 0x84DB
+#define GL_TEXTURE28 0x84DC
+#define GL_TEXTURE29 0x84DD
+#define GL_TEXTURE30 0x84DE
+#define GL_TEXTURE31 0x84DF
+#define GL_ACTIVE_TEXTURE 0x84E0
+#define GL_MULTISAMPLE 0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE 0x809F
+#define GL_SAMPLE_COVERAGE 0x80A0
+#define GL_SAMPLE_BUFFERS 0x80A8
+#define GL_SAMPLES 0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
+#define GL_TEXTURE_CUBE_MAP 0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
+#define GL_COMPRESSED_RGB 0x84ED
+#define GL_COMPRESSED_RGBA 0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT 0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0
+#define GL_TEXTURE_COMPRESSED 0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
+#define GL_CLAMP_TO_BORDER 0x812D
+#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1
+#define GL_MAX_TEXTURE_UNITS 0x84E2
+#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6
+#define GL_MULTISAMPLE_BIT 0x20000000
+#define GL_NORMAL_MAP 0x8511
+#define GL_REFLECTION_MAP 0x8512
+#define GL_COMPRESSED_ALPHA 0x84E9
+#define GL_COMPRESSED_LUMINANCE 0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB
+#define GL_COMPRESSED_INTENSITY 0x84EC
+#define GL_COMBINE 0x8570
+#define GL_COMBINE_RGB 0x8571
+#define GL_COMBINE_ALPHA 0x8572
+#define GL_SOURCE0_RGB 0x8580
+#define GL_SOURCE1_RGB 0x8581
+#define GL_SOURCE2_RGB 0x8582
+#define GL_SOURCE0_ALPHA 0x8588
+#define GL_SOURCE1_ALPHA 0x8589
+#define GL_SOURCE2_ALPHA 0x858A
+#define GL_OPERAND0_RGB 0x8590
+#define GL_OPERAND1_RGB 0x8591
+#define GL_OPERAND2_RGB 0x8592
+#define GL_OPERAND0_ALPHA 0x8598
+#define GL_OPERAND1_ALPHA 0x8599
+#define GL_OPERAND2_ALPHA 0x859A
+#define GL_RGB_SCALE 0x8573
+#define GL_ADD_SIGNED 0x8574
+#define GL_INTERPOLATE 0x8575
+#define GL_SUBTRACT 0x84E7
+#define GL_CONSTANT 0x8576
+#define GL_PRIMARY_COLOR 0x8577
+#define GL_PREVIOUS 0x8578
+#define GL_DOT3_RGB 0x86AE
+#define GL_DOT3_RGBA 0x86AF
+#define GL_BLEND_DST_RGB 0x80C8
+#define GL_BLEND_SRC_RGB 0x80C9
+#define GL_BLEND_DST_ALPHA 0x80CA
+#define GL_BLEND_SRC_ALPHA 0x80CB
+#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128
+#define GL_DEPTH_COMPONENT16 0x81A5
+#define GL_DEPTH_COMPONENT24 0x81A6
+#define GL_DEPTH_COMPONENT32 0x81A7
+#define GL_MIRRORED_REPEAT 0x8370
+#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD
+#define GL_TEXTURE_LOD_BIAS 0x8501
+#define GL_INCR_WRAP 0x8507
+#define GL_DECR_WRAP 0x8508
+#define GL_TEXTURE_DEPTH_SIZE 0x884A
+#define GL_TEXTURE_COMPARE_MODE 0x884C
+#define GL_TEXTURE_COMPARE_FUNC 0x884D
+#define GL_POINT_SIZE_MIN 0x8126
+#define GL_POINT_SIZE_MAX 0x8127
+#define GL_POINT_DISTANCE_ATTENUATION 0x8129
+#define GL_GENERATE_MIPMAP 0x8191
+#define GL_GENERATE_MIPMAP_HINT 0x8192
+#define GL_FOG_COORDINATE_SOURCE 0x8450
+#define GL_FOG_COORDINATE 0x8451
+#define GL_FRAGMENT_DEPTH 0x8452
+#define GL_CURRENT_FOG_COORDINATE 0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456
+#define GL_FOG_COORDINATE_ARRAY 0x8457
+#define GL_COLOR_SUM 0x8458
+#define GL_CURRENT_SECONDARY_COLOR 0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D
+#define GL_SECONDARY_COLOR_ARRAY 0x845E
+#define GL_TEXTURE_FILTER_CONTROL 0x8500
+#define GL_DEPTH_TEXTURE_MODE 0x884B
+#define GL_COMPARE_R_TO_TEXTURE 0x884E
+#define GL_BLEND_COLOR 0x8005
+#define GL_BLEND_EQUATION 0x8009
+#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_FUNC_ADD 0x8006
+#define GL_FUNC_REVERSE_SUBTRACT 0x800B
+#define GL_FUNC_SUBTRACT 0x800A
+#define GL_MIN 0x8007
+#define GL_MAX 0x8008
+#define GL_BUFFER_SIZE 0x8764
+#define GL_BUFFER_USAGE 0x8765
+#define GL_QUERY_COUNTER_BITS 0x8864
+#define GL_CURRENT_QUERY 0x8865
+#define GL_QUERY_RESULT 0x8866
+#define GL_QUERY_RESULT_AVAILABLE 0x8867
+#define GL_ARRAY_BUFFER 0x8892
+#define GL_ELEMENT_ARRAY_BUFFER 0x8893
+#define GL_ARRAY_BUFFER_BINDING 0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+#define GL_READ_ONLY 0x88B8
+#define GL_WRITE_ONLY 0x88B9
+#define GL_READ_WRITE 0x88BA
+#define GL_BUFFER_ACCESS 0x88BB
+#define GL_BUFFER_MAPPED 0x88BC
+#define GL_BUFFER_MAP_POINTER 0x88BD
+#define GL_STREAM_DRAW 0x88E0
+#define GL_STREAM_READ 0x88E1
+#define GL_STREAM_COPY 0x88E2
+#define GL_STATIC_DRAW 0x88E4
+#define GL_STATIC_READ 0x88E5
+#define GL_STATIC_COPY 0x88E6
+#define GL_DYNAMIC_DRAW 0x88E8
+#define GL_DYNAMIC_READ 0x88E9
+#define GL_DYNAMIC_COPY 0x88EA
+#define GL_SAMPLES_PASSED 0x8914
+#define GL_SRC1_ALPHA 0x8589
+#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E
+#define GL_FOG_COORD_SRC 0x8450
+#define GL_FOG_COORD 0x8451
+#define GL_CURRENT_FOG_COORD 0x8453
+#define GL_FOG_COORD_ARRAY_TYPE 0x8454
+#define GL_FOG_COORD_ARRAY_STRIDE 0x8455
+#define GL_FOG_COORD_ARRAY_POINTER 0x8456
+#define GL_FOG_COORD_ARRAY 0x8457
+#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D
+#define GL_SRC0_RGB 0x8580
+#define GL_SRC1_RGB 0x8581
+#define GL_SRC2_RGB 0x8582
+#define GL_SRC0_ALPHA 0x8588
+#define GL_SRC2_ALPHA 0x858A
+#define GL_BLEND_EQUATION_RGB 0x8009
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
+#define GL_CURRENT_VERTEX_ATTRIB 0x8626
+#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
+#define GL_STENCIL_BACK_FUNC 0x8800
+#define GL_STENCIL_BACK_FAIL 0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
+#define GL_MAX_DRAW_BUFFERS 0x8824
+#define GL_DRAW_BUFFER0 0x8825
+#define GL_DRAW_BUFFER1 0x8826
+#define GL_DRAW_BUFFER2 0x8827
+#define GL_DRAW_BUFFER3 0x8828
+#define GL_DRAW_BUFFER4 0x8829
+#define GL_DRAW_BUFFER5 0x882A
+#define GL_DRAW_BUFFER6 0x882B
+#define GL_DRAW_BUFFER7 0x882C
+#define GL_DRAW_BUFFER8 0x882D
+#define GL_DRAW_BUFFER9 0x882E
+#define GL_DRAW_BUFFER10 0x882F
+#define GL_DRAW_BUFFER11 0x8830
+#define GL_DRAW_BUFFER12 0x8831
+#define GL_DRAW_BUFFER13 0x8832
+#define GL_DRAW_BUFFER14 0x8833
+#define GL_DRAW_BUFFER15 0x8834
+#define GL_BLEND_EQUATION_ALPHA 0x883D
+#define GL_MAX_VERTEX_ATTRIBS 0x8869
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
+#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872
+#define GL_FRAGMENT_SHADER 0x8B30
+#define GL_VERTEX_SHADER 0x8B31
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
+#define GL_MAX_VARYING_FLOATS 0x8B4B
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
+#define GL_SHADER_TYPE 0x8B4F
+#define GL_FLOAT_VEC2 0x8B50
+#define GL_FLOAT_VEC3 0x8B51
+#define GL_FLOAT_VEC4 0x8B52
+#define GL_INT_VEC2 0x8B53
+#define GL_INT_VEC3 0x8B54
+#define GL_INT_VEC4 0x8B55
+#define GL_BOOL 0x8B56
+#define GL_BOOL_VEC2 0x8B57
+#define GL_BOOL_VEC3 0x8B58
+#define GL_BOOL_VEC4 0x8B59
+#define GL_FLOAT_MAT2 0x8B5A
+#define GL_FLOAT_MAT3 0x8B5B
+#define GL_FLOAT_MAT4 0x8B5C
+#define GL_SAMPLER_1D 0x8B5D
+#define GL_SAMPLER_2D 0x8B5E
+#define GL_SAMPLER_3D 0x8B5F
+#define GL_SAMPLER_CUBE 0x8B60
+#define GL_SAMPLER_1D_SHADOW 0x8B61
+#define GL_SAMPLER_2D_SHADOW 0x8B62
+#define GL_DELETE_STATUS 0x8B80
+#define GL_COMPILE_STATUS 0x8B81
+#define GL_LINK_STATUS 0x8B82
+#define GL_VALIDATE_STATUS 0x8B83
+#define GL_INFO_LOG_LENGTH 0x8B84
+#define GL_ATTACHED_SHADERS 0x8B85
+#define GL_ACTIVE_UNIFORMS 0x8B86
+#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
+#define GL_SHADER_SOURCE_LENGTH 0x8B88
+#define GL_ACTIVE_ATTRIBUTES 0x8B89
+#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B
+#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
+#define GL_CURRENT_PROGRAM 0x8B8D
+#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0
+#define GL_LOWER_LEFT 0x8CA1
+#define GL_UPPER_LEFT 0x8CA2
+#define GL_STENCIL_BACK_REF 0x8CA3
+#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
+#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
+#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643
+#define GL_POINT_SPRITE 0x8861
+#define GL_COORD_REPLACE 0x8862
+#define GL_MAX_TEXTURE_COORDS 0x8871
+#define GL_PIXEL_PACK_BUFFER 0x88EB
+#define GL_PIXEL_UNPACK_BUFFER 0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF
+#define GL_FLOAT_MAT2x3 0x8B65
+#define GL_FLOAT_MAT2x4 0x8B66
+#define GL_FLOAT_MAT3x2 0x8B67
+#define GL_FLOAT_MAT3x4 0x8B68
+#define GL_FLOAT_MAT4x2 0x8B69
+#define GL_FLOAT_MAT4x3 0x8B6A
+#define GL_SRGB 0x8C40
+#define GL_SRGB8 0x8C41
+#define GL_SRGB_ALPHA 0x8C42
+#define GL_SRGB8_ALPHA8 0x8C43
+#define GL_COMPRESSED_SRGB 0x8C48
+#define GL_COMPRESSED_SRGB_ALPHA 0x8C49
+#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F
+#define GL_SLUMINANCE_ALPHA 0x8C44
+#define GL_SLUMINANCE8_ALPHA8 0x8C45
+#define GL_SLUMINANCE 0x8C46
+#define GL_SLUMINANCE8 0x8C47
+#define GL_COMPRESSED_SLUMINANCE 0x8C4A
+#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B
+#define GL_COMPARE_REF_TO_TEXTURE 0x884E
+#define GL_CLIP_DISTANCE0 0x3000
+#define GL_CLIP_DISTANCE1 0x3001
+#define GL_CLIP_DISTANCE2 0x3002
+#define GL_CLIP_DISTANCE3 0x3003
+#define GL_CLIP_DISTANCE4 0x3004
+#define GL_CLIP_DISTANCE5 0x3005
+#define GL_CLIP_DISTANCE6 0x3006
+#define GL_CLIP_DISTANCE7 0x3007
+#define GL_MAX_CLIP_DISTANCES 0x0D32
+#define GL_MAJOR_VERSION 0x821B
+#define GL_MINOR_VERSION 0x821C
+#define GL_NUM_EXTENSIONS 0x821D
+#define GL_CONTEXT_FLAGS 0x821E
+#define GL_COMPRESSED_RED 0x8225
+#define GL_COMPRESSED_RG 0x8226
+#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001
+#define GL_RGBA32F 0x8814
+#define GL_RGB32F 0x8815
+#define GL_RGBA16F 0x881A
+#define GL_RGB16F 0x881B
+#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD
+#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF
+#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904
+#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905
+#define GL_CLAMP_READ_COLOR 0x891C
+#define GL_FIXED_ONLY 0x891D
+#define GL_MAX_VARYING_COMPONENTS 0x8B4B
+#define GL_TEXTURE_1D_ARRAY 0x8C18
+#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19
+#define GL_TEXTURE_2D_ARRAY 0x8C1A
+#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B
+#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C
+#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D
+#define GL_R11F_G11F_B10F 0x8C3A
+#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B
+#define GL_RGB9_E5 0x8C3D
+#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E
+#define GL_TEXTURE_SHARED_SIZE 0x8C3F
+#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76
+#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80
+#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83
+#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84
+#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85
+#define GL_PRIMITIVES_GENERATED 0x8C87
+#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88
+#define GL_RASTERIZER_DISCARD 0x8C89
+#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B
+#define GL_INTERLEAVED_ATTRIBS 0x8C8C
+#define GL_SEPARATE_ATTRIBS 0x8C8D
+#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E
+#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F
+#define GL_RGBA32UI 0x8D70
+#define GL_RGB32UI 0x8D71
+#define GL_RGBA16UI 0x8D76
+#define GL_RGB16UI 0x8D77
+#define GL_RGBA8UI 0x8D7C
+#define GL_RGB8UI 0x8D7D
+#define GL_RGBA32I 0x8D82
+#define GL_RGB32I 0x8D83
+#define GL_RGBA16I 0x8D88
+#define GL_RGB16I 0x8D89
+#define GL_RGBA8I 0x8D8E
+#define GL_RGB8I 0x8D8F
+#define GL_RED_INTEGER 0x8D94
+#define GL_GREEN_INTEGER 0x8D95
+#define GL_BLUE_INTEGER 0x8D96
+#define GL_RGB_INTEGER 0x8D98
+#define GL_RGBA_INTEGER 0x8D99
+#define GL_BGR_INTEGER 0x8D9A
+#define GL_BGRA_INTEGER 0x8D9B
+#define GL_SAMPLER_1D_ARRAY 0x8DC0
+#define GL_SAMPLER_2D_ARRAY 0x8DC1
+#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3
+#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4
+#define GL_SAMPLER_CUBE_SHADOW 0x8DC5
+#define GL_UNSIGNED_INT_VEC2 0x8DC6
+#define GL_UNSIGNED_INT_VEC3 0x8DC7
+#define GL_UNSIGNED_INT_VEC4 0x8DC8
+#define GL_INT_SAMPLER_1D 0x8DC9
+#define GL_INT_SAMPLER_2D 0x8DCA
+#define GL_INT_SAMPLER_3D 0x8DCB
+#define GL_INT_SAMPLER_CUBE 0x8DCC
+#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE
+#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF
+#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1
+#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2
+#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3
+#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4
+#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6
+#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7
+#define GL_QUERY_WAIT 0x8E13
+#define GL_QUERY_NO_WAIT 0x8E14
+#define GL_QUERY_BY_REGION_WAIT 0x8E15
+#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16
+#define GL_BUFFER_ACCESS_FLAGS 0x911F
+#define GL_BUFFER_MAP_LENGTH 0x9120
+#define GL_BUFFER_MAP_OFFSET 0x9121
+#define GL_DEPTH_COMPONENT32F 0x8CAC
+#define GL_DEPTH32F_STENCIL8 0x8CAD
+#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD
+#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506
+#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210
+#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211
+#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212
+#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213
+#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214
+#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215
+#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216
+#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217
+#define GL_FRAMEBUFFER_DEFAULT 0x8218
+#define GL_FRAMEBUFFER_UNDEFINED 0x8219
+#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
+#define GL_MAX_RENDERBUFFER_SIZE 0x84E8
+#define GL_DEPTH_STENCIL 0x84F9
+#define GL_UNSIGNED_INT_24_8 0x84FA
+#define GL_DEPTH24_STENCIL8 0x88F0
+#define GL_TEXTURE_STENCIL_SIZE 0x88F1
+#define GL_TEXTURE_RED_TYPE 0x8C10
+#define GL_TEXTURE_GREEN_TYPE 0x8C11
+#define GL_TEXTURE_BLUE_TYPE 0x8C12
+#define GL_TEXTURE_ALPHA_TYPE 0x8C13
+#define GL_TEXTURE_DEPTH_TYPE 0x8C16
+#define GL_UNSIGNED_NORMALIZED 0x8C17
+#define GL_FRAMEBUFFER_BINDING 0x8CA6
+#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6
+#define GL_RENDERBUFFER_BINDING 0x8CA7
+#define GL_READ_FRAMEBUFFER 0x8CA8
+#define GL_DRAW_FRAMEBUFFER 0x8CA9
+#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA
+#define GL_RENDERBUFFER_SAMPLES 0x8CAB
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4
+#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB
+#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC
+#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
+#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF
+#define GL_COLOR_ATTACHMENT0 0x8CE0
+#define GL_COLOR_ATTACHMENT1 0x8CE1
+#define GL_COLOR_ATTACHMENT2 0x8CE2
+#define GL_COLOR_ATTACHMENT3 0x8CE3
+#define GL_COLOR_ATTACHMENT4 0x8CE4
+#define GL_COLOR_ATTACHMENT5 0x8CE5
+#define GL_COLOR_ATTACHMENT6 0x8CE6
+#define GL_COLOR_ATTACHMENT7 0x8CE7
+#define GL_COLOR_ATTACHMENT8 0x8CE8
+#define GL_COLOR_ATTACHMENT9 0x8CE9
+#define GL_COLOR_ATTACHMENT10 0x8CEA
+#define GL_COLOR_ATTACHMENT11 0x8CEB
+#define GL_COLOR_ATTACHMENT12 0x8CEC
+#define GL_COLOR_ATTACHMENT13 0x8CED
+#define GL_COLOR_ATTACHMENT14 0x8CEE
+#define GL_COLOR_ATTACHMENT15 0x8CEF
+#define GL_COLOR_ATTACHMENT16 0x8CF0
+#define GL_COLOR_ATTACHMENT17 0x8CF1
+#define GL_COLOR_ATTACHMENT18 0x8CF2
+#define GL_COLOR_ATTACHMENT19 0x8CF3
+#define GL_COLOR_ATTACHMENT20 0x8CF4
+#define GL_COLOR_ATTACHMENT21 0x8CF5
+#define GL_COLOR_ATTACHMENT22 0x8CF6
+#define GL_COLOR_ATTACHMENT23 0x8CF7
+#define GL_COLOR_ATTACHMENT24 0x8CF8
+#define GL_COLOR_ATTACHMENT25 0x8CF9
+#define GL_COLOR_ATTACHMENT26 0x8CFA
+#define GL_COLOR_ATTACHMENT27 0x8CFB
+#define GL_COLOR_ATTACHMENT28 0x8CFC
+#define GL_COLOR_ATTACHMENT29 0x8CFD
+#define GL_COLOR_ATTACHMENT30 0x8CFE
+#define GL_COLOR_ATTACHMENT31 0x8CFF
+#define GL_DEPTH_ATTACHMENT 0x8D00
+#define GL_STENCIL_ATTACHMENT 0x8D20
+#define GL_FRAMEBUFFER 0x8D40
+#define GL_RENDERBUFFER 0x8D41
+#define GL_RENDERBUFFER_WIDTH 0x8D42
+#define GL_RENDERBUFFER_HEIGHT 0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44
+#define GL_STENCIL_INDEX1 0x8D46
+#define GL_STENCIL_INDEX4 0x8D47
+#define GL_STENCIL_INDEX8 0x8D48
+#define GL_STENCIL_INDEX16 0x8D49
+#define GL_RENDERBUFFER_RED_SIZE 0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56
+#define GL_MAX_SAMPLES 0x8D57
+#define GL_INDEX 0x8222
+#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14
+#define GL_TEXTURE_INTENSITY_TYPE 0x8C15
+#define GL_FRAMEBUFFER_SRGB 0x8DB9
+#define GL_HALF_FLOAT 0x140B
+#define GL_MAP_READ_BIT 0x0001
+#define GL_MAP_WRITE_BIT 0x0002
+#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004
+#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008
+#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010
+#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020
+#define GL_COMPRESSED_RED_RGTC1 0x8DBB
+#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC
+#define GL_COMPRESSED_RG_RGTC2 0x8DBD
+#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE
+#define GL_RG 0x8227
+#define GL_RG_INTEGER 0x8228
+#define GL_R8 0x8229
+#define GL_R16 0x822A
+#define GL_RG8 0x822B
+#define GL_RG16 0x822C
+#define GL_R16F 0x822D
+#define GL_R32F 0x822E
+#define GL_RG16F 0x822F
+#define GL_RG32F 0x8230
+#define GL_R8I 0x8231
+#define GL_R8UI 0x8232
+#define GL_R16I 0x8233
+#define GL_R16UI 0x8234
+#define GL_R32I 0x8235
+#define GL_R32UI 0x8236
+#define GL_RG8I 0x8237
+#define GL_RG8UI 0x8238
+#define GL_RG16I 0x8239
+#define GL_RG16UI 0x823A
+#define GL_RG32I 0x823B
+#define GL_RG32UI 0x823C
+#define GL_VERTEX_ARRAY_BINDING 0x85B5
+#define GL_CLAMP_VERTEX_COLOR 0x891A
+#define GL_CLAMP_FRAGMENT_COLOR 0x891B
+#define GL_ALPHA_INTEGER 0x8D97
+#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_COLOR_TABLE 0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2
+#define GL_PROXY_COLOR_TABLE 0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
+#define GL_CONVOLUTION_1D 0x8010
+#define GL_CONVOLUTION_2D 0x8011
+#define GL_SEPARABLE_2D 0x8012
+#define GL_HISTOGRAM 0x8024
+#define GL_PROXY_HISTOGRAM 0x8025
+#define GL_MINMAX 0x802E
+#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB
+#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC
+#define GL_SHADER_BINARY_FORMAT_SPIR_V 0x9551
+#define GL_SPIR_V_BINARY 0x9552
+#define GL_PARAMETER_BUFFER 0x80EE
+#define GL_PARAMETER_BUFFER_BINDING 0x80EF
+#define GL_CONTEXT_FLAG_NO_ERROR_BIT 0x00000008
+#define GL_VERTICES_SUBMITTED 0x82EE
+#define GL_PRIMITIVES_SUBMITTED 0x82EF
+#define GL_VERTEX_SHADER_INVOCATIONS 0x82F0
+#define GL_TESS_CONTROL_SHADER_PATCHES 0x82F1
+#define GL_TESS_EVALUATION_SHADER_INVOCATIONS 0x82F2
+#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED 0x82F3
+#define GL_FRAGMENT_SHADER_INVOCATIONS 0x82F4
+#define GL_COMPUTE_SHADER_INVOCATIONS 0x82F5
+#define GL_CLIPPING_INPUT_PRIMITIVES 0x82F6
+#define GL_CLIPPING_OUTPUT_PRIMITIVES 0x82F7
+#define GL_POLYGON_OFFSET_CLAMP 0x8E1B
+#define GL_SPIR_V_EXTENSIONS 0x9553
+#define GL_NUM_SPIR_V_EXTENSIONS 0x9554
+#define GL_TEXTURE_MAX_ANISOTROPY 0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY 0x84FF
+#define GL_TRANSFORM_FEEDBACK_OVERFLOW 0x82EC
+#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW 0x82ED
+#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)(void);
+GLAPI PFNGLFINISHPROC glad_glFinish;
+#define glFinish glad_glFinish
+typedef void (APIENTRYP PFNGLFLUSHPROC)(void);
+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)(void);
+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 n, GLdouble f);
+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
+typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode);
+GLAPI PFNGLNEWLISTPROC glad_glNewList;
+#define glNewList glad_glNewList
+typedef void (APIENTRYP PFNGLENDLISTPROC)(void);
+GLAPI PFNGLENDLISTPROC glad_glEndList;
+#define glEndList glad_glEndList
+typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list);
+GLAPI PFNGLCALLLISTPROC glad_glCallList;
+#define glCallList glad_glCallList
+typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists);
+GLAPI PFNGLCALLLISTSPROC glad_glCallLists;
+#define glCallLists glad_glCallLists
+typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range);
+GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists;
+#define glDeleteLists glad_glDeleteLists
+typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range);
+GLAPI PFNGLGENLISTSPROC glad_glGenLists;
+#define glGenLists glad_glGenLists
+typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base);
+GLAPI PFNGLLISTBASEPROC glad_glListBase;
+#define glListBase glad_glListBase
+typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode);
+GLAPI PFNGLBEGINPROC glad_glBegin;
+#define glBegin glad_glBegin
+typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+GLAPI PFNGLBITMAPPROC glad_glBitmap;
+#define glBitmap glad_glBitmap
+typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue);
+GLAPI PFNGLCOLOR3BPROC glad_glColor3b;
+#define glColor3b glad_glColor3b
+typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v);
+GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv;
+#define glColor3bv glad_glColor3bv
+typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue);
+GLAPI PFNGLCOLOR3DPROC glad_glColor3d;
+#define glColor3d glad_glColor3d
+typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v);
+GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv;
+#define glColor3dv glad_glColor3dv
+typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue);
+GLAPI PFNGLCOLOR3FPROC glad_glColor3f;
+#define glColor3f glad_glColor3f
+typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v);
+GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv;
+#define glColor3fv glad_glColor3fv
+typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue);
+GLAPI PFNGLCOLOR3IPROC glad_glColor3i;
+#define glColor3i glad_glColor3i
+typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v);
+GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv;
+#define glColor3iv glad_glColor3iv
+typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue);
+GLAPI PFNGLCOLOR3SPROC glad_glColor3s;
+#define glColor3s glad_glColor3s
+typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v);
+GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv;
+#define glColor3sv glad_glColor3sv
+typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue);
+GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub;
+#define glColor3ub glad_glColor3ub
+typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v);
+GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv;
+#define glColor3ubv glad_glColor3ubv
+typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue);
+GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui;
+#define glColor3ui glad_glColor3ui
+typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v);
+GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv;
+#define glColor3uiv glad_glColor3uiv
+typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue);
+GLAPI PFNGLCOLOR3USPROC glad_glColor3us;
+#define glColor3us glad_glColor3us
+typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v);
+GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv;
+#define glColor3usv glad_glColor3usv
+typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+GLAPI PFNGLCOLOR4BPROC glad_glColor4b;
+#define glColor4b glad_glColor4b
+typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v);
+GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv;
+#define glColor4bv glad_glColor4bv
+typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+GLAPI PFNGLCOLOR4DPROC glad_glColor4d;
+#define glColor4d glad_glColor4d
+typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v);
+GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv;
+#define glColor4dv glad_glColor4dv
+typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+GLAPI PFNGLCOLOR4FPROC glad_glColor4f;
+#define glColor4f glad_glColor4f
+typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v);
+GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv;
+#define glColor4fv glad_glColor4fv
+typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha);
+GLAPI PFNGLCOLOR4IPROC glad_glColor4i;
+#define glColor4i glad_glColor4i
+typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v);
+GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv;
+#define glColor4iv glad_glColor4iv
+typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha);
+GLAPI PFNGLCOLOR4SPROC glad_glColor4s;
+#define glColor4s glad_glColor4s
+typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v);
+GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv;
+#define glColor4sv glad_glColor4sv
+typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub;
+#define glColor4ub glad_glColor4ub
+typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v);
+GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv;
+#define glColor4ubv glad_glColor4ubv
+typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha);
+GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui;
+#define glColor4ui glad_glColor4ui
+typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v);
+GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv;
+#define glColor4uiv glad_glColor4uiv
+typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha);
+GLAPI PFNGLCOLOR4USPROC glad_glColor4us;
+#define glColor4us glad_glColor4us
+typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v);
+GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv;
+#define glColor4usv glad_glColor4usv
+typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag);
+GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag;
+#define glEdgeFlag glad_glEdgeFlag
+typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag);
+GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv;
+#define glEdgeFlagv glad_glEdgeFlagv
+typedef void (APIENTRYP PFNGLENDPROC)(void);
+GLAPI PFNGLENDPROC glad_glEnd;
+#define glEnd glad_glEnd
+typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c);
+GLAPI PFNGLINDEXDPROC glad_glIndexd;
+#define glIndexd glad_glIndexd
+typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c);
+GLAPI PFNGLINDEXDVPROC glad_glIndexdv;
+#define glIndexdv glad_glIndexdv
+typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c);
+GLAPI PFNGLINDEXFPROC glad_glIndexf;
+#define glIndexf glad_glIndexf
+typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c);
+GLAPI PFNGLINDEXFVPROC glad_glIndexfv;
+#define glIndexfv glad_glIndexfv
+typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c);
+GLAPI PFNGLINDEXIPROC glad_glIndexi;
+#define glIndexi glad_glIndexi
+typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c);
+GLAPI PFNGLINDEXIVPROC glad_glIndexiv;
+#define glIndexiv glad_glIndexiv
+typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c);
+GLAPI PFNGLINDEXSPROC glad_glIndexs;
+#define glIndexs glad_glIndexs
+typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c);
+GLAPI PFNGLINDEXSVPROC glad_glIndexsv;
+#define glIndexsv glad_glIndexsv
+typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz);
+GLAPI PFNGLNORMAL3BPROC glad_glNormal3b;
+#define glNormal3b glad_glNormal3b
+typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v);
+GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv;
+#define glNormal3bv glad_glNormal3bv
+typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz);
+GLAPI PFNGLNORMAL3DPROC glad_glNormal3d;
+#define glNormal3d glad_glNormal3d
+typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v);
+GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv;
+#define glNormal3dv glad_glNormal3dv
+typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz);
+GLAPI PFNGLNORMAL3FPROC glad_glNormal3f;
+#define glNormal3f glad_glNormal3f
+typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v);
+GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv;
+#define glNormal3fv glad_glNormal3fv
+typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz);
+GLAPI PFNGLNORMAL3IPROC glad_glNormal3i;
+#define glNormal3i glad_glNormal3i
+typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v);
+GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv;
+#define glNormal3iv glad_glNormal3iv
+typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz);
+GLAPI PFNGLNORMAL3SPROC glad_glNormal3s;
+#define glNormal3s glad_glNormal3s
+typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v);
+GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv;
+#define glNormal3sv glad_glNormal3sv
+typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y);
+GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d;
+#define glRasterPos2d glad_glRasterPos2d
+typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v);
+GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv;
+#define glRasterPos2dv glad_glRasterPos2dv
+typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y);
+GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f;
+#define glRasterPos2f glad_glRasterPos2f
+typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v);
+GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv;
+#define glRasterPos2fv glad_glRasterPos2fv
+typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y);
+GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i;
+#define glRasterPos2i glad_glRasterPos2i
+typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v);
+GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv;
+#define glRasterPos2iv glad_glRasterPos2iv
+typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y);
+GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s;
+#define glRasterPos2s glad_glRasterPos2s
+typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v);
+GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv;
+#define glRasterPos2sv glad_glRasterPos2sv
+typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z);
+GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d;
+#define glRasterPos3d glad_glRasterPos3d
+typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v);
+GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv;
+#define glRasterPos3dv glad_glRasterPos3dv
+typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z);
+GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f;
+#define glRasterPos3f glad_glRasterPos3f
+typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v);
+GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv;
+#define glRasterPos3fv glad_glRasterPos3fv
+typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z);
+GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i;
+#define glRasterPos3i glad_glRasterPos3i
+typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v);
+GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv;
+#define glRasterPos3iv glad_glRasterPos3iv
+typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z);
+GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s;
+#define glRasterPos3s glad_glRasterPos3s
+typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v);
+GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv;
+#define glRasterPos3sv glad_glRasterPos3sv
+typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d;
+#define glRasterPos4d glad_glRasterPos4d
+typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v);
+GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv;
+#define glRasterPos4dv glad_glRasterPos4dv
+typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f;
+#define glRasterPos4f glad_glRasterPos4f
+typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v);
+GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv;
+#define glRasterPos4fv glad_glRasterPos4fv
+typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w);
+GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i;
+#define glRasterPos4i glad_glRasterPos4i
+typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v);
+GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv;
+#define glRasterPos4iv glad_glRasterPos4iv
+typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s;
+#define glRasterPos4s glad_glRasterPos4s
+typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v);
+GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv;
+#define glRasterPos4sv glad_glRasterPos4sv
+typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+GLAPI PFNGLRECTDPROC glad_glRectd;
+#define glRectd glad_glRectd
+typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2);
+GLAPI PFNGLRECTDVPROC glad_glRectdv;
+#define glRectdv glad_glRectdv
+typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+GLAPI PFNGLRECTFPROC glad_glRectf;
+#define glRectf glad_glRectf
+typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2);
+GLAPI PFNGLRECTFVPROC glad_glRectfv;
+#define glRectfv glad_glRectfv
+typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2);
+GLAPI PFNGLRECTIPROC glad_glRecti;
+#define glRecti glad_glRecti
+typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2);
+GLAPI PFNGLRECTIVPROC glad_glRectiv;
+#define glRectiv glad_glRectiv
+typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+GLAPI PFNGLRECTSPROC glad_glRects;
+#define glRects glad_glRects
+typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2);
+GLAPI PFNGLRECTSVPROC glad_glRectsv;
+#define glRectsv glad_glRectsv
+typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s);
+GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d;
+#define glTexCoord1d glad_glTexCoord1d
+typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v);
+GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv;
+#define glTexCoord1dv glad_glTexCoord1dv
+typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s);
+GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f;
+#define glTexCoord1f glad_glTexCoord1f
+typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v);
+GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv;
+#define glTexCoord1fv glad_glTexCoord1fv
+typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s);
+GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i;
+#define glTexCoord1i glad_glTexCoord1i
+typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v);
+GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv;
+#define glTexCoord1iv glad_glTexCoord1iv
+typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s);
+GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s;
+#define glTexCoord1s glad_glTexCoord1s
+typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v);
+GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv;
+#define glTexCoord1sv glad_glTexCoord1sv
+typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t);
+GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d;
+#define glTexCoord2d glad_glTexCoord2d
+typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v);
+GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv;
+#define glTexCoord2dv glad_glTexCoord2dv
+typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t);
+GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f;
+#define glTexCoord2f glad_glTexCoord2f
+typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v);
+GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv;
+#define glTexCoord2fv glad_glTexCoord2fv
+typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t);
+GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i;
+#define glTexCoord2i glad_glTexCoord2i
+typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v);
+GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv;
+#define glTexCoord2iv glad_glTexCoord2iv
+typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t);
+GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s;
+#define glTexCoord2s glad_glTexCoord2s
+typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v);
+GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv;
+#define glTexCoord2sv glad_glTexCoord2sv
+typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r);
+GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d;
+#define glTexCoord3d glad_glTexCoord3d
+typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v);
+GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv;
+#define glTexCoord3dv glad_glTexCoord3dv
+typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r);
+GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f;
+#define glTexCoord3f glad_glTexCoord3f
+typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v);
+GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv;
+#define glTexCoord3fv glad_glTexCoord3fv
+typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r);
+GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i;
+#define glTexCoord3i glad_glTexCoord3i
+typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v);
+GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv;
+#define glTexCoord3iv glad_glTexCoord3iv
+typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r);
+GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s;
+#define glTexCoord3s glad_glTexCoord3s
+typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v);
+GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv;
+#define glTexCoord3sv glad_glTexCoord3sv
+typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d;
+#define glTexCoord4d glad_glTexCoord4d
+typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v);
+GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv;
+#define glTexCoord4dv glad_glTexCoord4dv
+typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f;
+#define glTexCoord4f glad_glTexCoord4f
+typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v);
+GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv;
+#define glTexCoord4fv glad_glTexCoord4fv
+typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q);
+GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i;
+#define glTexCoord4i glad_glTexCoord4i
+typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v);
+GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv;
+#define glTexCoord4iv glad_glTexCoord4iv
+typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q);
+GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s;
+#define glTexCoord4s glad_glTexCoord4s
+typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v);
+GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv;
+#define glTexCoord4sv glad_glTexCoord4sv
+typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y);
+GLAPI PFNGLVERTEX2DPROC glad_glVertex2d;
+#define glVertex2d glad_glVertex2d
+typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v);
+GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv;
+#define glVertex2dv glad_glVertex2dv
+typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y);
+GLAPI PFNGLVERTEX2FPROC glad_glVertex2f;
+#define glVertex2f glad_glVertex2f
+typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v);
+GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv;
+#define glVertex2fv glad_glVertex2fv
+typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y);
+GLAPI PFNGLVERTEX2IPROC glad_glVertex2i;
+#define glVertex2i glad_glVertex2i
+typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v);
+GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv;
+#define glVertex2iv glad_glVertex2iv
+typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y);
+GLAPI PFNGLVERTEX2SPROC glad_glVertex2s;
+#define glVertex2s glad_glVertex2s
+typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v);
+GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv;
+#define glVertex2sv glad_glVertex2sv
+typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z);
+GLAPI PFNGLVERTEX3DPROC glad_glVertex3d;
+#define glVertex3d glad_glVertex3d
+typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v);
+GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv;
+#define glVertex3dv glad_glVertex3dv
+typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z);
+GLAPI PFNGLVERTEX3FPROC glad_glVertex3f;
+#define glVertex3f glad_glVertex3f
+typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v);
+GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv;
+#define glVertex3fv glad_glVertex3fv
+typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z);
+GLAPI PFNGLVERTEX3IPROC glad_glVertex3i;
+#define glVertex3i glad_glVertex3i
+typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v);
+GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv;
+#define glVertex3iv glad_glVertex3iv
+typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z);
+GLAPI PFNGLVERTEX3SPROC glad_glVertex3s;
+#define glVertex3s glad_glVertex3s
+typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v);
+GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv;
+#define glVertex3sv glad_glVertex3sv
+typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI PFNGLVERTEX4DPROC glad_glVertex4d;
+#define glVertex4d glad_glVertex4d
+typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v);
+GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv;
+#define glVertex4dv glad_glVertex4dv
+typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI PFNGLVERTEX4FPROC glad_glVertex4f;
+#define glVertex4f glad_glVertex4f
+typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v);
+GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv;
+#define glVertex4fv glad_glVertex4fv
+typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w);
+GLAPI PFNGLVERTEX4IPROC glad_glVertex4i;
+#define glVertex4i glad_glVertex4i
+typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v);
+GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv;
+#define glVertex4iv glad_glVertex4iv
+typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI PFNGLVERTEX4SPROC glad_glVertex4s;
+#define glVertex4s glad_glVertex4s
+typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v);
+GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv;
+#define glVertex4sv glad_glVertex4sv
+typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation);
+GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane;
+#define glClipPlane glad_glClipPlane
+typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode);
+GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial;
+#define glColorMaterial glad_glColorMaterial
+typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param);
+GLAPI PFNGLFOGFPROC glad_glFogf;
+#define glFogf glad_glFogf
+typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params);
+GLAPI PFNGLFOGFVPROC glad_glFogfv;
+#define glFogfv glad_glFogfv
+typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param);
+GLAPI PFNGLFOGIPROC glad_glFogi;
+#define glFogi glad_glFogi
+typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params);
+GLAPI PFNGLFOGIVPROC glad_glFogiv;
+#define glFogiv glad_glFogiv
+typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param);
+GLAPI PFNGLLIGHTFPROC glad_glLightf;
+#define glLightf glad_glLightf
+typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params);
+GLAPI PFNGLLIGHTFVPROC glad_glLightfv;
+#define glLightfv glad_glLightfv
+typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param);
+GLAPI PFNGLLIGHTIPROC glad_glLighti;
+#define glLighti glad_glLighti
+typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params);
+GLAPI PFNGLLIGHTIVPROC glad_glLightiv;
+#define glLightiv glad_glLightiv
+typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param);
+GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf;
+#define glLightModelf glad_glLightModelf
+typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params);
+GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv;
+#define glLightModelfv glad_glLightModelfv
+typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param);
+GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli;
+#define glLightModeli glad_glLightModeli
+typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params);
+GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv;
+#define glLightModeliv glad_glLightModeliv
+typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern);
+GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple;
+#define glLineStipple glad_glLineStipple
+typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param);
+GLAPI PFNGLMATERIALFPROC glad_glMaterialf;
+#define glMaterialf glad_glMaterialf
+typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params);
+GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv;
+#define glMaterialfv glad_glMaterialfv
+typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param);
+GLAPI PFNGLMATERIALIPROC glad_glMateriali;
+#define glMateriali glad_glMateriali
+typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params);
+GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv;
+#define glMaterialiv glad_glMaterialiv
+typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask);
+GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple;
+#define glPolygonStipple glad_glPolygonStipple
+typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode);
+GLAPI PFNGLSHADEMODELPROC glad_glShadeModel;
+#define glShadeModel glad_glShadeModel
+typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param);
+GLAPI PFNGLTEXENVFPROC glad_glTexEnvf;
+#define glTexEnvf glad_glTexEnvf
+typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params);
+GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv;
+#define glTexEnvfv glad_glTexEnvfv
+typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param);
+GLAPI PFNGLTEXENVIPROC glad_glTexEnvi;
+#define glTexEnvi glad_glTexEnvi
+typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params);
+GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv;
+#define glTexEnviv glad_glTexEnviv
+typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param);
+GLAPI PFNGLTEXGENDPROC glad_glTexGend;
+#define glTexGend glad_glTexGend
+typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params);
+GLAPI PFNGLTEXGENDVPROC glad_glTexGendv;
+#define glTexGendv glad_glTexGendv
+typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param);
+GLAPI PFNGLTEXGENFPROC glad_glTexGenf;
+#define glTexGenf glad_glTexGenf
+typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params);
+GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv;
+#define glTexGenfv glad_glTexGenfv
+typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param);
+GLAPI PFNGLTEXGENIPROC glad_glTexGeni;
+#define glTexGeni glad_glTexGeni
+typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params);
+GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv;
+#define glTexGeniv glad_glTexGeniv
+typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer);
+GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer;
+#define glFeedbackBuffer glad_glFeedbackBuffer
+typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer);
+GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer;
+#define glSelectBuffer glad_glSelectBuffer
+typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode);
+GLAPI PFNGLRENDERMODEPROC glad_glRenderMode;
+#define glRenderMode glad_glRenderMode
+typedef void (APIENTRYP PFNGLINITNAMESPROC)(void);
+GLAPI PFNGLINITNAMESPROC glad_glInitNames;
+#define glInitNames glad_glInitNames
+typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name);
+GLAPI PFNGLLOADNAMEPROC glad_glLoadName;
+#define glLoadName glad_glLoadName
+typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token);
+GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough;
+#define glPassThrough glad_glPassThrough
+typedef void (APIENTRYP PFNGLPOPNAMEPROC)(void);
+GLAPI PFNGLPOPNAMEPROC glad_glPopName;
+#define glPopName glad_glPopName
+typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name);
+GLAPI PFNGLPUSHNAMEPROC glad_glPushName;
+#define glPushName glad_glPushName
+typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum;
+#define glClearAccum glad_glClearAccum
+typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c);
+GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex;
+#define glClearIndex glad_glClearIndex
+typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask);
+GLAPI PFNGLINDEXMASKPROC glad_glIndexMask;
+#define glIndexMask glad_glIndexMask
+typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value);
+GLAPI PFNGLACCUMPROC glad_glAccum;
+#define glAccum glad_glAccum
+typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(void);
+GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib;
+#define glPopAttrib glad_glPopAttrib
+typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask);
+GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib;
+#define glPushAttrib glad_glPushAttrib
+typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+GLAPI PFNGLMAP1DPROC glad_glMap1d;
+#define glMap1d glad_glMap1d
+typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+GLAPI PFNGLMAP1FPROC glad_glMap1f;
+#define glMap1f glad_glMap1f
+typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+GLAPI PFNGLMAP2DPROC glad_glMap2d;
+#define glMap2d glad_glMap2d
+typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+GLAPI PFNGLMAP2FPROC glad_glMap2f;
+#define glMap2f glad_glMap2f
+typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2);
+GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d;
+#define glMapGrid1d glad_glMapGrid1d
+typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2);
+GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f;
+#define glMapGrid1f glad_glMapGrid1f
+typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d;
+#define glMapGrid2d glad_glMapGrid2d
+typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f;
+#define glMapGrid2f glad_glMapGrid2f
+typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u);
+GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d;
+#define glEvalCoord1d glad_glEvalCoord1d
+typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u);
+GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv;
+#define glEvalCoord1dv glad_glEvalCoord1dv
+typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u);
+GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f;
+#define glEvalCoord1f glad_glEvalCoord1f
+typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u);
+GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv;
+#define glEvalCoord1fv glad_glEvalCoord1fv
+typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v);
+GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d;
+#define glEvalCoord2d glad_glEvalCoord2d
+typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u);
+GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv;
+#define glEvalCoord2dv glad_glEvalCoord2dv
+typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v);
+GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f;
+#define glEvalCoord2f glad_glEvalCoord2f
+typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u);
+GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv;
+#define glEvalCoord2fv glad_glEvalCoord2fv
+typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2);
+GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1;
+#define glEvalMesh1 glad_glEvalMesh1
+typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i);
+GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1;
+#define glEvalPoint1 glad_glEvalPoint1
+typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2;
+#define glEvalMesh2 glad_glEvalMesh2
+typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j);
+GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2;
+#define glEvalPoint2 glad_glEvalPoint2
+typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref);
+GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc;
+#define glAlphaFunc glad_glAlphaFunc
+typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor);
+GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom;
+#define glPixelZoom glad_glPixelZoom
+typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param);
+GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf;
+#define glPixelTransferf glad_glPixelTransferf
+typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param);
+GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi;
+#define glPixelTransferi glad_glPixelTransferi
+typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values);
+GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv;
+#define glPixelMapfv glad_glPixelMapfv
+typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values);
+GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv;
+#define glPixelMapuiv glad_glPixelMapuiv
+typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values);
+GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv;
+#define glPixelMapusv glad_glPixelMapusv
+typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels;
+#define glCopyPixels glad_glCopyPixels
+typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
+GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels;
+#define glDrawPixels glad_glDrawPixels
+typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation);
+GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane;
+#define glGetClipPlane glad_glGetClipPlane
+typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params);
+GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv;
+#define glGetLightfv glad_glGetLightfv
+typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params);
+GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv;
+#define glGetLightiv glad_glGetLightiv
+typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v);
+GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv;
+#define glGetMapdv glad_glGetMapdv
+typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v);
+GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv;
+#define glGetMapfv glad_glGetMapfv
+typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v);
+GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv;
+#define glGetMapiv glad_glGetMapiv
+typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params);
+GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv;
+#define glGetMaterialfv glad_glGetMaterialfv
+typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params);
+GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv;
+#define glGetMaterialiv glad_glGetMaterialiv
+typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values);
+GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv;
+#define glGetPixelMapfv glad_glGetPixelMapfv
+typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values);
+GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv;
+#define glGetPixelMapuiv glad_glGetPixelMapuiv
+typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values);
+GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv;
+#define glGetPixelMapusv glad_glGetPixelMapusv
+typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask);
+GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple;
+#define glGetPolygonStipple glad_glGetPolygonStipple
+typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params);
+GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv;
+#define glGetTexEnvfv glad_glGetTexEnvfv
+typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params);
+GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv;
+#define glGetTexEnviv glad_glGetTexEnviv
+typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params);
+GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv;
+#define glGetTexGendv glad_glGetTexGendv
+typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params);
+GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv;
+#define glGetTexGenfv glad_glGetTexGenfv
+typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params);
+GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv;
+#define glGetTexGeniv glad_glGetTexGeniv
+typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list);
+GLAPI PFNGLISLISTPROC glad_glIsList;
+#define glIsList glad_glIsList
+typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLAPI PFNGLFRUSTUMPROC glad_glFrustum;
+#define glFrustum glad_glFrustum
+typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(void);
+GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity;
+#define glLoadIdentity glad_glLoadIdentity
+typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m);
+GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf;
+#define glLoadMatrixf glad_glLoadMatrixf
+typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m);
+GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd;
+#define glLoadMatrixd glad_glLoadMatrixd
+typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode);
+GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode;
+#define glMatrixMode glad_glMatrixMode
+typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m);
+GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf;
+#define glMultMatrixf glad_glMultMatrixf
+typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m);
+GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd;
+#define glMultMatrixd glad_glMultMatrixd
+typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLAPI PFNGLORTHOPROC glad_glOrtho;
+#define glOrtho glad_glOrtho
+typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(void);
+GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix;
+#define glPopMatrix glad_glPopMatrix
+typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(void);
+GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix;
+#define glPushMatrix glad_glPushMatrix
+typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+GLAPI PFNGLROTATEDPROC glad_glRotated;
+#define glRotated glad_glRotated
+typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+GLAPI PFNGLROTATEFPROC glad_glRotatef;
+#define glRotatef glad_glRotatef
+typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z);
+GLAPI PFNGLSCALEDPROC glad_glScaled;
+#define glScaled glad_glScaled
+typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z);
+GLAPI PFNGLSCALEFPROC glad_glScalef;
+#define glScalef glad_glScalef
+typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z);
+GLAPI PFNGLTRANSLATEDPROC glad_glTranslated;
+#define glTranslated glad_glTranslated
+typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z);
+GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef;
+#define glTranslatef glad_glTranslatef
+#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 PFNGLGETPOINTERVPROC)(GLenum pname, void **params);
+GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv;
+#define glGetPointerv glad_glGetPointerv
+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
+typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i);
+GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement;
+#define glArrayElement glad_glArrayElement
+typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer;
+#define glColorPointer glad_glColorPointer
+typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array);
+GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState;
+#define glDisableClientState glad_glDisableClientState
+typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer);
+GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer;
+#define glEdgeFlagPointer glad_glEdgeFlagPointer
+typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array);
+GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState;
+#define glEnableClientState glad_glEnableClientState
+typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer;
+#define glIndexPointer glad_glIndexPointer
+typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer);
+GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays;
+#define glInterleavedArrays glad_glInterleavedArrays
+typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer;
+#define glNormalPointer glad_glNormalPointer
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer;
+#define glTexCoordPointer glad_glTexCoordPointer
+typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer;
+#define glVertexPointer glad_glVertexPointer
+typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences);
+GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident;
+#define glAreTexturesResident glad_glAreTexturesResident
+typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities);
+GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures;
+#define glPrioritizeTextures glad_glPrioritizeTextures
+typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c);
+GLAPI PFNGLINDEXUBPROC glad_glIndexub;
+#define glIndexub glad_glIndexub
+typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c);
+GLAPI PFNGLINDEXUBVPROC glad_glIndexubv;
+#define glIndexubv glad_glIndexubv
+typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(void);
+GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib;
+#define glPopClientAttrib glad_glPopClientAttrib
+typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask);
+GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib;
+#define glPushClientAttrib glad_glPushClientAttrib
+#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
+typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture);
+GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture;
+#define glClientActiveTexture glad_glClientActiveTexture
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s);
+GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d;
+#define glMultiTexCoord1d glad_glMultiTexCoord1d
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v);
+GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv;
+#define glMultiTexCoord1dv glad_glMultiTexCoord1dv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s);
+GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f;
+#define glMultiTexCoord1f glad_glMultiTexCoord1f
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v);
+GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv;
+#define glMultiTexCoord1fv glad_glMultiTexCoord1fv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s);
+GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i;
+#define glMultiTexCoord1i glad_glMultiTexCoord1i
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v);
+GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv;
+#define glMultiTexCoord1iv glad_glMultiTexCoord1iv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s);
+GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s;
+#define glMultiTexCoord1s glad_glMultiTexCoord1s
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v);
+GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv;
+#define glMultiTexCoord1sv glad_glMultiTexCoord1sv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t);
+GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d;
+#define glMultiTexCoord2d glad_glMultiTexCoord2d
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v);
+GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv;
+#define glMultiTexCoord2dv glad_glMultiTexCoord2dv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t);
+GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f;
+#define glMultiTexCoord2f glad_glMultiTexCoord2f
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v);
+GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv;
+#define glMultiTexCoord2fv glad_glMultiTexCoord2fv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t);
+GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i;
+#define glMultiTexCoord2i glad_glMultiTexCoord2i
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v);
+GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv;
+#define glMultiTexCoord2iv glad_glMultiTexCoord2iv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t);
+GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s;
+#define glMultiTexCoord2s glad_glMultiTexCoord2s
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v);
+GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv;
+#define glMultiTexCoord2sv glad_glMultiTexCoord2sv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r);
+GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d;
+#define glMultiTexCoord3d glad_glMultiTexCoord3d
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v);
+GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv;
+#define glMultiTexCoord3dv glad_glMultiTexCoord3dv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r);
+GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f;
+#define glMultiTexCoord3f glad_glMultiTexCoord3f
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v);
+GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv;
+#define glMultiTexCoord3fv glad_glMultiTexCoord3fv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r);
+GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i;
+#define glMultiTexCoord3i glad_glMultiTexCoord3i
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v);
+GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv;
+#define glMultiTexCoord3iv glad_glMultiTexCoord3iv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r);
+GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s;
+#define glMultiTexCoord3s glad_glMultiTexCoord3s
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v);
+GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv;
+#define glMultiTexCoord3sv glad_glMultiTexCoord3sv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d;
+#define glMultiTexCoord4d glad_glMultiTexCoord4d
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v);
+GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv;
+#define glMultiTexCoord4dv glad_glMultiTexCoord4dv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f;
+#define glMultiTexCoord4f glad_glMultiTexCoord4f
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v);
+GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv;
+#define glMultiTexCoord4fv glad_glMultiTexCoord4fv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q);
+GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i;
+#define glMultiTexCoord4i glad_glMultiTexCoord4i
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v);
+GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv;
+#define glMultiTexCoord4iv glad_glMultiTexCoord4iv
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s;
+#define glMultiTexCoord4s glad_glMultiTexCoord4s
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v);
+GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv;
+#define glMultiTexCoord4sv glad_glMultiTexCoord4sv
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m);
+GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf;
+#define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m);
+GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd;
+#define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m);
+GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf;
+#define glMultTransposeMatrixf glad_glMultTransposeMatrixf
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m);
+GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd;
+#define glMultTransposeMatrixd glad_glMultTransposeMatrixd
+#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 PFNGLFOGCOORDFPROC)(GLfloat coord);
+GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf;
+#define glFogCoordf glad_glFogCoordf
+typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord);
+GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv;
+#define glFogCoordfv glad_glFogCoordfv
+typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord);
+GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd;
+#define glFogCoordd glad_glFogCoordd
+typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord);
+GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv;
+#define glFogCoorddv glad_glFogCoorddv
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer;
+#define glFogCoordPointer glad_glFogCoordPointer
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue);
+GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b;
+#define glSecondaryColor3b glad_glSecondaryColor3b
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v);
+GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv;
+#define glSecondaryColor3bv glad_glSecondaryColor3bv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue);
+GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d;
+#define glSecondaryColor3d glad_glSecondaryColor3d
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v);
+GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv;
+#define glSecondaryColor3dv glad_glSecondaryColor3dv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue);
+GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f;
+#define glSecondaryColor3f glad_glSecondaryColor3f
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v);
+GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv;
+#define glSecondaryColor3fv glad_glSecondaryColor3fv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue);
+GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i;
+#define glSecondaryColor3i glad_glSecondaryColor3i
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v);
+GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv;
+#define glSecondaryColor3iv glad_glSecondaryColor3iv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue);
+GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s;
+#define glSecondaryColor3s glad_glSecondaryColor3s
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v);
+GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv;
+#define glSecondaryColor3sv glad_glSecondaryColor3sv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue);
+GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub;
+#define glSecondaryColor3ub glad_glSecondaryColor3ub
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v);
+GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv;
+#define glSecondaryColor3ubv glad_glSecondaryColor3ubv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue);
+GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui;
+#define glSecondaryColor3ui glad_glSecondaryColor3ui
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v);
+GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv;
+#define glSecondaryColor3uiv glad_glSecondaryColor3uiv
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue);
+GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us;
+#define glSecondaryColor3us glad_glSecondaryColor3us
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v);
+GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv;
+#define glSecondaryColor3usv glad_glSecondaryColor3usv
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer);
+GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer;
+#define glSecondaryColorPointer glad_glSecondaryColorPointer
+typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y);
+GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d;
+#define glWindowPos2d glad_glWindowPos2d
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v);
+GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv;
+#define glWindowPos2dv glad_glWindowPos2dv
+typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y);
+GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f;
+#define glWindowPos2f glad_glWindowPos2f
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v);
+GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv;
+#define glWindowPos2fv glad_glWindowPos2fv
+typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y);
+GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i;
+#define glWindowPos2i glad_glWindowPos2i
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v);
+GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv;
+#define glWindowPos2iv glad_glWindowPos2iv
+typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y);
+GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s;
+#define glWindowPos2s glad_glWindowPos2s
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v);
+GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv;
+#define glWindowPos2sv glad_glWindowPos2sv
+typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z);
+GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d;
+#define glWindowPos3d glad_glWindowPos3d
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v);
+GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv;
+#define glWindowPos3dv glad_glWindowPos3dv
+typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z);
+GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f;
+#define glWindowPos3f glad_glWindowPos3f
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v);
+GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv;
+#define glWindowPos3fv glad_glWindowPos3fv
+typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z);
+GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i;
+#define glWindowPos3i glad_glWindowPos3i
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v);
+GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv;
+#define glWindowPos3iv glad_glWindowPos3iv
+typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z);
+GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s;
+#define glWindowPos3s glad_glWindowPos3s
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v);
+GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv;
+#define glWindowPos3sv glad_glWindowPos3sv
+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)(void);
+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)(void);
+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)(void);
+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 count, 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)(void);
+GLAPI PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback;
+#define glPauseTransformFeedback glad_glPauseTransformFeedback
+typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC)(void);
+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)(void);
+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 count, 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 count, 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 count, 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)(void);
+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)(void);
+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)(void);
+GLAPI PFNGLTEXTUREBARRIERPROC glad_glTextureBarrier;
+#define glTextureBarrier glad_glTextureBarrier
+#endif
+#ifndef GL_VERSION_4_6
+#define GL_VERSION_4_6 1
+GLAPI int GLAD_GL_VERSION_4_6;
+typedef void (APIENTRYP PFNGLSPECIALIZESHADERPROC)(GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue);
+GLAPI PFNGLSPECIALIZESHADERPROC glad_glSpecializeShader;
+#define glSpecializeShader glad_glSpecializeShader
+typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC)(GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);
+GLAPI PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC glad_glMultiDrawArraysIndirectCount;
+#define glMultiDrawArraysIndirectCount glad_glMultiDrawArraysIndirectCount
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC)(GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);
+GLAPI PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC glad_glMultiDrawElementsIndirectCount;
+#define glMultiDrawElementsIndirectCount glad_glMultiDrawElementsIndirectCount
+typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPPROC)(GLfloat factor, GLfloat units, GLfloat clamp);
+GLAPI PFNGLPOLYGONOFFSETCLAMPPROC glad_glPolygonOffsetClamp;
+#define glPolygonOffsetClamp glad_glPolygonOffsetClamp
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/external/nuklear/nuklear.h b/external/nuklear/nuklear.h
new file mode 100644
index 0000000..362f282
--- /dev/null
+++ b/external/nuklear/nuklear.h
@@ -0,0 +1,30500 @@
+/*
+/// # Nuklear
+/// ![](https://cloud.githubusercontent.com/assets/8057201/11761525/ae06f0ca-a0c6-11e5-819d-5610b25f6ef4.gif)
+///
+/// ## Contents
+/// 1. About section
+/// 2. Highlights section
+/// 3. Features section
+/// 4. Usage section
+/// 1. Flags section
+/// 2. Constants section
+/// 3. Dependencies section
+/// 5. Example section
+/// 6. API section
+/// 1. Context section
+/// 2. Input section
+/// 3. Drawing section
+/// 4. Window section
+/// 5. Layouting section
+/// 6. Groups section
+/// 7. Tree section
+/// 8. Properties section
+/// 7. License section
+/// 8. Changelog section
+/// 9. Gallery section
+/// 10. Credits section
+///
+/// ## About
+/// This is a minimal state immediate mode graphical user interface toolkit
+/// written in ANSI C and licensed under public domain. It was designed as a simple
+/// embeddable user interface for application and does not have any dependencies,
+/// a default renderbackend or OS window and input handling but instead provides a very modular
+/// library approach by using simple input state for input and draw
+/// commands describing primitive shapes as output. So instead of providing a
+/// layered library that tries to abstract over a number of platform and
+/// render backends it only focuses on the actual UI.
+///
+/// ## Highlights
+/// - Graphical user interface toolkit
+/// - Single header library
+/// - Written in C89 (a.k.a. ANSI C or ISO C90)
+/// - Small codebase (~18kLOC)
+/// - Focus on portability, efficiency and simplicity
+/// - No dependencies (not even the standard library if not wanted)
+/// - Fully skinnable and customizable
+/// - Low memory footprint with total memory control if needed or wanted
+/// - UTF-8 support
+/// - No global or hidden state
+/// - Customizable library modules (you can compile and use only what you need)
+/// - Optional font baker and vertex buffer output
+/// - [Code available on github](https://github.com/Immediate-Mode-UI/Nuklear/)
+///
+/// ## Features
+/// - Absolutely no platform dependent code
+/// - Memory management control ranging from/to
+/// - Ease of use by allocating everything from standard library
+/// - Control every byte of memory inside the library
+/// - Font handling control ranging from/to
+/// - Use your own font implementation for everything
+/// - Use this libraries internal font baking and handling API
+/// - Drawing output control ranging from/to
+/// - Simple shapes for more high level APIs which already have drawing capabilities
+/// - Hardware accessible anti-aliased vertex buffer output
+/// - Customizable colors and properties ranging from/to
+/// - Simple changes to color by filling a simple color table
+/// - Complete control with ability to use skinning to decorate widgets
+/// - Bendable UI library with widget ranging from/to
+/// - Basic widgets like buttons, checkboxes, slider, ...
+/// - Advanced widget like abstract comboboxes, contextual menus,...
+/// - Compile time configuration to only compile what you need
+/// - Subset which can be used if you do not want to link or use the standard library
+/// - Can be easily modified to only update on user input instead of frame updates
+///
+/// ## Usage
+/// This library is self contained in one single header file and can be used either
+/// in header only mode or in implementation mode. The header only mode is used
+/// by default when included and allows including this header in other headers
+/// and does not contain the actual implementation.
+///
+/// The implementation mode requires to define the preprocessor macro
+/// NK_IMPLEMENTATION in *one* .c/.cpp file before #including this file, e.g.:
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~C
+/// #define NK_IMPLEMENTATION
+/// #include "nuklear.h"
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Also optionally define the symbols listed in the section "OPTIONAL DEFINES"
+/// below in header and implementation mode if you want to use additional functionality
+/// or need more control over the library.
+///
+/// !!! WARNING
+/// Every time nuklear is included define the same compiler flags. This very important not doing so could lead to compiler errors or even worse stack corruptions.
+///
+/// ### Flags
+/// Flag | Description
+/// --------------------------------|------------------------------------------
+/// NK_PRIVATE | If defined declares all functions as static, so they can only be accessed inside the file that contains the implementation
+/// NK_INCLUDE_FIXED_TYPES | If defined it will include header `` for fixed sized types otherwise nuklear tries to select the correct type. If that fails it will throw a compiler error and you have to select the correct types yourself.
+/// NK_INCLUDE_DEFAULT_ALLOCATOR | If defined it will include header `` and provide additional functions to use this library without caring for memory allocation control and therefore ease memory management.
+/// NK_INCLUDE_STANDARD_IO | If defined it will include header `` and provide additional functions depending on file loading.
+/// NK_INCLUDE_STANDARD_VARARGS | If defined it will include header and provide additional functions depending on file loading.
+/// NK_INCLUDE_STANDARD_BOOL | If defined it will include header `` for nk_bool otherwise nuklear defines nk_bool as int.
+/// NK_INCLUDE_VERTEX_BUFFER_OUTPUT | Defining this adds a vertex draw command list backend to this library, which allows you to convert queue commands into vertex draw commands. This is mainly if you need a hardware accessible format for OpenGL, DirectX, Vulkan, Metal,...
+/// NK_INCLUDE_FONT_BAKING | Defining this adds `stb_truetype` and `stb_rect_pack` implementation to this library and provides font baking and rendering. If you already have font handling or do not want to use this font handler you don't have to define it.
+/// NK_INCLUDE_DEFAULT_FONT | Defining this adds the default font: ProggyClean.ttf into this library which can be loaded into a font atlas and allows using this library without having a truetype font
+/// NK_INCLUDE_COMMAND_USERDATA | Defining this adds a userdata pointer into each command. Can be useful for example if you want to provide custom shaders depending on the used widget. Can be combined with the style structures.
+/// NK_BUTTON_TRIGGER_ON_RELEASE | Different platforms require button clicks occurring either on buttons being pressed (up to down) or released (down to up). By default this library will react on buttons being pressed, but if you define this it will only trigger if a button is released.
+/// NK_ZERO_COMMAND_MEMORY | Defining this will zero out memory for each drawing command added to a drawing queue (inside nk_command_buffer_push). Zeroing command memory is very useful for fast checking (using memcmp) if command buffers are equal and avoid drawing frames when nothing on screen has changed since previous frame.
+/// NK_UINT_DRAW_INDEX | Defining this will set the size of vertex index elements when using NK_VERTEX_BUFFER_OUTPUT to 32bit instead of the default of 16bit
+/// NK_KEYSTATE_BASED_INPUT | Define this if your backend uses key state for each frame rather than key press/release events
+///
+/// !!! WARNING
+/// The following flags will pull in the standard C library:
+/// - NK_INCLUDE_DEFAULT_ALLOCATOR
+/// - NK_INCLUDE_STANDARD_IO
+/// - NK_INCLUDE_STANDARD_VARARGS
+///
+/// !!! WARNING
+/// The following flags if defined need to be defined for both header and implementation:
+/// - NK_INCLUDE_FIXED_TYPES
+/// - NK_INCLUDE_DEFAULT_ALLOCATOR
+/// - NK_INCLUDE_STANDARD_VARARGS
+/// - NK_INCLUDE_STANDARD_BOOL
+/// - NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+/// - NK_INCLUDE_FONT_BAKING
+/// - NK_INCLUDE_DEFAULT_FONT
+/// - NK_INCLUDE_STANDARD_VARARGS
+/// - NK_INCLUDE_COMMAND_USERDATA
+/// - NK_UINT_DRAW_INDEX
+///
+/// ### Constants
+/// Define | Description
+/// --------------------------------|---------------------------------------
+/// NK_BUFFER_DEFAULT_INITIAL_SIZE | Initial buffer size allocated by all buffers while using the default allocator functions included by defining NK_INCLUDE_DEFAULT_ALLOCATOR. If you don't want to allocate the default 4k memory then redefine it.
+/// NK_MAX_NUMBER_BUFFER | Maximum buffer size for the conversion buffer between float and string Under normal circumstances this should be more than sufficient.
+/// NK_INPUT_MAX | Defines the max number of bytes which can be added as text input in one frame. Under normal circumstances this should be more than sufficient.
+///
+/// !!! WARNING
+/// The following constants if defined need to be defined for both header and implementation:
+/// - NK_MAX_NUMBER_BUFFER
+/// - NK_BUFFER_DEFAULT_INITIAL_SIZE
+/// - NK_INPUT_MAX
+///
+/// ### Dependencies
+/// Function | Description
+/// ------------|---------------------------------------------------------------
+/// NK_ASSERT | If you don't define this, nuklear will use with assert().
+/// NK_MEMSET | You can define this to 'memset' or your own memset implementation replacement. If not nuklear will use its own version.
+/// NK_MEMCPY | You can define this to 'memcpy' or your own memcpy implementation replacement. If not nuklear will use its own version.
+/// NK_INV_SQRT | You can define this to your own inverse sqrt implementation replacement. If not nuklear will use its own slow and not highly accurate version.
+/// NK_SIN | You can define this to 'sinf' or your own sine implementation replacement. If not nuklear will use its own approximation implementation.
+/// NK_COS | You can define this to 'cosf' or your own cosine implementation replacement. If not nuklear will use its own approximation implementation.
+/// NK_STRTOD | You can define this to `strtod` or your own string to double conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!).
+/// NK_DTOA | You can define this to `dtoa` or your own double to string conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!).
+/// NK_VSNPRINTF| If you define `NK_INCLUDE_STANDARD_VARARGS` as well as `NK_INCLUDE_STANDARD_IO` and want to be safe define this to `vsnprintf` on compilers supporting later versions of C or C++. By default nuklear will check for your stdlib version in C as well as compiler version in C++. if `vsnprintf` is available it will define it to `vsnprintf` directly. If not defined and if you have older versions of C or C++ it will be defined to `vsprintf` which is unsafe.
+///
+/// !!! WARNING
+/// The following dependencies will pull in the standard C library if not redefined:
+/// - NK_ASSERT
+///
+/// !!! WARNING
+/// The following dependencies if defined need to be defined for both header and implementation:
+/// - NK_ASSERT
+///
+/// !!! WARNING
+/// The following dependencies if defined need to be defined only for the implementation part:
+/// - NK_MEMSET
+/// - NK_MEMCPY
+/// - NK_SQRT
+/// - NK_SIN
+/// - NK_COS
+/// - NK_STRTOD
+/// - NK_DTOA
+/// - NK_VSNPRINTF
+///
+/// ## Example
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// // init gui state
+/// enum {EASY, HARD};
+/// static int op = EASY;
+/// static float value = 0.6f;
+/// static int i = 20;
+/// struct nk_context ctx;
+///
+/// nk_init_fixed(&ctx, calloc(1, MAX_MEMORY), MAX_MEMORY, &font);
+/// if (nk_begin(&ctx, "Show", nk_rect(50, 50, 220, 220),
+/// NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_CLOSABLE)) {
+/// // fixed widget pixel width
+/// nk_layout_row_static(&ctx, 30, 80, 1);
+/// if (nk_button_label(&ctx, "button")) {
+/// // event handling
+/// }
+///
+/// // fixed widget window ratio width
+/// nk_layout_row_dynamic(&ctx, 30, 2);
+/// if (nk_option_label(&ctx, "easy", op == EASY)) op = EASY;
+/// if (nk_option_label(&ctx, "hard", op == HARD)) op = HARD;
+///
+/// // custom widget pixel width
+/// nk_layout_row_begin(&ctx, NK_STATIC, 30, 2);
+/// {
+/// nk_layout_row_push(&ctx, 50);
+/// nk_label(&ctx, "Volume:", NK_TEXT_LEFT);
+/// nk_layout_row_push(&ctx, 110);
+/// nk_slider_float(&ctx, 0, &value, 1.0f, 0.1f);
+/// }
+/// nk_layout_row_end(&ctx);
+/// }
+/// nk_end(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// ![](https://cloud.githubusercontent.com/assets/8057201/10187981/584ecd68-675c-11e5-897c-822ef534a876.png)
+///
+/// ## API
+///
+*/
+#ifndef NK_SINGLE_FILE
+ #define NK_SINGLE_FILE
+#endif
+
+#ifndef NK_NUKLEAR_H_
+#define NK_NUKLEAR_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * ==============================================================
+ *
+ * CONSTANTS
+ *
+ * ===============================================================
+ */
+#define NK_UNDEFINED (-1.0f)
+#define NK_UTF_INVALID 0xFFFD /* internal invalid utf8 rune */
+#define NK_UTF_SIZE 4 /* describes the number of bytes a glyph consists of*/
+#ifndef NK_INPUT_MAX
+ #define NK_INPUT_MAX 16
+#endif
+#ifndef NK_MAX_NUMBER_BUFFER
+ #define NK_MAX_NUMBER_BUFFER 64
+#endif
+#ifndef NK_SCROLLBAR_HIDING_TIMEOUT
+ #define NK_SCROLLBAR_HIDING_TIMEOUT 4.0f
+#endif
+/*
+ * ==============================================================
+ *
+ * HELPER
+ *
+ * ===============================================================
+ */
+#ifndef NK_API
+ #ifdef NK_PRIVATE
+ #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199409L))
+ #define NK_API static inline
+ #elif defined(__cplusplus)
+ #define NK_API static inline
+ #else
+ #define NK_API static
+ #endif
+ #else
+ #define NK_API extern
+ #endif
+#endif
+#ifndef NK_LIB
+ #ifdef NK_SINGLE_FILE
+ #define NK_LIB static
+ #else
+ #define NK_LIB extern
+ #endif
+#endif
+
+#define NK_INTERN static
+#define NK_STORAGE static
+#define NK_GLOBAL static
+
+#define NK_FLAG(x) (1 << (x))
+#define NK_STRINGIFY(x) #x
+#define NK_MACRO_STRINGIFY(x) NK_STRINGIFY(x)
+#define NK_STRING_JOIN_IMMEDIATE(arg1, arg2) arg1 ## arg2
+#define NK_STRING_JOIN_DELAY(arg1, arg2) NK_STRING_JOIN_IMMEDIATE(arg1, arg2)
+#define NK_STRING_JOIN(arg1, arg2) NK_STRING_JOIN_DELAY(arg1, arg2)
+
+#ifdef _MSC_VER
+ #define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__COUNTER__)
+#else
+ #define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__LINE__)
+#endif
+
+#ifndef NK_STATIC_ASSERT
+ #define NK_STATIC_ASSERT(exp) typedef char NK_UNIQUE_NAME(_dummy_array)[(exp)?1:-1]
+#endif
+
+#ifndef NK_FILE_LINE
+#ifdef _MSC_VER
+ #define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__COUNTER__)
+#else
+ #define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__LINE__)
+#endif
+#endif
+
+#define NK_MIN(a,b) ((a) < (b) ? (a) : (b))
+#define NK_MAX(a,b) ((a) < (b) ? (b) : (a))
+#define NK_CLAMP(i,v,x) (NK_MAX(NK_MIN(v,x), i))
+
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+ #include
+ #if defined(_MSC_VER) && (_MSC_VER >= 1600) /* VS 2010 and above */
+ #include
+ #define NK_PRINTF_FORMAT_STRING _Printf_format_string_
+ #else
+ #define NK_PRINTF_FORMAT_STRING
+ #endif
+ #if defined(__GNUC__)
+ #define NK_PRINTF_VARARG_FUNC(fmtargnumber) __attribute__((format(__printf__, fmtargnumber, fmtargnumber+1)))
+ #define NK_PRINTF_VALIST_FUNC(fmtargnumber) __attribute__((format(__printf__, fmtargnumber, 0)))
+ #else
+ #define NK_PRINTF_VARARG_FUNC(fmtargnumber)
+ #define NK_PRINTF_VALIST_FUNC(fmtargnumber)
+ #endif
+#endif
+
+/*
+ * ===============================================================
+ *
+ * BASIC
+ *
+ * ===============================================================
+ */
+#ifdef NK_INCLUDE_FIXED_TYPES
+ #include
+ #define NK_INT8 int8_t
+ #define NK_UINT8 uint8_t
+ #define NK_INT16 int16_t
+ #define NK_UINT16 uint16_t
+ #define NK_INT32 int32_t
+ #define NK_UINT32 uint32_t
+ #define NK_SIZE_TYPE uintptr_t
+ #define NK_POINTER_TYPE uintptr_t
+#else
+ #ifndef NK_INT8
+ #define NK_INT8 signed char
+ #endif
+ #ifndef NK_UINT8
+ #define NK_UINT8 unsigned char
+ #endif
+ #ifndef NK_INT16
+ #define NK_INT16 signed short
+ #endif
+ #ifndef NK_UINT16
+ #define NK_UINT16 unsigned short
+ #endif
+ #ifndef NK_INT32
+ #if defined(_MSC_VER)
+ #define NK_INT32 __int32
+ #else
+ #define NK_INT32 signed int
+ #endif
+ #endif
+ #ifndef NK_UINT32
+ #if defined(_MSC_VER)
+ #define NK_UINT32 unsigned __int32
+ #else
+ #define NK_UINT32 unsigned int
+ #endif
+ #endif
+ #ifndef NK_SIZE_TYPE
+ #if defined(_WIN64) && defined(_MSC_VER)
+ #define NK_SIZE_TYPE unsigned __int64
+ #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
+ #define NK_SIZE_TYPE unsigned __int32
+ #elif defined(__GNUC__) || defined(__clang__)
+ #if defined(__x86_64__) || defined(__ppc64__) || defined(__PPC64__) || defined(__aarch64__)
+ #define NK_SIZE_TYPE unsigned long
+ #else
+ #define NK_SIZE_TYPE unsigned int
+ #endif
+ #else
+ #define NK_SIZE_TYPE unsigned long
+ #endif
+ #endif
+ #ifndef NK_POINTER_TYPE
+ #if defined(_WIN64) && defined(_MSC_VER)
+ #define NK_POINTER_TYPE unsigned __int64
+ #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
+ #define NK_POINTER_TYPE unsigned __int32
+ #elif defined(__GNUC__) || defined(__clang__)
+ #if defined(__x86_64__) || defined(__ppc64__) || defined(__PPC64__) || defined(__aarch64__)
+ #define NK_POINTER_TYPE unsigned long
+ #else
+ #define NK_POINTER_TYPE unsigned int
+ #endif
+ #else
+ #define NK_POINTER_TYPE unsigned long
+ #endif
+ #endif
+#endif
+
+#ifndef NK_BOOL
+ #ifdef NK_INCLUDE_STANDARD_BOOL
+ #include
+ #define NK_BOOL nv_bool
+ #else
+ #define NK_BOOL int /* could be char, use int for drop-in replacement backwards compatibility */
+ #endif
+#endif
+
+typedef NK_INT8 nk_char;
+typedef NK_UINT8 nk_uchar;
+typedef NK_UINT8 nk_byte;
+typedef NK_INT16 nk_short;
+typedef NK_UINT16 nk_ushort;
+typedef NK_INT32 nk_int;
+typedef NK_UINT32 nk_uint;
+typedef NK_SIZE_TYPE nk_size;
+typedef NK_POINTER_TYPE nk_ptr;
+typedef NK_BOOL nk_bool;
+
+typedef nk_uint nk_hash;
+typedef nk_uint nk_flags;
+typedef nk_uint nk_rune;
+
+/* Make sure correct type size:
+ * This will fire with a negative subscript error if the type sizes
+ * are set incorrectly by the compiler, and compile out if not */
+NK_STATIC_ASSERT(sizeof(nk_short) == 2);
+NK_STATIC_ASSERT(sizeof(nk_ushort) == 2);
+NK_STATIC_ASSERT(sizeof(nk_uint) == 4);
+NK_STATIC_ASSERT(sizeof(nk_int) == 4);
+NK_STATIC_ASSERT(sizeof(nk_byte) == 1);
+NK_STATIC_ASSERT(sizeof(nk_flags) >= 4);
+NK_STATIC_ASSERT(sizeof(nk_rune) >= 4);
+NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*));
+NK_STATIC_ASSERT(sizeof(nk_ptr) >= sizeof(void*));
+#ifdef NK_INCLUDE_STANDARD_BOOL
+NK_STATIC_ASSERT(sizeof(nk_bool) == sizeof(nv_bool));
+#else
+NK_STATIC_ASSERT(sizeof(nk_bool) >= 2);
+#endif
+
+/* ============================================================================
+ *
+ * API
+ *
+ * =========================================================================== */
+struct nk_buffer;
+struct nk_allocator;
+struct nk_command_buffer;
+struct nk_draw_command;
+struct nk_convert_config;
+struct nk_style_item;
+struct nk_text_edit;
+struct nk_draw_list;
+struct nk_user_font;
+struct nk_panel;
+struct nk_context;
+struct nk_draw_vertex_layout_element;
+struct nk_style_button;
+struct nk_style_toggle;
+struct nk_style_selectable;
+struct nk_style_slide;
+struct nk_style_progress;
+struct nk_style_scrollbar;
+struct nk_style_edit;
+struct nk_style_property;
+struct nk_style_chart;
+struct nk_style_combo;
+struct nk_style_tab;
+struct nk_style_window_header;
+struct nk_style_window;
+
+enum {nk_false, nk_true};
+struct nk_color {nk_byte r,g,b,a;};
+struct nk_colorf {float r,g,b,a;};
+struct nk_vec2 {float x,y;};
+struct nk_vec2i {short x, y;};
+struct nk_rect {float x,y,w,h;};
+struct nk_recti {short x,y,w,h;};
+typedef char nk_glyph[NK_UTF_SIZE];
+typedef union {void *ptr; int id;} nk_handle;
+struct nk_image {nk_handle handle; nk_ushort w, h; nk_ushort region[4];};
+struct nk_nine_slice {struct nk_image img; nk_ushort l, t, r, b;};
+struct nk_cursor {struct nk_image img; struct nk_vec2 size, offset;};
+struct nk_scroll {nk_uint x, y;};
+
+enum nk_heading {NK_UP, NK_RIGHT, NK_DOWN, NK_LEFT};
+enum nk_button_behavior {NK_BUTTON_DEFAULT, NK_BUTTON_REPEATER};
+enum nk_modify {NK_FIXED = nk_false, NK_MODIFIABLE = nk_true};
+enum nk_orientation {NK_VERTICAL, NK_HORIZONTAL};
+enum nk_collapse_states {NK_MINIMIZED = nk_false, NK_MAXIMIZED = nk_true};
+enum nk_show_states {NK_HIDDEN = nk_false, NK_SHOWN = nk_true};
+enum nk_chart_type {NK_CHART_LINES, NK_CHART_COLUMN, NK_CHART_MAX};
+enum nk_chart_event {NK_CHART_HOVERING = 0x01, NK_CHART_CLICKED = 0x02};
+enum nk_color_format {NK_RGB, NK_RGBA};
+enum nk_popup_type {NK_POPUP_STATIC, NK_POPUP_DYNAMIC};
+enum nk_layout_format {NK_DYNAMIC, NK_STATIC};
+enum nk_tree_type {NK_TREE_NODE, NK_TREE_TAB};
+
+typedef void*(*nk_plugin_alloc)(nk_handle, void *old, nk_size);
+typedef void (*nk_plugin_free)(nk_handle, void *old);
+typedef nk_bool(*nk_plugin_filter)(const struct nk_text_edit*, nk_rune unicode);
+typedef void(*nk_plugin_paste)(nk_handle, struct nk_text_edit*);
+typedef void(*nk_plugin_copy)(nk_handle, const char*, int len);
+
+struct nk_allocator {
+ nk_handle userdata;
+ nk_plugin_alloc alloc;
+ nk_plugin_free free;
+};
+enum nk_symbol_type {
+ NK_SYMBOL_NONE,
+ NK_SYMBOL_X,
+ NK_SYMBOL_UNDERSCORE,
+ NK_SYMBOL_CIRCLE_SOLID,
+ NK_SYMBOL_CIRCLE_OUTLINE,
+ NK_SYMBOL_RECT_SOLID,
+ NK_SYMBOL_RECT_OUTLINE,
+ NK_SYMBOL_TRIANGLE_UP,
+ NK_SYMBOL_TRIANGLE_DOWN,
+ NK_SYMBOL_TRIANGLE_LEFT,
+ NK_SYMBOL_TRIANGLE_RIGHT,
+ NK_SYMBOL_PLUS,
+ NK_SYMBOL_MINUS,
+ NK_SYMBOL_MAX
+};
+/* =============================================================================
+ *
+ * CONTEXT
+ *
+ * =============================================================================*/
+/*/// ### Context
+/// Contexts are the main entry point and the majestro of nuklear and contain all required state.
+/// They are used for window, memory, input, style, stack, commands and time management and need
+/// to be passed into all nuklear GUI specific functions.
+///
+/// #### Usage
+/// To use a context it first has to be initialized which can be achieved by calling
+/// one of either `nk_init_default`, `nk_init_fixed`, `nk_init`, `nk_init_custom`.
+/// Each takes in a font handle and a specific way of handling memory. Memory control
+/// hereby ranges from standard library to just specifying a fixed sized block of memory
+/// which nuklear has to manage itself from.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// // [...]
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// --------------------|-------------------------------------------------------
+/// __nk_init_default__ | Initializes context with standard library memory allocation (malloc,free)
+/// __nk_init_fixed__ | Initializes context from single fixed size memory block
+/// __nk_init__ | Initializes context with memory allocator callbacks for alloc and free
+/// __nk_init_custom__ | Initializes context from two buffers. One for draw commands the other for window/panel/table allocations
+/// __nk_clear__ | Called at the end of the frame to reset and prepare the context for the next frame
+/// __nk_free__ | Shutdown and free all memory allocated inside the context
+/// __nk_set_user_data__| Utility function to pass user data to draw command
+ */
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+/*/// #### nk_init_default
+/// Initializes a `nk_context` struct with a default standard library allocator.
+/// Should be used if you don't want to be bothered with memory management in nuklear.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_init_default(struct nk_context *ctx, const struct nk_user_font *font);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|---------------------------------------------------------------
+/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
+/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
+///
+/// Returns either `false(0)` on failure or `true(1)` on success.
+///
+*/
+NK_API nk_bool nk_init_default(struct nk_context*, const struct nk_user_font*);
+#endif
+/*/// #### nk_init_fixed
+/// Initializes a `nk_context` struct from single fixed size memory block
+/// Should be used if you want complete control over nuklear's memory management.
+/// Especially recommended for system with little memory or systems with virtual memory.
+/// For the later case you can just allocate for example 16MB of virtual memory
+/// and only the required amount of memory will actually be committed.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, const struct nk_user_font *font);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// !!! Warning
+/// make sure the passed memory block is aligned correctly for `nk_draw_commands`.
+///
+/// Parameter | Description
+/// ------------|--------------------------------------------------------------
+/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
+/// __memory__ | Must point to a previously allocated memory block
+/// __size__ | Must contain the total size of __memory__
+/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
+///
+/// Returns either `false(0)` on failure or `true(1)` on success.
+*/
+NK_API nk_bool nk_init_fixed(struct nk_context*, void *memory, nk_size size, const struct nk_user_font*);
+/*/// #### nk_init
+/// Initializes a `nk_context` struct with memory allocation callbacks for nuklear to allocate
+/// memory from. Used internally for `nk_init_default` and provides a kitchen sink allocation
+/// interface to nuklear. Can be useful for cases like monitoring memory consumption.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_init(struct nk_context *ctx, struct nk_allocator *alloc, const struct nk_user_font *font);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|---------------------------------------------------------------
+/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
+/// __alloc__ | Must point to a previously allocated memory allocator
+/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
+///
+/// Returns either `false(0)` on failure or `true(1)` on success.
+*/
+NK_API nk_bool nk_init(struct nk_context*, struct nk_allocator*, const struct nk_user_font*);
+/*/// #### nk_init_custom
+/// Initializes a `nk_context` struct from two different either fixed or growing
+/// buffers. The first buffer is for allocating draw commands while the second buffer is
+/// used for allocating windows, panels and state tables.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font *font);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|---------------------------------------------------------------
+/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
+/// __cmds__ | Must point to a previously initialized memory buffer either fixed or dynamic to store draw commands into
+/// __pool__ | Must point to a previously initialized memory buffer either fixed or dynamic to store windows, panels and tables
+/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
+///
+/// Returns either `false(0)` on failure or `true(1)` on success.
+*/
+NK_API nk_bool nk_init_custom(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font*);
+/*/// #### nk_clear
+/// Resets the context state at the end of the frame. This includes mostly
+/// garbage collector tasks like removing windows or table not called and therefore
+/// used anymore.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_clear(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+*/
+NK_API void nk_clear(struct nk_context*);
+/*/// #### nk_free
+/// Frees all memory allocated by nuklear. Not needed if context was
+/// initialized with `nk_init_fixed`.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_free(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+*/
+NK_API void nk_free(struct nk_context*);
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+/*/// #### nk_set_user_data
+/// Sets the currently passed userdata passed down into each draw command.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_set_user_data(struct nk_context *ctx, nk_handle data);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|--------------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __data__ | Handle with either pointer or index to be passed into every draw commands
+*/
+NK_API void nk_set_user_data(struct nk_context*, nk_handle handle);
+#endif
+/* =============================================================================
+ *
+ * INPUT
+ *
+ * =============================================================================*/
+/*/// ### Input
+/// The input API is responsible for holding the current input state composed of
+/// mouse, key and text input states.
+/// It is worth noting that no direct OS or window handling is done in nuklear.
+/// Instead all input state has to be provided by platform specific code. This on one hand
+/// expects more work from the user and complicates usage but on the other hand
+/// provides simple abstraction over a big number of platforms, libraries and other
+/// already provided functionality.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_input_begin(&ctx);
+/// while (GetEvent(&evt)) {
+/// if (evt.type == MOUSE_MOVE)
+/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
+/// else if (evt.type == [...]) {
+/// // [...]
+/// }
+/// } nk_input_end(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Usage
+/// Input state needs to be provided to nuklear by first calling `nk_input_begin`
+/// which resets internal state like delta mouse position and button transitions.
+/// After `nk_input_begin` all current input state needs to be provided. This includes
+/// mouse motion, button and key pressed and released, text input and scrolling.
+/// Both event- or state-based input handling are supported by this API
+/// and should work without problems. Finally after all input state has been
+/// mirrored `nk_input_end` needs to be called to finish input process.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// Event evt;
+/// nk_input_begin(&ctx);
+/// while (GetEvent(&evt)) {
+/// if (evt.type == MOUSE_MOVE)
+/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
+/// else if (evt.type == [...]) {
+/// // [...]
+/// }
+/// }
+/// nk_input_end(&ctx);
+/// // [...]
+/// nk_clear(&ctx);
+/// } nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// --------------------|-------------------------------------------------------
+/// __nk_input_begin__ | Begins the input mirroring process. Needs to be called before all other `nk_input_xxx` calls
+/// __nk_input_motion__ | Mirrors mouse cursor position
+/// __nk_input_key__ | Mirrors key state with either pressed or released
+/// __nk_input_button__ | Mirrors mouse button state with either pressed or released
+/// __nk_input_scroll__ | Mirrors mouse scroll values
+/// __nk_input_char__ | Adds a single ASCII text character into an internal text buffer
+/// __nk_input_glyph__ | Adds a single multi-byte UTF-8 character into an internal text buffer
+/// __nk_input_unicode__| Adds a single unicode rune into an internal text buffer
+/// __nk_input_end__ | Ends the input mirroring process by calculating state changes. Don't call any `nk_input_xxx` function referenced above after this call
+*/
+enum nk_keys {
+ NK_KEY_NONE,
+ NK_KEY_SHIFT,
+ NK_KEY_CTRL,
+ NK_KEY_DEL,
+ NK_KEY_ENTER,
+ NK_KEY_TAB,
+ NK_KEY_BACKSPACE,
+ NK_KEY_COPY,
+ NK_KEY_CUT,
+ NK_KEY_PASTE,
+ NK_KEY_UP,
+ NK_KEY_DOWN,
+ NK_KEY_LEFT,
+ NK_KEY_RIGHT,
+ /* Shortcuts: text field */
+ NK_KEY_TEXT_INSERT_MODE,
+ NK_KEY_TEXT_REPLACE_MODE,
+ NK_KEY_TEXT_RESET_MODE,
+ NK_KEY_TEXT_LINE_START,
+ NK_KEY_TEXT_LINE_END,
+ NK_KEY_TEXT_START,
+ NK_KEY_TEXT_END,
+ NK_KEY_TEXT_UNDO,
+ NK_KEY_TEXT_REDO,
+ NK_KEY_TEXT_SELECT_ALL,
+ NK_KEY_TEXT_WORD_LEFT,
+ NK_KEY_TEXT_WORD_RIGHT,
+ /* Shortcuts: scrollbar */
+ NK_KEY_SCROLL_START,
+ NK_KEY_SCROLL_END,
+ NK_KEY_SCROLL_DOWN,
+ NK_KEY_SCROLL_UP,
+ NK_KEY_MAX
+};
+enum nk_buttons {
+ NK_BUTTON_LEFT,
+ NK_BUTTON_MIDDLE,
+ NK_BUTTON_RIGHT,
+ NK_BUTTON_DOUBLE,
+ NK_BUTTON_MAX
+};
+/*/// #### nk_input_begin
+/// Begins the input mirroring process by resetting text, scroll
+/// mouse, previous mouse position and movement as well as key state transitions,
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_begin(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+*/
+NK_API void nk_input_begin(struct nk_context*);
+/*/// #### nk_input_motion
+/// Mirrors current mouse position to nuklear
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_motion(struct nk_context *ctx, int x, int y);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __x__ | Must hold an integer describing the current mouse cursor x-position
+/// __y__ | Must hold an integer describing the current mouse cursor y-position
+*/
+NK_API void nk_input_motion(struct nk_context*, int x, int y);
+/*/// #### nk_input_key
+/// Mirrors the state of a specific key to nuklear
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_key(struct nk_context*, enum nk_keys key, nk_bool down);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __key__ | Must be any value specified in enum `nk_keys` that needs to be mirrored
+/// __down__ | Must be 0 for key is up and 1 for key is down
+*/
+NK_API void nk_input_key(struct nk_context*, enum nk_keys, nk_bool down);
+/*/// #### nk_input_button
+/// Mirrors the state of a specific mouse button to nuklear
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_button(struct nk_context *ctx, enum nk_buttons btn, int x, int y, nk_bool down);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __btn__ | Must be any value specified in enum `nk_buttons` that needs to be mirrored
+/// __x__ | Must contain an integer describing mouse cursor x-position on click up/down
+/// __y__ | Must contain an integer describing mouse cursor y-position on click up/down
+/// __down__ | Must be 0 for key is up and 1 for key is down
+*/
+NK_API void nk_input_button(struct nk_context*, enum nk_buttons, int x, int y, nk_bool down);
+/*/// #### nk_input_scroll
+/// Copies the last mouse scroll value to nuklear. Is generally
+/// a scroll value. So does not have to come from mouse and could also originate
+/// TODO finish this sentence
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_scroll(struct nk_context *ctx, struct nk_vec2 val);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __val__ | vector with both X- as well as Y-scroll value
+*/
+NK_API void nk_input_scroll(struct nk_context*, struct nk_vec2 val);
+/*/// #### nk_input_char
+/// Copies a single ASCII character into an internal text buffer
+/// This is basically a helper function to quickly push ASCII characters into
+/// nuklear.
+///
+/// !!! Note
+/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_char(struct nk_context *ctx, char c);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __c__ | Must be a single ASCII character preferable one that can be printed
+*/
+NK_API void nk_input_char(struct nk_context*, char);
+/*/// #### nk_input_glyph
+/// Converts an encoded unicode rune into UTF-8 and copies the result into an
+/// internal text buffer.
+///
+/// !!! Note
+/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_glyph(struct nk_context *ctx, const nk_glyph g);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __g__ | UTF-32 unicode codepoint
+*/
+NK_API void nk_input_glyph(struct nk_context*, const nk_glyph);
+/*/// #### nk_input_unicode
+/// Converts a unicode rune into UTF-8 and copies the result
+/// into an internal text buffer.
+/// !!! Note
+/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_unicode(struct nk_context*, nk_rune rune);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+/// __rune__ | UTF-32 unicode codepoint
+*/
+NK_API void nk_input_unicode(struct nk_context*, nk_rune);
+/*/// #### nk_input_end
+/// End the input mirroring process by resetting mouse grabbing
+/// state to ensure the mouse cursor is not grabbed indefinitely.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_input_end(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to a previously initialized `nk_context` struct
+*/
+NK_API void nk_input_end(struct nk_context*);
+/* =============================================================================
+ *
+ * DRAWING
+ *
+ * =============================================================================*/
+/*/// ### Drawing
+/// This library was designed to be render backend agnostic so it does
+/// not draw anything to screen directly. Instead all drawn shapes, widgets
+/// are made of, are buffered into memory and make up a command queue.
+/// Each frame therefore fills the command buffer with draw commands
+/// that then need to be executed by the user and his own render backend.
+/// After that the command buffer needs to be cleared and a new frame can be
+/// started. It is probably important to note that the command buffer is the main
+/// drawing API and the optional vertex buffer API only takes this format and
+/// converts it into a hardware accessible format.
+///
+/// #### Usage
+/// To draw all draw commands accumulated over a frame you need your own render
+/// backend able to draw a number of 2D primitives. This includes at least
+/// filled and stroked rectangles, circles, text, lines, triangles and scissors.
+/// As soon as this criterion is met you can iterate over each draw command
+/// and execute each draw command in a interpreter like fashion:
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// switch (cmd->type) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case //...:
+/// //[...]
+/// }
+/// }
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// In program flow context draw commands need to be executed after input has been
+/// gathered and the complete UI with windows and their contained widgets have
+/// been executed and before calling `nk_clear` which frees all previously
+/// allocated draw commands.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// Event evt;
+/// nk_input_begin(&ctx);
+/// while (GetEvent(&evt)) {
+/// if (evt.type == MOUSE_MOVE)
+/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
+/// else if (evt.type == [...]) {
+/// [...]
+/// }
+/// }
+/// nk_input_end(&ctx);
+/// //
+/// // [...]
+/// //
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// switch (cmd->type) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case ...:
+/// // [...]
+/// }
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// You probably noticed that you have to draw all of the UI each frame which is
+/// quite wasteful. While the actual UI updating loop is quite fast rendering
+/// without actually needing it is not. So there are multiple things you could do.
+///
+/// First is only update on input. This of course is only an option if your
+/// application only depends on the UI and does not require any outside calculations.
+/// If you actually only update on input make sure to update the UI two times each
+/// frame and call `nk_clear` directly after the first pass and only draw in
+/// the second pass. In addition it is recommended to also add additional timers
+/// to make sure the UI is not drawn more than a fixed number of frames per second.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// // [...wait for input ]
+/// // [...do two UI passes ...]
+/// do_ui(...)
+/// nk_clear(&ctx);
+/// do_ui(...)
+/// //
+/// // draw
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// switch (cmd->type) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case ...:
+/// //[...]
+/// }
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// The second probably more applicable trick is to only draw if anything changed.
+/// It is not really useful for applications with continuous draw loop but
+/// quite useful for desktop applications. To actually get nuklear to only
+/// draw on changes you first have to define `NK_ZERO_COMMAND_MEMORY` and
+/// allocate a memory buffer that will store each unique drawing output.
+/// After each frame you compare the draw command memory inside the library
+/// with your allocated buffer by memcmp. If memcmp detects differences
+/// you have to copy the command buffer into the allocated buffer
+/// and then draw like usual (this example uses fixed memory but you could
+/// use dynamically allocated memory).
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// //[... other defines ...]
+/// #define NK_ZERO_COMMAND_MEMORY
+/// #include "nuklear.h"
+/// //
+/// // setup context
+/// struct nk_context ctx;
+/// void *last = calloc(1,64*1024);
+/// void *buf = calloc(1,64*1024);
+/// nk_init_fixed(&ctx, buf, 64*1024);
+/// //
+/// // loop
+/// while (1) {
+/// // [...input...]
+/// // [...ui...]
+/// void *cmds = nk_buffer_memory(&ctx.memory);
+/// if (memcmp(cmds, last, ctx.memory.allocated)) {
+/// memcpy(last,cmds,ctx.memory.allocated);
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// switch (cmd->type) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case ...:
+/// // [...]
+/// }
+/// }
+/// }
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Finally while using draw commands makes sense for higher abstracted platforms like
+/// X11 and Win32 or drawing libraries it is often desirable to use graphics
+/// hardware directly. Therefore it is possible to just define
+/// `NK_INCLUDE_VERTEX_BUFFER_OUTPUT` which includes optional vertex output.
+/// To access the vertex output you first have to convert all draw commands into
+/// vertexes by calling `nk_convert` which takes in your preferred vertex format.
+/// After successfully converting all draw commands just iterate over and execute all
+/// vertex draw commands:
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// // fill configuration
+/// struct your_vertex
+/// {
+/// float pos[2]; // important to keep it to 2 floats
+/// float uv[2];
+/// unsigned char col[4];
+/// };
+/// struct nk_convert_config cfg = {};
+/// static const struct nk_draw_vertex_layout_element vertex_layout[] = {
+/// {NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct your_vertex, pos)},
+/// {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct your_vertex, uv)},
+/// {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, NK_OFFSETOF(struct your_vertex, col)},
+/// {NK_VERTEX_LAYOUT_END}
+/// };
+/// cfg.shape_AA = NK_ANTI_ALIASING_ON;
+/// cfg.line_AA = NK_ANTI_ALIASING_ON;
+/// cfg.vertex_layout = vertex_layout;
+/// cfg.vertex_size = sizeof(struct your_vertex);
+/// cfg.vertex_alignment = NK_ALIGNOF(struct your_vertex);
+/// cfg.circle_segment_count = 22;
+/// cfg.curve_segment_count = 22;
+/// cfg.arc_segment_count = 22;
+/// cfg.global_alpha = 1.0f;
+/// cfg.tex_null = dev->tex_null;
+/// //
+/// // setup buffers and convert
+/// struct nk_buffer cmds, verts, idx;
+/// nk_buffer_init_default(&cmds);
+/// nk_buffer_init_default(&verts);
+/// nk_buffer_init_default(&idx);
+/// nk_convert(&ctx, &cmds, &verts, &idx, &cfg);
+/// //
+/// // draw
+/// nk_draw_foreach(cmd, &ctx, &cmds) {
+/// if (!cmd->elem_count) continue;
+/// //[...]
+/// }
+/// nk_buffer_free(&cms);
+/// nk_buffer_free(&verts);
+/// nk_buffer_free(&idx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// --------------------|-------------------------------------------------------
+/// __nk__begin__ | Returns the first draw command in the context draw command list to be drawn
+/// __nk__next__ | Increments the draw command iterator to the next command inside the context draw command list
+/// __nk_foreach__ | Iterates over each draw command inside the context draw command list
+/// __nk_convert__ | Converts from the abstract draw commands list into a hardware accessible vertex format
+/// __nk_draw_begin__ | Returns the first vertex command in the context vertex draw list to be executed
+/// __nk__draw_next__ | Increments the vertex command iterator to the next command inside the context vertex command list
+/// __nk__draw_end__ | Returns the end of the vertex draw list
+/// __nk_draw_foreach__ | Iterates over each vertex draw command inside the vertex draw list
+*/
+enum nk_anti_aliasing {NK_ANTI_ALIASING_OFF, NK_ANTI_ALIASING_ON};
+enum nk_convert_result {
+ NK_CONVERT_SUCCESS = 0,
+ NK_CONVERT_INVALID_PARAM = 1,
+ NK_CONVERT_COMMAND_BUFFER_FULL = NK_FLAG(1),
+ NK_CONVERT_VERTEX_BUFFER_FULL = NK_FLAG(2),
+ NK_CONVERT_ELEMENT_BUFFER_FULL = NK_FLAG(3)
+};
+struct nk_draw_null_texture {
+ nk_handle texture; /* texture handle to a texture with a white pixel */
+ struct nk_vec2 uv; /* coordinates to a white pixel in the texture */
+};
+struct nk_convert_config {
+ float global_alpha; /* global alpha value */
+ enum nk_anti_aliasing line_AA; /* line anti-aliasing flag can be turned off if you are tight on memory */
+ enum nk_anti_aliasing shape_AA; /* shape anti-aliasing flag can be turned off if you are tight on memory */
+ unsigned circle_segment_count; /* number of segments used for circles: default to 22 */
+ unsigned arc_segment_count; /* number of segments used for arcs: default to 22 */
+ unsigned curve_segment_count; /* number of segments used for curves: default to 22 */
+ struct nk_draw_null_texture tex_null; /* handle to texture with a white pixel for shape drawing */
+ const struct nk_draw_vertex_layout_element *vertex_layout; /* describes the vertex output format and packing */
+ nk_size vertex_size; /* sizeof one vertex for vertex packing */
+ nk_size vertex_alignment; /* vertex alignment: Can be obtained by NK_ALIGNOF */
+};
+/*/// #### nk__begin
+/// Returns a draw command list iterator to iterate all draw
+/// commands accumulated over one frame.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// const struct nk_command* nk__begin(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | must point to an previously initialized `nk_context` struct at the end of a frame
+///
+/// Returns draw command pointer pointing to the first command inside the draw command list
+*/
+NK_API const struct nk_command* nk__begin(struct nk_context*);
+/*/// #### nk__next
+/// Returns draw command pointer pointing to the next command inside the draw command list
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// const struct nk_command* nk__next(struct nk_context*, const struct nk_command*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+/// __cmd__ | Must point to an previously a draw command either returned by `nk__begin` or `nk__next`
+///
+/// Returns draw command pointer pointing to the next command inside the draw command list
+*/
+NK_API const struct nk_command* nk__next(struct nk_context*, const struct nk_command*);
+/*/// #### nk_foreach
+/// Iterates over each draw command inside the context draw command list
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// #define nk_foreach(c, ctx)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+/// __cmd__ | Command pointer initialized to NULL
+///
+/// Iterates over each draw command inside the context draw command list
+*/
+#define nk_foreach(c, ctx) for((c) = nk__begin(ctx); (c) != 0; (c) = nk__next(ctx,c))
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+/*/// #### nk_convert
+/// Converts all internal draw commands into vertex draw commands and fills
+/// three buffers with vertexes, vertex draw commands and vertex indices. The vertex format
+/// as well as some other configuration values have to be configured by filling out a
+/// `nk_convert_config` struct.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_flags nk_convert(struct nk_context *ctx, struct nk_buffer *cmds,
+/// struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+/// __cmds__ | Must point to a previously initialized buffer to hold converted vertex draw commands
+/// __vertices__| Must point to a previously initialized buffer to hold all produced vertices
+/// __elements__| Must point to a previously initialized buffer to hold all produced vertex indices
+/// __config__ | Must point to a filled out `nk_config` struct to configure the conversion process
+///
+/// Returns one of enum nk_convert_result error codes
+///
+/// Parameter | Description
+/// --------------------------------|-----------------------------------------------------------
+/// NK_CONVERT_SUCCESS | Signals a successful draw command to vertex buffer conversion
+/// NK_CONVERT_INVALID_PARAM | An invalid argument was passed in the function call
+/// NK_CONVERT_COMMAND_BUFFER_FULL | The provided buffer for storing draw commands is full or failed to allocate more memory
+/// NK_CONVERT_VERTEX_BUFFER_FULL | The provided buffer for storing vertices is full or failed to allocate more memory
+/// NK_CONVERT_ELEMENT_BUFFER_FULL | The provided buffer for storing indices is full or failed to allocate more memory
+*/
+NK_API nk_flags nk_convert(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*);
+/*/// #### nk__draw_begin
+/// Returns a draw vertex command buffer iterator to iterate over the vertex draw command buffer
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
+///
+/// Returns vertex draw command pointer pointing to the first command inside the vertex draw command buffer
+*/
+NK_API const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*);
+/*/// #### nk__draw_end
+/// Returns the vertex draw command at the end of the vertex draw command buffer
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// const struct nk_draw_command* nk__draw_end(const struct nk_context *ctx, const struct nk_buffer *buf);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
+///
+/// Returns vertex draw command pointer pointing to the end of the last vertex draw command inside the vertex draw command buffer
+*/
+NK_API const struct nk_draw_command* nk__draw_end(const struct nk_context*, const struct nk_buffer*);
+/*/// #### nk__draw_next
+/// Increments the vertex draw command buffer iterator
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __cmd__ | Must point to an previously either by `nk__draw_begin` or `nk__draw_next` returned vertex draw command
+/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+///
+/// Returns vertex draw command pointer pointing to the end of the last vertex draw command inside the vertex draw command buffer
+*/
+NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*);
+/*/// #### nk_draw_foreach
+/// Iterates over each vertex draw command inside a vertex draw command buffer
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// #define nk_draw_foreach(cmd,ctx, b)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __cmd__ | `nk_draw_command`iterator set to NULL
+/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
+/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
+*/
+#define nk_draw_foreach(cmd,ctx, b) for((cmd)=nk__draw_begin(ctx, b); (cmd)!=0; (cmd)=nk__draw_next(cmd, b, ctx))
+#endif
+/* =============================================================================
+ *
+ * WINDOW
+ *
+ * =============================================================================
+/// ### Window
+/// Windows are the main persistent state used inside nuklear and are life time
+/// controlled by simply "retouching" (i.e. calling) each window each frame.
+/// All widgets inside nuklear can only be added inside the function pair `nk_begin_xxx`
+/// and `nk_end`. Calling any widgets outside these two functions will result in an
+/// assert in debug or no state change in release mode.
+///
+/// Each window holds frame persistent state like position, size, flags, state tables,
+/// and some garbage collected internal persistent widget state. Each window
+/// is linked into a window stack list which determines the drawing and overlapping
+/// order. The topmost window thereby is the currently active window.
+///
+/// To change window position inside the stack occurs either automatically by
+/// user input by being clicked on or programmatically by calling `nk_window_focus`.
+/// Windows by default are visible unless explicitly being defined with flag
+/// `NK_WINDOW_HIDDEN`, the user clicked the close button on windows with flag
+/// `NK_WINDOW_CLOSABLE` or if a window was explicitly hidden by calling
+/// `nk_window_show`. To explicitly close and destroy a window call `nk_window_close`.
+///
+/// #### Usage
+/// To create and keep a window you have to call one of the two `nk_begin_xxx`
+/// functions to start window declarations and `nk_end` at the end. Furthermore it
+/// is recommended to check the return value of `nk_begin_xxx` and only process
+/// widgets inside the window if the value is not 0. Either way you have to call
+/// `nk_end` at the end of window declarations. Furthermore, do not attempt to
+/// nest `nk_begin_xxx` calls which will hopefully result in an assert or if not
+/// in a segmentation fault.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // [... widgets ...]
+/// }
+/// nk_end(ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// In the grand concept window and widget declarations need to occur after input
+/// handling and before drawing to screen. Not doing so can result in higher
+/// latency or at worst invalid behavior. Furthermore make sure that `nk_clear`
+/// is called at the end of the frame. While nuklear's default platform backends
+/// already call `nk_clear` for you if you write your own backend not calling
+/// `nk_clear` can cause asserts or even worse undefined behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// Event evt;
+/// nk_input_begin(&ctx);
+/// while (GetEvent(&evt)) {
+/// if (evt.type == MOUSE_MOVE)
+/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
+/// else if (evt.type == [...]) {
+/// nk_input_xxx(...);
+/// }
+/// }
+/// nk_input_end(&ctx);
+///
+/// if (nk_begin_xxx(...) {
+/// //[...]
+/// }
+/// nk_end(ctx);
+///
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case //...:
+/// //[...]
+/// }
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// ------------------------------------|----------------------------------------
+/// nk_begin | Starts a new window; needs to be called every frame for every window (unless hidden) or otherwise the window gets removed
+/// nk_begin_titled | Extended window start with separated title and identifier to allow multiple windows with same name but not title
+/// nk_end | Needs to be called at the end of the window building process to process scaling, scrollbars and general cleanup
+//
+/// nk_window_find | Finds and returns the window with give name
+/// nk_window_get_bounds | Returns a rectangle with screen position and size of the currently processed window.
+/// nk_window_get_position | Returns the position of the currently processed window
+/// nk_window_get_size | Returns the size with width and height of the currently processed window
+/// nk_window_get_width | Returns the width of the currently processed window
+/// nk_window_get_height | Returns the height of the currently processed window
+/// nk_window_get_panel | Returns the underlying panel which contains all processing state of the current window
+/// nk_window_get_content_region | Returns the position and size of the currently visible and non-clipped space inside the currently processed window
+/// nk_window_get_content_region_min | Returns the upper rectangle position of the currently visible and non-clipped space inside the currently processed window
+/// nk_window_get_content_region_max | Returns the upper rectangle position of the currently visible and non-clipped space inside the currently processed window
+/// nk_window_get_content_region_size | Returns the size of the currently visible and non-clipped space inside the currently processed window
+/// nk_window_get_canvas | Returns the draw command buffer. Can be used to draw custom widgets
+/// nk_window_get_scroll | Gets the scroll offset of the current window
+/// nk_window_has_focus | Returns if the currently processed window is currently active
+/// nk_window_is_collapsed | Returns if the window with given name is currently minimized/collapsed
+/// nk_window_is_closed | Returns if the currently processed window was closed
+/// nk_window_is_hidden | Returns if the currently processed window was hidden
+/// nk_window_is_active | Same as nk_window_has_focus for some reason
+/// nk_window_is_hovered | Returns if the currently processed window is currently being hovered by mouse
+/// nk_window_is_any_hovered | Return if any window currently hovered
+/// nk_item_is_any_active | Returns if any window or widgets is currently hovered or active
+//
+/// nk_window_set_bounds | Updates position and size of the currently processed window
+/// nk_window_set_position | Updates position of the currently process window
+/// nk_window_set_size | Updates the size of the currently processed window
+/// nk_window_set_focus | Set the currently processed window as active window
+/// nk_window_set_scroll | Sets the scroll offset of the current window
+//
+/// nk_window_close | Closes the window with given window name which deletes the window at the end of the frame
+/// nk_window_collapse | Collapses the window with given window name
+/// nk_window_collapse_if | Collapses the window with given window name if the given condition was met
+/// nk_window_show | Hides a visible or reshows a hidden window
+/// nk_window_show_if | Hides/shows a window depending on condition
+*/
+/*
+/// #### nk_panel_flags
+/// Flag | Description
+/// ----------------------------|----------------------------------------
+/// NK_WINDOW_BORDER | Draws a border around the window to visually separate window from the background
+/// NK_WINDOW_MOVABLE | The movable flag indicates that a window can be moved by user input or by dragging the window header
+/// NK_WINDOW_SCALABLE | The scalable flag indicates that a window can be scaled by user input by dragging a scaler icon at the button of the window
+/// NK_WINDOW_CLOSABLE | Adds a closable icon into the header
+/// NK_WINDOW_MINIMIZABLE | Adds a minimize icon into the header
+/// NK_WINDOW_NO_SCROLLBAR | Removes the scrollbar from the window
+/// NK_WINDOW_TITLE | Forces a header at the top at the window showing the title
+/// NK_WINDOW_SCROLL_AUTO_HIDE | Automatically hides the window scrollbar if no user interaction: also requires delta time in `nk_context` to be set each frame
+/// NK_WINDOW_BACKGROUND | Always keep window in the background
+/// NK_WINDOW_SCALE_LEFT | Puts window scaler in the left-bottom corner instead right-bottom
+/// NK_WINDOW_NO_INPUT | Prevents window of scaling, moving or getting focus
+///
+/// #### nk_collapse_states
+/// State | Description
+/// ----------------|-----------------------------------------------------------
+/// __NK_MINIMIZED__| UI section is collapsed and not visible until maximized
+/// __NK_MAXIMIZED__| UI section is extended and visible until minimized
+///
+*/
+enum nk_panel_flags {
+ NK_WINDOW_BORDER = NK_FLAG(0),
+ NK_WINDOW_MOVABLE = NK_FLAG(1),
+ NK_WINDOW_SCALABLE = NK_FLAG(2),
+ NK_WINDOW_CLOSABLE = NK_FLAG(3),
+ NK_WINDOW_MINIMIZABLE = NK_FLAG(4),
+ NK_WINDOW_NO_SCROLLBAR = NK_FLAG(5),
+ NK_WINDOW_TITLE = NK_FLAG(6),
+ NK_WINDOW_SCROLL_AUTO_HIDE = NK_FLAG(7),
+ NK_WINDOW_BACKGROUND = NK_FLAG(8),
+ NK_WINDOW_SCALE_LEFT = NK_FLAG(9),
+ NK_WINDOW_NO_INPUT = NK_FLAG(10)
+};
+/*/// #### nk_begin
+/// Starts a new window; needs to be called every frame for every
+/// window (unless hidden) or otherwise the window gets removed
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __title__ | Window title and identifier. Needs to be persistent over frames to identify the window
+/// __bounds__ | Initial position and window size. However if you do not define `NK_WINDOW_SCALABLE` or `NK_WINDOW_MOVABLE` you can set window position and size every frame
+/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different window behaviors
+///
+/// Returns `true(1)` if the window can be filled up with widgets from this point
+/// until `nk_end` or `false(0)` otherwise for example if minimized
+*/
+NK_API nk_bool nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags);
+/*/// #### nk_begin_titled
+/// Extended window start with separated title and identifier to allow multiple
+/// windows with same title but not name
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Window identifier. Needs to be persistent over frames to identify the window
+/// __title__ | Window title displayed inside header if flag `NK_WINDOW_TITLE` or either `NK_WINDOW_CLOSABLE` or `NK_WINDOW_MINIMIZED` was set
+/// __bounds__ | Initial position and window size. However if you do not define `NK_WINDOW_SCALABLE` or `NK_WINDOW_MOVABLE` you can set window position and size every frame
+/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different window behaviors
+///
+/// Returns `true(1)` if the window can be filled up with widgets from this point
+/// until `nk_end` or `false(0)` otherwise for example if minimized
+*/
+NK_API nk_bool nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags);
+/*/// #### nk_end
+/// Needs to be called at the end of the window building process to process scaling, scrollbars and general cleanup.
+/// All widget calls after this functions will result in asserts or no state changes
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_end(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+*/
+NK_API void nk_end(struct nk_context *ctx);
+/*/// #### nk_window_find
+/// Finds and returns a window from passed name
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_window *nk_window_find(struct nk_context *ctx, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Window identifier
+///
+/// Returns a `nk_window` struct pointing to the identified window or NULL if
+/// no window with the given name was found
+*/
+NK_API struct nk_window *nk_window_find(struct nk_context *ctx, const char *name);
+/*/// #### nk_window_get_bounds
+/// Returns a rectangle with screen position and size of the currently processed window
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_rect nk_window_get_bounds(const struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns a `nk_rect` struct with window upper left window position and size
+*/
+NK_API struct nk_rect nk_window_get_bounds(const struct nk_context *ctx);
+/*/// #### nk_window_get_position
+/// Returns the position of the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_window_get_position(const struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns a `nk_vec2` struct with window upper left position
+*/
+NK_API struct nk_vec2 nk_window_get_position(const struct nk_context *ctx);
+/*/// #### nk_window_get_size
+/// Returns the size with width and height of the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_window_get_size(const struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns a `nk_vec2` struct with window width and height
+*/
+NK_API struct nk_vec2 nk_window_get_size(const struct nk_context*);
+/*/// #### nk_window_get_width
+/// Returns the width of the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// float nk_window_get_width(const struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns the current window width
+*/
+NK_API float nk_window_get_width(const struct nk_context*);
+/*/// #### nk_window_get_height
+/// Returns the height of the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// float nk_window_get_height(const struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns the current window height
+*/
+NK_API float nk_window_get_height(const struct nk_context*);
+/*/// #### nk_window_get_panel
+/// Returns the underlying panel which contains all processing state of the current window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// !!! WARNING
+/// Do not keep the returned panel pointer around, it is only valid until `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_panel* nk_window_get_panel(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns a pointer to window internal `nk_panel` state.
+*/
+NK_API struct nk_panel* nk_window_get_panel(struct nk_context*);
+/*/// #### nk_window_get_content_region
+/// Returns the position and size of the currently visible and non-clipped space
+/// inside the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_rect nk_window_get_content_region(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `nk_rect` struct with screen position and size (no scrollbar offset)
+/// of the visible space inside the current window
+*/
+NK_API struct nk_rect nk_window_get_content_region(struct nk_context*);
+/*/// #### nk_window_get_content_region_min
+/// Returns the upper left position of the currently visible and non-clipped
+/// space inside the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_window_get_content_region_min(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// returns `nk_vec2` struct with upper left screen position (no scrollbar offset)
+/// of the visible space inside the current window
+*/
+NK_API struct nk_vec2 nk_window_get_content_region_min(struct nk_context*);
+/*/// #### nk_window_get_content_region_max
+/// Returns the lower right screen position of the currently visible and
+/// non-clipped space inside the currently processed window.
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_window_get_content_region_max(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `nk_vec2` struct with lower right screen position (no scrollbar offset)
+/// of the visible space inside the current window
+*/
+NK_API struct nk_vec2 nk_window_get_content_region_max(struct nk_context*);
+/*/// #### nk_window_get_content_region_size
+/// Returns the size of the currently visible and non-clipped space inside the
+/// currently processed window
+///
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_window_get_content_region_size(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `nk_vec2` struct with size the visible space inside the current window
+*/
+NK_API struct nk_vec2 nk_window_get_content_region_size(struct nk_context*);
+/*/// #### nk_window_get_canvas
+/// Returns the draw command buffer. Can be used to draw custom widgets
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// !!! WARNING
+/// Do not keep the returned command buffer pointer around it is only valid until `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_command_buffer* nk_window_get_canvas(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns a pointer to window internal `nk_command_buffer` struct used as
+/// drawing canvas. Can be used to do custom drawing.
+*/
+NK_API struct nk_command_buffer* nk_window_get_canvas(struct nk_context*);
+/*/// #### nk_window_get_scroll
+/// Gets the scroll offset for the current window
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_get_scroll(struct nk_context *ctx, nk_uint *offset_x, nk_uint *offset_y);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// -------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __offset_x__ | A pointer to the x offset output (or NULL to ignore)
+/// __offset_y__ | A pointer to the y offset output (or NULL to ignore)
+*/
+NK_API void nk_window_get_scroll(struct nk_context*, nk_uint *offset_x, nk_uint *offset_y);
+/*/// #### nk_window_has_focus
+/// Returns if the currently processed window is currently active
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_has_focus(const struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `false(0)` if current window is not active or `true(1)` if it is
+*/
+NK_API nk_bool nk_window_has_focus(const struct nk_context*);
+/*/// #### nk_window_is_hovered
+/// Return if the current window is being hovered
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_is_hovered(struct nk_context *ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `true(1)` if current window is hovered or `false(0)` otherwise
+*/
+NK_API nk_bool nk_window_is_hovered(struct nk_context*);
+/*/// #### nk_window_is_collapsed
+/// Returns if the window with given name is currently minimized/collapsed
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_is_collapsed(struct nk_context *ctx, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of window you want to check if it is collapsed
+///
+/// Returns `true(1)` if current window is minimized and `false(0)` if window not
+/// found or is not minimized
+*/
+NK_API nk_bool nk_window_is_collapsed(struct nk_context *ctx, const char *name);
+/*/// #### nk_window_is_closed
+/// Returns if the window with given name was closed by calling `nk_close`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_is_closed(struct nk_context *ctx, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of window you want to check if it is closed
+///
+/// Returns `true(1)` if current window was closed or `false(0)` window not found or not closed
+*/
+NK_API nk_bool nk_window_is_closed(struct nk_context*, const char*);
+/*/// #### nk_window_is_hidden
+/// Returns if the window with given name is hidden
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_is_hidden(struct nk_context *ctx, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of window you want to check if it is hidden
+///
+/// Returns `true(1)` if current window is hidden or `false(0)` window not found or visible
+*/
+NK_API nk_bool nk_window_is_hidden(struct nk_context*, const char*);
+/*/// #### nk_window_is_active
+/// Same as nk_window_has_focus for some reason
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_is_active(struct nk_context *ctx, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of window you want to check if it is active
+///
+/// Returns `true(1)` if current window is active or `false(0)` window not found or not active
+*/
+NK_API nk_bool nk_window_is_active(struct nk_context*, const char*);
+/*/// #### nk_window_is_any_hovered
+/// Returns if the any window is being hovered
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_window_is_any_hovered(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `true(1)` if any window is hovered or `false(0)` otherwise
+*/
+NK_API nk_bool nk_window_is_any_hovered(struct nk_context*);
+/*/// #### nk_item_is_any_active
+/// Returns if the any window is being hovered or any widget is currently active.
+/// Can be used to decide if input should be processed by UI or your specific input handling.
+/// Example could be UI and 3D camera to move inside a 3D space.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_item_is_any_active(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+///
+/// Returns `true(1)` if any window is hovered or any item is active or `false(0)` otherwise
+*/
+NK_API nk_bool nk_item_is_any_active(struct nk_context*);
+/*/// #### nk_window_set_bounds
+/// Updates position and size of window with passed in name
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_set_bounds(struct nk_context*, const char *name, struct nk_rect bounds);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to modify both position and size
+/// __bounds__ | Must point to a `nk_rect` struct with the new position and size
+*/
+NK_API void nk_window_set_bounds(struct nk_context*, const char *name, struct nk_rect bounds);
+/*/// #### nk_window_set_position
+/// Updates position of window with passed name
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_set_position(struct nk_context*, const char *name, struct nk_vec2 pos);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to modify both position
+/// __pos__ | Must point to a `nk_vec2` struct with the new position
+*/
+NK_API void nk_window_set_position(struct nk_context*, const char *name, struct nk_vec2 pos);
+/*/// #### nk_window_set_size
+/// Updates size of window with passed in name
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_set_size(struct nk_context*, const char *name, struct nk_vec2);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to modify both window size
+/// __size__ | Must point to a `nk_vec2` struct with new window size
+*/
+NK_API void nk_window_set_size(struct nk_context*, const char *name, struct nk_vec2);
+/*/// #### nk_window_set_focus
+/// Sets the window with given name as active
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_set_focus(struct nk_context*, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to set focus on
+*/
+NK_API void nk_window_set_focus(struct nk_context*, const char *name);
+/*/// #### nk_window_set_scroll
+/// Sets the scroll offset for the current window
+/// !!! WARNING
+/// Only call this function between calls `nk_begin_xxx` and `nk_end`
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_set_scroll(struct nk_context *ctx, nk_uint offset_x, nk_uint offset_y);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// -------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __offset_x__ | The x offset to scroll to
+/// __offset_y__ | The y offset to scroll to
+*/
+NK_API void nk_window_set_scroll(struct nk_context*, nk_uint offset_x, nk_uint offset_y);
+/*/// #### nk_window_close
+/// Closes a window and marks it for being freed at the end of the frame
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_close(struct nk_context *ctx, const char *name);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to close
+*/
+NK_API void nk_window_close(struct nk_context *ctx, const char *name);
+/*/// #### nk_window_collapse
+/// Updates collapse state of a window with given name
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states state);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to close
+/// __state__ | value out of nk_collapse_states section
+*/
+NK_API void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states state);
+/*/// #### nk_window_collapse_if
+/// Updates collapse state of a window with given name if given condition is met
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to either collapse or maximize
+/// __state__ | value out of nk_collapse_states section the window should be put into
+/// __cond__ | condition that has to be met to actually commit the collapse state change
+*/
+NK_API void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond);
+/*/// #### nk_window_show
+/// updates visibility state of a window with given name
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_show(struct nk_context*, const char *name, enum nk_show_states);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to either collapse or maximize
+/// __state__ | state with either visible or hidden to modify the window with
+*/
+NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_states);
+/*/// #### nk_window_show_if
+/// Updates visibility state of a window with given name if a given condition is met
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __name__ | Identifier of the window to either hide or show
+/// __state__ | state with either visible or hidden to modify the window with
+/// __cond__ | condition that has to be met to actually commit the visibility state change
+*/
+NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond);
+/*/// #### nk_window_show_if
+/// Line for visual separation. Draws a line with thickness determined by the current row height.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ----------------|-------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __color__ | Color of the horizontal line
+/// __rounding__ | Whether or not to make the line round
+*/
+NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk_bool rounding);
+/* =============================================================================
+ *
+ * LAYOUT
+ *
+ * =============================================================================
+/// ### Layouting
+/// Layouting in general describes placing widget inside a window with position and size.
+/// While in this particular implementation there are five different APIs for layouting
+/// each with different trade offs between control and ease of use.
+///
+/// All layouting methods in this library are based around the concept of a row.
+/// A row has a height the window content grows by and a number of columns and each
+/// layouting method specifies how each widget is placed inside the row.
+/// After a row has been allocated by calling a layouting functions and then
+/// filled with widgets will advance an internal pointer over the allocated row.
+///
+/// To actually define a layout you just call the appropriate layouting function
+/// and each subsequent widget call will place the widget as specified. Important
+/// here is that if you define more widgets then columns defined inside the layout
+/// functions it will allocate the next row without you having to make another layouting
+/// call.
+///
+/// Biggest limitation with using all these APIs outside the `nk_layout_space_xxx` API
+/// is that you have to define the row height for each. However the row height
+/// often depends on the height of the font.
+///
+/// To fix that internally nuklear uses a minimum row height that is set to the
+/// height plus padding of currently active font and overwrites the row height
+/// value if zero.
+///
+/// If you manually want to change the minimum row height then
+/// use nk_layout_set_min_row_height, and use nk_layout_reset_min_row_height to
+/// reset it back to be derived from font height.
+///
+/// Also if you change the font in nuklear it will automatically change the minimum
+/// row height for you and. This means if you change the font but still want
+/// a minimum row height smaller than the font you have to repush your value.
+///
+/// For actually more advanced UI I would even recommend using the `nk_layout_space_xxx`
+/// layouting method in combination with a cassowary constraint solver (there are
+/// some versions on github with permissive license model) to take over all control over widget
+/// layouting yourself. However for quick and dirty layouting using all the other layouting
+/// functions should be fine.
+///
+/// #### Usage
+/// 1. __nk_layout_row_dynamic__
+/// The easiest layouting function is `nk_layout_row_dynamic`. It provides each
+/// widgets with same horizontal space inside the row and dynamically grows
+/// if the owning window grows in width. So the number of columns dictates
+/// the size of each widget dynamically by formula:
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// widget_width = (window_width - padding - spacing) * (1/column_count)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Just like all other layouting APIs if you define more widget than columns this
+/// library will allocate a new row and keep all layouting parameters previously
+/// defined.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // first row with height: 30 composed of two widgets
+/// nk_layout_row_dynamic(&ctx, 30, 2);
+/// nk_widget(...);
+/// nk_widget(...);
+/// //
+/// // second row with same parameter as defined above
+/// nk_widget(...);
+/// nk_widget(...);
+/// //
+/// // third row uses 0 for height which will use auto layouting
+/// nk_layout_row_dynamic(&ctx, 0, 2);
+/// nk_widget(...);
+/// nk_widget(...);
+/// }
+/// nk_end(...);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// 2. __nk_layout_row_static__
+/// Another easy layouting function is `nk_layout_row_static`. It provides each
+/// widget with same horizontal pixel width inside the row and does not grow
+/// if the owning window scales smaller or bigger.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // first row with height: 30 composed of two widgets with width: 80
+/// nk_layout_row_static(&ctx, 30, 80, 2);
+/// nk_widget(...);
+/// nk_widget(...);
+/// //
+/// // second row with same parameter as defined above
+/// nk_widget(...);
+/// nk_widget(...);
+/// //
+/// // third row uses 0 for height which will use auto layouting
+/// nk_layout_row_static(&ctx, 0, 80, 2);
+/// nk_widget(...);
+/// nk_widget(...);
+/// }
+/// nk_end(...);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// 3. __nk_layout_row_xxx__
+/// A little bit more advanced layouting API are functions `nk_layout_row_begin`,
+/// `nk_layout_row_push` and `nk_layout_row_end`. They allow to directly
+/// specify each column pixel or window ratio in a row. It supports either
+/// directly setting per column pixel width or widget window ratio but not
+/// both. Furthermore it is a immediate mode API so each value is directly
+/// pushed before calling a widget. Therefore the layout is not automatically
+/// repeating like the last two layouting functions.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // first row with height: 25 composed of two widgets with width 60 and 40
+/// nk_layout_row_begin(ctx, NK_STATIC, 25, 2);
+/// nk_layout_row_push(ctx, 60);
+/// nk_widget(...);
+/// nk_layout_row_push(ctx, 40);
+/// nk_widget(...);
+/// nk_layout_row_end(ctx);
+/// //
+/// // second row with height: 25 composed of two widgets with window ratio 0.25 and 0.75
+/// nk_layout_row_begin(ctx, NK_DYNAMIC, 25, 2);
+/// nk_layout_row_push(ctx, 0.25f);
+/// nk_widget(...);
+/// nk_layout_row_push(ctx, 0.75f);
+/// nk_widget(...);
+/// nk_layout_row_end(ctx);
+/// //
+/// // third row with auto generated height: composed of two widgets with window ratio 0.25 and 0.75
+/// nk_layout_row_begin(ctx, NK_DYNAMIC, 0, 2);
+/// nk_layout_row_push(ctx, 0.25f);
+/// nk_widget(...);
+/// nk_layout_row_push(ctx, 0.75f);
+/// nk_widget(...);
+/// nk_layout_row_end(ctx);
+/// }
+/// nk_end(...);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// 4. __nk_layout_row__
+/// The array counterpart to API nk_layout_row_xxx is the single nk_layout_row
+/// functions. Instead of pushing either pixel or window ratio for every widget
+/// it allows to define it by array. The trade of for less control is that
+/// `nk_layout_row` is automatically repeating. Otherwise the behavior is the
+/// same.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // two rows with height: 30 composed of two widgets with width 60 and 40
+/// const float ratio[] = {60,40};
+/// nk_layout_row(ctx, NK_STATIC, 30, 2, ratio);
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// //
+/// // two rows with height: 30 composed of two widgets with window ratio 0.25 and 0.75
+/// const float ratio[] = {0.25, 0.75};
+/// nk_layout_row(ctx, NK_DYNAMIC, 30, 2, ratio);
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// //
+/// // two rows with auto generated height composed of two widgets with window ratio 0.25 and 0.75
+/// const float ratio[] = {0.25, 0.75};
+/// nk_layout_row(ctx, NK_DYNAMIC, 30, 2, ratio);
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// }
+/// nk_end(...);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// 5. __nk_layout_row_template_xxx__
+/// The most complex and second most flexible API is a simplified flexbox version without
+/// line wrapping and weights for dynamic widgets. It is an immediate mode API but
+/// unlike `nk_layout_row_xxx` it has auto repeat behavior and needs to be called
+/// before calling the templated widgets.
+/// The row template layout has three different per widget size specifier. The first
+/// one is the `nk_layout_row_template_push_static` with fixed widget pixel width.
+/// They do not grow if the row grows and will always stay the same.
+/// The second size specifier is `nk_layout_row_template_push_variable`
+/// which defines a minimum widget size but it also can grow if more space is available
+/// not taken by other widgets.
+/// Finally there are dynamic widgets with `nk_layout_row_template_push_dynamic`
+/// which are completely flexible and unlike variable widgets can even shrink
+/// to zero if not enough space is provided.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // two rows with height: 30 composed of three widgets
+/// nk_layout_row_template_begin(ctx, 30);
+/// nk_layout_row_template_push_dynamic(ctx);
+/// nk_layout_row_template_push_variable(ctx, 80);
+/// nk_layout_row_template_push_static(ctx, 80);
+/// nk_layout_row_template_end(ctx);
+/// //
+/// // first row
+/// nk_widget(...); // dynamic widget can go to zero if not enough space
+/// nk_widget(...); // variable widget with min 80 pixel but can grow bigger if enough space
+/// nk_widget(...); // static widget with fixed 80 pixel width
+/// //
+/// // second row same layout
+/// nk_widget(...);
+/// nk_widget(...);
+/// nk_widget(...);
+/// }
+/// nk_end(...);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// 6. __nk_layout_space_xxx__
+/// Finally the most flexible API directly allows you to place widgets inside the
+/// window. The space layout API is an immediate mode API which does not support
+/// row auto repeat and directly sets position and size of a widget. Position
+/// and size hereby can be either specified as ratio of allocated space or
+/// allocated space local position and pixel size. Since this API is quite
+/// powerful there are a number of utility functions to get the available space
+/// and convert between local allocated space and screen space.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_begin_xxx(...) {
+/// // static row with height: 500 (you can set column count to INT_MAX if you don't want to be bothered)
+/// nk_layout_space_begin(ctx, NK_STATIC, 500, INT_MAX);
+/// nk_layout_space_push(ctx, nk_rect(0,0,150,200));
+/// nk_widget(...);
+/// nk_layout_space_push(ctx, nk_rect(200,200,100,200));
+/// nk_widget(...);
+/// nk_layout_space_end(ctx);
+/// //
+/// // dynamic row with height: 500 (you can set column count to INT_MAX if you don't want to be bothered)
+/// nk_layout_space_begin(ctx, NK_DYNAMIC, 500, INT_MAX);
+/// nk_layout_space_push(ctx, nk_rect(0.5,0.5,0.1,0.1));
+/// nk_widget(...);
+/// nk_layout_space_push(ctx, nk_rect(0.7,0.6,0.1,0.1));
+/// nk_widget(...);
+/// }
+/// nk_end(...);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// ----------------------------------------|------------------------------------
+/// nk_layout_set_min_row_height | Set the currently used minimum row height to a specified value
+/// nk_layout_reset_min_row_height | Resets the currently used minimum row height to font height
+/// nk_layout_widget_bounds | Calculates current width a static layout row can fit inside a window
+/// nk_layout_ratio_from_pixel | Utility functions to calculate window ratio from pixel size
+//
+/// nk_layout_row_dynamic | Current layout is divided into n same sized growing columns
+/// nk_layout_row_static | Current layout is divided into n same fixed sized columns
+/// nk_layout_row_begin | Starts a new row with given height and number of columns
+/// nk_layout_row_push | Pushes another column with given size or window ratio
+/// nk_layout_row_end | Finished previously started row
+/// nk_layout_row | Specifies row columns in array as either window ratio or size
+//
+/// nk_layout_row_template_begin | Begins the row template declaration
+/// nk_layout_row_template_push_dynamic | Adds a dynamic column that dynamically grows and can go to zero if not enough space
+/// nk_layout_row_template_push_variable | Adds a variable column that dynamically grows but does not shrink below specified pixel width
+/// nk_layout_row_template_push_static | Adds a static column that does not grow and will always have the same size
+/// nk_layout_row_template_end | Marks the end of the row template
+//
+/// nk_layout_space_begin | Begins a new layouting space that allows to specify each widgets position and size
+/// nk_layout_space_push | Pushes position and size of the next widget in own coordinate space either as pixel or ratio
+/// nk_layout_space_end | Marks the end of the layouting space
+//
+/// nk_layout_space_bounds | Callable after nk_layout_space_begin and returns total space allocated
+/// nk_layout_space_to_screen | Converts vector from nk_layout_space coordinate space into screen space
+/// nk_layout_space_to_local | Converts vector from screen space into nk_layout_space coordinates
+/// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space
+/// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates
+*/
+
+enum nk_widget_align {
+ NK_WIDGET_ALIGN_LEFT = 0x01,
+ NK_WIDGET_ALIGN_CENTERED = 0x02,
+ NK_WIDGET_ALIGN_RIGHT = 0x04,
+ NK_WIDGET_ALIGN_TOP = 0x08,
+ NK_WIDGET_ALIGN_MIDDLE = 0x10,
+ NK_WIDGET_ALIGN_BOTTOM = 0x20
+};
+enum nk_widget_alignment {
+ NK_WIDGET_LEFT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_LEFT,
+ NK_WIDGET_CENTERED = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_CENTERED,
+ NK_WIDGET_RIGHT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_RIGHT
+};
+
+/*/// #### nk_layout_set_min_row_height
+/// Sets the currently used minimum row height.
+/// !!! WARNING
+/// The passed height needs to include both your preferred row height
+/// as well as padding. No internal padding is added.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_set_min_row_height(struct nk_context*, float height);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __height__ | New minimum row height to be used for auto generating the row height
+*/
+NK_API void nk_layout_set_min_row_height(struct nk_context*, float height);
+/*/// #### nk_layout_reset_min_row_height
+/// Reset the currently used minimum row height back to `font_height + text_padding + padding`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_reset_min_row_height(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+*/
+NK_API void nk_layout_reset_min_row_height(struct nk_context*);
+/*/// #### nk_layout_widget_bounds
+/// Returns the width of the next row allocate by one of the layouting functions
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_rect nk_layout_widget_bounds(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+///
+/// Return `nk_rect` with both position and size of the next row
+*/
+NK_API struct nk_rect nk_layout_widget_bounds(struct nk_context*);
+/*/// #### nk_layout_ratio_from_pixel
+/// Utility functions to calculate window ratio from pixel size
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __pixel__ | Pixel_width to convert to window ratio
+///
+/// Returns `nk_rect` with both position and size of the next row
+*/
+NK_API float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width);
+/*/// #### nk_layout_row_dynamic
+/// Sets current row layout to share horizontal space
+/// between @cols number of widgets evenly. Once called all subsequent widget
+/// calls greater than @cols will allocate a new row with same layout.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __height__ | Holds height of each widget in row or zero for auto layouting
+/// __columns__ | Number of widget inside row
+*/
+NK_API void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols);
+/*/// #### nk_layout_row_static
+/// Sets current row layout to fill @cols number of widgets
+/// in row with same @item_width horizontal size. Once called all subsequent widget
+/// calls greater than @cols will allocate a new row with same layout.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __height__ | Holds height of each widget in row or zero for auto layouting
+/// __width__ | Holds pixel width of each widget in the row
+/// __columns__ | Number of widget inside row
+*/
+NK_API void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols);
+/*/// #### nk_layout_row_begin
+/// Starts a new dynamic or fixed row with given height and columns.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __fmt__ | either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns
+/// __height__ | holds height of each widget in row or zero for auto layouting
+/// __columns__ | Number of widget inside row
+*/
+NK_API void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols);
+/*/// #### nk_layout_row_push
+/// Specifies either window ratio or width of a single column
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_push(struct nk_context*, float value);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __value__ | either a window ratio or fixed width depending on @fmt in previous `nk_layout_row_begin` call
+*/
+NK_API void nk_layout_row_push(struct nk_context*, float value);
+/*/// #### nk_layout_row_end
+/// Finished previously started row
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_end(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+*/
+NK_API void nk_layout_row_end(struct nk_context*);
+/*/// #### nk_layout_row
+/// Specifies row columns in array as either window ratio or size
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __fmt__ | Either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns
+/// __height__ | Holds height of each widget in row or zero for auto layouting
+/// __columns__ | Number of widget inside row
+*/
+NK_API void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio);
+/*/// #### nk_layout_row_template_begin
+/// Begins the row template declaration
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_template_begin(struct nk_context*, float row_height);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __height__ | Holds height of each widget in row or zero for auto layouting
+*/
+NK_API void nk_layout_row_template_begin(struct nk_context*, float row_height);
+/*/// #### nk_layout_row_template_push_dynamic
+/// Adds a dynamic column that dynamically grows and can go to zero if not enough space
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_template_push_dynamic(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __height__ | Holds height of each widget in row or zero for auto layouting
+*/
+NK_API void nk_layout_row_template_push_dynamic(struct nk_context*);
+/*/// #### nk_layout_row_template_push_variable
+/// Adds a variable column that dynamically grows but does not shrink below specified pixel width
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_template_push_variable(struct nk_context*, float min_width);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __width__ | Holds the minimum pixel width the next column must always be
+*/
+NK_API void nk_layout_row_template_push_variable(struct nk_context*, float min_width);
+/*/// #### nk_layout_row_template_push_static
+/// Adds a static column that does not grow and will always have the same size
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_template_push_static(struct nk_context*, float width);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __width__ | Holds the absolute pixel width value the next column must be
+*/
+NK_API void nk_layout_row_template_push_static(struct nk_context*, float width);
+/*/// #### nk_layout_row_template_end
+/// Marks the end of the row template
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_row_template_end(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+*/
+NK_API void nk_layout_row_template_end(struct nk_context*);
+/*/// #### nk_layout_space_begin
+/// Begins a new layouting space that allows to specify each widgets position and size.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
+/// __fmt__ | Either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns
+/// __height__ | Holds height of each widget in row or zero for auto layouting
+/// __columns__ | Number of widgets inside row
+*/
+NK_API void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count);
+/*/// #### nk_layout_space_push
+/// Pushes position and size of the next widget in own coordinate space either as pixel or ratio
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_space_push(struct nk_context *ctx, struct nk_rect bounds);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+/// __bounds__ | Position and size in laoyut space local coordinates
+*/
+NK_API void nk_layout_space_push(struct nk_context*, struct nk_rect bounds);
+/*/// #### nk_layout_space_end
+/// Marks the end of the layout space
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_layout_space_end(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+*/
+NK_API void nk_layout_space_end(struct nk_context*);
+/*/// #### nk_layout_space_bounds
+/// Utility function to calculate total space allocated for `nk_layout_space`
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_rect nk_layout_space_bounds(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+///
+/// Returns `nk_rect` holding the total space allocated
+*/
+NK_API struct nk_rect nk_layout_space_bounds(struct nk_context*);
+/*/// #### nk_layout_space_to_screen
+/// Converts vector from nk_layout_space coordinate space into screen space
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+/// __vec__ | Position to convert from layout space into screen coordinate space
+///
+/// Returns transformed `nk_vec2` in screen space coordinates
+*/
+NK_API struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2);
+/*/// #### nk_layout_space_to_local
+/// Converts vector from layout space into screen space
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+/// __vec__ | Position to convert from screen space into layout coordinate space
+///
+/// Returns transformed `nk_vec2` in layout space coordinates
+*/
+NK_API struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2);
+/*/// #### nk_layout_space_rect_to_screen
+/// Converts rectangle from screen space into layout space
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+/// __bounds__ | Rectangle to convert from layout space into screen space
+///
+/// Returns transformed `nk_rect` in screen space coordinates
+*/
+NK_API struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect);
+/*/// #### nk_layout_space_rect_to_local
+/// Converts rectangle from layout space into screen space
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+/// __bounds__ | Rectangle to convert from layout space into screen space
+///
+/// Returns transformed `nk_rect` in layout space coordinates
+*/
+NK_API struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect);
+
+/*/// #### nk_spacer
+/// Spacer is a dummy widget that consumes space as usual but doesn't draw anything
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_spacer(struct nk_context* );
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
+///
+*/
+NK_API void nk_spacer(struct nk_context* );
+
+
+/* =============================================================================
+ *
+ * GROUP
+ *
+ * =============================================================================
+/// ### Groups
+/// Groups are basically windows inside windows. They allow to subdivide space
+/// in a window to layout widgets as a group. Almost all more complex widget
+/// layouting requirements can be solved using groups and basic layouting
+/// fuctionality. Groups just like windows are identified by an unique name and
+/// internally keep track of scrollbar offsets by default. However additional
+/// versions are provided to directly manage the scrollbar.
+///
+/// #### Usage
+/// To create a group you have to call one of the three `nk_group_begin_xxx`
+/// functions to start group declarations and `nk_group_end` at the end. Furthermore it
+/// is required to check the return value of `nk_group_begin_xxx` and only process
+/// widgets inside the window if the value is not 0.
+/// Nesting groups is possible and even encouraged since many layouting schemes
+/// can only be achieved by nesting. Groups, unlike windows, need `nk_group_end`
+/// to be only called if the corresponding `nk_group_begin_xxx` call does not return 0:
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_group_begin_xxx(ctx, ...) {
+/// // [... widgets ...]
+/// nk_group_end(ctx);
+/// }
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// In the grand concept groups can be called after starting a window
+/// with `nk_begin_xxx` and before calling `nk_end`:
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// // Input
+/// Event evt;
+/// nk_input_begin(&ctx);
+/// while (GetEvent(&evt)) {
+/// if (evt.type == MOUSE_MOVE)
+/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
+/// else if (evt.type == [...]) {
+/// nk_input_xxx(...);
+/// }
+/// }
+/// nk_input_end(&ctx);
+/// //
+/// // Window
+/// if (nk_begin_xxx(...) {
+/// // [...widgets...]
+/// nk_layout_row_dynamic(...);
+/// if (nk_group_begin_xxx(ctx, ...) {
+/// //[... widgets ...]
+/// nk_group_end(ctx);
+/// }
+/// }
+/// nk_end(ctx);
+/// //
+/// // Draw
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// switch (cmd->type) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case ...:
+/// // [...]
+/// }
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+/// #### Reference
+/// Function | Description
+/// --------------------------------|-------------------------------------------
+/// nk_group_begin | Start a new group with internal scrollbar handling
+/// nk_group_begin_titled | Start a new group with separated name and title and internal scrollbar handling
+/// nk_group_end | Ends a group. Should only be called if nk_group_begin returned non-zero
+/// nk_group_scrolled_offset_begin | Start a new group with manual separated handling of scrollbar x- and y-offset
+/// nk_group_scrolled_begin | Start a new group with manual scrollbar handling
+/// nk_group_scrolled_end | Ends a group with manual scrollbar handling. Should only be called if nk_group_begin returned non-zero
+/// nk_group_get_scroll | Gets the scroll offset for the given group
+/// nk_group_set_scroll | Sets the scroll offset for the given group
+*/
+/*/// #### nk_group_begin
+/// Starts a new widget group. Requires a previous layouting function to specify a pos/size.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_group_begin(struct nk_context*, const char *title, nk_flags);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __title__ | Must be an unique identifier for this group that is also used for the group header
+/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different group behaviors
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_group_begin(struct nk_context*, const char *title, nk_flags);
+/*/// #### nk_group_begin_titled
+/// Starts a new widget group. Requires a previous layouting function to specify a pos/size.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __id__ | Must be an unique identifier for this group
+/// __title__ | Group header title
+/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different group behaviors
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags);
+/*/// #### nk_group_end
+/// Ends a widget group
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_group_end(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+*/
+NK_API void nk_group_end(struct nk_context*);
+/*/// #### nk_group_scrolled_offset_begin
+/// starts a new widget group. requires a previous layouting function to specify
+/// a size. Does not keep track of scrollbar.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __x_offset__| Scrollbar x-offset to offset all widgets inside the group horizontally.
+/// __y_offset__| Scrollbar y-offset to offset all widgets inside the group vertically
+/// __title__ | Window unique group title used to both identify and display in the group header
+/// __flags__ | Window flags from the nk_panel_flags section
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags);
+/*/// #### nk_group_scrolled_begin
+/// Starts a new widget group. requires a previous
+/// layouting function to specify a size. Does not keep track of scrollbar.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __off__ | Both x- and y- scroll offset. Allows for manual scrollbar control
+/// __title__ | Window unique group title used to both identify and display in the group header
+/// __flags__ | Window flags from nk_panel_flags section
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags);
+/*/// #### nk_group_scrolled_end
+/// Ends a widget group after calling nk_group_scrolled_offset_begin or nk_group_scrolled_begin.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_group_scrolled_end(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+*/
+NK_API void nk_group_scrolled_end(struct nk_context*);
+/*/// #### nk_group_get_scroll
+/// Gets the scroll position of the given group.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_group_get_scroll(struct nk_context*, const char *id, nk_uint *x_offset, nk_uint *y_offset);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// -------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __id__ | The id of the group to get the scroll position of
+/// __x_offset__ | A pointer to the x offset output (or NULL to ignore)
+/// __y_offset__ | A pointer to the y offset output (or NULL to ignore)
+*/
+NK_API void nk_group_get_scroll(struct nk_context*, const char *id, nk_uint *x_offset, nk_uint *y_offset);
+/*/// #### nk_group_set_scroll
+/// Sets the scroll position of the given group.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_group_set_scroll(struct nk_context*, const char *id, nk_uint x_offset, nk_uint y_offset);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// -------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __id__ | The id of the group to scroll
+/// __x_offset__ | The x offset to scroll to
+/// __y_offset__ | The y offset to scroll to
+*/
+NK_API void nk_group_set_scroll(struct nk_context*, const char *id, nk_uint x_offset, nk_uint y_offset);
+/* =============================================================================
+ *
+ * TREE
+ *
+ * =============================================================================
+/// ### Tree
+/// Trees represent two different concept. First the concept of a collapsible
+/// UI section that can be either in a hidden or visible state. They allow the UI
+/// user to selectively minimize the current set of visible UI to comprehend.
+/// The second concept are tree widgets for visual UI representation of trees.
+///
+/// Trees thereby can be nested for tree representations and multiple nested
+/// collapsible UI sections. All trees are started by calling of the
+/// `nk_tree_xxx_push_tree` functions and ended by calling one of the
+/// `nk_tree_xxx_pop_xxx()` functions. Each starting functions takes a title label
+/// and optionally an image to be displayed and the initial collapse state from
+/// the nk_collapse_states section.
+///
+/// The runtime state of the tree is either stored outside the library by the caller
+/// or inside which requires a unique ID. The unique ID can either be generated
+/// automatically from `__FILE__` and `__LINE__` with function `nk_tree_push`,
+/// by `__FILE__` and a user provided ID generated for example by loop index with
+/// function `nk_tree_push_id` or completely provided from outside by user with
+/// function `nk_tree_push_hashed`.
+///
+/// #### Usage
+/// To create a tree you have to call one of the seven `nk_tree_xxx_push_xxx`
+/// functions to start a collapsible UI section and `nk_tree_xxx_pop` to mark the
+/// end.
+/// Each starting function will either return `false(0)` if the tree is collapsed
+/// or hidden and therefore does not need to be filled with content or `true(1)`
+/// if visible and required to be filled.
+///
+/// !!! Note
+/// The tree header does not require and layouting function and instead
+/// calculates a auto height based on the currently used font size
+///
+/// The tree ending functions only need to be called if the tree content is
+/// actually visible. So make sure the tree push function is guarded by `if`
+/// and the pop call is only taken if the tree is visible.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// if (nk_tree_push(ctx, NK_TREE_TAB, "Tree", NK_MINIMIZED)) {
+/// nk_layout_row_dynamic(...);
+/// nk_widget(...);
+/// nk_tree_pop(ctx);
+/// }
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// ----------------------------|-------------------------------------------
+/// nk_tree_push | Start a collapsible UI section with internal state management
+/// nk_tree_push_id | Start a collapsible UI section with internal state management callable in a look
+/// nk_tree_push_hashed | Start a collapsible UI section with internal state management with full control over internal unique ID use to store state
+/// nk_tree_image_push | Start a collapsible UI section with image and label header
+/// nk_tree_image_push_id | Start a collapsible UI section with image and label header and internal state management callable in a look
+/// nk_tree_image_push_hashed | Start a collapsible UI section with image and label header and internal state management with full control over internal unique ID use to store state
+/// nk_tree_pop | Ends a collapsible UI section
+//
+/// nk_tree_state_push | Start a collapsible UI section with external state management
+/// nk_tree_state_image_push | Start a collapsible UI section with image and label header and external state management
+/// nk_tree_state_pop | Ends a collapsabale UI section
+///
+/// #### nk_tree_type
+/// Flag | Description
+/// ----------------|----------------------------------------
+/// NK_TREE_NODE | Highlighted tree header to mark a collapsible UI section
+/// NK_TREE_TAB | Non-highlighted tree header closer to tree representations
+*/
+/*/// #### nk_tree_push
+/// Starts a collapsible UI section with internal state management
+/// !!! WARNING
+/// To keep track of the runtime tree collapsible state this function uses
+/// defines `__FILE__` and `__LINE__` to generate a unique ID. If you want
+/// to call this function in a loop please use `nk_tree_push_id` or
+/// `nk_tree_push_hashed` instead.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// #define nk_tree_push(ctx, type, title, state)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __title__ | Label printed in the tree header
+/// __state__ | Initial tree state value out of nk_collapse_states
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+#define nk_tree_push(ctx, type, title, state) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__)
+/*/// #### nk_tree_push_id
+/// Starts a collapsible UI section with internal state management callable in a look
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// #define nk_tree_push_id(ctx, type, title, state, id)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __title__ | Label printed in the tree header
+/// __state__ | Initial tree state value out of nk_collapse_states
+/// __id__ | Loop counter index if this function is called in a loop
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+#define nk_tree_push_id(ctx, type, title, state, id) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id)
+/*/// #### nk_tree_push_hashed
+/// Start a collapsible UI section with internal state management with full
+/// control over internal unique ID used to store state
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __title__ | Label printed in the tree header
+/// __state__ | Initial tree state value out of nk_collapse_states
+/// __hash__ | Memory block or string to generate the ID from
+/// __len__ | Size of passed memory block or string in __hash__
+/// __seed__ | Seeding value if this function is called in a loop or default to `0`
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
+/*/// #### nk_tree_image_push
+/// Start a collapsible UI section with image and label header
+/// !!! WARNING
+/// To keep track of the runtime tree collapsible state this function uses
+/// defines `__FILE__` and `__LINE__` to generate a unique ID. If you want
+/// to call this function in a loop please use `nk_tree_image_push_id` or
+/// `nk_tree_image_push_hashed` instead.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// #define nk_tree_image_push(ctx, type, img, title, state)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+//
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __img__ | Image to display inside the header on the left of the label
+/// __title__ | Label printed in the tree header
+/// __state__ | Initial tree state value out of nk_collapse_states
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+#define nk_tree_image_push(ctx, type, img, title, state) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__)
+/*/// #### nk_tree_image_push_id
+/// Start a collapsible UI section with image and label header and internal state
+/// management callable in a look
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// #define nk_tree_image_push_id(ctx, type, img, title, state, id)
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __img__ | Image to display inside the header on the left of the label
+/// __title__ | Label printed in the tree header
+/// __state__ | Initial tree state value out of nk_collapse_states
+/// __id__ | Loop counter index if this function is called in a loop
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+#define nk_tree_image_push_id(ctx, type, img, title, state, id) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id)
+/*/// #### nk_tree_image_push_hashed
+/// Start a collapsible UI section with internal state management with full
+/// control over internal unique ID used to store state
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __img__ | Image to display inside the header on the left of the label
+/// __title__ | Label printed in the tree header
+/// __state__ | Initial tree state value out of nk_collapse_states
+/// __hash__ | Memory block or string to generate the ID from
+/// __len__ | Size of passed memory block or string in __hash__
+/// __seed__ | Seeding value if this function is called in a loop or default to `0`
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
+/*/// #### nk_tree_pop
+/// Ends a collapsabale UI section
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_tree_pop(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
+*/
+NK_API void nk_tree_pop(struct nk_context*);
+/*/// #### nk_tree_state_push
+/// Start a collapsible UI section with external state management
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __title__ | Label printed in the tree header
+/// __state__ | Persistent state to update
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state);
+/*/// #### nk_tree_state_image_push
+/// Start a collapsible UI section with image and label header and external state management
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// nk_bool nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
+/// __img__ | Image to display inside the header on the left of the label
+/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
+/// __title__ | Label printed in the tree header
+/// __state__ | Persistent state to update
+///
+/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
+*/
+NK_API nk_bool nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state);
+/*/// #### nk_tree_state_pop
+/// Ends a collapsabale UI section
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_tree_state_pop(struct nk_context*);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// ------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
+*/
+NK_API void nk_tree_state_pop(struct nk_context*);
+
+#define nk_tree_element_push(ctx, type, title, state, sel) nk_tree_element_push_hashed(ctx, type, title, state, sel, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__)
+#define nk_tree_element_push_id(ctx, type, title, state, sel, id) nk_tree_element_push_hashed(ctx, type, title, state, sel, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id)
+NK_API nk_bool nk_tree_element_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, nk_bool *selected, const char *hash, int len, int seed);
+NK_API nk_bool nk_tree_element_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, nk_bool *selected, const char *hash, int len,int seed);
+NK_API void nk_tree_element_pop(struct nk_context*);
+
+/* =============================================================================
+ *
+ * LIST VIEW
+ *
+ * ============================================================================= */
+struct nk_list_view {
+/* public: */
+ int begin, end, count;
+/* private: */
+ int total_height;
+ struct nk_context *ctx;
+ nk_uint *scroll_pointer;
+ nk_uint scroll_value;
+};
+NK_API nk_bool nk_list_view_begin(struct nk_context*, struct nk_list_view *out, const char *id, nk_flags, int row_height, int row_count);
+NK_API void nk_list_view_end(struct nk_list_view*);
+/* =============================================================================
+ *
+ * WIDGET
+ *
+ * ============================================================================= */
+enum nk_widget_layout_states {
+ NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */
+ NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */
+ NK_WIDGET_ROM, /* The widget is partially visible and cannot be updated */
+ NK_WIDGET_DISABLED /* The widget is manually disabled and acts like NK_WIDGET_ROM */
+};
+enum nk_widget_states {
+ NK_WIDGET_STATE_MODIFIED = NK_FLAG(1),
+ NK_WIDGET_STATE_INACTIVE = NK_FLAG(2), /* widget is neither active nor hovered */
+ NK_WIDGET_STATE_ENTERED = NK_FLAG(3), /* widget has been hovered on the current frame */
+ NK_WIDGET_STATE_HOVER = NK_FLAG(4), /* widget is being hovered */
+ NK_WIDGET_STATE_ACTIVED = NK_FLAG(5),/* widget is currently activated */
+ NK_WIDGET_STATE_LEFT = NK_FLAG(6), /* widget is from this frame on not hovered anymore */
+ NK_WIDGET_STATE_HOVERED = NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED, /* widget is being hovered */
+ NK_WIDGET_STATE_ACTIVE = NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED /* widget is currently activated */
+};
+NK_API enum nk_widget_layout_states nk_widget(struct nk_rect*, const struct nk_context*);
+NK_API enum nk_widget_layout_states nk_widget_fitting(struct nk_rect*, struct nk_context*, struct nk_vec2);
+NK_API struct nk_rect nk_widget_bounds(struct nk_context*);
+NK_API struct nk_vec2 nk_widget_position(struct nk_context*);
+NK_API struct nk_vec2 nk_widget_size(struct nk_context*);
+NK_API float nk_widget_width(struct nk_context*);
+NK_API float nk_widget_height(struct nk_context*);
+NK_API nk_bool nk_widget_is_hovered(struct nk_context*);
+NK_API nk_bool nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons);
+NK_API nk_bool nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, nk_bool down);
+NK_API void nk_spacing(struct nk_context*, int cols);
+NK_API void nk_widget_disable_begin(struct nk_context* ctx);
+NK_API void nk_widget_disable_end(struct nk_context* ctx);
+/* =============================================================================
+ *
+ * TEXT
+ *
+ * ============================================================================= */
+enum nk_text_align {
+ NK_TEXT_ALIGN_LEFT = 0x01,
+ NK_TEXT_ALIGN_CENTERED = 0x02,
+ NK_TEXT_ALIGN_RIGHT = 0x04,
+ NK_TEXT_ALIGN_TOP = 0x08,
+ NK_TEXT_ALIGN_MIDDLE = 0x10,
+ NK_TEXT_ALIGN_BOTTOM = 0x20
+};
+enum nk_text_alignment {
+ NK_TEXT_LEFT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT,
+ NK_TEXT_CENTERED = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED,
+ NK_TEXT_RIGHT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT
+};
+NK_API void nk_text(struct nk_context*, const char*, int, nk_flags);
+NK_API void nk_text_colored(struct nk_context*, const char*, int, nk_flags, struct nk_color);
+NK_API void nk_text_wrap(struct nk_context*, const char*, int);
+NK_API void nk_text_wrap_colored(struct nk_context*, const char*, int, struct nk_color);
+NK_API void nk_label(struct nk_context*, const char*, nk_flags align);
+NK_API void nk_label_colored(struct nk_context*, const char*, nk_flags align, struct nk_color);
+NK_API void nk_label_wrap(struct nk_context*, const char*);
+NK_API void nk_label_colored_wrap(struct nk_context*, const char*, struct nk_color);
+NK_API void nk_image(struct nk_context*, struct nk_image);
+NK_API void nk_image_color(struct nk_context*, struct nk_image, struct nk_color);
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+NK_API void nk_labelf(struct nk_context*, nk_flags, NK_PRINTF_FORMAT_STRING const char*, ...) NK_PRINTF_VARARG_FUNC(3);
+NK_API void nk_labelf_colored(struct nk_context*, nk_flags, struct nk_color, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(4);
+NK_API void nk_labelf_wrap(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(2);
+NK_API void nk_labelf_colored_wrap(struct nk_context*, struct nk_color, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(3);
+NK_API void nk_labelfv(struct nk_context*, nk_flags, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(3);
+NK_API void nk_labelfv_colored(struct nk_context*, nk_flags, struct nk_color, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(4);
+NK_API void nk_labelfv_wrap(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(2);
+NK_API void nk_labelfv_colored_wrap(struct nk_context*, struct nk_color, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(3);
+NK_API void nk_value_bool(struct nk_context*, const char *prefix, int);
+NK_API void nk_value_int(struct nk_context*, const char *prefix, int);
+NK_API void nk_value_uint(struct nk_context*, const char *prefix, unsigned int);
+NK_API void nk_value_float(struct nk_context*, const char *prefix, float);
+NK_API void nk_value_color_byte(struct nk_context*, const char *prefix, struct nk_color);
+NK_API void nk_value_color_float(struct nk_context*, const char *prefix, struct nk_color);
+NK_API void nk_value_color_hex(struct nk_context*, const char *prefix, struct nk_color);
+#endif
+/* =============================================================================
+ *
+ * BUTTON
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_button_text(struct nk_context*, const char *title, int len);
+NK_API nk_bool nk_button_label(struct nk_context*, const char *title);
+NK_API nk_bool nk_button_color(struct nk_context*, struct nk_color);
+NK_API nk_bool nk_button_symbol(struct nk_context*, enum nk_symbol_type);
+NK_API nk_bool nk_button_image(struct nk_context*, struct nk_image img);
+NK_API nk_bool nk_button_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags text_alignment);
+NK_API nk_bool nk_button_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
+NK_API nk_bool nk_button_image_label(struct nk_context*, struct nk_image img, const char*, nk_flags text_alignment);
+NK_API nk_bool nk_button_image_text(struct nk_context*, struct nk_image img, const char*, int, nk_flags alignment);
+NK_API nk_bool nk_button_text_styled(struct nk_context*, const struct nk_style_button*, const char *title, int len);
+NK_API nk_bool nk_button_label_styled(struct nk_context*, const struct nk_style_button*, const char *title);
+NK_API nk_bool nk_button_symbol_styled(struct nk_context*, const struct nk_style_button*, enum nk_symbol_type);
+NK_API nk_bool nk_button_image_styled(struct nk_context*, const struct nk_style_button*, struct nk_image img);
+NK_API nk_bool nk_button_symbol_text_styled(struct nk_context*,const struct nk_style_button*, enum nk_symbol_type, const char*, int, nk_flags alignment);
+NK_API nk_bool nk_button_symbol_label_styled(struct nk_context *ctx, const struct nk_style_button *style, enum nk_symbol_type symbol, const char *title, nk_flags align);
+NK_API nk_bool nk_button_image_label_styled(struct nk_context*,const struct nk_style_button*, struct nk_image img, const char*, nk_flags text_alignment);
+NK_API nk_bool nk_button_image_text_styled(struct nk_context*,const struct nk_style_button*, struct nk_image img, const char*, int, nk_flags alignment);
+NK_API void nk_button_set_behavior(struct nk_context*, enum nk_button_behavior);
+NK_API nk_bool nk_button_push_behavior(struct nk_context*, enum nk_button_behavior);
+NK_API nk_bool nk_button_pop_behavior(struct nk_context*);
+/* =============================================================================
+ *
+ * CHECKBOX
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active);
+NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active);
+NK_API nk_bool nk_check_text_align(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment);
+NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value);
+NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value);
+NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active);
+NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment);
+NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active);
+NK_API nk_bool nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment);
+NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value);
+NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value);
+/* =============================================================================
+ *
+ * RADIO BUTTON
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active);
+NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment);
+NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active);
+NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment);
+NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active);
+NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment);
+NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active);
+NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment);
+/* =============================================================================
+ *
+ * SELECTABLE
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_selectable_label(struct nk_context*, const char*, nk_flags align, nk_bool *value);
+NK_API nk_bool nk_selectable_text(struct nk_context*, const char*, int, nk_flags align, nk_bool *value);
+NK_API nk_bool nk_selectable_image_label(struct nk_context*,struct nk_image, const char*, nk_flags align, nk_bool *value);
+NK_API nk_bool nk_selectable_image_text(struct nk_context*,struct nk_image, const char*, int, nk_flags align, nk_bool *value);
+NK_API nk_bool nk_selectable_symbol_label(struct nk_context*,enum nk_symbol_type, const char*, nk_flags align, nk_bool *value);
+NK_API nk_bool nk_selectable_symbol_text(struct nk_context*,enum nk_symbol_type, const char*, int, nk_flags align, nk_bool *value);
+
+NK_API nk_bool nk_select_label(struct nk_context*, const char*, nk_flags align, nk_bool value);
+NK_API nk_bool nk_select_text(struct nk_context*, const char*, int, nk_flags align, nk_bool value);
+NK_API nk_bool nk_select_image_label(struct nk_context*, struct nk_image,const char*, nk_flags align, nk_bool value);
+NK_API nk_bool nk_select_image_text(struct nk_context*, struct nk_image,const char*, int, nk_flags align, nk_bool value);
+NK_API nk_bool nk_select_symbol_label(struct nk_context*,enum nk_symbol_type, const char*, nk_flags align, nk_bool value);
+NK_API nk_bool nk_select_symbol_text(struct nk_context*,enum nk_symbol_type, const char*, int, nk_flags align, nk_bool value);
+
+/* =============================================================================
+ *
+ * SLIDER
+ *
+ * ============================================================================= */
+NK_API float nk_slide_float(struct nk_context*, float min, float val, float max, float step);
+NK_API int nk_slide_int(struct nk_context*, int min, int val, int max, int step);
+NK_API nk_bool nk_slider_float(struct nk_context*, float min, float *val, float max, float step);
+NK_API nk_bool nk_slider_int(struct nk_context*, int min, int *val, int max, int step);
+/* =============================================================================
+ *
+ * PROGRESSBAR
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_progress(struct nk_context*, nk_size *cur, nk_size max, nk_bool modifyable);
+NK_API nk_size nk_prog(struct nk_context*, nk_size cur, nk_size max, nk_bool modifyable);
+
+/* =============================================================================
+ *
+ * COLOR PICKER
+ *
+ * ============================================================================= */
+NK_API struct nk_colorf nk_color_picker(struct nk_context*, struct nk_colorf, enum nk_color_format);
+NK_API nk_bool nk_color_pick(struct nk_context*, struct nk_colorf*, enum nk_color_format);
+/* =============================================================================
+ *
+ * PROPERTIES
+ *
+ * =============================================================================
+/// ### Properties
+/// Properties are the main value modification widgets in Nuklear. Changing a value
+/// can be achieved by dragging, adding/removing incremental steps on button click
+/// or by directly typing a number.
+///
+/// #### Usage
+/// Each property requires a unique name for identification that is also used for
+/// displaying a label. If you want to use the same name multiple times make sure
+/// add a '#' before your name. The '#' will not be shown but will generate a
+/// unique ID. Each property also takes in a minimum and maximum value. If you want
+/// to make use of the complete number range of a type just use the provided
+/// type limits from `limits.h`. For example `INT_MIN` and `INT_MAX` for
+/// `nk_property_int` and `nk_propertyi`. In additional each property takes in
+/// a increment value that will be added or subtracted if either the increment
+/// decrement button is clicked. Finally there is a value for increment per pixel
+/// dragged that is added or subtracted from the value.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// int value = 0;
+/// struct nk_context ctx;
+/// nk_init_xxx(&ctx, ...);
+/// while (1) {
+/// // Input
+/// Event evt;
+/// nk_input_begin(&ctx);
+/// while (GetEvent(&evt)) {
+/// if (evt.type == MOUSE_MOVE)
+/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
+/// else if (evt.type == [...]) {
+/// nk_input_xxx(...);
+/// }
+/// }
+/// nk_input_end(&ctx);
+/// //
+/// // Window
+/// if (nk_begin_xxx(...) {
+/// // Property
+/// nk_layout_row_dynamic(...);
+/// nk_property_int(ctx, "ID", INT_MIN, &value, INT_MAX, 1, 1);
+/// }
+/// nk_end(ctx);
+/// //
+/// // Draw
+/// const struct nk_command *cmd = 0;
+/// nk_foreach(cmd, &ctx) {
+/// switch (cmd->type) {
+/// case NK_COMMAND_LINE:
+/// your_draw_line_function(...)
+/// break;
+/// case NK_COMMAND_RECT
+/// your_draw_rect_function(...)
+/// break;
+/// case ...:
+/// // [...]
+/// }
+/// nk_clear(&ctx);
+/// }
+/// nk_free(&ctx);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// #### Reference
+/// Function | Description
+/// --------------------|-------------------------------------------
+/// nk_property_int | Integer property directly modifying a passed in value
+/// nk_property_float | Float property directly modifying a passed in value
+/// nk_property_double | Double property directly modifying a passed in value
+/// nk_propertyi | Integer property returning the modified int value
+/// nk_propertyf | Float property returning the modified float value
+/// nk_propertyd | Double property returning the modified double value
+///
+*/
+/*/// #### nk_property_int
+/// Integer property directly modifying a passed in value
+/// !!! WARNING
+/// To generate a unique property ID using the same label make sure to insert
+/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_property_int(struct nk_context *ctx, const char *name, int min, int *val, int max, int step, float inc_per_pixel);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// --------------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
+/// __name__ | String used both as a label as well as a unique identifier
+/// __min__ | Minimum value not allowed to be underflown
+/// __val__ | Integer pointer to be modified
+/// __max__ | Maximum value not allowed to be overflown
+/// __step__ | Increment added and subtracted on increment and decrement button
+/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
+*/
+NK_API void nk_property_int(struct nk_context*, const char *name, int min, int *val, int max, int step, float inc_per_pixel);
+/*/// #### nk_property_float
+/// Float property directly modifying a passed in value
+/// !!! WARNING
+/// To generate a unique property ID using the same label make sure to insert
+/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_property_float(struct nk_context *ctx, const char *name, float min, float *val, float max, float step, float inc_per_pixel);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// --------------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
+/// __name__ | String used both as a label as well as a unique identifier
+/// __min__ | Minimum value not allowed to be underflown
+/// __val__ | Float pointer to be modified
+/// __max__ | Maximum value not allowed to be overflown
+/// __step__ | Increment added and subtracted on increment and decrement button
+/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
+*/
+NK_API void nk_property_float(struct nk_context*, const char *name, float min, float *val, float max, float step, float inc_per_pixel);
+/*/// #### nk_property_double
+/// Double property directly modifying a passed in value
+/// !!! WARNING
+/// To generate a unique property ID using the same label make sure to insert
+/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// void nk_property_double(struct nk_context *ctx, const char *name, double min, double *val, double max, double step, double inc_per_pixel);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// --------------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
+/// __name__ | String used both as a label as well as a unique identifier
+/// __min__ | Minimum value not allowed to be underflown
+/// __val__ | Double pointer to be modified
+/// __max__ | Maximum value not allowed to be overflown
+/// __step__ | Increment added and subtracted on increment and decrement button
+/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
+*/
+NK_API void nk_property_double(struct nk_context*, const char *name, double min, double *val, double max, double step, float inc_per_pixel);
+/*/// #### nk_propertyi
+/// Integer property modifying a passed in value and returning the new value
+/// !!! WARNING
+/// To generate a unique property ID using the same label make sure to insert
+/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// int nk_propertyi(struct nk_context *ctx, const char *name, int min, int val, int max, int step, float inc_per_pixel);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// --------------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
+/// __name__ | String used both as a label as well as a unique identifier
+/// __min__ | Minimum value not allowed to be underflown
+/// __val__ | Current integer value to be modified and returned
+/// __max__ | Maximum value not allowed to be overflown
+/// __step__ | Increment added and subtracted on increment and decrement button
+/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
+///
+/// Returns the new modified integer value
+*/
+NK_API int nk_propertyi(struct nk_context*, const char *name, int min, int val, int max, int step, float inc_per_pixel);
+/*/// #### nk_propertyf
+/// Float property modifying a passed in value and returning the new value
+/// !!! WARNING
+/// To generate a unique property ID using the same label make sure to insert
+/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// float nk_propertyf(struct nk_context *ctx, const char *name, float min, float val, float max, float step, float inc_per_pixel);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// --------------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
+/// __name__ | String used both as a label as well as a unique identifier
+/// __min__ | Minimum value not allowed to be underflown
+/// __val__ | Current float value to be modified and returned
+/// __max__ | Maximum value not allowed to be overflown
+/// __step__ | Increment added and subtracted on increment and decrement button
+/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
+///
+/// Returns the new modified float value
+*/
+NK_API float nk_propertyf(struct nk_context*, const char *name, float min, float val, float max, float step, float inc_per_pixel);
+/*/// #### nk_propertyd
+/// Float property modifying a passed in value and returning the new value
+/// !!! WARNING
+/// To generate a unique property ID using the same label make sure to insert
+/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
+///
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
+/// float nk_propertyd(struct nk_context *ctx, const char *name, double min, double val, double max, double step, double inc_per_pixel);
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+///
+/// Parameter | Description
+/// --------------------|-----------------------------------------------------------
+/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
+/// __name__ | String used both as a label as well as a unique identifier
+/// __min__ | Minimum value not allowed to be underflown
+/// __val__ | Current double value to be modified and returned
+/// __max__ | Maximum value not allowed to be overflown
+/// __step__ | Increment added and subtracted on increment and decrement button
+/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
+///
+/// Returns the new modified double value
+*/
+NK_API double nk_propertyd(struct nk_context*, const char *name, double min, double val, double max, double step, float inc_per_pixel);
+/* =============================================================================
+ *
+ * TEXT EDIT
+ *
+ * ============================================================================= */
+enum nk_edit_flags {
+ NK_EDIT_DEFAULT = 0,
+ NK_EDIT_READ_ONLY = NK_FLAG(0),
+ NK_EDIT_AUTO_SELECT = NK_FLAG(1),
+ NK_EDIT_SIG_ENTER = NK_FLAG(2),
+ NK_EDIT_ALLOW_TAB = NK_FLAG(3),
+ NK_EDIT_NO_CURSOR = NK_FLAG(4),
+ NK_EDIT_SELECTABLE = NK_FLAG(5),
+ NK_EDIT_CLIPBOARD = NK_FLAG(6),
+ NK_EDIT_CTRL_ENTER_NEWLINE = NK_FLAG(7),
+ NK_EDIT_NO_HORIZONTAL_SCROLL = NK_FLAG(8),
+ NK_EDIT_ALWAYS_INSERT_MODE = NK_FLAG(9),
+ NK_EDIT_MULTILINE = NK_FLAG(10),
+ NK_EDIT_GOTO_END_ON_ACTIVATE = NK_FLAG(11)
+};
+enum nk_edit_types {
+ NK_EDIT_SIMPLE = NK_EDIT_ALWAYS_INSERT_MODE,
+ NK_EDIT_FIELD = NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD,
+ NK_EDIT_BOX = NK_EDIT_ALWAYS_INSERT_MODE| NK_EDIT_SELECTABLE| NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD,
+ NK_EDIT_EDITOR = NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB| NK_EDIT_CLIPBOARD
+};
+enum nk_edit_events {
+ NK_EDIT_ACTIVE = NK_FLAG(0), /* edit widget is currently being modified */
+ NK_EDIT_INACTIVE = NK_FLAG(1), /* edit widget is not active and is not being modified */
+ NK_EDIT_ACTIVATED = NK_FLAG(2), /* edit widget went from state inactive to state active */
+ NK_EDIT_DEACTIVATED = NK_FLAG(3), /* edit widget went from state active to state inactive */
+ NK_EDIT_COMMITED = NK_FLAG(4) /* edit widget has received an enter and lost focus */
+};
+NK_API nk_flags nk_edit_string(struct nk_context*, nk_flags, char *buffer, int *len, int max, nk_plugin_filter);
+NK_API nk_flags nk_edit_string_zero_terminated(struct nk_context*, nk_flags, char *buffer, int max, nk_plugin_filter);
+NK_API nk_flags nk_edit_buffer(struct nk_context*, nk_flags, struct nk_text_edit*, nk_plugin_filter);
+NK_API void nk_edit_focus(struct nk_context*, nk_flags flags);
+NK_API void nk_edit_unfocus(struct nk_context*);
+/* =============================================================================
+ *
+ * CHART
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_chart_begin(struct nk_context*, enum nk_chart_type, int num, float min, float max);
+NK_API nk_bool nk_chart_begin_colored(struct nk_context*, enum nk_chart_type, struct nk_color, struct nk_color active, int num, float min, float max);
+NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type, int count, float min_value, float max_value);
+NK_API void nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type, struct nk_color, struct nk_color active, int count, float min_value, float max_value);
+NK_API nk_flags nk_chart_push(struct nk_context*, float);
+NK_API nk_flags nk_chart_push_slot(struct nk_context*, float, int);
+NK_API void nk_chart_end(struct nk_context*);
+NK_API void nk_plot(struct nk_context*, enum nk_chart_type, const float *values, int count, int offset);
+NK_API void nk_plot_function(struct nk_context*, enum nk_chart_type, void *userdata, float(*value_getter)(void* user, int index), int count, int offset);
+/* =============================================================================
+ *
+ * POPUP
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_popup_begin(struct nk_context*, enum nk_popup_type, const char*, nk_flags, struct nk_rect bounds);
+NK_API void nk_popup_close(struct nk_context*);
+NK_API void nk_popup_end(struct nk_context*);
+NK_API void nk_popup_get_scroll(struct nk_context*, nk_uint *offset_x, nk_uint *offset_y);
+NK_API void nk_popup_set_scroll(struct nk_context*, nk_uint offset_x, nk_uint offset_y);
+/* =============================================================================
+ *
+ * COMBOBOX
+ *
+ * ============================================================================= */
+NK_API int nk_combo(struct nk_context*, const char **items, int count, int selected, int item_height, struct nk_vec2 size);
+NK_API int nk_combo_separator(struct nk_context*, const char *items_separated_by_separator, int separator, int selected, int count, int item_height, struct nk_vec2 size);
+NK_API int nk_combo_string(struct nk_context*, const char *items_separated_by_zeros, int selected, int count, int item_height, struct nk_vec2 size);
+NK_API int nk_combo_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void *userdata, int selected, int count, int item_height, struct nk_vec2 size);
+NK_API void nk_combobox(struct nk_context*, const char **items, int count, int *selected, int item_height, struct nk_vec2 size);
+NK_API void nk_combobox_string(struct nk_context*, const char *items_separated_by_zeros, int *selected, int count, int item_height, struct nk_vec2 size);
+NK_API void nk_combobox_separator(struct nk_context*, const char *items_separated_by_separator, int separator, int *selected, int count, int item_height, struct nk_vec2 size);
+NK_API void nk_combobox_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void*, int *selected, int count, int item_height, struct nk_vec2 size);
+/* =============================================================================
+ *
+ * ABSTRACT COMBOBOX
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_combo_begin_text(struct nk_context*, const char *selected, int, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_label(struct nk_context*, const char *selected, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_color(struct nk_context*, struct nk_color color, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_symbol(struct nk_context*, enum nk_symbol_type, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_symbol_label(struct nk_context*, const char *selected, enum nk_symbol_type, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_symbol_text(struct nk_context*, const char *selected, int, enum nk_symbol_type, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_image(struct nk_context*, struct nk_image img, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_image_label(struct nk_context*, const char *selected, struct nk_image, struct nk_vec2 size);
+NK_API nk_bool nk_combo_begin_image_text(struct nk_context*, const char *selected, int, struct nk_image, struct nk_vec2 size);
+NK_API nk_bool nk_combo_item_label(struct nk_context*, const char*, nk_flags alignment);
+NK_API nk_bool nk_combo_item_text(struct nk_context*, const char*,int, nk_flags alignment);
+NK_API nk_bool nk_combo_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment);
+NK_API nk_bool nk_combo_item_image_text(struct nk_context*, struct nk_image, const char*, int,nk_flags alignment);
+NK_API nk_bool nk_combo_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment);
+NK_API nk_bool nk_combo_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
+NK_API void nk_combo_close(struct nk_context*);
+NK_API void nk_combo_end(struct nk_context*);
+/* =============================================================================
+ *
+ * CONTEXTUAL
+ *
+ * ============================================================================= */
+NK_API nk_bool nk_contextual_begin(struct nk_context*, nk_flags, struct nk_vec2, struct nk_rect trigger_bounds);
+NK_API nk_bool nk_contextual_item_text(struct nk_context*, const char*, int,nk_flags align);
+NK_API nk_bool nk_contextual_item_label(struct nk_context*, const char*, nk_flags align);
+NK_API nk_bool nk_contextual_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment);
+NK_API nk_bool nk_contextual_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment);
+NK_API nk_bool nk_contextual_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment);
+NK_API nk_bool nk_contextual_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
+NK_API void nk_contextual_close(struct nk_context*);
+NK_API void nk_contextual_end(struct nk_context*);
+/* =============================================================================
+ *
+ * TOOLTIP
+ *
+ * ============================================================================= */
+NK_API void nk_tooltip(struct nk_context*, const char*);
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+NK_API void nk_tooltipf(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, ...) NK_PRINTF_VARARG_FUNC(2);
+NK_API void nk_tooltipfv(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(2);
+#endif
+NK_API nk_bool nk_tooltip_begin(struct nk_context*, float width);
+NK_API void nk_tooltip_end(struct nk_context*);
+/* =============================================================================
+ *
+ * MENU
+ *
+ * ============================================================================= */
+NK_API void nk_menubar_begin(struct nk_context*);
+NK_API void nk_menubar_end(struct nk_context*);
+NK_API nk_bool nk_menu_begin_text(struct nk_context*, const char* title, int title_len, nk_flags align, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_label(struct nk_context*, const char*, nk_flags align, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_image(struct nk_context*, const char*, struct nk_image, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_image_text(struct nk_context*, const char*, int,nk_flags align,struct nk_image, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_image_label(struct nk_context*, const char*, nk_flags align,struct nk_image, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_symbol(struct nk_context*, const char*, enum nk_symbol_type, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_symbol_text(struct nk_context*, const char*, int,nk_flags align,enum nk_symbol_type, struct nk_vec2 size);
+NK_API nk_bool nk_menu_begin_symbol_label(struct nk_context*, const char*, nk_flags align,enum nk_symbol_type, struct nk_vec2 size);
+NK_API nk_bool nk_menu_item_text(struct nk_context*, const char*, int,nk_flags align);
+NK_API nk_bool nk_menu_item_label(struct nk_context*, const char*, nk_flags alignment);
+NK_API nk_bool nk_menu_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment);
+NK_API nk_bool nk_menu_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment);
+NK_API nk_bool nk_menu_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
+NK_API nk_bool nk_menu_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment);
+NK_API void nk_menu_close(struct nk_context*);
+NK_API void nk_menu_end(struct nk_context*);
+/* =============================================================================
+ *
+ * STYLE
+ *
+ * ============================================================================= */
+
+#define NK_WIDGET_DISABLED_FACTOR 0.5f
+
+enum nk_style_colors {
+ NK_COLOR_TEXT,
+ NK_COLOR_WINDOW,
+ NK_COLOR_HEADER,
+ NK_COLOR_BORDER,
+ NK_COLOR_BUTTON,
+ NK_COLOR_BUTTON_HOVER,
+ NK_COLOR_BUTTON_ACTIVE,
+ NK_COLOR_TOGGLE,
+ NK_COLOR_TOGGLE_HOVER,
+ NK_COLOR_TOGGLE_CURSOR,
+ NK_COLOR_SELECT,
+ NK_COLOR_SELECT_ACTIVE,
+ NK_COLOR_SLIDER,
+ NK_COLOR_SLIDER_CURSOR,
+ NK_COLOR_SLIDER_CURSOR_HOVER,
+ NK_COLOR_SLIDER_CURSOR_ACTIVE,
+ NK_COLOR_PROPERTY,
+ NK_COLOR_EDIT,
+ NK_COLOR_EDIT_CURSOR,
+ NK_COLOR_COMBO,
+ NK_COLOR_CHART,
+ NK_COLOR_CHART_COLOR,
+ NK_COLOR_CHART_COLOR_HIGHLIGHT,
+ NK_COLOR_SCROLLBAR,
+ NK_COLOR_SCROLLBAR_CURSOR,
+ NK_COLOR_SCROLLBAR_CURSOR_HOVER,
+ NK_COLOR_SCROLLBAR_CURSOR_ACTIVE,
+ NK_COLOR_TAB_HEADER,
+ NK_COLOR_COUNT
+};
+enum nk_style_cursor {
+ NK_CURSOR_ARROW,
+ NK_CURSOR_TEXT,
+ NK_CURSOR_MOVE,
+ NK_CURSOR_RESIZE_VERTICAL,
+ NK_CURSOR_RESIZE_HORIZONTAL,
+ NK_CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT,
+ NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT,
+ NK_CURSOR_COUNT
+};
+NK_API void nk_style_default(struct nk_context*);
+NK_API void nk_style_from_table(struct nk_context*, const struct nk_color*);
+NK_API void nk_style_load_cursor(struct nk_context*, enum nk_style_cursor, const struct nk_cursor*);
+NK_API void nk_style_load_all_cursors(struct nk_context*, struct nk_cursor*);
+NK_API const char* nk_style_get_color_by_name(enum nk_style_colors);
+NK_API void nk_style_set_font(struct nk_context*, const struct nk_user_font*);
+NK_API nk_bool nk_style_set_cursor(struct nk_context*, enum nk_style_cursor);
+NK_API void nk_style_show_cursor(struct nk_context*);
+NK_API void nk_style_hide_cursor(struct nk_context*);
+
+NK_API nk_bool nk_style_push_font(struct nk_context*, const struct nk_user_font*);
+NK_API nk_bool nk_style_push_float(struct nk_context*, float*, float);
+NK_API nk_bool nk_style_push_vec2(struct nk_context*, struct nk_vec2*, struct nk_vec2);
+NK_API nk_bool nk_style_push_style_item(struct nk_context*, struct nk_style_item*, struct nk_style_item);
+NK_API nk_bool nk_style_push_flags(struct nk_context*, nk_flags*, nk_flags);
+NK_API nk_bool nk_style_push_color(struct nk_context*, struct nk_color*, struct nk_color);
+
+NK_API nk_bool nk_style_pop_font(struct nk_context*);
+NK_API nk_bool nk_style_pop_float(struct nk_context*);
+NK_API nk_bool nk_style_pop_vec2(struct nk_context*);
+NK_API nk_bool nk_style_pop_style_item(struct nk_context*);
+NK_API nk_bool nk_style_pop_flags(struct nk_context*);
+NK_API nk_bool nk_style_pop_color(struct nk_context*);
+/* =============================================================================
+ *
+ * COLOR
+ *
+ * ============================================================================= */
+NK_API struct nk_color nk_rgb(int r, int g, int b);
+NK_API struct nk_color nk_rgb_iv(const int *rgb);
+NK_API struct nk_color nk_rgb_bv(const nk_byte* rgb);
+NK_API struct nk_color nk_rgb_f(float r, float g, float b);
+NK_API struct nk_color nk_rgb_fv(const float *rgb);
+NK_API struct nk_color nk_rgb_cf(struct nk_colorf c);
+NK_API struct nk_color nk_rgb_hex(const char *rgb);
+NK_API struct nk_color nk_rgb_factor(struct nk_color col, const float factor);
+
+NK_API struct nk_color nk_rgba(int r, int g, int b, int a);
+NK_API struct nk_color nk_rgba_u32(nk_uint);
+NK_API struct nk_color nk_rgba_iv(const int *rgba);
+NK_API struct nk_color nk_rgba_bv(const nk_byte *rgba);
+NK_API struct nk_color nk_rgba_f(float r, float g, float b, float a);
+NK_API struct nk_color nk_rgba_fv(const float *rgba);
+NK_API struct nk_color nk_rgba_cf(struct nk_colorf c);
+NK_API struct nk_color nk_rgba_hex(const char *rgb);
+
+NK_API struct nk_colorf nk_hsva_colorf(float h, float s, float v, float a);
+NK_API struct nk_colorf nk_hsva_colorfv(float *c);
+NK_API void nk_colorf_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_colorf in);
+NK_API void nk_colorf_hsva_fv(float *hsva, struct nk_colorf in);
+
+NK_API struct nk_color nk_hsv(int h, int s, int v);
+NK_API struct nk_color nk_hsv_iv(const int *hsv);
+NK_API struct nk_color nk_hsv_bv(const nk_byte *hsv);
+NK_API struct nk_color nk_hsv_f(float h, float s, float v);
+NK_API struct nk_color nk_hsv_fv(const float *hsv);
+
+NK_API struct nk_color nk_hsva(int h, int s, int v, int a);
+NK_API struct nk_color nk_hsva_iv(const int *hsva);
+NK_API struct nk_color nk_hsva_bv(const nk_byte *hsva);
+NK_API struct nk_color nk_hsva_f(float h, float s, float v, float a);
+NK_API struct nk_color nk_hsva_fv(const float *hsva);
+
+/* color (conversion nuklear --> user) */
+NK_API void nk_color_f(float *r, float *g, float *b, float *a, struct nk_color);
+NK_API void nk_color_fv(float *rgba_out, struct nk_color);
+NK_API struct nk_colorf nk_color_cf(struct nk_color);
+NK_API void nk_color_d(double *r, double *g, double *b, double *a, struct nk_color);
+NK_API void nk_color_dv(double *rgba_out, struct nk_color);
+
+NK_API nk_uint nk_color_u32(struct nk_color);
+NK_API void nk_color_hex_rgba(char *output, struct nk_color);
+NK_API void nk_color_hex_rgb(char *output, struct nk_color);
+
+NK_API void nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color);
+NK_API void nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color);
+NK_API void nk_color_hsv_iv(int *hsv_out, struct nk_color);
+NK_API void nk_color_hsv_bv(nk_byte *hsv_out, struct nk_color);
+NK_API void nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color);
+NK_API void nk_color_hsv_fv(float *hsv_out, struct nk_color);
+
+NK_API void nk_color_hsva_i(int *h, int *s, int *v, int *a, struct nk_color);
+NK_API void nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color);
+NK_API void nk_color_hsva_iv(int *hsva_out, struct nk_color);
+NK_API void nk_color_hsva_bv(nk_byte *hsva_out, struct nk_color);
+NK_API void nk_color_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_color);
+NK_API void nk_color_hsva_fv(float *hsva_out, struct nk_color);
+/* =============================================================================
+ *
+ * IMAGE
+ *
+ * ============================================================================= */
+NK_API nk_handle nk_handle_ptr(void*);
+NK_API nk_handle nk_handle_id(int);
+NK_API struct nk_image nk_image_handle(nk_handle);
+NK_API struct nk_image nk_image_ptr(void*);
+NK_API struct nk_image nk_image_id(int);
+NK_API nk_bool nk_image_is_subimage(const struct nk_image* img);
+NK_API struct nk_image nk_subimage_ptr(void*, nk_ushort w, nk_ushort h, struct nk_rect sub_region);
+NK_API struct nk_image nk_subimage_id(int, nk_ushort w, nk_ushort h, struct nk_rect sub_region);
+NK_API struct nk_image nk_subimage_handle(nk_handle, nk_ushort w, nk_ushort h, struct nk_rect sub_region);
+/* =============================================================================
+ *
+ * 9-SLICE
+ *
+ * ============================================================================= */
+NK_API struct nk_nine_slice nk_nine_slice_handle(nk_handle, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
+NK_API struct nk_nine_slice nk_nine_slice_ptr(void*, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
+NK_API struct nk_nine_slice nk_nine_slice_id(int, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
+NK_API int nk_nine_slice_is_sub9slice(const struct nk_nine_slice* img);
+NK_API struct nk_nine_slice nk_sub9slice_ptr(void*, nk_ushort w, nk_ushort h, struct nk_rect sub_region, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
+NK_API struct nk_nine_slice nk_sub9slice_id(int, nk_ushort w, nk_ushort h, struct nk_rect sub_region, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
+NK_API struct nk_nine_slice nk_sub9slice_handle(nk_handle, nk_ushort w, nk_ushort h, struct nk_rect sub_region, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
+/* =============================================================================
+ *
+ * MATH
+ *
+ * ============================================================================= */
+NK_API nk_hash nk_murmur_hash(const void *key, int len, nk_hash seed);
+NK_API void nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r, float pad_x, float pad_y, enum nk_heading);
+
+NK_API struct nk_vec2 nk_vec2(float x, float y);
+NK_API struct nk_vec2 nk_vec2i(int x, int y);
+NK_API struct nk_vec2 nk_vec2v(const float *xy);
+NK_API struct nk_vec2 nk_vec2iv(const int *xy);
+
+NK_API struct nk_rect nk_get_null_rect(void);
+NK_API struct nk_rect nk_rect(float x, float y, float w, float h);
+NK_API struct nk_rect nk_recti(int x, int y, int w, int h);
+NK_API struct nk_rect nk_recta(struct nk_vec2 pos, struct nk_vec2 size);
+NK_API struct nk_rect nk_rectv(const float *xywh);
+NK_API struct nk_rect nk_rectiv(const int *xywh);
+NK_API struct nk_vec2 nk_rect_pos(struct nk_rect);
+NK_API struct nk_vec2 nk_rect_size(struct nk_rect);
+/* =============================================================================
+ *
+ * STRING
+ *
+ * ============================================================================= */
+NK_API int nk_strlen(const char *str);
+NK_API int nk_stricmp(const char *s1, const char *s2);
+NK_API int nk_stricmpn(const char *s1, const char *s2, int n);
+NK_API int nk_strtoi(const char *str, const char **endptr);
+NK_API float nk_strtof(const char *str, const char **endptr);
+#ifndef NK_STRTOD
+#define NK_STRTOD nk_strtod
+NK_API double nk_strtod(const char *str, const char **endptr);
+#endif
+NK_API int nk_strfilter(const char *text, const char *regexp);
+NK_API int nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score);
+NK_API int nk_strmatch_fuzzy_text(const char *txt, int txt_len, const char *pattern, int *out_score);
+/* =============================================================================
+ *
+ * UTF-8
+ *
+ * ============================================================================= */
+NK_API int nk_utf_decode(const char*, nk_rune*, int);
+NK_API int nk_utf_encode(nk_rune, char*, int);
+NK_API int nk_utf_len(const char*, int byte_len);
+NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune *unicode, int *len);
+/* ===============================================================
+ *
+ * FONT
+ *
+ * ===============================================================*/
+/*/// ### Font
+/// Font handling in this library was designed to be quite customizable and lets
+/// you decide what you want to use and what you want to provide. There are three
+/// different ways to use the font atlas. The first two will use your font
+/// handling scheme and only requires essential data to run nuklear. The next
+/// slightly more advanced features is font handling with vertex buffer output.
+/// Finally the most complex API wise is using nuklear's font baking API.
+//
+/// #### Using your own implementation without vertex buffer output
+///
+/// So first up the easiest way to do font handling is by just providing a
+/// `nk_user_font` struct which only requires the height in pixel of the used
+/// font and a callback to calculate the width of a string. This way of handling
+/// fonts is best fitted for using the normal draw shape command API where you
+/// do all the text drawing yourself and the library does not require any kind
+/// of deeper knowledge about which font handling mechanism you use.
+/// IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist
+/// over the complete life time! I know this sucks but it is currently the only
+/// way to switch between fonts.
+///
+/// ```c
+/// float your_text_width_calculation(nk_handle handle, float height, const char *text, int len)
+/// {
+/// your_font_type *type = handle.ptr;
+/// float text_width = ...;
+/// return text_width;
+/// }
+///
+/// struct nk_user_font font;
+/// font.userdata.ptr = &your_font_class_or_struct;
+/// font.height = your_font_height;
+/// font.width = your_text_width_calculation;
+///
+/// struct nk_context ctx;
+/// nk_init_default(&ctx, &font);
+/// ```
+/// #### Using your own implementation with vertex buffer output
+///
+/// While the first approach works fine if you don't want to use the optional
+/// vertex buffer output it is not enough if you do. To get font handling working
+/// for these cases you have to provide two additional parameters inside the
+/// `nk_user_font`. First a texture atlas handle used to draw text as subimages
+/// of a bigger font atlas texture and a callback to query a character's glyph
+/// information (offset, size, ...). So it is still possible to provide your own
+/// font and use the vertex buffer output.
+///
+/// ```c
+/// float your_text_width_calculation(nk_handle handle, float height, const char *text, int len)
+/// {
+/// your_font_type *type = handle.ptr;
+/// float text_width = ...;
+/// return text_width;
+/// }
+/// void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint)
+/// {
+/// your_font_type *type = handle.ptr;
+/// glyph.width = ...;
+/// glyph.height = ...;
+/// glyph.xadvance = ...;
+/// glyph.uv[0].x = ...;
+/// glyph.uv[0].y = ...;
+/// glyph.uv[1].x = ...;
+/// glyph.uv[1].y = ...;
+/// glyph.offset.x = ...;
+/// glyph.offset.y = ...;
+/// }
+///
+/// struct nk_user_font font;
+/// font.userdata.ptr = &your_font_class_or_struct;
+/// font.height = your_font_height;
+/// font.width = your_text_width_calculation;
+/// font.query = query_your_font_glyph;
+/// font.texture.id = your_font_texture;
+///
+/// struct nk_context ctx;
+/// nk_init_default(&ctx, &font);
+/// ```
+///
+/// #### Nuklear font baker
+///
+/// The final approach if you do not have a font handling functionality or don't
+/// want to use it in this library is by using the optional font baker.
+/// The font baker APIs can be used to create a font plus font atlas texture
+/// and can be used with or without the vertex buffer output.
+///
+/// It still uses the `nk_user_font` struct and the two different approaches
+/// previously stated still work. The font baker is not located inside
+/// `nk_context` like all other systems since it can be understood as more of
+/// an extension to nuklear and does not really depend on any `nk_context` state.
+///
+/// Font baker need to be initialized first by one of the nk_font_atlas_init_xxx
+/// functions. If you don't care about memory just call the default version
+/// `nk_font_atlas_init_default` which will allocate all memory from the standard library.
+/// If you want to control memory allocation but you don't care if the allocated
+/// memory is temporary and therefore can be freed directly after the baking process
+/// is over or permanent you can call `nk_font_atlas_init`.
+///
+/// After successfully initializing the font baker you can add Truetype(.ttf) fonts from
+/// different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`.
+/// functions. Adding font will permanently store each font, font config and ttf memory block(!)
+/// inside the font atlas and allows to reuse the font atlas. If you don't want to reuse
+/// the font baker by for example adding additional fonts you can call
+/// `nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end).
+///
+/// As soon as you added all fonts you wanted you can now start the baking process
+/// for every selected glyph to image by calling `nk_font_atlas_bake`.
+/// The baking process returns image memory, width and height which can be used to
+/// either create your own image object or upload it to any graphics library.
+/// No matter which case you finally have to call `nk_font_atlas_end` which
+/// will free all temporary memory including the font atlas image so make sure
+/// you created our texture beforehand. `nk_font_atlas_end` requires a handle
+/// to your font texture or object and optionally fills a `struct nk_draw_null_texture`
+/// which can be used for the optional vertex output. If you don't want it just
+/// set the argument to `NULL`.
+///
+/// At this point you are done and if you don't want to reuse the font atlas you
+/// can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration
+/// memory. Finally if you don't use the font atlas and any of it's fonts anymore
+/// you need to call `nk_font_atlas_clear` to free all memory still being used.
+///
+/// ```c
+/// struct nk_font_atlas atlas;
+/// nk_font_atlas_init_default(&atlas);
+/// nk_font_atlas_begin(&atlas);
+/// nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0);
+/// nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0);
+/// const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32);
+/// nk_font_atlas_end(&atlas, nk_handle_id(texture), 0);
+///
+/// struct nk_context ctx;
+/// nk_init_default(&ctx, &font->handle);
+/// while (1) {
+///
+/// }
+/// nk_font_atlas_clear(&atlas);
+/// ```
+/// The font baker API is probably the most complex API inside this library and
+/// I would suggest reading some of my examples `example/` to get a grip on how
+/// to use the font atlas. There are a number of details I left out. For example
+/// how to merge fonts, configure a font with `nk_font_config` to use other languages,
+/// use another texture coordinate format and a lot more:
+///
+/// ```c
+/// struct nk_font_config cfg = nk_font_config(font_pixel_height);
+/// cfg.merge_mode = nk_false or nk_true;
+/// cfg.range = nk_font_korean_glyph_ranges();
+/// cfg.coord_type = NK_COORD_PIXEL;
+/// nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg);
+/// ```
+*/
+struct nk_user_font_glyph;
+typedef float(*nk_text_width_f)(nk_handle, float h, const char*, int len);
+typedef void(*nk_query_font_glyph_f)(nk_handle handle, float font_height,
+ struct nk_user_font_glyph *glyph,
+ nk_rune codepoint, nk_rune next_codepoint);
+
+#if defined(NK_INCLUDE_VERTEX_BUFFER_OUTPUT) || defined(NK_INCLUDE_SOFTWARE_FONT)
+struct nk_user_font_glyph {
+ struct nk_vec2 uv[2];
+ /* texture coordinates */
+ struct nk_vec2 offset;
+ /* offset between top left and glyph */
+ float width, height;
+ /* size of the glyph */
+ float xadvance;
+ /* offset to the next glyph */
+};
+#endif
+
+struct nk_user_font {
+ nk_handle userdata;
+ /* user provided font handle */
+ float height;
+ /* max height of the font */
+ nk_text_width_f width;
+ /* font string width in pixel callback */
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+ nk_query_font_glyph_f query;
+ /* font glyph callback to query drawing info */
+ nk_handle texture;
+ /* texture handle to the used font atlas or texture */
+#endif
+};
+
+#ifdef NK_INCLUDE_FONT_BAKING
+enum nk_font_coord_type {
+ NK_COORD_UV, /* texture coordinates inside font glyphs are clamped between 0-1 */
+ NK_COORD_PIXEL /* texture coordinates inside font glyphs are in absolute pixel */
+};
+
+struct nk_font;
+struct nk_baked_font {
+ float height;
+ /* height of the font */
+ float ascent, descent;
+ /* font glyphs ascent and descent */
+ nk_rune glyph_offset;
+ /* glyph array offset inside the font glyph baking output array */
+ nk_rune glyph_count;
+ /* number of glyphs of this font inside the glyph baking array output */
+ const nk_rune *ranges;
+ /* font codepoint ranges as pairs of (from/to) and 0 as last element */
+};
+
+struct nk_font_config {
+ struct nk_font_config *next;
+ /* NOTE: only used internally */
+ void *ttf_blob;
+ /* pointer to loaded TTF file memory block.
+ * NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */
+ nk_size ttf_size;
+ /* size of the loaded TTF file memory block
+ * NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */
+
+ unsigned char ttf_data_owned_by_atlas;
+ /* used inside font atlas: default to: 0*/
+ unsigned char merge_mode;
+ /* merges this font into the last font */
+ unsigned char pixel_snap;
+ /* align every character to pixel boundary (if true set oversample (1,1)) */
+ unsigned char oversample_v, oversample_h;
+ /* rasterize at high quality for sub-pixel position */
+ unsigned char padding[3];
+
+ float size;
+ /* baked pixel height of the font */
+ enum nk_font_coord_type coord_type;
+ /* texture coordinate format with either pixel or UV coordinates */
+ struct nk_vec2 spacing;
+ /* extra pixel spacing between glyphs */
+ const nk_rune *range;
+ /* list of unicode ranges (2 values per range, zero terminated) */
+ struct nk_baked_font *font;
+ /* font to setup in the baking process: NOTE: not needed for font atlas */
+ nk_rune fallback_glyph;
+ /* fallback glyph to use if a given rune is not found */
+ struct nk_font_config *n;
+ struct nk_font_config *p;
+};
+
+struct nk_font_glyph {
+ nk_rune codepoint;
+ float xadvance;
+ float x0, y0, x1, y1, w, h;
+ float u0, v0, u1, v1;
+};
+
+struct nk_font {
+ struct nk_font *next;
+ struct nk_user_font handle;
+ struct nk_baked_font info;
+ float scale;
+ struct nk_font_glyph *glyphs;
+ const struct nk_font_glyph *fallback;
+ nk_rune fallback_codepoint;
+ nk_handle texture;
+ struct nk_font_config *config;
+};
+
+enum nk_font_atlas_format {
+ NK_FONT_ATLAS_ALPHA8,
+ NK_FONT_ATLAS_RGBA32
+};
+
+struct nk_font_atlas {
+ void *pixel;
+ int tex_width;
+ int tex_height;
+
+ struct nk_allocator permanent;
+ struct nk_allocator temporary;
+
+ struct nk_recti custom;
+ struct nk_cursor cursors[NK_CURSOR_COUNT];
+
+ int glyph_count;
+ struct nk_font_glyph *glyphs;
+ struct nk_font *default_font;
+ struct nk_font *fonts;
+ struct nk_font_config *config;
+ int font_num;
+};
+
+/* some language glyph codepoint ranges */
+NK_API const nk_rune *nk_font_default_glyph_ranges(void);
+NK_API const nk_rune *nk_font_chinese_glyph_ranges(void);
+NK_API const nk_rune *nk_font_cyrillic_glyph_ranges(void);
+NK_API const nk_rune *nk_font_korean_glyph_ranges(void);
+
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void nk_font_atlas_init_default(struct nk_font_atlas*);
+#endif
+NK_API void nk_font_atlas_init(struct nk_font_atlas*, struct nk_allocator*);
+NK_API void nk_font_atlas_init_custom(struct nk_font_atlas*, struct nk_allocator *persistent, struct nk_allocator *transient);
+NK_API void nk_font_atlas_begin(struct nk_font_atlas*);
+NK_API struct nk_font_config nk_font_config(float pixel_height);
+NK_API struct nk_font *nk_font_atlas_add(struct nk_font_atlas*, const struct nk_font_config*);
+#ifdef NK_INCLUDE_DEFAULT_FONT
+NK_API struct nk_font* nk_font_atlas_add_default(struct nk_font_atlas*, float height, const struct nk_font_config*);
+#endif
+NK_API struct nk_font* nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory, nk_size size, float height, const struct nk_font_config *config);
+#ifdef NK_INCLUDE_STANDARD_IO
+NK_API struct nk_font* nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path, float height, const struct nk_font_config*);
+#endif
+NK_API struct nk_font *nk_font_atlas_add_compressed(struct nk_font_atlas*, void *memory, nk_size size, float height, const struct nk_font_config*);
+NK_API struct nk_font* nk_font_atlas_add_compressed_base85(struct nk_font_atlas*, const char *data, float height, const struct nk_font_config *config);
+NK_API const void* nk_font_atlas_bake(struct nk_font_atlas*, int *width, int *height, enum nk_font_atlas_format);
+NK_API void nk_font_atlas_end(struct nk_font_atlas*, nk_handle tex, struct nk_draw_null_texture*);
+NK_API const struct nk_font_glyph* nk_font_find_glyph(struct nk_font*, nk_rune unicode);
+NK_API void nk_font_atlas_cleanup(struct nk_font_atlas *atlas);
+NK_API void nk_font_atlas_clear(struct nk_font_atlas*);
+
+#endif
+
+/* ==============================================================
+ *
+ * MEMORY BUFFER
+ *
+ * ===============================================================*/
+/*/// ### Memory Buffer
+/// A basic (double)-buffer with linear allocation and resetting as only
+/// freeing policy. The buffer's main purpose is to control all memory management
+/// inside the GUI toolkit and still leave memory control as much as possible in
+/// the hand of the user while also making sure the library is easy to use if
+/// not as much control is needed.
+/// In general all memory inside this library can be provided from the user in
+/// three different ways.
+///
+/// The first way and the one providing most control is by just passing a fixed
+/// size memory block. In this case all control lies in the hand of the user
+/// since he can exactly control where the memory comes from and how much memory
+/// the library should consume. Of course using the fixed size API removes the
+/// ability to automatically resize a buffer if not enough memory is provided so
+/// you have to take over the resizing. While being a fixed sized buffer sounds
+/// quite limiting, it is very effective in this library since the actual memory
+/// consumption is quite stable and has a fixed upper bound for a lot of cases.
+///
+/// If you don't want to think about how much memory the library should allocate
+/// at all time or have a very dynamic UI with unpredictable memory consumption
+/// habits but still want control over memory allocation you can use the dynamic
+/// allocator based API. The allocator consists of two callbacks for allocating
+/// and freeing memory and optional userdata so you can plugin your own allocator.
+///
+/// The final and easiest way can be used by defining
+/// NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory
+/// allocation functions malloc and free and takes over complete control over
+/// memory in this library.
+*/
+struct nk_memory_status {
+ void *memory;
+ unsigned int type;
+ nk_size size;
+ nk_size allocated;
+ nk_size needed;
+ nk_size calls;
+};
+
+enum nk_allocation_type {
+ NK_BUFFER_FIXED,
+ NK_BUFFER_DYNAMIC
+};
+
+enum nk_buffer_allocation_type {
+ NK_BUFFER_FRONT,
+ NK_BUFFER_BACK,
+ NK_BUFFER_MAX
+};
+
+struct nk_buffer_marker {
+ nk_bool active;
+ nk_size offset;
+};
+
+struct nk_memory {void *ptr;nk_size size;};
+struct nk_buffer {
+ struct nk_buffer_marker marker[NK_BUFFER_MAX];
+ /* buffer marker to free a buffer to a certain offset */
+ struct nk_allocator pool;
+ /* allocator callback for dynamic buffers */
+ enum nk_allocation_type type;
+ /* memory management type */
+ struct nk_memory memory;
+ /* memory and size of the current memory block */
+ float grow_factor;
+ /* growing factor for dynamic memory management */
+ nk_size allocated;
+ /* total amount of memory allocated */
+ nk_size needed;
+ /* totally consumed memory given that enough memory is present */
+ nk_size calls;
+ /* number of allocation calls */
+ nk_size size;
+ /* current size of the buffer */
+};
+
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void nk_buffer_init_default(struct nk_buffer*);
+#endif
+NK_API void nk_buffer_init(struct nk_buffer*, const struct nk_allocator*, nk_size size);
+NK_API void nk_buffer_init_fixed(struct nk_buffer*, void *memory, nk_size size);
+NK_API void nk_buffer_info(struct nk_memory_status*, struct nk_buffer*);
+NK_API void nk_buffer_push(struct nk_buffer*, enum nk_buffer_allocation_type type, const void *memory, nk_size size, nk_size align);
+NK_API void nk_buffer_mark(struct nk_buffer*, enum nk_buffer_allocation_type type);
+NK_API void nk_buffer_reset(struct nk_buffer*, enum nk_buffer_allocation_type type);
+NK_API void nk_buffer_clear(struct nk_buffer*);
+NK_API void nk_buffer_free(struct nk_buffer*);
+NK_API void *nk_buffer_memory(struct nk_buffer*);
+NK_API const void *nk_buffer_memory_const(const struct nk_buffer*);
+NK_API nk_size nk_buffer_total(struct nk_buffer*);
+
+/* ==============================================================
+ *
+ * STRING
+ *
+ * ===============================================================*/
+/* Basic string buffer which is only used in context with the text editor
+ * to manage and manipulate dynamic or fixed size string content. This is _NOT_
+ * the default string handling method. The only instance you should have any contact
+ * with this API is if you interact with an `nk_text_edit` object inside one of the
+ * copy and paste functions and even there only for more advanced cases. */
+struct nk_str {
+ struct nk_buffer buffer;
+ int len; /* in codepoints/runes/glyphs */
+};
+
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void nk_str_init_default(struct nk_str*);
+#endif
+NK_API void nk_str_init(struct nk_str*, const struct nk_allocator*, nk_size size);
+NK_API void nk_str_init_fixed(struct nk_str*, void *memory, nk_size size);
+NK_API void nk_str_clear(struct nk_str*);
+NK_API void nk_str_free(struct nk_str*);
+
+NK_API int nk_str_append_text_char(struct nk_str*, const char*, int);
+NK_API int nk_str_append_str_char(struct nk_str*, const char*);
+NK_API int nk_str_append_text_utf8(struct nk_str*, const char*, int);
+NK_API int nk_str_append_str_utf8(struct nk_str*, const char*);
+NK_API int nk_str_append_text_runes(struct nk_str*, const nk_rune*, int);
+NK_API int nk_str_append_str_runes(struct nk_str*, const nk_rune*);
+
+NK_API int nk_str_insert_at_char(struct nk_str*, int pos, const char*, int);
+NK_API int nk_str_insert_at_rune(struct nk_str*, int pos, const char*, int);
+
+NK_API int nk_str_insert_text_char(struct nk_str*, int pos, const char*, int);
+NK_API int nk_str_insert_str_char(struct nk_str*, int pos, const char*);
+NK_API int nk_str_insert_text_utf8(struct nk_str*, int pos, const char*, int);
+NK_API int nk_str_insert_str_utf8(struct nk_str*, int pos, const char*);
+NK_API int nk_str_insert_text_runes(struct nk_str*, int pos, const nk_rune*, int);
+NK_API int nk_str_insert_str_runes(struct nk_str*, int pos, const nk_rune*);
+
+NK_API void nk_str_remove_chars(struct nk_str*, int len);
+NK_API void nk_str_remove_runes(struct nk_str *str, int len);
+NK_API void nk_str_delete_chars(struct nk_str*, int pos, int len);
+NK_API void nk_str_delete_runes(struct nk_str*, int pos, int len);
+
+NK_API char *nk_str_at_char(struct nk_str*, int pos);
+NK_API char *nk_str_at_rune(struct nk_str*, int pos, nk_rune *unicode, int *len);
+NK_API nk_rune nk_str_rune_at(const struct nk_str*, int pos);
+NK_API const char *nk_str_at_char_const(const struct nk_str*, int pos);
+NK_API const char *nk_str_at_const(const struct nk_str*, int pos, nk_rune *unicode, int *len);
+
+NK_API char *nk_str_get(struct nk_str*);
+NK_API const char *nk_str_get_const(const struct nk_str*);
+NK_API int nk_str_len(struct nk_str*);
+NK_API int nk_str_len_char(struct nk_str*);
+
+/*===============================================================
+ *
+ * TEXT EDITOR
+ *
+ * ===============================================================*/
+/*/// ### Text Editor
+/// Editing text in this library is handled by either `nk_edit_string` or
+/// `nk_edit_buffer`. But like almost everything in this library there are multiple
+/// ways of doing it and a balance between control and ease of use with memory
+/// as well as functionality controlled by flags.
+///
+/// This library generally allows three different levels of memory control:
+/// First of is the most basic way of just providing a simple char array with
+/// string length. This method is probably the easiest way of handling simple
+/// user text input. Main upside is complete control over memory while the biggest
+/// downside in comparison with the other two approaches is missing undo/redo.
+///
+/// For UIs that require undo/redo the second way was created. It is based on
+/// a fixed size nk_text_edit struct, which has an internal undo/redo stack.
+/// This is mainly useful if you want something more like a text editor but don't want
+/// to have a dynamically growing buffer.
+///
+/// The final way is using a dynamically growing nk_text_edit struct, which
+/// has both a default version if you don't care where memory comes from and an
+/// allocator version if you do. While the text editor is quite powerful for its
+/// complexity I would not recommend editing gigabytes of data with it.
+/// It is rather designed for uses cases which make sense for a GUI library not for
+/// an full blown text editor.
+ */
+#ifndef NK_TEXTEDIT_UNDOSTATECOUNT
+#define NK_TEXTEDIT_UNDOSTATECOUNT 99
+#endif
+
+#ifndef NK_TEXTEDIT_UNDOCHARCOUNT
+#define NK_TEXTEDIT_UNDOCHARCOUNT 999
+#endif
+
+struct nk_text_edit;
+struct nk_clipboard {
+ nk_handle userdata;
+ nk_plugin_paste paste;
+ nk_plugin_copy copy;
+};
+
+struct nk_text_undo_record {
+ int where;
+ short insert_length;
+ short delete_length;
+ short char_storage;
+};
+
+struct nk_text_undo_state {
+ struct nk_text_undo_record undo_rec[NK_TEXTEDIT_UNDOSTATECOUNT];
+ nk_rune undo_char[NK_TEXTEDIT_UNDOCHARCOUNT];
+ short undo_point;
+ short redo_point;
+ short undo_char_point;
+ short redo_char_point;
+};
+
+enum nk_text_edit_type {
+ NK_TEXT_EDIT_SINGLE_LINE,
+ NK_TEXT_EDIT_MULTI_LINE
+};
+
+enum nk_text_edit_mode {
+ NK_TEXT_EDIT_MODE_VIEW,
+ NK_TEXT_EDIT_MODE_INSERT,
+ NK_TEXT_EDIT_MODE_REPLACE
+};
+
+struct nk_text_edit {
+ struct nk_clipboard clip;
+ struct nk_str string;
+ nk_plugin_filter filter;
+ struct nk_vec2 scrollbar;
+
+ int cursor;
+ int select_start;
+ int select_end;
+ unsigned char mode;
+ unsigned char cursor_at_end_of_line;
+ unsigned char initialized;
+ unsigned char has_preferred_x;
+ unsigned char single_line;
+ unsigned char active;
+ unsigned char padding1;
+ float preferred_x;
+ struct nk_text_undo_state undo;
+};
+
+/* filter function */
+NK_API nk_bool nk_filter_default(const struct nk_text_edit*, nk_rune unicode);
+NK_API nk_bool nk_filter_ascii(const struct nk_text_edit*, nk_rune unicode);
+NK_API nk_bool nk_filter_float(const struct nk_text_edit*, nk_rune unicode);
+NK_API nk_bool nk_filter_decimal(const struct nk_text_edit*, nk_rune unicode);
+NK_API nk_bool nk_filter_hex(const struct nk_text_edit*, nk_rune unicode);
+NK_API nk_bool nk_filter_oct(const struct nk_text_edit*, nk_rune unicode);
+NK_API nk_bool nk_filter_binary(const struct nk_text_edit*, nk_rune unicode);
+
+/* text editor */
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void nk_textedit_init_default(struct nk_text_edit*);
+#endif
+NK_API void nk_textedit_init(struct nk_text_edit*, struct nk_allocator*, nk_size size);
+NK_API void nk_textedit_init_fixed(struct nk_text_edit*, void *memory, nk_size size);
+NK_API void nk_textedit_free(struct nk_text_edit*);
+NK_API void nk_textedit_text(struct nk_text_edit*, const char*, int total_len);
+NK_API void nk_textedit_delete(struct nk_text_edit*, int where, int len);
+NK_API void nk_textedit_delete_selection(struct nk_text_edit*);
+NK_API void nk_textedit_select_all(struct nk_text_edit*);
+NK_API nk_bool nk_textedit_cut(struct nk_text_edit*);
+NK_API nk_bool nk_textedit_paste(struct nk_text_edit*, char const*, int len);
+NK_API void nk_textedit_undo(struct nk_text_edit*);
+NK_API void nk_textedit_redo(struct nk_text_edit*);
+
+/* ===============================================================
+ *
+ * DRAWING
+ *
+ * ===============================================================*/
+/*/// ### Drawing
+/// This library was designed to be render backend agnostic so it does
+/// not draw anything to screen. Instead all drawn shapes, widgets
+/// are made of, are buffered into memory and make up a command queue.
+/// Each frame therefore fills the command buffer with draw commands
+/// that then need to be executed by the user and his own render backend.
+/// After that the command buffer needs to be cleared and a new frame can be
+/// started. It is probably important to note that the command buffer is the main
+/// drawing API and the optional vertex buffer API only takes this format and
+/// converts it into a hardware accessible format.
+///
+/// To use the command queue to draw your own widgets you can access the
+/// command buffer of each window by calling `nk_window_get_canvas` after
+/// previously having called `nk_begin`:
+///
+/// ```c
+/// void draw_red_rectangle_widget(struct nk_context *ctx)
+/// {
+/// struct nk_command_buffer *canvas;
+/// struct nk_input *input = &ctx->input;
+/// canvas = nk_window_get_canvas(ctx);
+///
+/// struct nk_rect space;
+/// enum nk_widget_layout_states state;
+/// state = nk_widget(&space, ctx);
+/// if (!state) return;
+///
+/// if (state != NK_WIDGET_ROM)
+/// update_your_widget_by_user_input(...);
+/// nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0));
+/// }
+///
+/// if (nk_begin(...)) {
+/// nk_layout_row_dynamic(ctx, 25, 1);
+/// draw_red_rectangle_widget(ctx);
+/// }
+/// nk_end(..)
+///
+/// ```
+/// Important to know if you want to create your own widgets is the `nk_widget`
+/// call. It allocates space on the panel reserved for this widget to be used,
+/// but also returns the state of the widget space. If your widget is not seen and does
+/// not have to be updated it is '0' and you can just return. If it only has
+/// to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both
+/// update and draw your widget. The reason for separating is to only draw and
+/// update what is actually necessary which is crucial for performance.
+*/
+enum nk_command_type {
+ NK_COMMAND_NOP,
+ NK_COMMAND_SCISSOR,
+ NK_COMMAND_LINE,
+ NK_COMMAND_CURVE,
+ NK_COMMAND_RECT,
+ NK_COMMAND_RECT_FILLED,
+ NK_COMMAND_RECT_MULTI_COLOR,
+ NK_COMMAND_CIRCLE,
+ NK_COMMAND_CIRCLE_FILLED,
+ NK_COMMAND_ARC,
+ NK_COMMAND_ARC_FILLED,
+ NK_COMMAND_TRIANGLE,
+ NK_COMMAND_TRIANGLE_FILLED,
+ NK_COMMAND_POLYGON,
+ NK_COMMAND_POLYGON_FILLED,
+ NK_COMMAND_POLYLINE,
+ NK_COMMAND_TEXT,
+ NK_COMMAND_IMAGE,
+ NK_COMMAND_CUSTOM
+};
+
+/* command base and header of every command inside the buffer */
+struct nk_command {
+ enum nk_command_type type;
+ nk_size next;
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ nk_handle userdata;
+#endif
+};
+
+struct nk_command_scissor {
+ struct nk_command header;
+ short x, y;
+ unsigned short w, h;
+};
+
+struct nk_command_line {
+ struct nk_command header;
+ unsigned short line_thickness;
+ struct nk_vec2i begin;
+ struct nk_vec2i end;
+ struct nk_color color;
+};
+
+struct nk_command_curve {
+ struct nk_command header;
+ unsigned short line_thickness;
+ struct nk_vec2i begin;
+ struct nk_vec2i end;
+ struct nk_vec2i ctrl[2];
+ struct nk_color color;
+};
+
+struct nk_command_rect {
+ struct nk_command header;
+ unsigned short rounding;
+ unsigned short line_thickness;
+ short x, y;
+ unsigned short w, h;
+ struct nk_color color;
+};
+
+struct nk_command_rect_filled {
+ struct nk_command header;
+ unsigned short rounding;
+ short x, y;
+ unsigned short w, h;
+ struct nk_color color;
+};
+
+struct nk_command_rect_multi_color {
+ struct nk_command header;
+ short x, y;
+ unsigned short w, h;
+ struct nk_color left;
+ struct nk_color top;
+ struct nk_color bottom;
+ struct nk_color right;
+};
+
+struct nk_command_triangle {
+ struct nk_command header;
+ unsigned short line_thickness;
+ struct nk_vec2i a;
+ struct nk_vec2i b;
+ struct nk_vec2i c;
+ struct nk_color color;
+};
+
+struct nk_command_triangle_filled {
+ struct nk_command header;
+ struct nk_vec2i a;
+ struct nk_vec2i b;
+ struct nk_vec2i c;
+ struct nk_color color;
+};
+
+struct nk_command_circle {
+ struct nk_command header;
+ short x, y;
+ unsigned short line_thickness;
+ unsigned short w, h;
+ struct nk_color color;
+};
+
+struct nk_command_circle_filled {
+ struct nk_command header;
+ short x, y;
+ unsigned short w, h;
+ struct nk_color color;
+};
+
+struct nk_command_arc {
+ struct nk_command header;
+ short cx, cy;
+ unsigned short r;
+ unsigned short line_thickness;
+ float a[2];
+ struct nk_color color;
+};
+
+struct nk_command_arc_filled {
+ struct nk_command header;
+ short cx, cy;
+ unsigned short r;
+ float a[2];
+ struct nk_color color;
+};
+
+struct nk_command_polygon {
+ struct nk_command header;
+ struct nk_color color;
+ unsigned short line_thickness;
+ unsigned short point_count;
+ struct nk_vec2i points[1];
+};
+
+struct nk_command_polygon_filled {
+ struct nk_command header;
+ struct nk_color color;
+ unsigned short point_count;
+ struct nk_vec2i points[1];
+};
+
+struct nk_command_polyline {
+ struct nk_command header;
+ struct nk_color color;
+ unsigned short line_thickness;
+ unsigned short point_count;
+ struct nk_vec2i points[1];
+};
+
+struct nk_command_image {
+ struct nk_command header;
+ short x, y;
+ unsigned short w, h;
+ struct nk_image img;
+ struct nk_color col;
+};
+
+typedef void (*nk_command_custom_callback)(void *canvas, short x,short y,
+ unsigned short w, unsigned short h, nk_handle callback_data);
+struct nk_command_custom {
+ struct nk_command header;
+ short x, y;
+ unsigned short w, h;
+ nk_handle callback_data;
+ nk_command_custom_callback callback;
+};
+
+struct nk_command_text {
+ struct nk_command header;
+ const struct nk_user_font *font;
+ struct nk_color background;
+ struct nk_color foreground;
+ short x, y;
+ unsigned short w, h;
+ float height;
+ int length;
+ char string[1];
+};
+
+enum nk_command_clipping {
+ NK_CLIPPING_OFF = nk_false,
+ NK_CLIPPING_ON = nk_true
+};
+
+struct nk_command_buffer {
+ struct nk_buffer *base;
+ struct nk_rect clip;
+ int use_clipping;
+ nk_handle userdata;
+ nk_size begin, end, last;
+};
+
+/* shape outlines */
+NK_API void nk_stroke_line(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float line_thickness, struct nk_color);
+NK_API void nk_stroke_curve(struct nk_command_buffer*, float, float, float, float, float, float, float, float, float line_thickness, struct nk_color);
+NK_API void nk_stroke_rect(struct nk_command_buffer*, struct nk_rect, float rounding, float line_thickness, struct nk_color);
+NK_API void nk_stroke_circle(struct nk_command_buffer*, struct nk_rect, float line_thickness, struct nk_color);
+NK_API void nk_stroke_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, float line_thickness, struct nk_color);
+NK_API void nk_stroke_triangle(struct nk_command_buffer*, float, float, float, float, float, float, float line_thichness, struct nk_color);
+NK_API void nk_stroke_polyline(struct nk_command_buffer*, float *points, int point_count, float line_thickness, struct nk_color col);
+NK_API void nk_stroke_polygon(struct nk_command_buffer*, float*, int point_count, float line_thickness, struct nk_color);
+
+/* filled shades */
+NK_API void nk_fill_rect(struct nk_command_buffer*, struct nk_rect, float rounding, struct nk_color);
+NK_API void nk_fill_rect_multi_color(struct nk_command_buffer*, struct nk_rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom);
+NK_API void nk_fill_circle(struct nk_command_buffer*, struct nk_rect, struct nk_color);
+NK_API void nk_fill_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, struct nk_color);
+NK_API void nk_fill_triangle(struct nk_command_buffer*, float x0, float y0, float x1, float y1, float x2, float y2, struct nk_color);
+NK_API void nk_fill_polygon(struct nk_command_buffer*, float*, int point_count, struct nk_color);
+
+/* misc */
+NK_API void nk_draw_image(struct nk_command_buffer*, struct nk_rect, const struct nk_image*, struct nk_color);
+NK_API void nk_draw_nine_slice(struct nk_command_buffer*, struct nk_rect, const struct nk_nine_slice*, struct nk_color);
+NK_API void nk_draw_text(struct nk_command_buffer*, struct nk_rect, const char *text, int len, const struct nk_user_font*, struct nk_color, struct nk_color);
+NK_API void nk_push_scissor(struct nk_command_buffer*, struct nk_rect);
+NK_API void nk_push_custom(struct nk_command_buffer*, struct nk_rect, nk_command_custom_callback, nk_handle usr);
+
+/* ===============================================================
+ *
+ * INPUT
+ *
+ * ===============================================================*/
+struct nk_mouse_button {
+ nk_bool down;
+ unsigned int clicked;
+ struct nk_vec2 clicked_pos;
+};
+struct nk_mouse {
+ struct nk_mouse_button buttons[NK_BUTTON_MAX];
+ struct nk_vec2 pos;
+#ifdef NK_BUTTON_TRIGGER_ON_RELEASE
+ struct nk_vec2 down_pos;
+#endif
+ struct nk_vec2 prev;
+ struct nk_vec2 delta;
+ struct nk_vec2 scroll_delta;
+ unsigned char grab;
+ unsigned char grabbed;
+ unsigned char ungrab;
+};
+
+struct nk_key {
+ nk_bool down;
+ unsigned int clicked;
+};
+struct nk_keyboard {
+ struct nk_key keys[NK_KEY_MAX];
+ char text[NK_INPUT_MAX];
+ int text_len;
+};
+
+struct nk_input {
+ struct nk_keyboard keyboard;
+ struct nk_mouse mouse;
+};
+
+NK_API nk_bool nk_input_has_mouse_click(const struct nk_input*, enum nk_buttons);
+NK_API nk_bool nk_input_has_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect);
+NK_API nk_bool nk_input_has_mouse_click_in_button_rect(const struct nk_input*, enum nk_buttons, struct nk_rect);
+NK_API nk_bool nk_input_has_mouse_click_down_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect, nk_bool down);
+NK_API nk_bool nk_input_is_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect);
+NK_API nk_bool nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b, nk_bool down);
+NK_API nk_bool nk_input_any_mouse_click_in_rect(const struct nk_input*, struct nk_rect);
+NK_API nk_bool nk_input_is_mouse_prev_hovering_rect(const struct nk_input*, struct nk_rect);
+NK_API nk_bool nk_input_is_mouse_hovering_rect(const struct nk_input*, struct nk_rect);
+NK_API nk_bool nk_input_mouse_clicked(const struct nk_input*, enum nk_buttons, struct nk_rect);
+NK_API nk_bool nk_input_is_mouse_down(const struct nk_input*, enum nk_buttons);
+NK_API nk_bool nk_input_is_mouse_pressed(const struct nk_input*, enum nk_buttons);
+NK_API nk_bool nk_input_is_mouse_released(const struct nk_input*, enum nk_buttons);
+NK_API nk_bool nk_input_is_key_pressed(const struct nk_input*, enum nk_keys);
+NK_API nk_bool nk_input_is_key_released(const struct nk_input*, enum nk_keys);
+NK_API nk_bool nk_input_is_key_down(const struct nk_input*, enum nk_keys);
+
+/* ===============================================================
+ *
+ * DRAW LIST
+ *
+ * ===============================================================*/
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+/* ### Draw List
+/// The optional vertex buffer draw list provides a 2D drawing context
+/// with antialiasing functionality which takes basic filled or outlined shapes
+/// or a path and outputs vertexes, elements and draw commands.
+/// The actual draw list API is not required to be used directly while using this
+/// library since converting the default library draw command output is done by
+/// just calling `nk_convert` but I decided to still make this library accessible
+/// since it can be useful.
+///
+/// The draw list is based on a path buffering and polygon and polyline
+/// rendering API which allows a lot of ways to draw 2D content to screen.
+/// In fact it is probably more powerful than needed but allows even more crazy
+/// things than this library provides by default.
+*/
+#ifdef NK_UINT_DRAW_INDEX
+typedef nk_uint nk_draw_index;
+#else
+typedef nk_ushort nk_draw_index;
+#endif
+enum nk_draw_list_stroke {
+ NK_STROKE_OPEN = nk_false,
+ /* build up path has no connection back to the beginning */
+ NK_STROKE_CLOSED = nk_true
+ /* build up path has a connection back to the beginning */
+};
+
+enum nk_draw_vertex_layout_attribute {
+ NK_VERTEX_POSITION,
+ NK_VERTEX_COLOR,
+ NK_VERTEX_TEXCOORD,
+ NK_VERTEX_ATTRIBUTE_COUNT
+};
+
+enum nk_draw_vertex_layout_format {
+ NK_FORMAT_SCHAR,
+ NK_FORMAT_SSHORT,
+ NK_FORMAT_SINT,
+ NK_FORMAT_UCHAR,
+ NK_FORMAT_USHORT,
+ NK_FORMAT_UINT,
+ NK_FORMAT_FLOAT,
+ NK_FORMAT_DOUBLE,
+
+NK_FORMAT_COLOR_BEGIN,
+ NK_FORMAT_R8G8B8 = NK_FORMAT_COLOR_BEGIN,
+ NK_FORMAT_R16G15B16,
+ NK_FORMAT_R32G32B32,
+
+ NK_FORMAT_R8G8B8A8,
+ NK_FORMAT_B8G8R8A8,
+ NK_FORMAT_R16G15B16A16,
+ NK_FORMAT_R32G32B32A32,
+ NK_FORMAT_R32G32B32A32_FLOAT,
+ NK_FORMAT_R32G32B32A32_DOUBLE,
+
+ NK_FORMAT_RGB32,
+ NK_FORMAT_RGBA32,
+NK_FORMAT_COLOR_END = NK_FORMAT_RGBA32,
+ NK_FORMAT_COUNT
+};
+
+#define NK_VERTEX_LAYOUT_END NK_VERTEX_ATTRIBUTE_COUNT,NK_FORMAT_COUNT,0
+struct nk_draw_vertex_layout_element {
+ enum nk_draw_vertex_layout_attribute attribute;
+ enum nk_draw_vertex_layout_format format;
+ nk_size offset;
+};
+
+struct nk_draw_command {
+ unsigned int elem_count;
+ /* number of elements in the current draw batch */
+ struct nk_rect clip_rect;
+ /* current screen clipping rectangle */
+ nk_handle texture;
+ /* current texture to set */
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ nk_handle userdata;
+#endif
+};
+
+struct nk_draw_list {
+ struct nk_rect clip_rect;
+ struct nk_vec2 circle_vtx[12];
+ struct nk_convert_config config;
+
+ struct nk_buffer *buffer;
+ struct nk_buffer *vertices;
+ struct nk_buffer *elements;
+
+ unsigned int element_count;
+ unsigned int vertex_count;
+ unsigned int cmd_count;
+ nk_size cmd_offset;
+
+ unsigned int path_count;
+ unsigned int path_offset;
+
+ enum nk_anti_aliasing line_AA;
+ enum nk_anti_aliasing shape_AA;
+
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ nk_handle userdata;
+#endif
+};
+
+/* draw list */
+NK_API void nk_draw_list_init(struct nk_draw_list*);
+NK_API void nk_draw_list_setup(struct nk_draw_list*, const struct nk_convert_config*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, enum nk_anti_aliasing line_aa,enum nk_anti_aliasing shape_aa);
+
+/* drawing */
+#define nk_draw_list_foreach(cmd, can, b) for((cmd)=nk__draw_list_begin(can, b); (cmd)!=0; (cmd)=nk__draw_list_next(cmd, b, can))
+NK_API const struct nk_draw_command* nk__draw_list_begin(const struct nk_draw_list*, const struct nk_buffer*);
+NK_API const struct nk_draw_command* nk__draw_list_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_draw_list*);
+NK_API const struct nk_draw_command* nk__draw_list_end(const struct nk_draw_list*, const struct nk_buffer*);
+
+/* path */
+NK_API void nk_draw_list_path_clear(struct nk_draw_list*);
+NK_API void nk_draw_list_path_line_to(struct nk_draw_list*, struct nk_vec2 pos);
+NK_API void nk_draw_list_path_arc_to_fast(struct nk_draw_list*, struct nk_vec2 center, float radius, int a_min, int a_max);
+NK_API void nk_draw_list_path_arc_to(struct nk_draw_list*, struct nk_vec2 center, float radius, float a_min, float a_max, unsigned int segments);
+NK_API void nk_draw_list_path_rect_to(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, float rounding);
+NK_API void nk_draw_list_path_curve_to(struct nk_draw_list*, struct nk_vec2 p2, struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments);
+NK_API void nk_draw_list_path_fill(struct nk_draw_list*, struct nk_color);
+NK_API void nk_draw_list_path_stroke(struct nk_draw_list*, struct nk_color, enum nk_draw_list_stroke closed, float thickness);
+
+/* stroke */
+NK_API void nk_draw_list_stroke_line(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_color, float thickness);
+NK_API void nk_draw_list_stroke_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding, float thickness);
+NK_API void nk_draw_list_stroke_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color, float thickness);
+NK_API void nk_draw_list_stroke_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color, unsigned int segs, float thickness);
+NK_API void nk_draw_list_stroke_curve(struct nk_draw_list*, struct nk_vec2 p0, struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1, struct nk_color, unsigned int segments, float thickness);
+NK_API void nk_draw_list_stroke_poly_line(struct nk_draw_list*, const struct nk_vec2 *pnts, const unsigned int cnt, struct nk_color, enum nk_draw_list_stroke, float thickness, enum nk_anti_aliasing);
+
+/* fill */
+NK_API void nk_draw_list_fill_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding);
+NK_API void nk_draw_list_fill_rect_multi_color(struct nk_draw_list*, struct nk_rect rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom);
+NK_API void nk_draw_list_fill_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color);
+NK_API void nk_draw_list_fill_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color col, unsigned int segs);
+NK_API void nk_draw_list_fill_poly_convex(struct nk_draw_list*, const struct nk_vec2 *points, const unsigned int count, struct nk_color, enum nk_anti_aliasing);
+
+/* misc */
+NK_API void nk_draw_list_add_image(struct nk_draw_list*, struct nk_image texture, struct nk_rect rect, struct nk_color);
+NK_API void nk_draw_list_add_text(struct nk_draw_list*, const struct nk_user_font*, struct nk_rect, const char *text, int len, float font_height, struct nk_color);
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+NK_API void nk_draw_list_push_userdata(struct nk_draw_list*, nk_handle userdata);
+#endif
+
+#endif
+
+/* ===============================================================
+ *
+ * GUI
+ *
+ * ===============================================================*/
+enum nk_style_item_type {
+ NK_STYLE_ITEM_COLOR,
+ NK_STYLE_ITEM_IMAGE,
+ NK_STYLE_ITEM_NINE_SLICE
+};
+
+union nk_style_item_data {
+ struct nk_color color;
+ struct nk_image image;
+ struct nk_nine_slice slice;
+};
+
+struct nk_style_item {
+ enum nk_style_item_type type;
+ union nk_style_item_data data;
+};
+
+struct nk_style_text {
+ struct nk_color color;
+ struct nk_vec2 padding;
+ float color_factor;
+ float disabled_factor;
+};
+
+struct nk_style_button {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+ float color_factor_background;
+
+ /* text */
+ struct nk_color text_background;
+ struct nk_color text_normal;
+ struct nk_color text_hover;
+ struct nk_color text_active;
+ nk_flags text_alignment;
+ float color_factor_text;
+
+ /* properties */
+ float border;
+ float rounding;
+ struct nk_vec2 padding;
+ struct nk_vec2 image_padding;
+ struct nk_vec2 touch_padding;
+ float disabled_factor;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle userdata);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle userdata);
+};
+
+struct nk_style_toggle {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+
+ /* cursor */
+ struct nk_style_item cursor_normal;
+ struct nk_style_item cursor_hover;
+
+ /* text */
+ struct nk_color text_normal;
+ struct nk_color text_hover;
+ struct nk_color text_active;
+ struct nk_color text_background;
+ nk_flags text_alignment;
+
+ /* properties */
+ struct nk_vec2 padding;
+ struct nk_vec2 touch_padding;
+ float spacing;
+ float border;
+ float color_factor;
+ float disabled_factor;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle);
+};
+
+struct nk_style_selectable {
+ /* background (inactive) */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item pressed;
+
+ /* background (active) */
+ struct nk_style_item normal_active;
+ struct nk_style_item hover_active;
+ struct nk_style_item pressed_active;
+
+ /* text color (inactive) */
+ struct nk_color text_normal;
+ struct nk_color text_hover;
+ struct nk_color text_pressed;
+
+ /* text color (active) */
+ struct nk_color text_normal_active;
+ struct nk_color text_hover_active;
+ struct nk_color text_pressed_active;
+ struct nk_color text_background;
+ nk_flags text_alignment;
+
+ /* properties */
+ float rounding;
+ struct nk_vec2 padding;
+ struct nk_vec2 touch_padding;
+ struct nk_vec2 image_padding;
+ float color_factor;
+ float disabled_factor;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle);
+};
+
+struct nk_style_slider {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+
+ /* background bar */
+ struct nk_color bar_normal;
+ struct nk_color bar_hover;
+ struct nk_color bar_active;
+ struct nk_color bar_filled;
+
+ /* cursor */
+ struct nk_style_item cursor_normal;
+ struct nk_style_item cursor_hover;
+ struct nk_style_item cursor_active;
+
+ /* properties */
+ float border;
+ float rounding;
+ float bar_height;
+ struct nk_vec2 padding;
+ struct nk_vec2 spacing;
+ struct nk_vec2 cursor_size;
+ float color_factor;
+ float disabled_factor;
+
+ /* optional buttons */
+ int show_buttons;
+ struct nk_style_button inc_button;
+ struct nk_style_button dec_button;
+ enum nk_symbol_type inc_symbol;
+ enum nk_symbol_type dec_symbol;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle);
+};
+
+struct nk_style_progress {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+
+ /* cursor */
+ struct nk_style_item cursor_normal;
+ struct nk_style_item cursor_hover;
+ struct nk_style_item cursor_active;
+ struct nk_color cursor_border_color;
+
+ /* properties */
+ float rounding;
+ float border;
+ float cursor_border;
+ float cursor_rounding;
+ struct nk_vec2 padding;
+ float color_factor;
+ float disabled_factor;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle);
+};
+
+struct nk_style_scrollbar {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+
+ /* cursor */
+ struct nk_style_item cursor_normal;
+ struct nk_style_item cursor_hover;
+ struct nk_style_item cursor_active;
+ struct nk_color cursor_border_color;
+
+ /* properties */
+ float border;
+ float rounding;
+ float border_cursor;
+ float rounding_cursor;
+ struct nk_vec2 padding;
+ float color_factor;
+ float disabled_factor;
+
+ /* optional buttons */
+ int show_buttons;
+ struct nk_style_button inc_button;
+ struct nk_style_button dec_button;
+ enum nk_symbol_type inc_symbol;
+ enum nk_symbol_type dec_symbol;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle);
+};
+
+struct nk_style_edit {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+ struct nk_style_scrollbar scrollbar;
+
+ /* cursor */
+ struct nk_color cursor_normal;
+ struct nk_color cursor_hover;
+ struct nk_color cursor_text_normal;
+ struct nk_color cursor_text_hover;
+
+ /* text (unselected) */
+ struct nk_color text_normal;
+ struct nk_color text_hover;
+ struct nk_color text_active;
+
+ /* text (selected) */
+ struct nk_color selected_normal;
+ struct nk_color selected_hover;
+ struct nk_color selected_text_normal;
+ struct nk_color selected_text_hover;
+
+ /* properties */
+ float border;
+ float rounding;
+ float cursor_size;
+ struct nk_vec2 scrollbar_size;
+ struct nk_vec2 padding;
+ float row_padding;
+ float color_factor;
+ float disabled_factor;
+};
+
+struct nk_style_property {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+
+ /* text */
+ struct nk_color label_normal;
+ struct nk_color label_hover;
+ struct nk_color label_active;
+
+ /* symbols */
+ enum nk_symbol_type sym_left;
+ enum nk_symbol_type sym_right;
+
+ /* properties */
+ float border;
+ float rounding;
+ struct nk_vec2 padding;
+ float color_factor;
+ float disabled_factor;
+
+ struct nk_style_edit edit;
+ struct nk_style_button inc_button;
+ struct nk_style_button dec_button;
+
+ /* optional user callbacks */
+ nk_handle userdata;
+ void(*draw_begin)(struct nk_command_buffer*, nk_handle);
+ void(*draw_end)(struct nk_command_buffer*, nk_handle);
+};
+
+struct nk_style_chart {
+ /* colors */
+ struct nk_style_item background;
+ struct nk_color border_color;
+ struct nk_color selected_color;
+ struct nk_color color;
+
+ /* properties */
+ float border;
+ float rounding;
+ struct nk_vec2 padding;
+ float color_factor;
+ float disabled_factor;
+ nk_bool show_markers;
+};
+
+struct nk_style_combo {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+ struct nk_color border_color;
+
+ /* label */
+ struct nk_color label_normal;
+ struct nk_color label_hover;
+ struct nk_color label_active;
+
+ /* symbol */
+ struct nk_color symbol_normal;
+ struct nk_color symbol_hover;
+ struct nk_color symbol_active;
+
+ /* button */
+ struct nk_style_button button;
+ enum nk_symbol_type sym_normal;
+ enum nk_symbol_type sym_hover;
+ enum nk_symbol_type sym_active;
+
+ /* properties */
+ float border;
+ float rounding;
+ struct nk_vec2 content_padding;
+ struct nk_vec2 button_padding;
+ struct nk_vec2 spacing;
+ float color_factor;
+ float disabled_factor;
+};
+
+struct nk_style_tab {
+ /* background */
+ struct nk_style_item background;
+ struct nk_color border_color;
+ struct nk_color text;
+
+ /* button */
+ struct nk_style_button tab_maximize_button;
+ struct nk_style_button tab_minimize_button;
+ struct nk_style_button node_maximize_button;
+ struct nk_style_button node_minimize_button;
+ enum nk_symbol_type sym_minimize;
+ enum nk_symbol_type sym_maximize;
+
+ /* properties */
+ float border;
+ float rounding;
+ float indent;
+ struct nk_vec2 padding;
+ struct nk_vec2 spacing;
+ float color_factor;
+ float disabled_factor;
+};
+
+enum nk_style_header_align {
+ NK_HEADER_LEFT,
+ NK_HEADER_RIGHT
+};
+struct nk_style_window_header {
+ /* background */
+ struct nk_style_item normal;
+ struct nk_style_item hover;
+ struct nk_style_item active;
+
+ /* button */
+ struct nk_style_button close_button;
+ struct nk_style_button minimize_button;
+ enum nk_symbol_type close_symbol;
+ enum nk_symbol_type minimize_symbol;
+ enum nk_symbol_type maximize_symbol;
+
+ /* title */
+ struct nk_color label_normal;
+ struct nk_color label_hover;
+ struct nk_color label_active;
+
+ /* properties */
+ enum nk_style_header_align align;
+ struct nk_vec2 padding;
+ struct nk_vec2 label_padding;
+ struct nk_vec2 spacing;
+};
+
+struct nk_style_window {
+ struct nk_style_window_header header;
+ struct nk_style_item fixed_background;
+ struct nk_color background;
+
+ struct nk_color border_color;
+ struct nk_color popup_border_color;
+ struct nk_color combo_border_color;
+ struct nk_color contextual_border_color;
+ struct nk_color menu_border_color;
+ struct nk_color group_border_color;
+ struct nk_color tooltip_border_color;
+ struct nk_style_item scaler;
+
+ float border;
+ float combo_border;
+ float contextual_border;
+ float menu_border;
+ float group_border;
+ float tooltip_border;
+ float popup_border;
+ float min_row_height_padding;
+
+ float rounding;
+ struct nk_vec2 spacing;
+ struct nk_vec2 scrollbar_size;
+ struct nk_vec2 min_size;
+
+ struct nk_vec2 padding;
+ struct nk_vec2 group_padding;
+ struct nk_vec2 popup_padding;
+ struct nk_vec2 combo_padding;
+ struct nk_vec2 contextual_padding;
+ struct nk_vec2 menu_padding;
+ struct nk_vec2 tooltip_padding;
+};
+
+struct nk_style {
+ const struct nk_user_font *font;
+ const struct nk_cursor *cursors[NK_CURSOR_COUNT];
+ const struct nk_cursor *cursor_active;
+ struct nk_cursor *cursor_last;
+ int cursor_visible;
+
+ struct nk_style_text text;
+ struct nk_style_button button;
+ struct nk_style_button contextual_button;
+ struct nk_style_button menu_button;
+ struct nk_style_toggle option;
+ struct nk_style_toggle checkbox;
+ struct nk_style_selectable selectable;
+ struct nk_style_slider slider;
+ struct nk_style_progress progress;
+ struct nk_style_property property;
+ struct nk_style_edit edit;
+ struct nk_style_chart chart;
+ struct nk_style_scrollbar scrollh;
+ struct nk_style_scrollbar scrollv;
+ struct nk_style_tab tab;
+ struct nk_style_combo combo;
+ struct nk_style_window window;
+};
+
+NK_API struct nk_style_item nk_style_item_color(struct nk_color);
+NK_API struct nk_style_item nk_style_item_image(struct nk_image img);
+NK_API struct nk_style_item nk_style_item_nine_slice(struct nk_nine_slice slice);
+NK_API struct nk_style_item nk_style_item_hide(void);
+
+/*==============================================================
+ * PANEL
+ * =============================================================*/
+#ifndef NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS
+#define NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS 16
+#endif
+#ifndef NK_CHART_MAX_SLOT
+#define NK_CHART_MAX_SLOT 4
+#endif
+
+enum nk_panel_type {
+ NK_PANEL_NONE = 0,
+ NK_PANEL_WINDOW = NK_FLAG(0),
+ NK_PANEL_GROUP = NK_FLAG(1),
+ NK_PANEL_POPUP = NK_FLAG(2),
+ NK_PANEL_CONTEXTUAL = NK_FLAG(4),
+ NK_PANEL_COMBO = NK_FLAG(5),
+ NK_PANEL_MENU = NK_FLAG(6),
+ NK_PANEL_TOOLTIP = NK_FLAG(7)
+};
+enum nk_panel_set {
+ NK_PANEL_SET_NONBLOCK = NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP,
+ NK_PANEL_SET_POPUP = NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP,
+ NK_PANEL_SET_SUB = NK_PANEL_SET_POPUP|NK_PANEL_GROUP
+};
+
+struct nk_chart_slot {
+ enum nk_chart_type type;
+ struct nk_color color;
+ struct nk_color highlight;
+ float min, max, range;
+ int count;
+ struct nk_vec2 last;
+ int index;
+ nk_bool show_markers;
+};
+
+struct nk_chart {
+ int slot;
+ float x, y, w, h;
+ struct nk_chart_slot slots[NK_CHART_MAX_SLOT];
+};
+
+enum nk_panel_row_layout_type {
+ NK_LAYOUT_DYNAMIC_FIXED = 0,
+ NK_LAYOUT_DYNAMIC_ROW,
+ NK_LAYOUT_DYNAMIC_FREE,
+ NK_LAYOUT_DYNAMIC,
+ NK_LAYOUT_STATIC_FIXED,
+ NK_LAYOUT_STATIC_ROW,
+ NK_LAYOUT_STATIC_FREE,
+ NK_LAYOUT_STATIC,
+ NK_LAYOUT_TEMPLATE,
+ NK_LAYOUT_COUNT
+};
+struct nk_row_layout {
+ enum nk_panel_row_layout_type type;
+ int index;
+ float height;
+ float min_height;
+ int columns;
+ const float *ratio;
+ float item_width;
+ float item_height;
+ float item_offset;
+ float filled;
+ struct nk_rect item;
+ int tree_depth;
+ float templates[NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS];
+};
+
+struct nk_popup_buffer {
+ nk_size begin;
+ nk_size parent;
+ nk_size last;
+ nk_size end;
+ nk_bool active;
+};
+
+struct nk_menu_state {
+ float x, y, w, h;
+ struct nk_scroll offset;
+};
+
+struct nk_panel {
+ enum nk_panel_type type;
+ nk_flags flags;
+ struct nk_rect bounds;
+ nk_uint *offset_x;
+ nk_uint *offset_y;
+ float at_x, at_y, max_x;
+ float footer_height;
+ float header_height;
+ float border;
+ unsigned int has_scrolling;
+ struct nk_rect clip;
+ struct nk_menu_state menu;
+ struct nk_row_layout row;
+ struct nk_chart chart;
+ struct nk_command_buffer *buffer;
+ struct nk_panel *parent;
+};
+
+/*==============================================================
+ * WINDOW
+ * =============================================================*/
+#ifndef NK_WINDOW_MAX_NAME
+#define NK_WINDOW_MAX_NAME 64
+#endif
+
+struct nk_table;
+enum nk_window_flags {
+ NK_WINDOW_PRIVATE = NK_FLAG(11),
+ NK_WINDOW_DYNAMIC = NK_WINDOW_PRIVATE,
+ /* special window type growing up in height while being filled to a certain maximum height */
+ NK_WINDOW_ROM = NK_FLAG(12),
+ /* sets window widgets into a read only mode and does not allow input changes */
+ NK_WINDOW_NOT_INTERACTIVE = NK_WINDOW_ROM|NK_WINDOW_NO_INPUT,
+ /* prevents all interaction caused by input to either window or widgets inside */
+ NK_WINDOW_HIDDEN = NK_FLAG(13),
+ /* Hides window and stops any window interaction and drawing */
+ NK_WINDOW_CLOSED = NK_FLAG(14),
+ /* Directly closes and frees the window at the end of the frame */
+ NK_WINDOW_MINIMIZED = NK_FLAG(15),
+ /* marks the window as minimized */
+ NK_WINDOW_REMOVE_ROM = NK_FLAG(16)
+ /* Removes read only mode at the end of the window */
+};
+
+struct nk_popup_state {
+ struct nk_window *win;
+ enum nk_panel_type type;
+ struct nk_popup_buffer buf;
+ nk_hash name;
+ nk_bool active;
+ unsigned combo_count;
+ unsigned con_count, con_old;
+ unsigned active_con;
+ struct nk_rect header;
+};
+
+struct nk_edit_state {
+ nk_hash name;
+ unsigned int seq;
+ unsigned int old;
+ int active, prev;
+ int cursor;
+ int sel_start;
+ int sel_end;
+ struct nk_scroll scrollbar;
+ unsigned char mode;
+ unsigned char single_line;
+};
+
+struct nk_property_state {
+ int active, prev;
+ char buffer[NK_MAX_NUMBER_BUFFER];
+ int length;
+ int cursor;
+ int select_start;
+ int select_end;
+ nk_hash name;
+ unsigned int seq;
+ unsigned int old;
+ int state;
+};
+
+struct nk_window {
+ unsigned int seq;
+ nk_hash name;
+ char name_string[NK_WINDOW_MAX_NAME];
+ nk_flags flags;
+
+ struct nk_rect bounds;
+ struct nk_scroll scrollbar;
+ struct nk_command_buffer buffer;
+ struct nk_panel *layout;
+ float scrollbar_hiding_timer;
+
+ /* persistent widget state */
+ struct nk_property_state property;
+ struct nk_popup_state popup;
+ struct nk_edit_state edit;
+ unsigned int scrolled;
+ nk_bool widgets_disabled;
+
+ struct nk_table *tables;
+ unsigned int table_count;
+
+ /* window list hooks */
+ struct nk_window *next;
+ struct nk_window *prev;
+ struct nk_window *parent;
+};
+
+/*==============================================================
+ * STACK
+ * =============================================================*/
+/*/// ### Stack
+/// The style modifier stack can be used to temporarily change a
+/// property inside `nk_style`. For example if you want a special
+/// red button you can temporarily push the old button color onto a stack
+/// draw the button with a red color and then you just pop the old color
+/// back from the stack:
+///
+/// nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0)));
+/// nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0)));
+/// nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0)));
+/// nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2));
+///
+/// nk_button(...);
+///
+/// nk_style_pop_style_item(ctx);
+/// nk_style_pop_style_item(ctx);
+/// nk_style_pop_style_item(ctx);
+/// nk_style_pop_vec2(ctx);
+///
+/// Nuklear has a stack for style_items, float properties, vector properties,
+/// flags, colors, fonts and for button_behavior. Each has it's own fixed size stack
+/// which can be changed at compile time.
+ */
+#ifndef NK_BUTTON_BEHAVIOR_STACK_SIZE
+#define NK_BUTTON_BEHAVIOR_STACK_SIZE 8
+#endif
+
+#ifndef NK_FONT_STACK_SIZE
+#define NK_FONT_STACK_SIZE 8
+#endif
+
+#ifndef NK_STYLE_ITEM_STACK_SIZE
+#define NK_STYLE_ITEM_STACK_SIZE 16
+#endif
+
+#ifndef NK_FLOAT_STACK_SIZE
+#define NK_FLOAT_STACK_SIZE 32
+#endif
+
+#ifndef NK_VECTOR_STACK_SIZE
+#define NK_VECTOR_STACK_SIZE 16
+#endif
+
+#ifndef NK_FLAGS_STACK_SIZE
+#define NK_FLAGS_STACK_SIZE 32
+#endif
+
+#ifndef NK_COLOR_STACK_SIZE
+#define NK_COLOR_STACK_SIZE 32
+#endif
+
+#define NK_CONFIGURATION_STACK_TYPE(prefix, name, type)\
+ struct nk_config_stack_##name##_element {\
+ prefix##_##type *address;\
+ prefix##_##type old_value;\
+ }
+#define NK_CONFIG_STACK(type,size)\
+ struct nk_config_stack_##type {\
+ int head;\
+ struct nk_config_stack_##type##_element elements[size];\
+ }
+
+#define nk_float float
+NK_CONFIGURATION_STACK_TYPE(struct nk, style_item, style_item);
+NK_CONFIGURATION_STACK_TYPE(nk ,float, float);
+NK_CONFIGURATION_STACK_TYPE(struct nk, vec2, vec2);
+NK_CONFIGURATION_STACK_TYPE(nk ,flags, flags);
+NK_CONFIGURATION_STACK_TYPE(struct nk, color, color);
+NK_CONFIGURATION_STACK_TYPE(const struct nk, user_font, user_font*);
+NK_CONFIGURATION_STACK_TYPE(enum nk, button_behavior, button_behavior);
+
+NK_CONFIG_STACK(style_item, NK_STYLE_ITEM_STACK_SIZE);
+NK_CONFIG_STACK(float, NK_FLOAT_STACK_SIZE);
+NK_CONFIG_STACK(vec2, NK_VECTOR_STACK_SIZE);
+NK_CONFIG_STACK(flags, NK_FLAGS_STACK_SIZE);
+NK_CONFIG_STACK(color, NK_COLOR_STACK_SIZE);
+NK_CONFIG_STACK(user_font, NK_FONT_STACK_SIZE);
+NK_CONFIG_STACK(button_behavior, NK_BUTTON_BEHAVIOR_STACK_SIZE);
+
+struct nk_configuration_stacks {
+ struct nk_config_stack_style_item style_items;
+ struct nk_config_stack_float floats;
+ struct nk_config_stack_vec2 vectors;
+ struct nk_config_stack_flags flags;
+ struct nk_config_stack_color colors;
+ struct nk_config_stack_user_font fonts;
+ struct nk_config_stack_button_behavior button_behaviors;
+};
+
+/*==============================================================
+ * CONTEXT
+ * =============================================================*/
+#define NK_VALUE_PAGE_CAPACITY \
+ (((NK_MAX(sizeof(struct nk_window),sizeof(struct nk_panel)) / sizeof(nk_uint))) / 2)
+
+struct nk_table {
+ unsigned int seq;
+ unsigned int size;
+ nk_hash keys[NK_VALUE_PAGE_CAPACITY];
+ nk_uint values[NK_VALUE_PAGE_CAPACITY];
+ struct nk_table *next, *prev;
+};
+
+union nk_page_data {
+ struct nk_table tbl;
+ struct nk_panel pan;
+ struct nk_window win;
+};
+
+struct nk_page_element {
+ union nk_page_data data;
+ struct nk_page_element *next;
+ struct nk_page_element *prev;
+};
+
+struct nk_page {
+ unsigned int size;
+ struct nk_page *next;
+ struct nk_page_element win[1];
+};
+
+struct nk_pool {
+ struct nk_allocator alloc;
+ enum nk_allocation_type type;
+ unsigned int page_count;
+ struct nk_page *pages;
+ struct nk_page_element *freelist;
+ unsigned capacity;
+ nk_size size;
+ nk_size cap;
+};
+
+struct nk_context {
+/* public: can be accessed freely */
+ struct nk_input input;
+ struct nk_style style;
+ struct nk_buffer memory;
+ struct nk_clipboard clip;
+ nk_flags last_widget_state;
+ enum nk_button_behavior button_behavior;
+ struct nk_configuration_stacks stacks;
+ float delta_time_seconds;
+
+/* private:
+ should only be accessed if you
+ know what you are doing */
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+ struct nk_draw_list draw_list;
+#endif
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ nk_handle userdata;
+#endif
+ /* text editor objects are quite big because of an internal
+ * undo/redo stack. Therefore it does not make sense to have one for
+ * each window for temporary use cases, so I only provide *one* instance
+ * for all windows. This works because the content is cleared anyway */
+ struct nk_text_edit text_edit;
+ /* draw buffer used for overlay drawing operation like cursor */
+ struct nk_command_buffer overlay;
+
+ /* windows */
+ int build;
+ int use_pool;
+ struct nk_pool pool;
+ struct nk_window *begin;
+ struct nk_window *end;
+ struct nk_window *active;
+ struct nk_window *current;
+ struct nk_page_element *freelist;
+ unsigned int count;
+ unsigned int seq;
+};
+
+/* ==============================================================
+ * MATH
+ * =============================================================== */
+#define NK_PI 3.141592654f
+#define NK_UTF_INVALID 0xFFFD
+#define NK_MAX_FLOAT_PRECISION 2
+
+#define NK_UNUSED(x) ((void)(x))
+#define NK_SATURATE(x) (NK_MAX(0, NK_MIN(1.0f, x)))
+#define NK_LEN(a) (sizeof(a)/sizeof(a)[0])
+#define NK_ABS(a) (((a) < 0) ? -(a) : (a))
+#define NK_BETWEEN(x, a, b) ((a) <= (x) && (x) < (b))
+#define NK_INBOX(px, py, x, y, w, h)\
+ (NK_BETWEEN(px,x,x+w) && NK_BETWEEN(py,y,y+h))
+#define NK_INTERSECT(x0, y0, w0, h0, x1, y1, w1, h1) \
+ ((x1 < (x0 + w0)) && (x0 < (x1 + w1)) && \
+ (y1 < (y0 + h0)) && (y0 < (y1 + h1)))
+#define NK_CONTAINS(x, y, w, h, bx, by, bw, bh)\
+ (NK_INBOX(x,y, bx, by, bw, bh) && NK_INBOX(x+w,y+h, bx, by, bw, bh))
+
+#define nk_vec2_sub(a, b) nk_vec2((a).x - (b).x, (a).y - (b).y)
+#define nk_vec2_add(a, b) nk_vec2((a).x + (b).x, (a).y + (b).y)
+#define nk_vec2_len_sqr(a) ((a).x*(a).x+(a).y*(a).y)
+#define nk_vec2_muls(a, t) nk_vec2((a).x * (t), (a).y * (t))
+
+#define nk_ptr_add(t, p, i) ((t*)((void*)((nk_byte*)(p) + (i))))
+#define nk_ptr_add_const(t, p, i) ((const t*)((const void*)((const nk_byte*)(p) + (i))))
+#define nk_zero_struct(s) nk_zero(&s, sizeof(s))
+
+/* ==============================================================
+ * ALIGNMENT
+ * =============================================================== */
+/* Pointer to Integer type conversion for pointer alignment */
+#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC*/
+# define NK_UINT_TO_PTR(x) ((void*)(__PTRDIFF_TYPE__)(x))
+# define NK_PTR_TO_UINT(x) ((nk_size)(__PTRDIFF_TYPE__)(x))
+#elif !defined(__GNUC__) /* works for compilers other than LLVM */
+# define NK_UINT_TO_PTR(x) ((void*)&((char*)0)[x])
+# define NK_PTR_TO_UINT(x) ((nk_size)(((char*)x)-(char*)0))
+#elif defined(NK_USE_FIXED_TYPES) /* used if we have */
+# define NK_UINT_TO_PTR(x) ((void*)(uintptr_t)(x))
+# define NK_PTR_TO_UINT(x) ((uintptr_t)(x))
+#else /* generates warning but works */
+# define NK_UINT_TO_PTR(x) ((void*)(x))
+# define NK_PTR_TO_UINT(x) ((nk_size)(x))
+#endif
+
+#define NK_ALIGN_PTR(x, mask)\
+ (NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x) + (mask-1)) & ~(mask-1))))
+#define NK_ALIGN_PTR_BACK(x, mask)\
+ (NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x)) & ~(mask-1))))
+
+#if (defined(__GNUC__) && __GNUC__ >= 4) || defined(__clang__)
+#define NK_OFFSETOF(st,m) (__builtin_offsetof(st,m))
+#else
+#define NK_OFFSETOF(st,m) ((nk_ptr)&(((st*)0)->m))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+template struct nk_alignof;
+template struct nk_helper{enum {value = size_diff};};
+template struct nk_helper{enum {value = nk_alignof::value};};
+template struct nk_alignof{struct Big {T x; char c;}; enum {
+ diff = sizeof(Big) - sizeof(T), value = nk_helper::value};};
+#define NK_ALIGNOF(t) (nk_alignof::value)
+#else
+#define NK_ALIGNOF(t) NK_OFFSETOF(struct {char c; t _h;}, _h)
+#endif
+
+#define NK_CONTAINER_OF(ptr,type,member)\
+ (type*)((void*)((char*)(1 ? (ptr): &((type*)0)->member) - NK_OFFSETOF(type, member)))
+
+
+
+#endif /* NK_NUKLEAR_H_ */
+
+#ifdef NK_IMPLEMENTATION
+
+#ifndef NK_INTERNAL_H
+#define NK_INTERNAL_H
+
+#ifndef NK_POOL_DEFAULT_CAPACITY
+#define NK_POOL_DEFAULT_CAPACITY 16
+#endif
+
+#ifndef NK_DEFAULT_COMMAND_BUFFER_SIZE
+#define NK_DEFAULT_COMMAND_BUFFER_SIZE (4*1024)
+#endif
+
+#ifndef NK_BUFFER_DEFAULT_INITIAL_SIZE
+#define NK_BUFFER_DEFAULT_INITIAL_SIZE (4*1024)
+#endif
+
+/* standard library headers */
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+#include /* malloc, free */
+#endif
+#ifdef NK_INCLUDE_STANDARD_IO
+#include /* fopen, fclose,... */
+#endif
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+#include /* valist, va_start, va_end, ... */
+#endif
+#ifndef NK_ASSERT
+#include
+#define NK_ASSERT(expr) assert(expr)
+#endif
+
+#define NK_DEFAULT (-1)
+
+#ifndef NK_VSNPRINTF
+/* If your compiler does support `vsnprintf` I would highly recommend
+ * defining this to vsnprintf instead since `vsprintf` is basically
+ * unbelievable unsafe and should *NEVER* be used. But I have to support
+ * it since C89 only provides this unsafe version. */
+ #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) ||\
+ (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
+ (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L)) ||\
+ (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500)) ||\
+ defined(_ISOC99_SOURCE) || defined(_BSD_SOURCE)
+ #define NK_VSNPRINTF(s,n,f,a) vsnprintf(s,n,f,a)
+ #else
+ #define NK_VSNPRINTF(s,n,f,a) vsprintf(s,f,a)
+ #endif
+#endif
+
+#define NK_SCHAR_MIN (-127)
+#define NK_SCHAR_MAX 127
+#define NK_UCHAR_MIN 0
+#define NK_UCHAR_MAX 256
+#define NK_SSHORT_MIN (-32767)
+#define NK_SSHORT_MAX 32767
+#define NK_USHORT_MIN 0
+#define NK_USHORT_MAX 65535
+#define NK_SINT_MIN (-2147483647)
+#define NK_SINT_MAX 2147483647
+#define NK_UINT_MIN 0
+#define NK_UINT_MAX 4294967295u
+
+/* Make sure correct type size:
+ * This will fire with a negative subscript error if the type sizes
+ * are set incorrectly by the compiler, and compile out if not */
+NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*));
+NK_STATIC_ASSERT(sizeof(nk_ptr) == sizeof(void*));
+NK_STATIC_ASSERT(sizeof(nk_flags) >= 4);
+NK_STATIC_ASSERT(sizeof(nk_rune) >= 4);
+NK_STATIC_ASSERT(sizeof(nk_ushort) == 2);
+NK_STATIC_ASSERT(sizeof(nk_short) == 2);
+NK_STATIC_ASSERT(sizeof(nk_uint) == 4);
+NK_STATIC_ASSERT(sizeof(nk_int) == 4);
+NK_STATIC_ASSERT(sizeof(nk_byte) == 1);
+#ifdef NK_INCLUDE_STANDARD_BOOL
+NK_STATIC_ASSERT(sizeof(nk_bool) == sizeof(nv_bool));
+#else
+NK_STATIC_ASSERT(sizeof(nk_bool) == 4);
+#endif
+
+NK_GLOBAL const struct nk_rect nk_null_rect = {-8192.0f, -8192.0f, 16384, 16384};
+#define NK_FLOAT_PRECISION 0.00000000000001
+
+NK_GLOBAL const struct nk_color nk_red = {255,0,0,255};
+NK_GLOBAL const struct nk_color nk_green = {0,255,0,255};
+NK_GLOBAL const struct nk_color nk_blue = {0,0,255,255};
+NK_GLOBAL const struct nk_color nk_white = {255,255,255,255};
+NK_GLOBAL const struct nk_color nk_black = {0,0,0,255};
+NK_GLOBAL const struct nk_color nk_yellow = {255,255,0,255};
+
+/* widget */
+#define nk_widget_state_reset(s)\
+ if ((*(s)) & NK_WIDGET_STATE_MODIFIED)\
+ (*(s)) = NK_WIDGET_STATE_INACTIVE|NK_WIDGET_STATE_MODIFIED;\
+ else (*(s)) = NK_WIDGET_STATE_INACTIVE;
+
+/* math */
+#ifndef NK_INV_SQRT
+NK_LIB float nk_inv_sqrt(float n);
+#endif
+#ifndef NK_SIN
+NK_LIB float nk_sin(float x);
+#endif
+#ifndef NK_COS
+NK_LIB float nk_cos(float x);
+#endif
+NK_LIB nk_uint nk_round_up_pow2(nk_uint v);
+NK_LIB struct nk_rect nk_shrink_rect(struct nk_rect r, float amount);
+NK_LIB struct nk_rect nk_pad_rect(struct nk_rect r, struct nk_vec2 pad);
+NK_LIB void nk_unify(struct nk_rect *clip, const struct nk_rect *a, float x0, float y0, float x1, float y1);
+NK_LIB double nk_pow(double x, int n);
+NK_LIB int nk_ifloord(double x);
+NK_LIB int nk_ifloorf(float x);
+NK_LIB int nk_iceilf(float x);
+NK_LIB int nk_log10(double n);
+
+/* util */
+enum {NK_DO_NOT_STOP_ON_NEW_LINE, NK_STOP_ON_NEW_LINE};
+NK_LIB nk_bool nk_is_lower(int c);
+NK_LIB nk_bool nk_is_upper(int c);
+NK_LIB int nk_to_upper(int c);
+NK_LIB int nk_to_lower(int c);
+
+#ifndef NK_MEMCPY
+NK_LIB void* nk_memcopy(void *dst, const void *src, nk_size n);
+#endif
+#ifndef NK_MEMSET
+NK_LIB void nk_memset(void *ptr, int c0, nk_size size);
+#endif
+NK_LIB void nk_zero(void *ptr, nk_size size);
+NK_LIB char *nk_itoa(char *s, long n);
+NK_LIB int nk_string_float_limit(char *string, int prec);
+#ifndef NK_DTOA
+NK_LIB char *nk_dtoa(char *s, double n);
+#endif
+NK_LIB int nk_text_clamp(const struct nk_user_font *font, const char *text, int text_len, float space, int *glyphs, float *text_width, nk_rune *sep_list, int sep_count);
+NK_LIB struct nk_vec2 nk_text_calculate_text_bounds(const struct nk_user_font *font, const char *begin, int byte_len, float row_height, const char **remaining, struct nk_vec2 *out_offset, int *glyphs, int op);
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+NK_LIB int nk_strfmt(char *buf, int buf_size, const char *fmt, va_list args);
+#endif
+#ifdef NK_INCLUDE_STANDARD_IO
+NK_LIB char *nk_file_load(const char* path, nk_size* siz, struct nk_allocator *alloc);
+#endif
+
+/* buffer */
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_LIB void* nk_malloc(nk_handle unused, void *old,nk_size size);
+NK_LIB void nk_mfree(nk_handle unused, void *ptr);
+#endif
+NK_LIB void* nk_buffer_align(void *unaligned, nk_size align, nk_size *alignment, enum nk_buffer_allocation_type type);
+NK_LIB void* nk_buffer_alloc(struct nk_buffer *b, enum nk_buffer_allocation_type type, nk_size size, nk_size align);
+NK_LIB void* nk_buffer_realloc(struct nk_buffer *b, nk_size capacity, nk_size *size);
+
+/* draw */
+NK_LIB void nk_command_buffer_init(struct nk_command_buffer *cb, struct nk_buffer *b, enum nk_command_clipping clip);
+NK_LIB void nk_command_buffer_reset(struct nk_command_buffer *b);
+NK_LIB void* nk_command_buffer_push(struct nk_command_buffer* b, enum nk_command_type t, nk_size size);
+NK_LIB void nk_draw_symbol(struct nk_command_buffer *out, enum nk_symbol_type type, struct nk_rect content, struct nk_color background, struct nk_color foreground, float border_width, const struct nk_user_font *font);
+
+/* buffering */
+NK_LIB void nk_start_buffer(struct nk_context *ctx, struct nk_command_buffer *b);
+NK_LIB void nk_start(struct nk_context *ctx, struct nk_window *win);
+NK_LIB void nk_start_popup(struct nk_context *ctx, struct nk_window *win);
+NK_LIB void nk_finish_popup(struct nk_context *ctx, struct nk_window*);
+NK_LIB void nk_finish_buffer(struct nk_context *ctx, struct nk_command_buffer *b);
+NK_LIB void nk_finish(struct nk_context *ctx, struct nk_window *w);
+NK_LIB void nk_build(struct nk_context *ctx);
+
+/* text editor */
+NK_LIB void nk_textedit_clear_state(struct nk_text_edit *state, enum nk_text_edit_type type, nk_plugin_filter filter);
+NK_LIB void nk_textedit_click(struct nk_text_edit *state, float x, float y, const struct nk_user_font *font, float row_height);
+NK_LIB void nk_textedit_drag(struct nk_text_edit *state, float x, float y, const struct nk_user_font *font, float row_height);
+NK_LIB void nk_textedit_key(struct nk_text_edit *state, enum nk_keys key, int shift_mod, const struct nk_user_font *font, float row_height);
+
+/* window */
+enum nk_window_insert_location {
+ NK_INSERT_BACK, /* inserts window into the back of list (front of screen) */
+ NK_INSERT_FRONT /* inserts window into the front of list (back of screen) */
+};
+NK_LIB void *nk_create_window(struct nk_context *ctx);
+NK_LIB void nk_remove_window(struct nk_context*, struct nk_window*);
+NK_LIB void nk_free_window(struct nk_context *ctx, struct nk_window *win);
+NK_LIB struct nk_window *nk_find_window(struct nk_context *ctx, nk_hash hash, const char *name);
+NK_LIB void nk_insert_window(struct nk_context *ctx, struct nk_window *win, enum nk_window_insert_location loc);
+
+/* pool */
+NK_LIB void nk_pool_init(struct nk_pool *pool, struct nk_allocator *alloc, unsigned int capacity);
+NK_LIB void nk_pool_free(struct nk_pool *pool);
+NK_LIB void nk_pool_init_fixed(struct nk_pool *pool, void *memory, nk_size size);
+NK_LIB struct nk_page_element *nk_pool_alloc(struct nk_pool *pool);
+
+/* page-element */
+NK_LIB struct nk_page_element* nk_create_page_element(struct nk_context *ctx);
+NK_LIB void nk_link_page_element_into_freelist(struct nk_context *ctx, struct nk_page_element *elem);
+NK_LIB void nk_free_page_element(struct nk_context *ctx, struct nk_page_element *elem);
+
+/* table */
+NK_LIB struct nk_table* nk_create_table(struct nk_context *ctx);
+NK_LIB void nk_remove_table(struct nk_window *win, struct nk_table *tbl);
+NK_LIB void nk_free_table(struct nk_context *ctx, struct nk_table *tbl);
+NK_LIB void nk_push_table(struct nk_window *win, struct nk_table *tbl);
+NK_LIB nk_uint *nk_add_value(struct nk_context *ctx, struct nk_window *win, nk_hash name, nk_uint value);
+NK_LIB nk_uint *nk_find_value(struct nk_window *win, nk_hash name);
+
+/* panel */
+NK_LIB void *nk_create_panel(struct nk_context *ctx);
+NK_LIB void nk_free_panel(struct nk_context*, struct nk_panel *pan);
+NK_LIB nk_bool nk_panel_has_header(nk_flags flags, const char *title);
+NK_LIB struct nk_vec2 nk_panel_get_padding(const struct nk_style *style, enum nk_panel_type type);
+NK_LIB float nk_panel_get_border(const struct nk_style *style, nk_flags flags, enum nk_panel_type type);
+NK_LIB struct nk_color nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type);
+NK_LIB nk_bool nk_panel_is_sub(enum nk_panel_type type);
+NK_LIB nk_bool nk_panel_is_nonblock(enum nk_panel_type type);
+NK_LIB nk_bool nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type);
+NK_LIB void nk_panel_end(struct nk_context *ctx);
+
+/* layout */
+NK_LIB float nk_layout_row_calculate_usable_space(const struct nk_style *style, enum nk_panel_type type, float total_space, int columns);
+NK_LIB void nk_panel_layout(const struct nk_context *ctx, struct nk_window *win, float height, int cols);
+NK_LIB void nk_row_layout(struct nk_context *ctx, enum nk_layout_format fmt, float height, int cols, int width);
+NK_LIB void nk_panel_alloc_row(const struct nk_context *ctx, struct nk_window *win);
+NK_LIB void nk_layout_widget_space(struct nk_rect *bounds, const struct nk_context *ctx, struct nk_window *win, int modify);
+NK_LIB void nk_panel_alloc_space(struct nk_rect *bounds, const struct nk_context *ctx);
+NK_LIB void nk_layout_peek(struct nk_rect *bounds, struct nk_context *ctx);
+
+/* popup */
+NK_LIB nk_bool nk_nonblock_begin(struct nk_context *ctx, nk_flags flags, struct nk_rect body, struct nk_rect header, enum nk_panel_type panel_type);
+
+/* text */
+struct nk_text {
+ struct nk_vec2 padding;
+ struct nk_color background;
+ struct nk_color text;
+};
+NK_LIB void nk_widget_text(struct nk_command_buffer *o, struct nk_rect b, const char *string, int len, const struct nk_text *t, nk_flags a, const struct nk_user_font *f);
+NK_LIB void nk_widget_text_wrap(struct nk_command_buffer *o, struct nk_rect b, const char *string, int len, const struct nk_text *t, const struct nk_user_font *f);
+
+/* button */
+NK_LIB nk_bool nk_button_behavior(nk_flags *state, struct nk_rect r, const struct nk_input *i, enum nk_button_behavior behavior);
+NK_LIB const struct nk_style_item* nk_draw_button(struct nk_command_buffer *out, const struct nk_rect *bounds, nk_flags state, const struct nk_style_button *style);
+NK_LIB nk_bool nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, const struct nk_style_button *style, const struct nk_input *in, enum nk_button_behavior behavior, struct nk_rect *content);
+NK_LIB void nk_draw_button_text(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, const char *txt, int len, nk_flags text_alignment, const struct nk_user_font *font);
+NK_LIB nk_bool nk_do_button_text(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *string, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_input *in, const struct nk_user_font *font);
+NK_LIB void nk_draw_button_symbol(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, enum nk_symbol_type type, const struct nk_user_font *font);
+NK_LIB nk_bool nk_do_button_symbol(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, enum nk_symbol_type symbol, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_input *in, const struct nk_user_font *font);
+NK_LIB void nk_draw_button_image(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, const struct nk_image *img);
+NK_LIB nk_bool nk_do_button_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, struct nk_image img, enum nk_button_behavior b, const struct nk_style_button *style, const struct nk_input *in);
+NK_LIB void nk_draw_button_text_symbol(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *label, const struct nk_rect *symbol, nk_flags state, const struct nk_style_button *style, const char *str, int len, enum nk_symbol_type type, const struct nk_user_font *font);
+NK_LIB nk_bool nk_do_button_text_symbol(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, enum nk_symbol_type symbol, const char *str, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_user_font *font, const struct nk_input *in);
+NK_LIB void nk_draw_button_text_image(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *label, const struct nk_rect *image, nk_flags state, const struct nk_style_button *style, const char *str, int len, const struct nk_user_font *font, const struct nk_image *img);
+NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, struct nk_image img, const char* str, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_user_font *font, const struct nk_input *in);
+
+/* toggle */
+enum nk_toggle_type {
+ NK_TOGGLE_CHECK,
+ NK_TOGGLE_OPTION
+};
+NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active);
+NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment);
+NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment);
+NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment);
+
+/* progress */
+NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable);
+NK_LIB void nk_draw_progress(struct nk_command_buffer *out, nk_flags state, const struct nk_style_progress *style, const struct nk_rect *bounds, const struct nk_rect *scursor, nk_size value, nk_size max);
+NK_LIB nk_size nk_do_progress(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, nk_size value, nk_size max, nk_bool modifiable, const struct nk_style_progress *style, struct nk_input *in);
+
+/* slider */
+NK_LIB float nk_slider_behavior(nk_flags *state, struct nk_rect *logical_cursor, struct nk_rect *visual_cursor, struct nk_input *in, struct nk_rect bounds, float slider_min, float slider_max, float slider_value, float slider_step, float slider_steps);
+NK_LIB void nk_draw_slider(struct nk_command_buffer *out, nk_flags state, const struct nk_style_slider *style, const struct nk_rect *bounds, const struct nk_rect *visual_cursor, float min, float value, float max);
+NK_LIB float nk_do_slider(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, float min, float val, float max, float step, const struct nk_style_slider *style, struct nk_input *in, const struct nk_user_font *font);
+
+/* scrollbar */
+NK_LIB float nk_scrollbar_behavior(nk_flags *state, struct nk_input *in, int has_scrolling, const struct nk_rect *scroll, const struct nk_rect *cursor, const struct nk_rect *empty0, const struct nk_rect *empty1, float scroll_offset, float target, float scroll_step, enum nk_orientation o);
+NK_LIB void nk_draw_scrollbar(struct nk_command_buffer *out, nk_flags state, const struct nk_style_scrollbar *style, const struct nk_rect *bounds, const struct nk_rect *scroll);
+NK_LIB float nk_do_scrollbarv(nk_flags *state, struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, float offset, float target, float step, float button_pixel_inc, const struct nk_style_scrollbar *style, struct nk_input *in, const struct nk_user_font *font);
+NK_LIB float nk_do_scrollbarh(nk_flags *state, struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, float offset, float target, float step, float button_pixel_inc, const struct nk_style_scrollbar *style, struct nk_input *in, const struct nk_user_font *font);
+
+/* selectable */
+NK_LIB void nk_draw_selectable(struct nk_command_buffer *out, nk_flags state, const struct nk_style_selectable *style, nk_bool active, const struct nk_rect *bounds, const struct nk_rect *icon, const struct nk_image *img, enum nk_symbol_type sym, const char *string, int len, nk_flags align, const struct nk_user_font *font);
+NK_LIB nk_bool nk_do_selectable(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *str, int len, nk_flags align, nk_bool *value, const struct nk_style_selectable *style, const struct nk_input *in, const struct nk_user_font *font);
+NK_LIB nk_bool nk_do_selectable_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *str, int len, nk_flags align, nk_bool *value, const struct nk_image *img, const struct nk_style_selectable *style, const struct nk_input *in, const struct nk_user_font *font);
+
+/* edit */
+NK_LIB void nk_edit_draw_text(struct nk_command_buffer *out, const struct nk_style_edit *style, float pos_x, float pos_y, float x_offset, const char *text, int byte_len, float row_height, const struct nk_user_font *font, struct nk_color background, struct nk_color foreground, nk_bool is_selected);
+NK_LIB nk_flags nk_do_edit(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, nk_flags flags, nk_plugin_filter filter, struct nk_text_edit *edit, const struct nk_style_edit *style, struct nk_input *in, const struct nk_user_font *font);
+
+/* color-picker */
+NK_LIB nk_bool nk_color_picker_behavior(nk_flags *state, const struct nk_rect *bounds, const struct nk_rect *matrix, const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, struct nk_colorf *color, const struct nk_input *in);
+NK_LIB void nk_draw_color_picker(struct nk_command_buffer *o, const struct nk_rect *matrix, const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, struct nk_colorf col);
+NK_LIB nk_bool nk_do_color_picker(nk_flags *state, struct nk_command_buffer *out, struct nk_colorf *col, enum nk_color_format fmt, struct nk_rect bounds, struct nk_vec2 padding, const struct nk_input *in, const struct nk_user_font *font);
+
+/* property */
+enum nk_property_status {
+ NK_PROPERTY_DEFAULT,
+ NK_PROPERTY_EDIT,
+ NK_PROPERTY_DRAG
+};
+enum nk_property_filter {
+ NK_FILTER_INT,
+ NK_FILTER_FLOAT
+};
+enum nk_property_kind {
+ NK_PROPERTY_INT,
+ NK_PROPERTY_FLOAT,
+ NK_PROPERTY_DOUBLE
+};
+union nk_property {
+ int i;
+ float f;
+ double d;
+};
+struct nk_property_variant {
+ enum nk_property_kind kind;
+ union nk_property value;
+ union nk_property min_value;
+ union nk_property max_value;
+ union nk_property step;
+};
+NK_LIB struct nk_property_variant nk_property_variant_int(int value, int min_value, int max_value, int step);
+NK_LIB struct nk_property_variant nk_property_variant_float(float value, float min_value, float max_value, float step);
+NK_LIB struct nk_property_variant nk_property_variant_double(double value, double min_value, double max_value, double step);
+
+NK_LIB void nk_drag_behavior(nk_flags *state, const struct nk_input *in, struct nk_rect drag, struct nk_property_variant *variant, float inc_per_pixel);
+NK_LIB void nk_property_behavior(nk_flags *ws, const struct nk_input *in, struct nk_rect property, struct nk_rect label, struct nk_rect edit, struct nk_rect empty, int *state, struct nk_property_variant *variant, float inc_per_pixel);
+NK_LIB void nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property *style, const struct nk_rect *bounds, const struct nk_rect *label, nk_flags state, const char *name, int len, const struct nk_user_font *font);
+NK_LIB void nk_do_property(nk_flags *ws, struct nk_command_buffer *out, struct nk_rect property, const char *name, struct nk_property_variant *variant, float inc_per_pixel, char *buffer, int *len, int *state, int *cursor, int *select_begin, int *select_end, const struct nk_style_property *style, enum nk_property_filter filter, struct nk_input *in, const struct nk_user_font *font, struct nk_text_edit *text_edit, enum nk_button_behavior behavior);
+NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant *variant, float inc_per_pixel, const enum nk_property_filter filter);
+
+#ifdef NK_INCLUDE_FONT_BAKING
+
+/**
+ * @def NK_NO_STB_RECT_PACK_IMPLEMENTATION
+ *
+ * When defined, will avoid enabling STB_RECT_PACK_IMPLEMENTATION for when stb_rect_pack.h is already implemented elsewhere.
+ */
+#ifndef NK_NO_STB_RECT_PACK_IMPLEMENTATION
+#define STB_RECT_PACK_IMPLEMENTATION
+#endif /* NK_NO_STB_RECT_PACK_IMPLEMENTATION */
+
+/**
+ * @def NK_NO_STB_TRUETYPE_IMPLEMENTATION
+ *
+ * When defined, will avoid enabling STB_TRUETYPE_IMPLEMENTATION for when stb_truetype.h is already implemented elsewhere.
+ */
+#ifndef NK_NO_STB_TRUETYPE_IMPLEMENTATION
+#define STB_TRUETYPE_IMPLEMENTATION
+#endif /* NK_NO_STB_TRUETYPE_IMPLEMENTATION */
+
+/* Allow consumer to define own STBTT_malloc/STBTT_free, and use the font atlas' allocator otherwise */
+#ifndef STBTT_malloc
+static void*
+nk_stbtt_malloc(nk_size size, void *user_data) {
+ struct nk_allocator *alloc = (struct nk_allocator *) user_data;
+ return alloc->alloc(alloc->userdata, 0, size);
+}
+
+static void
+nk_stbtt_free(void *ptr, void *user_data) {
+ struct nk_allocator *alloc = (struct nk_allocator *) user_data;
+ alloc->free(alloc->userdata, ptr);
+}
+
+#define STBTT_malloc(x,u) nk_stbtt_malloc(x,u)
+#define STBTT_free(x,u) nk_stbtt_free(x,u)
+
+#endif /* STBTT_malloc */
+
+#endif /* NK_INCLUDE_FONT_BAKING */
+
+#endif
+
+
+
+
+
+/* ===============================================================
+ *
+ * MATH
+ *
+ * ===============================================================*/
+/*/// ### Math
+/// Since nuklear is supposed to work on all systems providing floating point
+/// math without any dependencies I also had to implement my own math functions
+/// for sqrt, sin and cos. Since the actual highly accurate implementations for
+/// the standard library functions are quite complex and I do not need high
+/// precision for my use cases I use approximations.
+///
+/// Sqrt
+/// ----
+/// For square root nuklear uses the famous fast inverse square root:
+/// https://en.wikipedia.org/wiki/Fast_inverse_square_root with
+/// slightly tweaked magic constant. While on today's hardware it is
+/// probably not faster it is still fast and accurate enough for
+/// nuklear's use cases. IMPORTANT: this requires float format IEEE 754
+///
+/// Sine/Cosine
+/// -----------
+/// All constants inside both function are generated Remez's minimax
+/// approximations for value range 0...2*PI. The reason why I decided to
+/// approximate exactly that range is that nuklear only needs sine and
+/// cosine to generate circles which only requires that exact range.
+/// In addition I used Remez instead of Taylor for additional precision:
+/// www.lolengine.net/blog/2011/12/21/better-function-approximations.
+///
+/// The tool I used to generate constants for both sine and cosine
+/// (it can actually approximate a lot more functions) can be
+/// found here: www.lolengine.net/wiki/oss/lolremez
+*/
+#ifndef NK_INV_SQRT
+#define NK_INV_SQRT nk_inv_sqrt
+NK_LIB float
+nk_inv_sqrt(float n)
+{
+ float x2;
+ const float threehalfs = 1.5f;
+ union {nk_uint i; float f;} conv = {0};
+ conv.f = n;
+ x2 = n * 0.5f;
+ conv.i = 0x5f375A84 - (conv.i >> 1);
+ conv.f = conv.f * (threehalfs - (x2 * conv.f * conv.f));
+ return conv.f;
+}
+#endif
+#ifndef NK_SIN
+#define NK_SIN nk_sin
+NK_LIB float
+nk_sin(float x)
+{
+ NK_STORAGE const float a0 = +1.91059300966915117e-31f;
+ NK_STORAGE const float a1 = +1.00086760103908896f;
+ NK_STORAGE const float a2 = -1.21276126894734565e-2f;
+ NK_STORAGE const float a3 = -1.38078780785773762e-1f;
+ NK_STORAGE const float a4 = -2.67353392911981221e-2f;
+ NK_STORAGE const float a5 = +2.08026600266304389e-2f;
+ NK_STORAGE const float a6 = -3.03996055049204407e-3f;
+ NK_STORAGE const float a7 = +1.38235642404333740e-4f;
+ return a0 + x*(a1 + x*(a2 + x*(a3 + x*(a4 + x*(a5 + x*(a6 + x*a7))))));
+}
+#endif
+#ifndef NK_COS
+#define NK_COS nk_cos
+NK_LIB float
+nk_cos(float x)
+{
+ /* New implementation. Also generated using lolremez. */
+ /* Old version significantly deviated from expected results. */
+ NK_STORAGE const float a0 = 9.9995999154986614e-1f;
+ NK_STORAGE const float a1 = 1.2548995793001028e-3f;
+ NK_STORAGE const float a2 = -5.0648546280678015e-1f;
+ NK_STORAGE const float a3 = 1.2942246466519995e-2f;
+ NK_STORAGE const float a4 = 2.8668384702547972e-2f;
+ NK_STORAGE const float a5 = 7.3726485210586547e-3f;
+ NK_STORAGE const float a6 = -3.8510875386947414e-3f;
+ NK_STORAGE const float a7 = 4.7196604604366623e-4f;
+ NK_STORAGE const float a8 = -1.8776444013090451e-5f;
+ return a0 + x*(a1 + x*(a2 + x*(a3 + x*(a4 + x*(a5 + x*(a6 + x*(a7 + x*a8)))))));
+}
+#endif
+NK_LIB nk_uint
+nk_round_up_pow2(nk_uint v)
+{
+ v--;
+ v |= v >> 1;
+ v |= v >> 2;
+ v |= v >> 4;
+ v |= v >> 8;
+ v |= v >> 16;
+ v++;
+ return v;
+}
+NK_LIB double
+nk_pow(double x, int n)
+{
+ /* check the sign of n */
+ double r = 1;
+ int plus = n >= 0;
+ n = (plus) ? n : -n;
+ while (n > 0) {
+ if ((n & 1) == 1)
+ r *= x;
+ n /= 2;
+ x *= x;
+ }
+ return plus ? r : 1.0 / r;
+}
+NK_LIB int
+nk_ifloord(double x)
+{
+ x = (double)((int)x - ((x < 0.0) ? 1 : 0));
+ return (int)x;
+}
+NK_LIB int
+nk_ifloorf(float x)
+{
+ x = (float)((int)x - ((x < 0.0f) ? 1 : 0));
+ return (int)x;
+}
+NK_LIB int
+nk_iceilf(float x)
+{
+ if (x >= 0) {
+ int i = (int)x;
+ return (x > i) ? i+1: i;
+ } else {
+ int t = (int)x;
+ float r = x - (float)t;
+ return (r > 0.0f) ? t+1: t;
+ }
+}
+NK_LIB int
+nk_log10(double n)
+{
+ int neg;
+ int ret;
+ int exp = 0;
+
+ neg = (n < 0) ? 1 : 0;
+ ret = (neg) ? (int)-n : (int)n;
+ while ((ret / 10) > 0) {
+ ret /= 10;
+ exp++;
+ }
+ if (neg) exp = -exp;
+ return exp;
+}
+NK_API struct nk_rect
+nk_get_null_rect(void)
+{
+ return nk_null_rect;
+}
+NK_API struct nk_rect
+nk_rect(float x, float y, float w, float h)
+{
+ struct nk_rect r;
+ r.x = x; r.y = y;
+ r.w = w; r.h = h;
+ return r;
+}
+NK_API struct nk_rect
+nk_recti(int x, int y, int w, int h)
+{
+ struct nk_rect r;
+ r.x = (float)x;
+ r.y = (float)y;
+ r.w = (float)w;
+ r.h = (float)h;
+ return r;
+}
+NK_API struct nk_rect
+nk_recta(struct nk_vec2 pos, struct nk_vec2 size)
+{
+ return nk_rect(pos.x, pos.y, size.x, size.y);
+}
+NK_API struct nk_rect
+nk_rectv(const float *r)
+{
+ return nk_rect(r[0], r[1], r[2], r[3]);
+}
+NK_API struct nk_rect
+nk_rectiv(const int *r)
+{
+ return nk_recti(r[0], r[1], r[2], r[3]);
+}
+NK_API struct nk_vec2
+nk_rect_pos(struct nk_rect r)
+{
+ struct nk_vec2 ret;
+ ret.x = r.x; ret.y = r.y;
+ return ret;
+}
+NK_API struct nk_vec2
+nk_rect_size(struct nk_rect r)
+{
+ struct nk_vec2 ret;
+ ret.x = r.w; ret.y = r.h;
+ return ret;
+}
+NK_LIB struct nk_rect
+nk_shrink_rect(struct nk_rect r, float amount)
+{
+ struct nk_rect res;
+ r.w = NK_MAX(r.w, 2 * amount);
+ r.h = NK_MAX(r.h, 2 * amount);
+ res.x = r.x + amount;
+ res.y = r.y + amount;
+ res.w = r.w - 2 * amount;
+ res.h = r.h - 2 * amount;
+ return res;
+}
+NK_LIB struct nk_rect
+nk_pad_rect(struct nk_rect r, struct nk_vec2 pad)
+{
+ r.w = NK_MAX(r.w, 2 * pad.x);
+ r.h = NK_MAX(r.h, 2 * pad.y);
+ r.x += pad.x; r.y += pad.y;
+ r.w -= 2 * pad.x;
+ r.h -= 2 * pad.y;
+ return r;
+}
+NK_API struct nk_vec2
+nk_vec2(float x, float y)
+{
+ struct nk_vec2 ret;
+ ret.x = x; ret.y = y;
+ return ret;
+}
+NK_API struct nk_vec2
+nk_vec2i(int x, int y)
+{
+ struct nk_vec2 ret;
+ ret.x = (float)x;
+ ret.y = (float)y;
+ return ret;
+}
+NK_API struct nk_vec2
+nk_vec2v(const float *v)
+{
+ return nk_vec2(v[0], v[1]);
+}
+NK_API struct nk_vec2
+nk_vec2iv(const int *v)
+{
+ return nk_vec2i(v[0], v[1]);
+}
+NK_LIB void
+nk_unify(struct nk_rect *clip, const struct nk_rect *a, float x0, float y0,
+ float x1, float y1)
+{
+ NK_ASSERT(a);
+ NK_ASSERT(clip);
+ clip->x = NK_MAX(a->x, x0);
+ clip->y = NK_MAX(a->y, y0);
+ clip->w = NK_MIN(a->x + a->w, x1) - clip->x;
+ clip->h = NK_MIN(a->y + a->h, y1) - clip->y;
+ clip->w = NK_MAX(0, clip->w);
+ clip->h = NK_MAX(0, clip->h);
+}
+
+NK_API void
+nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r,
+ float pad_x, float pad_y, enum nk_heading direction)
+{
+ float w_half, h_half;
+ NK_ASSERT(result);
+
+ r.w = NK_MAX(2 * pad_x, r.w);
+ r.h = NK_MAX(2 * pad_y, r.h);
+ r.w = r.w - 2 * pad_x;
+ r.h = r.h - 2 * pad_y;
+
+ r.x = r.x + pad_x;
+ r.y = r.y + pad_y;
+
+ w_half = r.w / 2.0f;
+ h_half = r.h / 2.0f;
+
+ if (direction == NK_UP) {
+ result[0] = nk_vec2(r.x + w_half, r.y);
+ result[1] = nk_vec2(r.x + r.w, r.y + r.h);
+ result[2] = nk_vec2(r.x, r.y + r.h);
+ } else if (direction == NK_RIGHT) {
+ result[0] = nk_vec2(r.x, r.y);
+ result[1] = nk_vec2(r.x + r.w, r.y + h_half);
+ result[2] = nk_vec2(r.x, r.y + r.h);
+ } else if (direction == NK_DOWN) {
+ result[0] = nk_vec2(r.x, r.y);
+ result[1] = nk_vec2(r.x + r.w, r.y);
+ result[2] = nk_vec2(r.x + w_half, r.y + r.h);
+ } else {
+ result[0] = nk_vec2(r.x, r.y + h_half);
+ result[1] = nk_vec2(r.x + r.w, r.y);
+ result[2] = nk_vec2(r.x + r.w, r.y + r.h);
+ }
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * UTIL
+ *
+ * ===============================================================*/
+NK_INTERN int nk_str_match_here(const char *regexp, const char *text);
+NK_INTERN int nk_str_match_star(int c, const char *regexp, const char *text);
+NK_LIB nk_bool nk_is_lower(int c) {return (c >= 'a' && c <= 'z') || (c >= 0xE0 && c <= 0xFF);}
+NK_LIB nk_bool nk_is_upper(int c){return (c >= 'A' && c <= 'Z') || (c >= 0xC0 && c <= 0xDF);}
+NK_LIB int nk_to_upper(int c) {return (c >= 'a' && c <= 'z') ? (c - ('a' - 'A')) : c;}
+NK_LIB int nk_to_lower(int c) {return (c >= 'A' && c <= 'Z') ? (c - ('a' + 'A')) : c;}
+
+#ifndef NK_MEMCPY
+#define NK_MEMCPY nk_memcopy
+NK_LIB void*
+nk_memcopy(void *dst0, const void *src0, nk_size length)
+{
+ nk_ptr t;
+ char *dst = (char*)dst0;
+ const char *src = (const char*)src0;
+ if (length == 0 || dst == src)
+ goto done;
+
+ #define nk_word int
+ #define nk_wsize sizeof(nk_word)
+ #define nk_wmask (nk_wsize-1)
+ #define NK_TLOOP(s) if (t) NK_TLOOP1(s)
+ #define NK_TLOOP1(s) do { s; } while (--t)
+
+ if (dst < src) {
+ t = (nk_ptr)src; /* only need low bits */
+ if ((t | (nk_ptr)dst) & nk_wmask) {
+ if ((t ^ (nk_ptr)dst) & nk_wmask || length < nk_wsize)
+ t = length;
+ else
+ t = nk_wsize - (t & nk_wmask);
+ length -= t;
+ NK_TLOOP1(*dst++ = *src++);
+ }
+ t = length / nk_wsize;
+ NK_TLOOP(*(nk_word*)(void*)dst = *(const nk_word*)(const void*)src;
+ src += nk_wsize; dst += nk_wsize);
+ t = length & nk_wmask;
+ NK_TLOOP(*dst++ = *src++);
+ } else {
+ src += length;
+ dst += length;
+ t = (nk_ptr)src;
+ if ((t | (nk_ptr)dst) & nk_wmask) {
+ if ((t ^ (nk_ptr)dst) & nk_wmask || length <= nk_wsize)
+ t = length;
+ else
+ t &= nk_wmask;
+ length -= t;
+ NK_TLOOP1(*--dst = *--src);
+ }
+ t = length / nk_wsize;
+ NK_TLOOP(src -= nk_wsize; dst -= nk_wsize;
+ *(nk_word*)(void*)dst = *(const nk_word*)(const void*)src);
+ t = length & nk_wmask;
+ NK_TLOOP(*--dst = *--src);
+ }
+ #undef nk_word
+ #undef nk_wsize
+ #undef nk_wmask
+ #undef NK_TLOOP
+ #undef NK_TLOOP1
+done:
+ return (dst0);
+}
+#endif
+#ifndef NK_MEMSET
+#define NK_MEMSET nk_memset
+NK_LIB void
+nk_memset(void *ptr, int c0, nk_size size)
+{
+ #define nk_word unsigned
+ #define nk_wsize sizeof(nk_word)
+ #define nk_wmask (nk_wsize - 1)
+ nk_byte *dst = (nk_byte*)ptr;
+ unsigned c = 0;
+ nk_size t = 0;
+
+ if ((c = (nk_byte)c0) != 0) {
+ c = (c << 8) | c; /* at least 16-bits */
+ if (sizeof(unsigned int) > 2)
+ c = (c << 16) | c; /* at least 32-bits*/
+ }
+
+ /* too small of a word count */
+ dst = (nk_byte*)ptr;
+ if (size < 3 * nk_wsize) {
+ while (size--) *dst++ = (nk_byte)c0;
+ return;
+ }
+
+ /* align destination */
+ if ((t = NK_PTR_TO_UINT(dst) & nk_wmask) != 0) {
+ t = nk_wsize -t;
+ size -= t;
+ do {
+ *dst++ = (nk_byte)c0;
+ } while (--t != 0);
+ }
+
+ /* fill word */
+ t = size / nk_wsize;
+ do {
+ *(nk_word*)((void*)dst) = c;
+ dst += nk_wsize;
+ } while (--t != 0);
+
+ /* fill trailing bytes */
+ t = (size & nk_wmask);
+ if (t != 0) {
+ do {
+ *dst++ = (nk_byte)c0;
+ } while (--t != 0);
+ }
+
+ #undef nk_word
+ #undef nk_wsize
+ #undef nk_wmask
+}
+#endif
+NK_LIB void
+nk_zero(void *ptr, nk_size size)
+{
+ NK_ASSERT(ptr);
+ NK_MEMSET(ptr, 0, size);
+}
+NK_API int
+nk_strlen(const char *str)
+{
+ int siz = 0;
+ NK_ASSERT(str);
+ while (str && *str++ != '\0') siz++;
+ return siz;
+}
+NK_API int
+nk_strtoi(const char *str, const char **endptr)
+{
+ int neg = 1;
+ const char *p = str;
+ int value = 0;
+
+ NK_ASSERT(str);
+ if (!str) return 0;
+
+ /* skip whitespace */
+ while (*p == ' ') p++;
+ if (*p == '-') {
+ neg = -1;
+ p++;
+ }
+ while (*p && *p >= '0' && *p <= '9') {
+ value = value * 10 + (int) (*p - '0');
+ p++;
+ }
+ if (endptr)
+ *endptr = p;
+ return neg*value;
+}
+NK_API double
+nk_strtod(const char *str, const char **endptr)
+{
+ double m;
+ double neg = 1.0;
+ const char *p = str;
+ double value = 0;
+ double number = 0;
+
+ NK_ASSERT(str);
+ if (!str) return 0;
+
+ /* skip whitespace */
+ while (*p == ' ') p++;
+ if (*p == '-') {
+ neg = -1.0;
+ p++;
+ }
+
+ while (*p && *p != '.' && *p != 'e') {
+ value = value * 10.0 + (double) (*p - '0');
+ p++;
+ }
+
+ if (*p == '.') {
+ p++;
+ for(m = 0.1; *p && *p != 'e'; p++ ) {
+ value = value + (double) (*p - '0') * m;
+ m *= 0.1;
+ }
+ }
+ if (*p == 'e') {
+ int i, pow, div;
+ p++;
+ if (*p == '-') {
+ div = nk_true;
+ p++;
+ } else if (*p == '+') {
+ div = nk_false;
+ p++;
+ } else div = nk_false;
+
+ for (pow = 0; *p; p++)
+ pow = pow * 10 + (int) (*p - '0');
+
+ for (m = 1.0, i = 0; i < pow; i++)
+ m *= 10.0;
+
+ if (div)
+ value /= m;
+ else value *= m;
+ }
+ number = value * neg;
+ if (endptr)
+ *endptr = p;
+ return number;
+}
+NK_API float
+nk_strtof(const char *str, const char **endptr)
+{
+ float float_value;
+ double double_value;
+ double_value = NK_STRTOD(str, endptr);
+ float_value = (float)double_value;
+ return float_value;
+}
+NK_API int
+nk_stricmp(const char *s1, const char *s2)
+{
+ nk_int c1,c2,d;
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+ d = c1 - c2;
+ while (d) {
+ if (c1 <= 'Z' && c1 >= 'A') {
+ d += ('a' - 'A');
+ if (!d) break;
+ }
+ if (c2 <= 'Z' && c2 >= 'A') {
+ d -= ('a' - 'A');
+ if (!d) break;
+ }
+ return ((d >= 0) << 1) - 1;
+ }
+ } while (c1);
+ return 0;
+}
+NK_API int
+nk_stricmpn(const char *s1, const char *s2, int n)
+{
+ int c1,c2,d;
+ NK_ASSERT(n >= 0);
+ do {
+ c1 = *s1++;
+ c2 = *s2++;
+ if (!n--) return 0;
+
+ d = c1 - c2;
+ while (d) {
+ if (c1 <= 'Z' && c1 >= 'A') {
+ d += ('a' - 'A');
+ if (!d) break;
+ }
+ if (c2 <= 'Z' && c2 >= 'A') {
+ d -= ('a' - 'A');
+ if (!d) break;
+ }
+ return ((d >= 0) << 1) - 1;
+ }
+ } while (c1);
+ return 0;
+}
+NK_INTERN int
+nk_str_match_here(const char *regexp, const char *text)
+{
+ if (regexp[0] == '\0')
+ return 1;
+ if (regexp[1] == '*')
+ return nk_str_match_star(regexp[0], regexp+2, text);
+ if (regexp[0] == '$' && regexp[1] == '\0')
+ return *text == '\0';
+ if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text))
+ return nk_str_match_here(regexp+1, text+1);
+ return 0;
+}
+NK_INTERN int
+nk_str_match_star(int c, const char *regexp, const char *text)
+{
+ do {/* a '* matches zero or more instances */
+ if (nk_str_match_here(regexp, text))
+ return 1;
+ } while (*text != '\0' && (*text++ == c || c == '.'));
+ return 0;
+}
+NK_API int
+nk_strfilter(const char *text, const char *regexp)
+{
+ /*
+ c matches any literal character c
+ . matches any single character
+ ^ matches the beginning of the input string
+ $ matches the end of the input string
+ * matches zero or more occurrences of the previous character*/
+ if (regexp[0] == '^')
+ return nk_str_match_here(regexp+1, text);
+ do { /* must look even if string is empty */
+ if (nk_str_match_here(regexp, text))
+ return 1;
+ } while (*text++ != '\0');
+ return 0;
+}
+NK_API int
+nk_strmatch_fuzzy_text(const char *str, int str_len,
+ const char *pattern, int *out_score)
+{
+ /* Returns true if each character in pattern is found sequentially within str
+ * if found then out_score is also set. Score value has no intrinsic meaning.
+ * Range varies with pattern. Can only compare scores with same search pattern. */
+
+ /* bonus for adjacent matches */
+ #define NK_ADJACENCY_BONUS 5
+ /* bonus if match occurs after a separator */
+ #define NK_SEPARATOR_BONUS 10
+ /* bonus if match is uppercase and prev is lower */
+ #define NK_CAMEL_BONUS 10
+ /* penalty applied for every letter in str before the first match */
+ #define NK_LEADING_LETTER_PENALTY (-3)
+ /* maximum penalty for leading letters */
+ #define NK_MAX_LEADING_LETTER_PENALTY (-9)
+ /* penalty for every letter that doesn't matter */
+ #define NK_UNMATCHED_LETTER_PENALTY (-1)
+
+ /* loop variables */
+ int score = 0;
+ char const * pattern_iter = pattern;
+ int str_iter = 0;
+ int prev_matched = nk_false;
+ int prev_lower = nk_false;
+ /* true so if first letter match gets separator bonus*/
+ int prev_separator = nk_true;
+
+ /* use "best" matched letter if multiple string letters match the pattern */
+ char const * best_letter = 0;
+ int best_letter_score = 0;
+
+ /* loop over strings */
+ NK_ASSERT(str);
+ NK_ASSERT(pattern);
+ if (!str || !str_len || !pattern) return 0;
+ while (str_iter < str_len)
+ {
+ const char pattern_letter = *pattern_iter;
+ const char str_letter = str[str_iter];
+
+ int next_match = *pattern_iter != '\0' &&
+ nk_to_lower(pattern_letter) == nk_to_lower(str_letter);
+ int rematch = best_letter && nk_to_upper(*best_letter) == nk_to_upper(str_letter);
+
+ int advanced = next_match && best_letter;
+ int pattern_repeat = best_letter && *pattern_iter != '\0';
+ pattern_repeat = pattern_repeat &&
+ nk_to_lower(*best_letter) == nk_to_lower(pattern_letter);
+
+ if (advanced || pattern_repeat) {
+ score += best_letter_score;
+ best_letter = 0;
+ best_letter_score = 0;
+ }
+
+ if (next_match || rematch)
+ {
+ int new_score = 0;
+ /* Apply penalty for each letter before the first pattern match */
+ if (pattern_iter == pattern) {
+ int count = (int)(&str[str_iter] - str);
+ int penalty = NK_LEADING_LETTER_PENALTY * count;
+ if (penalty < NK_MAX_LEADING_LETTER_PENALTY)
+ penalty = NK_MAX_LEADING_LETTER_PENALTY;
+
+ score += penalty;
+ }
+
+ /* apply bonus for consecutive bonuses */
+ if (prev_matched)
+ new_score += NK_ADJACENCY_BONUS;
+
+ /* apply bonus for matches after a separator */
+ if (prev_separator)
+ new_score += NK_SEPARATOR_BONUS;
+
+ /* apply bonus across camel case boundaries */
+ if (prev_lower && nk_is_upper(str_letter))
+ new_score += NK_CAMEL_BONUS;
+
+ /* update pattern iter IFF the next pattern letter was matched */
+ if (next_match)
+ ++pattern_iter;
+
+ /* update best letter in str which may be for a "next" letter or a rematch */
+ if (new_score >= best_letter_score) {
+ /* apply penalty for now skipped letter */
+ if (best_letter != 0)
+ score += NK_UNMATCHED_LETTER_PENALTY;
+
+ best_letter = &str[str_iter];
+ best_letter_score = new_score;
+ }
+ prev_matched = nk_true;
+ } else {
+ score += NK_UNMATCHED_LETTER_PENALTY;
+ prev_matched = nk_false;
+ }
+
+ /* separators should be more easily defined */
+ prev_lower = nk_is_lower(str_letter) != 0;
+ prev_separator = str_letter == '_' || str_letter == ' ';
+
+ ++str_iter;
+ }
+
+ /* apply score for last match */
+ if (best_letter)
+ score += best_letter_score;
+
+ /* did not match full pattern */
+ if (*pattern_iter != '\0')
+ return nk_false;
+
+ if (out_score)
+ *out_score = score;
+ return nk_true;
+}
+NK_API int
+nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score)
+{
+ return nk_strmatch_fuzzy_text(str, nk_strlen(str), pattern, out_score);
+}
+NK_LIB int
+nk_string_float_limit(char *string, int prec)
+{
+ int dot = 0;
+ char *c = string;
+ while (*c) {
+ if (*c == '.') {
+ dot = 1;
+ c++;
+ continue;
+ }
+ if (dot == (prec+1)) {
+ *c = 0;
+ break;
+ }
+ if (dot > 0) dot++;
+ c++;
+ }
+ return (int)(c - string);
+}
+NK_INTERN void
+nk_strrev_ascii(char *s)
+{
+ int len = nk_strlen(s);
+ int end = len / 2;
+ int i = 0;
+ char t;
+ for (; i < end; ++i) {
+ t = s[i];
+ s[i] = s[len - 1 - i];
+ s[len -1 - i] = t;
+ }
+}
+NK_LIB char*
+nk_itoa(char *s, long n)
+{
+ long i = 0;
+ if (n == 0) {
+ s[i++] = '0';
+ s[i] = 0;
+ return s;
+ }
+ if (n < 0) {
+ s[i++] = '-';
+ n = -n;
+ }
+ while (n > 0) {
+ s[i++] = (char)('0' + (n % 10));
+ n /= 10;
+ }
+ s[i] = 0;
+ if (s[0] == '-')
+ ++s;
+
+ nk_strrev_ascii(s);
+ return s;
+}
+#ifndef NK_DTOA
+#define NK_DTOA nk_dtoa
+NK_LIB char*
+nk_dtoa(char *s, double n)
+{
+ int useExp = 0;
+ int digit = 0, m = 0, m1 = 0;
+ char *c = s;
+ int neg = 0;
+
+ NK_ASSERT(s);
+ if (!s) return 0;
+
+ if (n == 0.0) {
+ s[0] = '0'; s[1] = '\0';
+ return s;
+ }
+
+ neg = (n < 0);
+ if (neg) n = -n;
+
+ /* calculate magnitude */
+ m = nk_log10(n);
+ useExp = (m >= 14 || (neg && m >= 9) || m <= -9);
+ if (neg) *(c++) = '-';
+
+ /* set up for scientific notation */
+ if (useExp) {
+ if (m < 0)
+ m -= 1;
+ n = n / (double)nk_pow(10.0, m);
+ m1 = m;
+ m = 0;
+ }
+ if (m < 1.0) {
+ m = 0;
+ }
+
+ /* convert the number */
+ while (n > NK_FLOAT_PRECISION || m >= 0) {
+ double weight = nk_pow(10.0, m);
+ if (weight > 0) {
+ double t = (double)n / weight;
+ digit = nk_ifloord(t);
+ n -= ((double)digit * weight);
+ *(c++) = (char)('0' + (char)digit);
+ }
+ if (m == 0 && n > 0)
+ *(c++) = '.';
+ m--;
+ }
+
+ if (useExp) {
+ /* convert the exponent */
+ int i, j;
+ *(c++) = 'e';
+ if (m1 > 0) {
+ *(c++) = '+';
+ } else {
+ *(c++) = '-';
+ m1 = -m1;
+ }
+ m = 0;
+ while (m1 > 0) {
+ *(c++) = (char)('0' + (char)(m1 % 10));
+ m1 /= 10;
+ m++;
+ }
+ c -= m;
+ for (i = 0, j = m-1; i= buf_size) break;
+ iter++;
+
+ /* flag arguments */
+ while (*iter) {
+ if (*iter == '-') flag |= NK_ARG_FLAG_LEFT;
+ else if (*iter == '+') flag |= NK_ARG_FLAG_PLUS;
+ else if (*iter == ' ') flag |= NK_ARG_FLAG_SPACE;
+ else if (*iter == '#') flag |= NK_ARG_FLAG_NUM;
+ else if (*iter == '0') flag |= NK_ARG_FLAG_ZERO;
+ else break;
+ iter++;
+ }
+
+ /* width argument */
+ width = NK_DEFAULT;
+ if (*iter >= '1' && *iter <= '9') {
+ const char *end;
+ width = nk_strtoi(iter, &end);
+ if (end == iter)
+ width = -1;
+ else iter = end;
+ } else if (*iter == '*') {
+ width = va_arg(args, int);
+ iter++;
+ }
+
+ /* precision argument */
+ precision = NK_DEFAULT;
+ if (*iter == '.') {
+ iter++;
+ if (*iter == '*') {
+ precision = va_arg(args, int);
+ iter++;
+ } else {
+ const char *end;
+ precision = nk_strtoi(iter, &end);
+ if (end == iter)
+ precision = -1;
+ else iter = end;
+ }
+ }
+
+ /* length modifier */
+ if (*iter == 'h') {
+ if (*(iter+1) == 'h') {
+ arg_type = NK_ARG_TYPE_CHAR;
+ iter++;
+ } else arg_type = NK_ARG_TYPE_SHORT;
+ iter++;
+ } else if (*iter == 'l') {
+ arg_type = NK_ARG_TYPE_LONG;
+ iter++;
+ } else arg_type = NK_ARG_TYPE_DEFAULT;
+
+ /* specifier */
+ if (*iter == '%') {
+ NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT);
+ NK_ASSERT(precision == NK_DEFAULT);
+ NK_ASSERT(width == NK_DEFAULT);
+ if (len < buf_size)
+ buf[len++] = '%';
+ } else if (*iter == 's') {
+ /* string */
+ const char *str = va_arg(args, const char*);
+ NK_ASSERT(str != buf && "buffer and argument are not allowed to overlap!");
+ NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT);
+ NK_ASSERT(precision == NK_DEFAULT);
+ NK_ASSERT(width == NK_DEFAULT);
+ if (str == buf) return -1;
+ while (str && *str && len < buf_size)
+ buf[len++] = *str++;
+ } else if (*iter == 'n') {
+ /* current length callback */
+ signed int *n = va_arg(args, int*);
+ NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT);
+ NK_ASSERT(precision == NK_DEFAULT);
+ NK_ASSERT(width == NK_DEFAULT);
+ if (n) *n = len;
+ } else if (*iter == 'c' || *iter == 'i' || *iter == 'd') {
+ /* signed integer */
+ long value = 0;
+ const char *num_iter;
+ int num_len, num_print, padding;
+ int cur_precision = NK_MAX(precision, 1);
+ int cur_width = NK_MAX(width, 0);
+
+ /* retrieve correct value type */
+ if (arg_type == NK_ARG_TYPE_CHAR)
+ value = (signed char)va_arg(args, int);
+ else if (arg_type == NK_ARG_TYPE_SHORT)
+ value = (signed short)va_arg(args, int);
+ else if (arg_type == NK_ARG_TYPE_LONG)
+ value = va_arg(args, signed long);
+ else if (*iter == 'c')
+ value = (unsigned char)va_arg(args, int);
+ else value = va_arg(args, signed int);
+
+ /* convert number to string */
+ nk_itoa(number_buffer, value);
+ num_len = nk_strlen(number_buffer);
+ padding = NK_MAX(cur_width - NK_MAX(cur_precision, num_len), 0);
+ if ((flag & NK_ARG_FLAG_PLUS) || (flag & NK_ARG_FLAG_SPACE))
+ padding = NK_MAX(padding-1, 0);
+
+ /* fill left padding up to a total of `width` characters */
+ if (!(flag & NK_ARG_FLAG_LEFT)) {
+ while (padding-- > 0 && (len < buf_size)) {
+ if ((flag & NK_ARG_FLAG_ZERO) && (precision == NK_DEFAULT))
+ buf[len++] = '0';
+ else buf[len++] = ' ';
+ }
+ }
+
+ /* copy string value representation into buffer */
+ if ((flag & NK_ARG_FLAG_PLUS) && value >= 0 && len < buf_size)
+ buf[len++] = '+';
+ else if ((flag & NK_ARG_FLAG_SPACE) && value >= 0 && len < buf_size)
+ buf[len++] = ' ';
+
+ /* fill up to precision number of digits with '0' */
+ num_print = NK_MAX(cur_precision, num_len);
+ while (precision && (num_print > num_len) && (len < buf_size)) {
+ buf[len++] = '0';
+ num_print--;
+ }
+
+ /* copy string value representation into buffer */
+ num_iter = number_buffer;
+ while (precision && *num_iter && len < buf_size)
+ buf[len++] = *num_iter++;
+
+ /* fill right padding up to width characters */
+ if (flag & NK_ARG_FLAG_LEFT) {
+ while ((padding-- > 0) && (len < buf_size))
+ buf[len++] = ' ';
+ }
+ } else if (*iter == 'o' || *iter == 'x' || *iter == 'X' || *iter == 'u') {
+ /* unsigned integer */
+ unsigned long value = 0;
+ int num_len = 0, num_print, padding = 0;
+ int cur_precision = NK_MAX(precision, 1);
+ int cur_width = NK_MAX(width, 0);
+ unsigned int base = (*iter == 'o') ? 8: (*iter == 'u')? 10: 16;
+
+ /* print oct/hex/dec value */
+ const char *upper_output_format = "0123456789ABCDEF";
+ const char *lower_output_format = "0123456789abcdef";
+ const char *output_format = (*iter == 'x') ?
+ lower_output_format: upper_output_format;
+
+ /* retrieve correct value type */
+ if (arg_type == NK_ARG_TYPE_CHAR)
+ value = (unsigned char)va_arg(args, int);
+ else if (arg_type == NK_ARG_TYPE_SHORT)
+ value = (unsigned short)va_arg(args, int);
+ else if (arg_type == NK_ARG_TYPE_LONG)
+ value = va_arg(args, unsigned long);
+ else value = va_arg(args, unsigned int);
+
+ do {
+ /* convert decimal number into hex/oct number */
+ int digit = output_format[value % base];
+ if (num_len < NK_MAX_NUMBER_BUFFER)
+ number_buffer[num_len++] = (char)digit;
+ value /= base;
+ } while (value > 0);
+
+ num_print = NK_MAX(cur_precision, num_len);
+ padding = NK_MAX(cur_width - NK_MAX(cur_precision, num_len), 0);
+ if (flag & NK_ARG_FLAG_NUM)
+ padding = NK_MAX(padding-1, 0);
+
+ /* fill left padding up to a total of `width` characters */
+ if (!(flag & NK_ARG_FLAG_LEFT)) {
+ while ((padding-- > 0) && (len < buf_size)) {
+ if ((flag & NK_ARG_FLAG_ZERO) && (precision == NK_DEFAULT))
+ buf[len++] = '0';
+ else buf[len++] = ' ';
+ }
+ }
+
+ /* fill up to precision number of digits */
+ if (num_print && (flag & NK_ARG_FLAG_NUM)) {
+ if ((*iter == 'o') && (len < buf_size)) {
+ buf[len++] = '0';
+ } else if ((*iter == 'x') && ((len+1) < buf_size)) {
+ buf[len++] = '0';
+ buf[len++] = 'x';
+ } else if ((*iter == 'X') && ((len+1) < buf_size)) {
+ buf[len++] = '0';
+ buf[len++] = 'X';
+ }
+ }
+ while (precision && (num_print > num_len) && (len < buf_size)) {
+ buf[len++] = '0';
+ num_print--;
+ }
+
+ /* reverse number direction */
+ while (num_len > 0) {
+ if (precision && (len < buf_size))
+ buf[len++] = number_buffer[num_len-1];
+ num_len--;
+ }
+
+ /* fill right padding up to width characters */
+ if (flag & NK_ARG_FLAG_LEFT) {
+ while ((padding-- > 0) && (len < buf_size))
+ buf[len++] = ' ';
+ }
+ } else if (*iter == 'f') {
+ /* floating point */
+ const char *num_iter;
+ int cur_precision = (precision < 0) ? 6: precision;
+ int prefix, cur_width = NK_MAX(width, 0);
+ double value = va_arg(args, double);
+ int num_len = 0, frac_len = 0, dot = 0;
+ int padding = 0;
+
+ NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT);
+ NK_DTOA(number_buffer, value);
+ num_len = nk_strlen(number_buffer);
+
+ /* calculate padding */
+ num_iter = number_buffer;
+ while (*num_iter && *num_iter != '.')
+ num_iter++;
+
+ prefix = (*num_iter == '.')?(int)(num_iter - number_buffer)+1:0;
+ padding = NK_MAX(cur_width - (prefix + NK_MIN(cur_precision, num_len - prefix)) , 0);
+ if ((flag & NK_ARG_FLAG_PLUS) || (flag & NK_ARG_FLAG_SPACE))
+ padding = NK_MAX(padding-1, 0);
+
+ /* fill left padding up to a total of `width` characters */
+ if (!(flag & NK_ARG_FLAG_LEFT)) {
+ while (padding-- > 0 && (len < buf_size)) {
+ if (flag & NK_ARG_FLAG_ZERO)
+ buf[len++] = '0';
+ else buf[len++] = ' ';
+ }
+ }
+
+ /* copy string value representation into buffer */
+ num_iter = number_buffer;
+ if ((flag & NK_ARG_FLAG_PLUS) && (value >= 0) && (len < buf_size))
+ buf[len++] = '+';
+ else if ((flag & NK_ARG_FLAG_SPACE) && (value >= 0) && (len < buf_size))
+ buf[len++] = ' ';
+ while (*num_iter) {
+ if (dot) frac_len++;
+ if (len < buf_size)
+ buf[len++] = *num_iter;
+ if (*num_iter == '.') dot = 1;
+ if (frac_len >= cur_precision) break;
+ num_iter++;
+ }
+
+ /* fill number up to precision */
+ while (frac_len < cur_precision) {
+ if (!dot && len < buf_size) {
+ buf[len++] = '.';
+ dot = 1;
+ }
+ if (len < buf_size)
+ buf[len++] = '0';
+ frac_len++;
+ }
+
+ /* fill right padding up to width characters */
+ if (flag & NK_ARG_FLAG_LEFT) {
+ while ((padding-- > 0) && (len < buf_size))
+ buf[len++] = ' ';
+ }
+ } else {
+ /* Specifier not supported: g,G,e,E,p,z */
+ NK_ASSERT(0 && "specifier is not supported!");
+ return result;
+ }
+ }
+ buf[(len >= buf_size)?(buf_size-1):len] = 0;
+ result = (len >= buf_size)?-1:len;
+ return result;
+}
+#endif
+NK_LIB int
+nk_strfmt(char *buf, int buf_size, const char *fmt, va_list args)
+{
+ int result = -1;
+ NK_ASSERT(buf);
+ NK_ASSERT(buf_size);
+ if (!buf || !buf_size || !fmt) return 0;
+#ifdef NK_INCLUDE_STANDARD_IO
+ result = NK_VSNPRINTF(buf, (nk_size)buf_size, fmt, args);
+ result = (result >= buf_size) ? -1: result;
+ buf[buf_size-1] = 0;
+#else
+ result = nk_vsnprintf(buf, buf_size, fmt, args);
+#endif
+ return result;
+}
+#endif
+NK_API nk_hash
+nk_murmur_hash(const void * key, int len, nk_hash seed)
+{
+ /* 32-Bit MurmurHash3: https://code.google.com/p/smhasher/wiki/MurmurHash3*/
+ #define NK_ROTL(x,r) ((x) << (r) | ((x) >> (32 - r)))
+
+ nk_uint h1 = seed;
+ nk_uint k1;
+ const nk_byte *data = (const nk_byte*)key;
+ const nk_byte *keyptr = data;
+ nk_byte *k1ptr;
+ const int bsize = sizeof(k1);
+ const int nblocks = len/4;
+
+ const nk_uint c1 = 0xcc9e2d51;
+ const nk_uint c2 = 0x1b873593;
+ const nk_byte *tail;
+ int i;
+
+ /* body */
+ if (!key) return 0;
+ for (i = 0; i < nblocks; ++i, keyptr += bsize) {
+ k1ptr = (nk_byte*)&k1;
+ k1ptr[0] = keyptr[0];
+ k1ptr[1] = keyptr[1];
+ k1ptr[2] = keyptr[2];
+ k1ptr[3] = keyptr[3];
+
+ k1 *= c1;
+ k1 = NK_ROTL(k1,15);
+ k1 *= c2;
+
+ h1 ^= k1;
+ h1 = NK_ROTL(h1,13);
+ h1 = h1*5+0xe6546b64;
+ }
+
+ /* tail */
+ tail = (const nk_byte*)(data + nblocks*4);
+ k1 = 0;
+ switch (len & 3) {
+ case 3: k1 ^= (nk_uint)(tail[2] << 16); /* fallthrough */
+ case 2: k1 ^= (nk_uint)(tail[1] << 8u); /* fallthrough */
+ case 1: k1 ^= tail[0];
+ k1 *= c1;
+ k1 = NK_ROTL(k1,15);
+ k1 *= c2;
+ h1 ^= k1;
+ break;
+ default: break;
+ }
+
+ /* finalization */
+ h1 ^= (nk_uint)len;
+ /* fmix32 */
+ h1 ^= h1 >> 16;
+ h1 *= 0x85ebca6b;
+ h1 ^= h1 >> 13;
+ h1 *= 0xc2b2ae35;
+ h1 ^= h1 >> 16;
+
+ #undef NK_ROTL
+ return h1;
+}
+#ifdef NK_INCLUDE_STANDARD_IO
+NK_LIB char*
+nk_file_load(const char* path, nk_size* siz, struct nk_allocator *alloc)
+{
+ char *buf;
+ FILE *fd;
+ long ret;
+
+ NK_ASSERT(path);
+ NK_ASSERT(siz);
+ NK_ASSERT(alloc);
+ if (!path || !siz || !alloc)
+ return 0;
+
+ fd = fopen(path, "rb");
+ if (!fd) return 0;
+ fseek(fd, 0, SEEK_END);
+ ret = ftell(fd);
+ if (ret < 0) {
+ fclose(fd);
+ return 0;
+ }
+ *siz = (nk_size)ret;
+ fseek(fd, 0, SEEK_SET);
+ buf = (char*)alloc->alloc(alloc->userdata,0, *siz);
+ NK_ASSERT(buf);
+ if (!buf) {
+ fclose(fd);
+ return 0;
+ }
+ *siz = (nk_size)fread(buf, 1,*siz, fd);
+ fclose(fd);
+ return buf;
+}
+#endif
+NK_LIB int
+nk_text_clamp(const struct nk_user_font *font, const char *text,
+ int text_len, float space, int *glyphs, float *text_width,
+ nk_rune *sep_list, int sep_count)
+{
+ int i = 0;
+ int glyph_len = 0;
+ float last_width = 0;
+ nk_rune unicode = 0;
+ float width = 0;
+ int len = 0;
+ int g = 0;
+ float s;
+
+ int sep_len = 0;
+ int sep_g = 0;
+ float sep_width = 0;
+ sep_count = NK_MAX(sep_count,0);
+
+ glyph_len = nk_utf_decode(text, &unicode, text_len);
+ while (glyph_len && (width < space) && (len < text_len)) {
+ len += glyph_len;
+ s = font->width(font->userdata, font->height, text, len);
+ for (i = 0; i < sep_count; ++i) {
+ if (unicode != sep_list[i]) continue;
+ sep_width = last_width = width;
+ sep_g = g+1;
+ sep_len = len;
+ break;
+ }
+ if (i == sep_count){
+ last_width = sep_width = width;
+ sep_g = g+1;
+ }
+ width = s;
+ glyph_len = nk_utf_decode(&text[len], &unicode, text_len - len);
+ g++;
+ }
+ if (len >= text_len) {
+ *glyphs = g;
+ *text_width = last_width;
+ return len;
+ } else {
+ *glyphs = sep_g;
+ *text_width = sep_width;
+ return (!sep_len) ? len: sep_len;
+ }
+}
+NK_LIB struct nk_vec2
+nk_text_calculate_text_bounds(const struct nk_user_font *font,
+ const char *begin, int byte_len, float row_height, const char **remaining,
+ struct nk_vec2 *out_offset, int *glyphs, int op)
+{
+ float line_height = row_height;
+ struct nk_vec2 text_size = nk_vec2(0,0);
+ float line_width = 0.0f;
+
+ float glyph_width;
+ int glyph_len = 0;
+ nk_rune unicode = 0;
+ int text_len = 0;
+ if (!begin || byte_len <= 0 || !font)
+ return nk_vec2(0,row_height);
+
+ glyph_len = nk_utf_decode(begin, &unicode, byte_len);
+ if (!glyph_len) return text_size;
+ glyph_width = font->width(font->userdata, font->height, begin, glyph_len);
+
+ *glyphs = 0;
+ while ((text_len < byte_len) && glyph_len) {
+ if (unicode == '\n') {
+ text_size.x = NK_MAX(text_size.x, line_width);
+ text_size.y += line_height;
+ line_width = 0;
+ *glyphs+=1;
+ if (op == NK_STOP_ON_NEW_LINE)
+ break;
+
+ text_len++;
+ glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len);
+ continue;
+ }
+
+ if (unicode == '\r') {
+ text_len++;
+ *glyphs+=1;
+ glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len);
+ continue;
+ }
+
+ *glyphs = *glyphs + 1;
+ text_len += glyph_len;
+ line_width += (float)glyph_width;
+ glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len);
+ glyph_width = font->width(font->userdata, font->height, begin+text_len, glyph_len);
+ continue;
+ }
+
+ if (text_size.x < line_width)
+ text_size.x = line_width;
+ if (out_offset)
+ *out_offset = nk_vec2(line_width, text_size.y + line_height);
+ if (line_width > 0 || text_size.y == 0.0f)
+ text_size.y += line_height;
+ if (remaining)
+ *remaining = begin+text_len;
+ return text_size;
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * COLOR
+ *
+ * ===============================================================*/
+NK_INTERN int
+nk_parse_hex(const char *p, int length)
+{
+ int i = 0;
+ int len = 0;
+ while (len < length) {
+ i <<= 4;
+ if (p[len] >= 'a' && p[len] <= 'f')
+ i += ((p[len] - 'a') + 10);
+ else if (p[len] >= 'A' && p[len] <= 'F')
+ i += ((p[len] - 'A') + 10);
+ else i += (p[len] - '0');
+ len++;
+ }
+ return i;
+}
+NK_API struct nk_color
+nk_rgb_factor(struct nk_color col, const float factor)
+{
+ if (factor == 1.0f)
+ return col;
+ col.r = (nk_byte)(col.r * factor);
+ col.g = (nk_byte)(col.g * factor);
+ col.b = (nk_byte)(col.b * factor);
+ return col;
+}
+NK_API struct nk_color
+nk_rgba(int r, int g, int b, int a)
+{
+ struct nk_color ret;
+ ret.r = (nk_byte)NK_CLAMP(0, r, 255);
+ ret.g = (nk_byte)NK_CLAMP(0, g, 255);
+ ret.b = (nk_byte)NK_CLAMP(0, b, 255);
+ ret.a = (nk_byte)NK_CLAMP(0, a, 255);
+ return ret;
+}
+NK_API struct nk_color
+nk_rgb_hex(const char *rgb)
+{
+ struct nk_color col;
+ const char *c = rgb;
+ if (*c == '#') c++;
+ col.r = (nk_byte)nk_parse_hex(c, 2);
+ col.g = (nk_byte)nk_parse_hex(c+2, 2);
+ col.b = (nk_byte)nk_parse_hex(c+4, 2);
+ col.a = 255;
+ return col;
+}
+NK_API struct nk_color
+nk_rgba_hex(const char *rgb)
+{
+ struct nk_color col;
+ const char *c = rgb;
+ if (*c == '#') c++;
+ col.r = (nk_byte)nk_parse_hex(c, 2);
+ col.g = (nk_byte)nk_parse_hex(c+2, 2);
+ col.b = (nk_byte)nk_parse_hex(c+4, 2);
+ col.a = (nk_byte)nk_parse_hex(c+6, 2);
+ return col;
+}
+NK_API void
+nk_color_hex_rgba(char *output, struct nk_color col)
+{
+ #define NK_TO_HEX(i) ((i) <= 9 ? '0' + (i): 'A' - 10 + (i))
+ output[0] = (char)NK_TO_HEX((col.r & 0xF0) >> 4);
+ output[1] = (char)NK_TO_HEX((col.r & 0x0F));
+ output[2] = (char)NK_TO_HEX((col.g & 0xF0) >> 4);
+ output[3] = (char)NK_TO_HEX((col.g & 0x0F));
+ output[4] = (char)NK_TO_HEX((col.b & 0xF0) >> 4);
+ output[5] = (char)NK_TO_HEX((col.b & 0x0F));
+ output[6] = (char)NK_TO_HEX((col.a & 0xF0) >> 4);
+ output[7] = (char)NK_TO_HEX((col.a & 0x0F));
+ output[8] = '\0';
+ #undef NK_TO_HEX
+}
+NK_API void
+nk_color_hex_rgb(char *output, struct nk_color col)
+{
+ #define NK_TO_HEX(i) ((i) <= 9 ? '0' + (i): 'A' - 10 + (i))
+ output[0] = (char)NK_TO_HEX((col.r & 0xF0) >> 4);
+ output[1] = (char)NK_TO_HEX((col.r & 0x0F));
+ output[2] = (char)NK_TO_HEX((col.g & 0xF0) >> 4);
+ output[3] = (char)NK_TO_HEX((col.g & 0x0F));
+ output[4] = (char)NK_TO_HEX((col.b & 0xF0) >> 4);
+ output[5] = (char)NK_TO_HEX((col.b & 0x0F));
+ output[6] = '\0';
+ #undef NK_TO_HEX
+}
+NK_API struct nk_color
+nk_rgba_iv(const int *c)
+{
+ return nk_rgba(c[0], c[1], c[2], c[3]);
+}
+NK_API struct nk_color
+nk_rgba_bv(const nk_byte *c)
+{
+ return nk_rgba(c[0], c[1], c[2], c[3]);
+}
+NK_API struct nk_color
+nk_rgb(int r, int g, int b)
+{
+ struct nk_color ret;
+ ret.r = (nk_byte)NK_CLAMP(0, r, 255);
+ ret.g = (nk_byte)NK_CLAMP(0, g, 255);
+ ret.b = (nk_byte)NK_CLAMP(0, b, 255);
+ ret.a = (nk_byte)255;
+ return ret;
+}
+NK_API struct nk_color
+nk_rgb_iv(const int *c)
+{
+ return nk_rgb(c[0], c[1], c[2]);
+}
+NK_API struct nk_color
+nk_rgb_bv(const nk_byte* c)
+{
+ return nk_rgb(c[0], c[1], c[2]);
+}
+NK_API struct nk_color
+nk_rgba_u32(nk_uint in)
+{
+ struct nk_color ret;
+ ret.r = (in & 0xFF);
+ ret.g = ((in >> 8) & 0xFF);
+ ret.b = ((in >> 16) & 0xFF);
+ ret.a = (nk_byte)((in >> 24) & 0xFF);
+ return ret;
+}
+NK_API struct nk_color
+nk_rgba_f(float r, float g, float b, float a)
+{
+ struct nk_color ret;
+ ret.r = (nk_byte)(NK_SATURATE(r) * 255.0f);
+ ret.g = (nk_byte)(NK_SATURATE(g) * 255.0f);
+ ret.b = (nk_byte)(NK_SATURATE(b) * 255.0f);
+ ret.a = (nk_byte)(NK_SATURATE(a) * 255.0f);
+ return ret;
+}
+NK_API struct nk_color
+nk_rgba_fv(const float *c)
+{
+ return nk_rgba_f(c[0], c[1], c[2], c[3]);
+}
+NK_API struct nk_color
+nk_rgba_cf(struct nk_colorf c)
+{
+ return nk_rgba_f(c.r, c.g, c.b, c.a);
+}
+NK_API struct nk_color
+nk_rgb_f(float r, float g, float b)
+{
+ struct nk_color ret;
+ ret.r = (nk_byte)(NK_SATURATE(r) * 255.0f);
+ ret.g = (nk_byte)(NK_SATURATE(g) * 255.0f);
+ ret.b = (nk_byte)(NK_SATURATE(b) * 255.0f);
+ ret.a = 255;
+ return ret;
+}
+NK_API struct nk_color
+nk_rgb_fv(const float *c)
+{
+ return nk_rgb_f(c[0], c[1], c[2]);
+}
+NK_API struct nk_color
+nk_rgb_cf(struct nk_colorf c)
+{
+ return nk_rgb_f(c.r, c.g, c.b);
+}
+NK_API struct nk_color
+nk_hsv(int h, int s, int v)
+{
+ return nk_hsva(h, s, v, 255);
+}
+NK_API struct nk_color
+nk_hsv_iv(const int *c)
+{
+ return nk_hsv(c[0], c[1], c[2]);
+}
+NK_API struct nk_color
+nk_hsv_bv(const nk_byte *c)
+{
+ return nk_hsv(c[0], c[1], c[2]);
+}
+NK_API struct nk_color
+nk_hsv_f(float h, float s, float v)
+{
+ return nk_hsva_f(h, s, v, 1.0f);
+}
+NK_API struct nk_color
+nk_hsv_fv(const float *c)
+{
+ return nk_hsv_f(c[0], c[1], c[2]);
+}
+NK_API struct nk_color
+nk_hsva(int h, int s, int v, int a)
+{
+ float hf = ((float)NK_CLAMP(0, h, 255)) / 255.0f;
+ float sf = ((float)NK_CLAMP(0, s, 255)) / 255.0f;
+ float vf = ((float)NK_CLAMP(0, v, 255)) / 255.0f;
+ float af = ((float)NK_CLAMP(0, a, 255)) / 255.0f;
+ return nk_hsva_f(hf, sf, vf, af);
+}
+NK_API struct nk_color
+nk_hsva_iv(const int *c)
+{
+ return nk_hsva(c[0], c[1], c[2], c[3]);
+}
+NK_API struct nk_color
+nk_hsva_bv(const nk_byte *c)
+{
+ return nk_hsva(c[0], c[1], c[2], c[3]);
+}
+NK_API struct nk_colorf
+nk_hsva_colorf(float h, float s, float v, float a)
+{
+ int i;
+ float p, q, t, f;
+ struct nk_colorf out = {0,0,0,0};
+ if (s <= 0.0f) {
+ out.r = v; out.g = v; out.b = v; out.a = a;
+ return out;
+ }
+ h = h / (60.0f/360.0f);
+ i = (int)h;
+ f = h - (float)i;
+ p = v * (1.0f - s);
+ q = v * (1.0f - (s * f));
+ t = v * (1.0f - s * (1.0f - f));
+
+ switch (i) {
+ case 0: default: out.r = v; out.g = t; out.b = p; break;
+ case 1: out.r = q; out.g = v; out.b = p; break;
+ case 2: out.r = p; out.g = v; out.b = t; break;
+ case 3: out.r = p; out.g = q; out.b = v; break;
+ case 4: out.r = t; out.g = p; out.b = v; break;
+ case 5: out.r = v; out.g = p; out.b = q; break;}
+ out.a = a;
+ return out;
+}
+NK_API struct nk_colorf
+nk_hsva_colorfv(float *c)
+{
+ return nk_hsva_colorf(c[0], c[1], c[2], c[3]);
+}
+NK_API struct nk_color
+nk_hsva_f(float h, float s, float v, float a)
+{
+ struct nk_colorf c = nk_hsva_colorf(h, s, v, a);
+ return nk_rgba_f(c.r, c.g, c.b, c.a);
+}
+NK_API struct nk_color
+nk_hsva_fv(const float *c)
+{
+ return nk_hsva_f(c[0], c[1], c[2], c[3]);
+}
+NK_API nk_uint
+nk_color_u32(struct nk_color in)
+{
+ nk_uint out = (nk_uint)in.r;
+ out |= ((nk_uint)in.g << 8);
+ out |= ((nk_uint)in.b << 16);
+ out |= ((nk_uint)in.a << 24);
+ return out;
+}
+NK_API void
+nk_color_f(float *r, float *g, float *b, float *a, struct nk_color in)
+{
+ NK_STORAGE const float s = 1.0f/255.0f;
+ *r = (float)in.r * s;
+ *g = (float)in.g * s;
+ *b = (float)in.b * s;
+ *a = (float)in.a * s;
+}
+NK_API void
+nk_color_fv(float *c, struct nk_color in)
+{
+ nk_color_f(&c[0], &c[1], &c[2], &c[3], in);
+}
+NK_API struct nk_colorf
+nk_color_cf(struct nk_color in)
+{
+ struct nk_colorf o;
+ nk_color_f(&o.r, &o.g, &o.b, &o.a, in);
+ return o;
+}
+NK_API void
+nk_color_d(double *r, double *g, double *b, double *a, struct nk_color in)
+{
+ NK_STORAGE const double s = 1.0/255.0;
+ *r = (double)in.r * s;
+ *g = (double)in.g * s;
+ *b = (double)in.b * s;
+ *a = (double)in.a * s;
+}
+NK_API void
+nk_color_dv(double *c, struct nk_color in)
+{
+ nk_color_d(&c[0], &c[1], &c[2], &c[3], in);
+}
+NK_API void
+nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color in)
+{
+ float a;
+ nk_color_hsva_f(out_h, out_s, out_v, &a, in);
+}
+NK_API void
+nk_color_hsv_fv(float *out, struct nk_color in)
+{
+ float a;
+ nk_color_hsva_f(&out[0], &out[1], &out[2], &a, in);
+}
+NK_API void
+nk_colorf_hsva_f(float *out_h, float *out_s,
+ float *out_v, float *out_a, struct nk_colorf in)
+{
+ float chroma;
+ float K = 0.0f;
+ if (in.g < in.b) {
+ const float t = in.g; in.g = in.b; in.b = t;
+ K = -1.f;
+ }
+ if (in.r < in.g) {
+ const float t = in.r; in.r = in.g; in.g = t;
+ K = -2.f/6.0f - K;
+ }
+ chroma = in.r - ((in.g < in.b) ? in.g: in.b);
+ *out_h = NK_ABS(K + (in.g - in.b)/(6.0f * chroma + 1e-20f));
+ *out_s = chroma / (in.r + 1e-20f);
+ *out_v = in.r;
+ *out_a = in.a;
+
+}
+NK_API void
+nk_colorf_hsva_fv(float *hsva, struct nk_colorf in)
+{
+ nk_colorf_hsva_f(&hsva[0], &hsva[1], &hsva[2], &hsva[3], in);
+}
+NK_API void
+nk_color_hsva_f(float *out_h, float *out_s,
+ float *out_v, float *out_a, struct nk_color in)
+{
+ struct nk_colorf col;
+ nk_color_f(&col.r,&col.g,&col.b,&col.a, in);
+ nk_colorf_hsva_f(out_h, out_s, out_v, out_a, col);
+}
+NK_API void
+nk_color_hsva_fv(float *out, struct nk_color in)
+{
+ nk_color_hsva_f(&out[0], &out[1], &out[2], &out[3], in);
+}
+NK_API void
+nk_color_hsva_i(int *out_h, int *out_s, int *out_v,
+ int *out_a, struct nk_color in)
+{
+ float h,s,v,a;
+ nk_color_hsva_f(&h, &s, &v, &a, in);
+ *out_h = (nk_byte)(h * 255.0f);
+ *out_s = (nk_byte)(s * 255.0f);
+ *out_v = (nk_byte)(v * 255.0f);
+ *out_a = (nk_byte)(a * 255.0f);
+}
+NK_API void
+nk_color_hsva_iv(int *out, struct nk_color in)
+{
+ nk_color_hsva_i(&out[0], &out[1], &out[2], &out[3], in);
+}
+NK_API void
+nk_color_hsva_bv(nk_byte *out, struct nk_color in)
+{
+ int tmp[4];
+ nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in);
+ out[0] = (nk_byte)tmp[0];
+ out[1] = (nk_byte)tmp[1];
+ out[2] = (nk_byte)tmp[2];
+ out[3] = (nk_byte)tmp[3];
+}
+NK_API void
+nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color in)
+{
+ int tmp[4];
+ nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in);
+ *h = (nk_byte)tmp[0];
+ *s = (nk_byte)tmp[1];
+ *v = (nk_byte)tmp[2];
+ *a = (nk_byte)tmp[3];
+}
+NK_API void
+nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color in)
+{
+ int a;
+ nk_color_hsva_i(out_h, out_s, out_v, &a, in);
+}
+NK_API void
+nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color in)
+{
+ int tmp[4];
+ nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in);
+ *out_h = (nk_byte)tmp[0];
+ *out_s = (nk_byte)tmp[1];
+ *out_v = (nk_byte)tmp[2];
+}
+NK_API void
+nk_color_hsv_iv(int *out, struct nk_color in)
+{
+ nk_color_hsv_i(&out[0], &out[1], &out[2], in);
+}
+NK_API void
+nk_color_hsv_bv(nk_byte *out, struct nk_color in)
+{
+ int tmp[4];
+ nk_color_hsv_i(&tmp[0], &tmp[1], &tmp[2], in);
+ out[0] = (nk_byte)tmp[0];
+ out[1] = (nk_byte)tmp[1];
+ out[2] = (nk_byte)tmp[2];
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * UTF-8
+ *
+ * ===============================================================*/
+NK_GLOBAL const nk_byte nk_utfbyte[NK_UTF_SIZE+1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
+NK_GLOBAL const nk_byte nk_utfmask[NK_UTF_SIZE+1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
+NK_GLOBAL const nk_uint nk_utfmin[NK_UTF_SIZE+1] = {0, 0, 0x80, 0x800, 0x10000};
+NK_GLOBAL const nk_uint nk_utfmax[NK_UTF_SIZE+1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
+
+NK_INTERN int
+nk_utf_validate(nk_rune *u, int i)
+{
+ NK_ASSERT(u);
+ if (!u) return 0;
+ if (!NK_BETWEEN(*u, nk_utfmin[i], nk_utfmax[i]) ||
+ NK_BETWEEN(*u, 0xD800, 0xDFFF))
+ *u = NK_UTF_INVALID;
+ for (i = 1; *u > nk_utfmax[i]; ++i);
+ return i;
+}
+NK_INTERN nk_rune
+nk_utf_decode_byte(char c, int *i)
+{
+ NK_ASSERT(i);
+ if (!i) return 0;
+ for(*i = 0; *i < (int)NK_LEN(nk_utfmask); ++(*i)) {
+ if (((nk_byte)c & nk_utfmask[*i]) == nk_utfbyte[*i])
+ return (nk_byte)(c & ~nk_utfmask[*i]);
+ }
+ return 0;
+}
+NK_API int
+nk_utf_decode(const char *c, nk_rune *u, int clen)
+{
+ int i, j, len, type=0;
+ nk_rune udecoded;
+
+ NK_ASSERT(c);
+ NK_ASSERT(u);
+
+ if (!c || !u) return 0;
+ if (!clen) return 0;
+ *u = NK_UTF_INVALID;
+
+ udecoded = nk_utf_decode_byte(c[0], &len);
+ if (!NK_BETWEEN(len, 1, NK_UTF_SIZE))
+ return 1;
+
+ for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
+ udecoded = (udecoded << 6) | nk_utf_decode_byte(c[i], &type);
+ if (type != 0)
+ return j;
+ }
+ if (j < len)
+ return 0;
+ *u = udecoded;
+ nk_utf_validate(u, len);
+ return len;
+}
+NK_INTERN char
+nk_utf_encode_byte(nk_rune u, int i)
+{
+ return (char)((nk_utfbyte[i]) | ((nk_byte)u & ~nk_utfmask[i]));
+}
+NK_API int
+nk_utf_encode(nk_rune u, char *c, int clen)
+{
+ int len, i;
+ len = nk_utf_validate(&u, 0);
+ if (clen < len || !len || len > NK_UTF_SIZE)
+ return 0;
+
+ for (i = len - 1; i != 0; --i) {
+ c[i] = nk_utf_encode_byte(u, 0);
+ u >>= 6;
+ }
+ c[0] = nk_utf_encode_byte(u, len);
+ return len;
+}
+NK_API int
+nk_utf_len(const char *str, int len)
+{
+ const char *text;
+ int glyphs = 0;
+ int text_len;
+ int glyph_len;
+ int src_len = 0;
+ nk_rune unicode;
+
+ NK_ASSERT(str);
+ if (!str || !len) return 0;
+
+ text = str;
+ text_len = len;
+ glyph_len = nk_utf_decode(text, &unicode, text_len);
+ while (glyph_len && src_len < len) {
+ glyphs++;
+ src_len = src_len + glyph_len;
+ glyph_len = nk_utf_decode(text + src_len, &unicode, text_len - src_len);
+ }
+ return glyphs;
+}
+NK_API const char*
+nk_utf_at(const char *buffer, int length, int index,
+ nk_rune *unicode, int *len)
+{
+ int i = 0;
+ int src_len = 0;
+ int glyph_len = 0;
+ const char *text;
+ int text_len;
+
+ NK_ASSERT(buffer);
+ NK_ASSERT(unicode);
+ NK_ASSERT(len);
+
+ if (!buffer || !unicode || !len) return 0;
+ if (index < 0) {
+ *unicode = NK_UTF_INVALID;
+ *len = 0;
+ return 0;
+ }
+
+ text = buffer;
+ text_len = length;
+ glyph_len = nk_utf_decode(text, unicode, text_len);
+ while (glyph_len) {
+ if (i == index) {
+ *len = glyph_len;
+ break;
+ }
+
+ i++;
+ src_len = src_len + glyph_len;
+ glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len);
+ }
+ if (i != index) return 0;
+ return buffer + src_len;
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * BUFFER
+ *
+ * ===============================================================*/
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_LIB void*
+nk_malloc(nk_handle unused, void *old,nk_size size)
+{
+ NK_UNUSED(unused);
+ NK_UNUSED(old);
+ return malloc(size);
+}
+NK_LIB void
+nk_mfree(nk_handle unused, void *ptr)
+{
+ NK_UNUSED(unused);
+ free(ptr);
+}
+NK_API void
+nk_buffer_init_default(struct nk_buffer *buffer)
+{
+ struct nk_allocator alloc;
+ alloc.userdata.ptr = 0;
+ alloc.alloc = nk_malloc;
+ alloc.free = nk_mfree;
+ nk_buffer_init(buffer, &alloc, NK_BUFFER_DEFAULT_INITIAL_SIZE);
+}
+#endif
+
+NK_API void
+nk_buffer_init(struct nk_buffer *b, const struct nk_allocator *a,
+ nk_size initial_size)
+{
+ NK_ASSERT(b);
+ NK_ASSERT(a);
+ NK_ASSERT(initial_size);
+ if (!b || !a || !initial_size) return;
+
+ nk_zero(b, sizeof(*b));
+ b->type = NK_BUFFER_DYNAMIC;
+ b->memory.ptr = a->alloc(a->userdata,0, initial_size);
+ b->memory.size = initial_size;
+ b->size = initial_size;
+ b->grow_factor = 2.0f;
+ b->pool = *a;
+}
+NK_API void
+nk_buffer_init_fixed(struct nk_buffer *b, void *m, nk_size size)
+{
+ NK_ASSERT(b);
+ NK_ASSERT(m);
+ NK_ASSERT(size);
+ if (!b || !m || !size) return;
+
+ nk_zero(b, sizeof(*b));
+ b->type = NK_BUFFER_FIXED;
+ b->memory.ptr = m;
+ b->memory.size = size;
+ b->size = size;
+}
+NK_LIB void*
+nk_buffer_align(void *unaligned,
+ nk_size align, nk_size *alignment,
+ enum nk_buffer_allocation_type type)
+{
+ void *memory = 0;
+ switch (type) {
+ default:
+ case NK_BUFFER_MAX:
+ case NK_BUFFER_FRONT:
+ if (align) {
+ memory = NK_ALIGN_PTR(unaligned, align);
+ *alignment = (nk_size)((nk_byte*)memory - (nk_byte*)unaligned);
+ } else {
+ memory = unaligned;
+ *alignment = 0;
+ }
+ break;
+ case NK_BUFFER_BACK:
+ if (align) {
+ memory = NK_ALIGN_PTR_BACK(unaligned, align);
+ *alignment = (nk_size)((nk_byte*)unaligned - (nk_byte*)memory);
+ } else {
+ memory = unaligned;
+ *alignment = 0;
+ }
+ break;
+ }
+ return memory;
+}
+NK_LIB void*
+nk_buffer_realloc(struct nk_buffer *b, nk_size capacity, nk_size *size)
+{
+ void *temp;
+ nk_size buffer_size;
+
+ NK_ASSERT(b);
+ NK_ASSERT(size);
+ if (!b || !size || !b->pool.alloc || !b->pool.free)
+ return 0;
+
+ buffer_size = b->memory.size;
+ temp = b->pool.alloc(b->pool.userdata, b->memory.ptr, capacity);
+ NK_ASSERT(temp);
+ if (!temp) return 0;
+
+ *size = capacity;
+ if (temp != b->memory.ptr) {
+ NK_MEMCPY(temp, b->memory.ptr, buffer_size);
+ b->pool.free(b->pool.userdata, b->memory.ptr);
+ }
+
+ if (b->size == buffer_size) {
+ /* no back buffer so just set correct size */
+ b->size = capacity;
+ return temp;
+ } else {
+ /* copy back buffer to the end of the new buffer */
+ void *dst, *src;
+ nk_size back_size;
+ back_size = buffer_size - b->size;
+ dst = nk_ptr_add(void, temp, capacity - back_size);
+ src = nk_ptr_add(void, temp, b->size);
+ NK_MEMCPY(dst, src, back_size);
+ b->size = capacity - back_size;
+ }
+ return temp;
+}
+NK_LIB void*
+nk_buffer_alloc(struct nk_buffer *b, enum nk_buffer_allocation_type type,
+ nk_size size, nk_size align)
+{
+ int full;
+ nk_size alignment;
+ void *unaligned;
+ void *memory;
+
+ NK_ASSERT(b);
+ NK_ASSERT(size);
+ if (!b || !size) return 0;
+ b->needed += size;
+
+ /* calculate total size with needed alignment + size */
+ if (type == NK_BUFFER_FRONT)
+ unaligned = nk_ptr_add(void, b->memory.ptr, b->allocated);
+ else unaligned = nk_ptr_add(void, b->memory.ptr, b->size - size);
+ memory = nk_buffer_align(unaligned, align, &alignment, type);
+
+ /* check if buffer has enough memory*/
+ if (type == NK_BUFFER_FRONT)
+ full = ((b->allocated + size + alignment) > b->size);
+ else full = ((b->size - NK_MIN(b->size,(size + alignment))) <= b->allocated);
+
+ if (full) {
+ nk_size capacity;
+ if (b->type != NK_BUFFER_DYNAMIC)
+ return 0;
+ NK_ASSERT(b->pool.alloc && b->pool.free);
+ if (b->type != NK_BUFFER_DYNAMIC || !b->pool.alloc || !b->pool.free)
+ return 0;
+
+ /* buffer is full so allocate bigger buffer if dynamic */
+ capacity = (nk_size)((float)b->memory.size * b->grow_factor);
+ capacity = NK_MAX(capacity, nk_round_up_pow2((nk_uint)(b->allocated + size)));
+ b->memory.ptr = nk_buffer_realloc(b, capacity, &b->memory.size);
+ if (!b->memory.ptr) return 0;
+
+ /* align newly allocated pointer */
+ if (type == NK_BUFFER_FRONT)
+ unaligned = nk_ptr_add(void, b->memory.ptr, b->allocated);
+ else unaligned = nk_ptr_add(void, b->memory.ptr, b->size - size);
+ memory = nk_buffer_align(unaligned, align, &alignment, type);
+ }
+ if (type == NK_BUFFER_FRONT)
+ b->allocated += size + alignment;
+ else b->size -= (size + alignment);
+ b->needed += alignment;
+ b->calls++;
+ return memory;
+}
+NK_API void
+nk_buffer_push(struct nk_buffer *b, enum nk_buffer_allocation_type type,
+ const void *memory, nk_size size, nk_size align)
+{
+ void *mem = nk_buffer_alloc(b, type, size, align);
+ if (!mem) return;
+ NK_MEMCPY(mem, memory, size);
+}
+NK_API void
+nk_buffer_mark(struct nk_buffer *buffer, enum nk_buffer_allocation_type type)
+{
+ NK_ASSERT(buffer);
+ if (!buffer) return;
+ buffer->marker[type].active = nk_true;
+ if (type == NK_BUFFER_BACK)
+ buffer->marker[type].offset = buffer->size;
+ else buffer->marker[type].offset = buffer->allocated;
+}
+NK_API void
+nk_buffer_reset(struct nk_buffer *buffer, enum nk_buffer_allocation_type type)
+{
+ NK_ASSERT(buffer);
+ if (!buffer) return;
+ if (type == NK_BUFFER_BACK) {
+ /* reset back buffer either back to marker or empty */
+ buffer->needed -= (buffer->memory.size - buffer->marker[type].offset);
+ if (buffer->marker[type].active)
+ buffer->size = buffer->marker[type].offset;
+ else buffer->size = buffer->memory.size;
+ buffer->marker[type].active = nk_false;
+ } else {
+ /* reset front buffer either back to back marker or empty */
+ buffer->needed -= (buffer->allocated - buffer->marker[type].offset);
+ if (buffer->marker[type].active)
+ buffer->allocated = buffer->marker[type].offset;
+ else buffer->allocated = 0;
+ buffer->marker[type].active = nk_false;
+ }
+}
+NK_API void
+nk_buffer_clear(struct nk_buffer *b)
+{
+ NK_ASSERT(b);
+ if (!b) return;
+ b->allocated = 0;
+ b->size = b->memory.size;
+ b->calls = 0;
+ b->needed = 0;
+}
+NK_API void
+nk_buffer_free(struct nk_buffer *b)
+{
+ NK_ASSERT(b);
+ if (!b || !b->memory.ptr) return;
+ if (b->type == NK_BUFFER_FIXED) return;
+ if (!b->pool.free) return;
+ NK_ASSERT(b->pool.free);
+ b->pool.free(b->pool.userdata, b->memory.ptr);
+}
+NK_API void
+nk_buffer_info(struct nk_memory_status *s, struct nk_buffer *b)
+{
+ NK_ASSERT(b);
+ NK_ASSERT(s);
+ if (!s || !b) return;
+ s->allocated = b->allocated;
+ s->size = b->memory.size;
+ s->needed = b->needed;
+ s->memory = b->memory.ptr;
+ s->calls = b->calls;
+}
+NK_API void*
+nk_buffer_memory(struct nk_buffer *buffer)
+{
+ NK_ASSERT(buffer);
+ if (!buffer) return 0;
+ return buffer->memory.ptr;
+}
+NK_API const void*
+nk_buffer_memory_const(const struct nk_buffer *buffer)
+{
+ NK_ASSERT(buffer);
+ if (!buffer) return 0;
+ return buffer->memory.ptr;
+}
+NK_API nk_size
+nk_buffer_total(struct nk_buffer *buffer)
+{
+ NK_ASSERT(buffer);
+ if (!buffer) return 0;
+ return buffer->memory.size;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * STRING
+ *
+ * ===============================================================*/
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void
+nk_str_init_default(struct nk_str *str)
+{
+ struct nk_allocator alloc;
+ alloc.userdata.ptr = 0;
+ alloc.alloc = nk_malloc;
+ alloc.free = nk_mfree;
+ nk_buffer_init(&str->buffer, &alloc, 32);
+ str->len = 0;
+}
+#endif
+
+NK_API void
+nk_str_init(struct nk_str *str, const struct nk_allocator *alloc, nk_size size)
+{
+ nk_buffer_init(&str->buffer, alloc, size);
+ str->len = 0;
+}
+NK_API void
+nk_str_init_fixed(struct nk_str *str, void *memory, nk_size size)
+{
+ nk_buffer_init_fixed(&str->buffer, memory, size);
+ str->len = 0;
+}
+NK_API int
+nk_str_append_text_char(struct nk_str *s, const char *str, int len)
+{
+ char *mem;
+ NK_ASSERT(s);
+ NK_ASSERT(str);
+ if (!s || !str || !len) return 0;
+ mem = (char*)nk_buffer_alloc(&s->buffer, NK_BUFFER_FRONT, (nk_size)len * sizeof(char), 0);
+ if (!mem) return 0;
+ NK_MEMCPY(mem, str, (nk_size)len * sizeof(char));
+ s->len += nk_utf_len(str, len);
+ return len;
+}
+NK_API int
+nk_str_append_str_char(struct nk_str *s, const char *str)
+{
+ return nk_str_append_text_char(s, str, nk_strlen(str));
+}
+NK_API int
+nk_str_append_text_utf8(struct nk_str *str, const char *text, int len)
+{
+ int i = 0;
+ int byte_len = 0;
+ nk_rune unicode;
+ if (!str || !text || !len) return 0;
+ for (i = 0; i < len; ++i)
+ byte_len += nk_utf_decode(text+byte_len, &unicode, 4);
+ nk_str_append_text_char(str, text, byte_len);
+ return len;
+}
+NK_API int
+nk_str_append_str_utf8(struct nk_str *str, const char *text)
+{
+ int byte_len = 0;
+ int num_runes = 0;
+ int glyph_len = 0;
+ nk_rune unicode;
+ if (!str || !text) return 0;
+
+ glyph_len = byte_len = nk_utf_decode(text+byte_len, &unicode, 4);
+ while (unicode != '\0' && glyph_len) {
+ glyph_len = nk_utf_decode(text+byte_len, &unicode, 4);
+ byte_len += glyph_len;
+ num_runes++;
+ }
+ nk_str_append_text_char(str, text, byte_len);
+ return num_runes;
+}
+NK_API int
+nk_str_append_text_runes(struct nk_str *str, const nk_rune *text, int len)
+{
+ int i = 0;
+ int byte_len = 0;
+ nk_glyph glyph;
+
+ NK_ASSERT(str);
+ if (!str || !text || !len) return 0;
+ for (i = 0; i < len; ++i) {
+ byte_len = nk_utf_encode(text[i], glyph, NK_UTF_SIZE);
+ if (!byte_len) break;
+ nk_str_append_text_char(str, glyph, byte_len);
+ }
+ return len;
+}
+NK_API int
+nk_str_append_str_runes(struct nk_str *str, const nk_rune *runes)
+{
+ int i = 0;
+ nk_glyph glyph;
+ int byte_len;
+ NK_ASSERT(str);
+ if (!str || !runes) return 0;
+ while (runes[i] != '\0') {
+ byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE);
+ nk_str_append_text_char(str, glyph, byte_len);
+ i++;
+ }
+ return i;
+}
+NK_API int
+nk_str_insert_at_char(struct nk_str *s, int pos, const char *str, int len)
+{
+ int i;
+ void *mem;
+ char *src;
+ char *dst;
+
+ int copylen;
+ NK_ASSERT(s);
+ NK_ASSERT(str);
+ NK_ASSERT(len >= 0);
+ if (!s || !str || !len || (nk_size)pos > s->buffer.allocated) return 0;
+ if ((s->buffer.allocated + (nk_size)len >= s->buffer.memory.size) &&
+ (s->buffer.type == NK_BUFFER_FIXED)) return 0;
+
+ copylen = (int)s->buffer.allocated - pos;
+ if (!copylen) {
+ nk_str_append_text_char(s, str, len);
+ return 1;
+ }
+ mem = nk_buffer_alloc(&s->buffer, NK_BUFFER_FRONT, (nk_size)len * sizeof(char), 0);
+ if (!mem) return 0;
+
+ /* memmove */
+ NK_ASSERT(((int)pos + (int)len + ((int)copylen - 1)) >= 0);
+ NK_ASSERT(((int)pos + ((int)copylen - 1)) >= 0);
+ dst = nk_ptr_add(char, s->buffer.memory.ptr, pos + len + (copylen - 1));
+ src = nk_ptr_add(char, s->buffer.memory.ptr, pos + (copylen-1));
+ for (i = 0; i < copylen; ++i) *dst-- = *src--;
+ mem = nk_ptr_add(void, s->buffer.memory.ptr, pos);
+ NK_MEMCPY(mem, str, (nk_size)len * sizeof(char));
+ s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated);
+ return 1;
+}
+NK_API int
+nk_str_insert_at_rune(struct nk_str *str, int pos, const char *cstr, int len)
+{
+ int glyph_len;
+ nk_rune unicode;
+ const char *begin;
+ const char *buffer;
+
+ NK_ASSERT(str);
+ NK_ASSERT(cstr);
+ NK_ASSERT(len);
+ if (!str || !cstr || !len) return 0;
+ begin = nk_str_at_rune(str, pos, &unicode, &glyph_len);
+ if (!str->len)
+ return nk_str_append_text_char(str, cstr, len);
+ buffer = nk_str_get_const(str);
+ if (!begin) return 0;
+ return nk_str_insert_at_char(str, (int)(begin - buffer), cstr, len);
+}
+NK_API int
+nk_str_insert_text_char(struct nk_str *str, int pos, const char *text, int len)
+{
+ return nk_str_insert_text_utf8(str, pos, text, len);
+}
+NK_API int
+nk_str_insert_str_char(struct nk_str *str, int pos, const char *text)
+{
+ return nk_str_insert_text_utf8(str, pos, text, nk_strlen(text));
+}
+NK_API int
+nk_str_insert_text_utf8(struct nk_str *str, int pos, const char *text, int len)
+{
+ int i = 0;
+ int byte_len = 0;
+ nk_rune unicode;
+
+ NK_ASSERT(str);
+ NK_ASSERT(text);
+ if (!str || !text || !len) return 0;
+ for (i = 0; i < len; ++i)
+ byte_len += nk_utf_decode(text+byte_len, &unicode, 4);
+ nk_str_insert_at_rune(str, pos, text, byte_len);
+ return len;
+}
+NK_API int
+nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text)
+{
+ int byte_len = 0;
+ int num_runes = 0;
+ int glyph_len = 0;
+ nk_rune unicode;
+ if (!str || !text) return 0;
+
+ glyph_len = byte_len = nk_utf_decode(text+byte_len, &unicode, 4);
+ while (unicode != '\0' && glyph_len) {
+ glyph_len = nk_utf_decode(text+byte_len, &unicode, 4);
+ byte_len += glyph_len;
+ num_runes++;
+ }
+ nk_str_insert_at_rune(str, pos, text, byte_len);
+ return num_runes;
+}
+NK_API int
+nk_str_insert_text_runes(struct nk_str *str, int pos, const nk_rune *runes, int len)
+{
+ int i = 0;
+ int byte_len = 0;
+ nk_glyph glyph;
+
+ NK_ASSERT(str);
+ if (!str || !runes || !len) return 0;
+ for (i = 0; i < len; ++i) {
+ byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE);
+ if (!byte_len) break;
+ nk_str_insert_at_rune(str, pos+i, glyph, byte_len);
+ }
+ return len;
+}
+NK_API int
+nk_str_insert_str_runes(struct nk_str *str, int pos, const nk_rune *runes)
+{
+ int i = 0;
+ nk_glyph glyph;
+ int byte_len;
+ NK_ASSERT(str);
+ if (!str || !runes) return 0;
+ while (runes[i] != '\0') {
+ byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE);
+ nk_str_insert_at_rune(str, pos+i, glyph, byte_len);
+ i++;
+ }
+ return i;
+}
+NK_API void
+nk_str_remove_chars(struct nk_str *s, int len)
+{
+ NK_ASSERT(s);
+ NK_ASSERT(len >= 0);
+ if (!s || len < 0 || (nk_size)len > s->buffer.allocated) return;
+ NK_ASSERT(((int)s->buffer.allocated - (int)len) >= 0);
+ s->buffer.allocated -= (nk_size)len;
+ s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated);
+}
+NK_API void
+nk_str_remove_runes(struct nk_str *str, int len)
+{
+ int index;
+ const char *begin;
+ const char *end;
+ nk_rune unicode;
+
+ NK_ASSERT(str);
+ NK_ASSERT(len >= 0);
+ if (!str || len < 0) return;
+ if (len >= str->len) {
+ str->len = 0;
+ return;
+ }
+
+ index = str->len - len;
+ begin = nk_str_at_rune(str, index, &unicode, &len);
+ end = (const char*)str->buffer.memory.ptr + str->buffer.allocated;
+ nk_str_remove_chars(str, (int)(end-begin)+1);
+}
+NK_API void
+nk_str_delete_chars(struct nk_str *s, int pos, int len)
+{
+ NK_ASSERT(s);
+ if (!s || !len || (nk_size)pos > s->buffer.allocated ||
+ (nk_size)(pos + len) > s->buffer.allocated) return;
+
+ if ((nk_size)(pos + len) < s->buffer.allocated) {
+ /* memmove */
+ char *dst = nk_ptr_add(char, s->buffer.memory.ptr, pos);
+ char *src = nk_ptr_add(char, s->buffer.memory.ptr, pos + len);
+ NK_MEMCPY(dst, src, s->buffer.allocated - (nk_size)(pos + len));
+ NK_ASSERT(((int)s->buffer.allocated - (int)len) >= 0);
+ s->buffer.allocated -= (nk_size)len;
+ } else nk_str_remove_chars(s, len);
+ s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated);
+}
+NK_API void
+nk_str_delete_runes(struct nk_str *s, int pos, int len)
+{
+ char *temp;
+ nk_rune unicode;
+ char *begin;
+ char *end;
+ int unused;
+
+ NK_ASSERT(s);
+ NK_ASSERT(s->len >= pos + len);
+ if (s->len < pos + len)
+ len = NK_CLAMP(0, (s->len - pos), s->len);
+ if (!len) return;
+
+ temp = (char *)s->buffer.memory.ptr;
+ begin = nk_str_at_rune(s, pos, &unicode, &unused);
+ if (!begin) return;
+ s->buffer.memory.ptr = begin;
+ end = nk_str_at_rune(s, len, &unicode, &unused);
+ s->buffer.memory.ptr = temp;
+ if (!end) return;
+ nk_str_delete_chars(s, (int)(begin - temp), (int)(end - begin));
+}
+NK_API char*
+nk_str_at_char(struct nk_str *s, int pos)
+{
+ NK_ASSERT(s);
+ if (!s || pos > (int)s->buffer.allocated) return 0;
+ return nk_ptr_add(char, s->buffer.memory.ptr, pos);
+}
+NK_API char*
+nk_str_at_rune(struct nk_str *str, int pos, nk_rune *unicode, int *len)
+{
+ int i = 0;
+ int src_len = 0;
+ int glyph_len = 0;
+ char *text;
+ int text_len;
+
+ NK_ASSERT(str);
+ NK_ASSERT(unicode);
+ NK_ASSERT(len);
+
+ if (!str || !unicode || !len) return 0;
+ if (pos < 0) {
+ *unicode = 0;
+ *len = 0;
+ return 0;
+ }
+
+ text = (char*)str->buffer.memory.ptr;
+ text_len = (int)str->buffer.allocated;
+ glyph_len = nk_utf_decode(text, unicode, text_len);
+ while (glyph_len) {
+ if (i == pos) {
+ *len = glyph_len;
+ break;
+ }
+
+ i++;
+ src_len = src_len + glyph_len;
+ glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len);
+ }
+ if (i != pos) return 0;
+ return text + src_len;
+}
+NK_API const char*
+nk_str_at_char_const(const struct nk_str *s, int pos)
+{
+ NK_ASSERT(s);
+ if (!s || pos > (int)s->buffer.allocated) return 0;
+ return nk_ptr_add(char, s->buffer.memory.ptr, pos);
+}
+NK_API const char*
+nk_str_at_const(const struct nk_str *str, int pos, nk_rune *unicode, int *len)
+{
+ int i = 0;
+ int src_len = 0;
+ int glyph_len = 0;
+ char *text;
+ int text_len;
+
+ NK_ASSERT(str);
+ NK_ASSERT(unicode);
+ NK_ASSERT(len);
+
+ if (!str || !unicode || !len) return 0;
+ if (pos < 0) {
+ *unicode = 0;
+ *len = 0;
+ return 0;
+ }
+
+ text = (char*)str->buffer.memory.ptr;
+ text_len = (int)str->buffer.allocated;
+ glyph_len = nk_utf_decode(text, unicode, text_len);
+ while (glyph_len) {
+ if (i == pos) {
+ *len = glyph_len;
+ break;
+ }
+
+ i++;
+ src_len = src_len + glyph_len;
+ glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len);
+ }
+ if (i != pos) return 0;
+ return text + src_len;
+}
+NK_API nk_rune
+nk_str_rune_at(const struct nk_str *str, int pos)
+{
+ int len;
+ nk_rune unicode = 0;
+ nk_str_at_const(str, pos, &unicode, &len);
+ return unicode;
+}
+NK_API char*
+nk_str_get(struct nk_str *s)
+{
+ NK_ASSERT(s);
+ if (!s || !s->len || !s->buffer.allocated) return 0;
+ return (char*)s->buffer.memory.ptr;
+}
+NK_API const char*
+nk_str_get_const(const struct nk_str *s)
+{
+ NK_ASSERT(s);
+ if (!s || !s->len || !s->buffer.allocated) return 0;
+ return (const char*)s->buffer.memory.ptr;
+}
+NK_API int
+nk_str_len(struct nk_str *s)
+{
+ NK_ASSERT(s);
+ if (!s || !s->len || !s->buffer.allocated) return 0;
+ return s->len;
+}
+NK_API int
+nk_str_len_char(struct nk_str *s)
+{
+ NK_ASSERT(s);
+ if (!s || !s->len || !s->buffer.allocated) return 0;
+ return (int)s->buffer.allocated;
+}
+NK_API void
+nk_str_clear(struct nk_str *str)
+{
+ NK_ASSERT(str);
+ nk_buffer_clear(&str->buffer);
+ str->len = 0;
+}
+NK_API void
+nk_str_free(struct nk_str *str)
+{
+ NK_ASSERT(str);
+ nk_buffer_free(&str->buffer);
+ str->len = 0;
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * DRAW
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_command_buffer_init(struct nk_command_buffer *cb,
+ struct nk_buffer *b, enum nk_command_clipping clip)
+{
+ NK_ASSERT(cb);
+ NK_ASSERT(b);
+ if (!cb || !b) return;
+ cb->base = b;
+ cb->use_clipping = (int)clip;
+ cb->begin = b->allocated;
+ cb->end = b->allocated;
+ cb->last = b->allocated;
+}
+NK_LIB void
+nk_command_buffer_reset(struct nk_command_buffer *b)
+{
+ NK_ASSERT(b);
+ if (!b) return;
+ b->begin = 0;
+ b->end = 0;
+ b->last = 0;
+ b->clip = nk_null_rect;
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ b->userdata.ptr = 0;
+#endif
+}
+NK_LIB void*
+nk_command_buffer_push(struct nk_command_buffer* b,
+ enum nk_command_type t, nk_size size)
+{
+ NK_STORAGE const nk_size align = NK_ALIGNOF(struct nk_command);
+ struct nk_command *cmd;
+ nk_size alignment;
+ void *unaligned;
+ void *memory;
+
+ NK_ASSERT(b);
+ NK_ASSERT(b->base);
+ if (!b) return 0;
+ cmd = (struct nk_command*)nk_buffer_alloc(b->base,NK_BUFFER_FRONT,size,align);
+ if (!cmd) return 0;
+
+ /* make sure the offset to the next command is aligned */
+ b->last = (nk_size)((nk_byte*)cmd - (nk_byte*)b->base->memory.ptr);
+ unaligned = (nk_byte*)cmd + size;
+ memory = NK_ALIGN_PTR(unaligned, align);
+ alignment = (nk_size)((nk_byte*)memory - (nk_byte*)unaligned);
+#ifdef NK_ZERO_COMMAND_MEMORY
+ NK_MEMSET(cmd, 0, size + alignment);
+#endif
+
+ cmd->type = t;
+ cmd->next = b->base->allocated + alignment;
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ cmd->userdata = b->userdata;
+#endif
+ b->end = cmd->next;
+ return cmd;
+}
+NK_API void
+nk_push_scissor(struct nk_command_buffer *b, struct nk_rect r)
+{
+ struct nk_command_scissor *cmd;
+ NK_ASSERT(b);
+ if (!b) return;
+
+ b->clip.x = r.x;
+ b->clip.y = r.y;
+ b->clip.w = r.w;
+ b->clip.h = r.h;
+ cmd = (struct nk_command_scissor*)
+ nk_command_buffer_push(b, NK_COMMAND_SCISSOR, sizeof(*cmd));
+
+ if (!cmd) return;
+ cmd->x = (short)r.x;
+ cmd->y = (short)r.y;
+ cmd->w = (unsigned short)NK_MAX(0, r.w);
+ cmd->h = (unsigned short)NK_MAX(0, r.h);
+}
+NK_API void
+nk_stroke_line(struct nk_command_buffer *b, float x0, float y0,
+ float x1, float y1, float line_thickness, struct nk_color c)
+{
+ struct nk_command_line *cmd;
+ NK_ASSERT(b);
+ if (!b || line_thickness <= 0) return;
+ cmd = (struct nk_command_line*)
+ nk_command_buffer_push(b, NK_COMMAND_LINE, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->begin.x = (short)x0;
+ cmd->begin.y = (short)y0;
+ cmd->end.x = (short)x1;
+ cmd->end.y = (short)y1;
+ cmd->color = c;
+}
+NK_API void
+nk_stroke_curve(struct nk_command_buffer *b, float ax, float ay,
+ float ctrl0x, float ctrl0y, float ctrl1x, float ctrl1y,
+ float bx, float by, float line_thickness, struct nk_color col)
+{
+ struct nk_command_curve *cmd;
+ NK_ASSERT(b);
+ if (!b || col.a == 0 || line_thickness <= 0) return;
+
+ cmd = (struct nk_command_curve*)
+ nk_command_buffer_push(b, NK_COMMAND_CURVE, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->begin.x = (short)ax;
+ cmd->begin.y = (short)ay;
+ cmd->ctrl[0].x = (short)ctrl0x;
+ cmd->ctrl[0].y = (short)ctrl0y;
+ cmd->ctrl[1].x = (short)ctrl1x;
+ cmd->ctrl[1].y = (short)ctrl1y;
+ cmd->end.x = (short)bx;
+ cmd->end.y = (short)by;
+ cmd->color = col;
+}
+NK_API void
+nk_stroke_rect(struct nk_command_buffer *b, struct nk_rect rect,
+ float rounding, float line_thickness, struct nk_color c)
+{
+ struct nk_command_rect *cmd;
+ NK_ASSERT(b);
+ if (!b || c.a == 0 || rect.w == 0 || rect.h == 0 || line_thickness <= 0) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h,
+ clip->x, clip->y, clip->w, clip->h)) return;
+ }
+ cmd = (struct nk_command_rect*)
+ nk_command_buffer_push(b, NK_COMMAND_RECT, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->rounding = (unsigned short)rounding;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->x = (short)rect.x;
+ cmd->y = (short)rect.y;
+ cmd->w = (unsigned short)NK_MAX(0, rect.w);
+ cmd->h = (unsigned short)NK_MAX(0, rect.h);
+ cmd->color = c;
+}
+NK_API void
+nk_fill_rect(struct nk_command_buffer *b, struct nk_rect rect,
+ float rounding, struct nk_color c)
+{
+ struct nk_command_rect_filled *cmd;
+ NK_ASSERT(b);
+ if (!b || c.a == 0 || rect.w == 0 || rect.h == 0) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h,
+ clip->x, clip->y, clip->w, clip->h)) return;
+ }
+
+ cmd = (struct nk_command_rect_filled*)
+ nk_command_buffer_push(b, NK_COMMAND_RECT_FILLED, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->rounding = (unsigned short)rounding;
+ cmd->x = (short)rect.x;
+ cmd->y = (short)rect.y;
+ cmd->w = (unsigned short)NK_MAX(0, rect.w);
+ cmd->h = (unsigned short)NK_MAX(0, rect.h);
+ cmd->color = c;
+}
+NK_API void
+nk_fill_rect_multi_color(struct nk_command_buffer *b, struct nk_rect rect,
+ struct nk_color left, struct nk_color top, struct nk_color right,
+ struct nk_color bottom)
+{
+ struct nk_command_rect_multi_color *cmd;
+ NK_ASSERT(b);
+ if (!b || rect.w == 0 || rect.h == 0) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h,
+ clip->x, clip->y, clip->w, clip->h)) return;
+ }
+
+ cmd = (struct nk_command_rect_multi_color*)
+ nk_command_buffer_push(b, NK_COMMAND_RECT_MULTI_COLOR, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->x = (short)rect.x;
+ cmd->y = (short)rect.y;
+ cmd->w = (unsigned short)NK_MAX(0, rect.w);
+ cmd->h = (unsigned short)NK_MAX(0, rect.h);
+ cmd->left = left;
+ cmd->top = top;
+ cmd->right = right;
+ cmd->bottom = bottom;
+}
+NK_API void
+nk_stroke_circle(struct nk_command_buffer *b, struct nk_rect r,
+ float line_thickness, struct nk_color c)
+{
+ struct nk_command_circle *cmd;
+ if (!b || r.w == 0 || r.h == 0 || line_thickness <= 0) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INTERSECT(r.x, r.y, r.w, r.h, clip->x, clip->y, clip->w, clip->h))
+ return;
+ }
+
+ cmd = (struct nk_command_circle*)
+ nk_command_buffer_push(b, NK_COMMAND_CIRCLE, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->x = (short)r.x;
+ cmd->y = (short)r.y;
+ cmd->w = (unsigned short)NK_MAX(r.w, 0);
+ cmd->h = (unsigned short)NK_MAX(r.h, 0);
+ cmd->color = c;
+}
+NK_API void
+nk_fill_circle(struct nk_command_buffer *b, struct nk_rect r, struct nk_color c)
+{
+ struct nk_command_circle_filled *cmd;
+ NK_ASSERT(b);
+ if (!b || c.a == 0 || r.w == 0 || r.h == 0) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INTERSECT(r.x, r.y, r.w, r.h, clip->x, clip->y, clip->w, clip->h))
+ return;
+ }
+
+ cmd = (struct nk_command_circle_filled*)
+ nk_command_buffer_push(b, NK_COMMAND_CIRCLE_FILLED, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->x = (short)r.x;
+ cmd->y = (short)r.y;
+ cmd->w = (unsigned short)NK_MAX(r.w, 0);
+ cmd->h = (unsigned short)NK_MAX(r.h, 0);
+ cmd->color = c;
+}
+NK_API void
+nk_stroke_arc(struct nk_command_buffer *b, float cx, float cy, float radius,
+ float a_min, float a_max, float line_thickness, struct nk_color c)
+{
+ struct nk_command_arc *cmd;
+ if (!b || c.a == 0 || line_thickness <= 0) return;
+ cmd = (struct nk_command_arc*)
+ nk_command_buffer_push(b, NK_COMMAND_ARC, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->cx = (short)cx;
+ cmd->cy = (short)cy;
+ cmd->r = (unsigned short)radius;
+ cmd->a[0] = a_min;
+ cmd->a[1] = a_max;
+ cmd->color = c;
+}
+NK_API void
+nk_fill_arc(struct nk_command_buffer *b, float cx, float cy, float radius,
+ float a_min, float a_max, struct nk_color c)
+{
+ struct nk_command_arc_filled *cmd;
+ NK_ASSERT(b);
+ if (!b || c.a == 0) return;
+ cmd = (struct nk_command_arc_filled*)
+ nk_command_buffer_push(b, NK_COMMAND_ARC_FILLED, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->cx = (short)cx;
+ cmd->cy = (short)cy;
+ cmd->r = (unsigned short)radius;
+ cmd->a[0] = a_min;
+ cmd->a[1] = a_max;
+ cmd->color = c;
+}
+NK_API void
+nk_stroke_triangle(struct nk_command_buffer *b, float x0, float y0, float x1,
+ float y1, float x2, float y2, float line_thickness, struct nk_color c)
+{
+ struct nk_command_triangle *cmd;
+ NK_ASSERT(b);
+ if (!b || c.a == 0 || line_thickness <= 0) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INBOX(x0, y0, clip->x, clip->y, clip->w, clip->h) &&
+ !NK_INBOX(x1, y1, clip->x, clip->y, clip->w, clip->h) &&
+ !NK_INBOX(x2, y2, clip->x, clip->y, clip->w, clip->h))
+ return;
+ }
+
+ cmd = (struct nk_command_triangle*)
+ nk_command_buffer_push(b, NK_COMMAND_TRIANGLE, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->a.x = (short)x0;
+ cmd->a.y = (short)y0;
+ cmd->b.x = (short)x1;
+ cmd->b.y = (short)y1;
+ cmd->c.x = (short)x2;
+ cmd->c.y = (short)y2;
+ cmd->color = c;
+}
+NK_API void
+nk_fill_triangle(struct nk_command_buffer *b, float x0, float y0, float x1,
+ float y1, float x2, float y2, struct nk_color c)
+{
+ struct nk_command_triangle_filled *cmd;
+ NK_ASSERT(b);
+ if (!b || c.a == 0) return;
+ if (!b) return;
+ if (b->use_clipping) {
+ const struct nk_rect *clip = &b->clip;
+ if (!NK_INBOX(x0, y0, clip->x, clip->y, clip->w, clip->h) &&
+ !NK_INBOX(x1, y1, clip->x, clip->y, clip->w, clip->h) &&
+ !NK_INBOX(x2, y2, clip->x, clip->y, clip->w, clip->h))
+ return;
+ }
+
+ cmd = (struct nk_command_triangle_filled*)
+ nk_command_buffer_push(b, NK_COMMAND_TRIANGLE_FILLED, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->a.x = (short)x0;
+ cmd->a.y = (short)y0;
+ cmd->b.x = (short)x1;
+ cmd->b.y = (short)y1;
+ cmd->c.x = (short)x2;
+ cmd->c.y = (short)y2;
+ cmd->color = c;
+}
+NK_API void
+nk_stroke_polygon(struct nk_command_buffer *b, float *points, int point_count,
+ float line_thickness, struct nk_color col)
+{
+ int i;
+ nk_size size = 0;
+ struct nk_command_polygon *cmd;
+
+ NK_ASSERT(b);
+ if (!b || col.a == 0 || line_thickness <= 0) return;
+ size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count;
+ cmd = (struct nk_command_polygon*) nk_command_buffer_push(b, NK_COMMAND_POLYGON, size);
+ if (!cmd) return;
+ cmd->color = col;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ cmd->point_count = (unsigned short)point_count;
+ for (i = 0; i < point_count; ++i) {
+ cmd->points[i].x = (short)points[i*2];
+ cmd->points[i].y = (short)points[i*2+1];
+ }
+}
+NK_API void
+nk_fill_polygon(struct nk_command_buffer *b, float *points, int point_count,
+ struct nk_color col)
+{
+ int i;
+ nk_size size = 0;
+ struct nk_command_polygon_filled *cmd;
+
+ NK_ASSERT(b);
+ if (!b || col.a == 0) return;
+ size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count;
+ cmd = (struct nk_command_polygon_filled*)
+ nk_command_buffer_push(b, NK_COMMAND_POLYGON_FILLED, size);
+ if (!cmd) return;
+ cmd->color = col;
+ cmd->point_count = (unsigned short)point_count;
+ for (i = 0; i < point_count; ++i) {
+ cmd->points[i].x = (short)points[i*2+0];
+ cmd->points[i].y = (short)points[i*2+1];
+ }
+}
+NK_API void
+nk_stroke_polyline(struct nk_command_buffer *b, float *points, int point_count,
+ float line_thickness, struct nk_color col)
+{
+ int i;
+ nk_size size = 0;
+ struct nk_command_polyline *cmd;
+
+ NK_ASSERT(b);
+ if (!b || col.a == 0 || line_thickness <= 0) return;
+ size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count;
+ cmd = (struct nk_command_polyline*) nk_command_buffer_push(b, NK_COMMAND_POLYLINE, size);
+ if (!cmd) return;
+ cmd->color = col;
+ cmd->point_count = (unsigned short)point_count;
+ cmd->line_thickness = (unsigned short)line_thickness;
+ for (i = 0; i < point_count; ++i) {
+ cmd->points[i].x = (short)points[i*2];
+ cmd->points[i].y = (short)points[i*2+1];
+ }
+}
+NK_API void
+nk_draw_image(struct nk_command_buffer *b, struct nk_rect r,
+ const struct nk_image *img, struct nk_color col)
+{
+ struct nk_command_image *cmd;
+ NK_ASSERT(b);
+ if (!b) return;
+ if (b->use_clipping) {
+ const struct nk_rect *c = &b->clip;
+ if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h))
+ return;
+ }
+
+ cmd = (struct nk_command_image*)
+ nk_command_buffer_push(b, NK_COMMAND_IMAGE, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->x = (short)r.x;
+ cmd->y = (short)r.y;
+ cmd->w = (unsigned short)NK_MAX(0, r.w);
+ cmd->h = (unsigned short)NK_MAX(0, r.h);
+ cmd->img = *img;
+ cmd->col = col;
+}
+NK_API void
+nk_draw_nine_slice(struct nk_command_buffer *b, struct nk_rect r,
+ const struct nk_nine_slice *slc, struct nk_color col)
+{
+ struct nk_image img;
+ const struct nk_image *slcimg = (const struct nk_image*)slc;
+ nk_ushort rgnX, rgnY, rgnW, rgnH;
+ rgnX = slcimg->region[0];
+ rgnY = slcimg->region[1];
+ rgnW = slcimg->region[2];
+ rgnH = slcimg->region[3];
+
+ /* top-left */
+ img.handle = slcimg->handle;
+ img.w = slcimg->w;
+ img.h = slcimg->h;
+ img.region[0] = rgnX;
+ img.region[1] = rgnY;
+ img.region[2] = slc->l;
+ img.region[3] = slc->t;
+
+ nk_draw_image(b,
+ nk_rect(r.x, r.y, (float)slc->l, (float)slc->t),
+ &img, col);
+
+#define IMG_RGN(x, y, w, h) img.region[0] = (nk_ushort)(x); img.region[1] = (nk_ushort)(y); img.region[2] = (nk_ushort)(w); img.region[3] = (nk_ushort)(h);
+
+ /* top-center */
+ IMG_RGN(rgnX + slc->l, rgnY, rgnW - slc->l - slc->r, slc->t);
+ nk_draw_image(b,
+ nk_rect(r.x + (float)slc->l, r.y, (float)(r.w - slc->l - slc->r), (float)slc->t),
+ &img, col);
+
+ /* top-right */
+ IMG_RGN(rgnX + rgnW - slc->r, rgnY, slc->r, slc->t);
+ nk_draw_image(b,
+ nk_rect(r.x + r.w - (float)slc->r, r.y, (float)slc->r, (float)slc->t),
+ &img, col);
+
+ /* center-left */
+ IMG_RGN(rgnX, rgnY + slc->t, slc->l, rgnH - slc->t - slc->b);
+ nk_draw_image(b,
+ nk_rect(r.x, r.y + (float)slc->t, (float)slc->l, (float)(r.h - slc->t - slc->b)),
+ &img, col);
+
+ /* center */
+ IMG_RGN(rgnX + slc->l, rgnY + slc->t, rgnW - slc->l - slc->r, rgnH - slc->t - slc->b);
+ nk_draw_image(b,
+ nk_rect(r.x + (float)slc->l, r.y + (float)slc->t, (float)(r.w - slc->l - slc->r), (float)(r.h - slc->t - slc->b)),
+ &img, col);
+
+ /* center-right */
+ IMG_RGN(rgnX + rgnW - slc->r, rgnY + slc->t, slc->r, rgnH - slc->t - slc->b);
+ nk_draw_image(b,
+ nk_rect(r.x + r.w - (float)slc->r, r.y + (float)slc->t, (float)slc->r, (float)(r.h - slc->t - slc->b)),
+ &img, col);
+
+ /* bottom-left */
+ IMG_RGN(rgnX, rgnY + rgnH - slc->b, slc->l, slc->b);
+ nk_draw_image(b,
+ nk_rect(r.x, r.y + r.h - (float)slc->b, (float)slc->l, (float)slc->b),
+ &img, col);
+
+ /* bottom-center */
+ IMG_RGN(rgnX + slc->l, rgnY + rgnH - slc->b, rgnW - slc->l - slc->r, slc->b);
+ nk_draw_image(b,
+ nk_rect(r.x + (float)slc->l, r.y + r.h - (float)slc->b, (float)(r.w - slc->l - slc->r), (float)slc->b),
+ &img, col);
+
+ /* bottom-right */
+ IMG_RGN(rgnX + rgnW - slc->r, rgnY + rgnH - slc->b, slc->r, slc->b);
+ nk_draw_image(b,
+ nk_rect(r.x + r.w - (float)slc->r, r.y + r.h - (float)slc->b, (float)slc->r, (float)slc->b),
+ &img, col);
+
+#undef IMG_RGN
+}
+NK_API void
+nk_push_custom(struct nk_command_buffer *b, struct nk_rect r,
+ nk_command_custom_callback cb, nk_handle usr)
+{
+ struct nk_command_custom *cmd;
+ NK_ASSERT(b);
+ if (!b) return;
+ if (b->use_clipping) {
+ const struct nk_rect *c = &b->clip;
+ if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h))
+ return;
+ }
+
+ cmd = (struct nk_command_custom*)
+ nk_command_buffer_push(b, NK_COMMAND_CUSTOM, sizeof(*cmd));
+ if (!cmd) return;
+ cmd->x = (short)r.x;
+ cmd->y = (short)r.y;
+ cmd->w = (unsigned short)NK_MAX(0, r.w);
+ cmd->h = (unsigned short)NK_MAX(0, r.h);
+ cmd->callback_data = usr;
+ cmd->callback = cb;
+}
+NK_API void
+nk_draw_text(struct nk_command_buffer *b, struct nk_rect r,
+ const char *string, int length, const struct nk_user_font *font,
+ struct nk_color bg, struct nk_color fg)
+{
+ float text_width = 0;
+ struct nk_command_text *cmd;
+
+ NK_ASSERT(b);
+ NK_ASSERT(font);
+ if (!b || !string || !length || (bg.a == 0 && fg.a == 0)) return;
+ if (b->use_clipping) {
+ const struct nk_rect *c = &b->clip;
+ if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h))
+ return;
+ }
+
+ /* make sure text fits inside bounds */
+ text_width = font->width(font->userdata, font->height, string, length);
+ if (text_width > r.w){
+ int glyphs = 0;
+ float txt_width = (float)text_width;
+ length = nk_text_clamp(font, string, length, r.w, &glyphs, &txt_width, 0,0);
+ }
+
+ if (!length) return;
+ cmd = (struct nk_command_text*)
+ nk_command_buffer_push(b, NK_COMMAND_TEXT, sizeof(*cmd) + (nk_size)(length + 1));
+ if (!cmd) return;
+ cmd->x = (short)r.x;
+ cmd->y = (short)r.y;
+ cmd->w = (unsigned short)r.w;
+ cmd->h = (unsigned short)r.h;
+ cmd->background = bg;
+ cmd->foreground = fg;
+ cmd->font = font;
+ cmd->length = length;
+ cmd->height = font->height;
+ NK_MEMCPY(cmd->string, string, (nk_size)length);
+ cmd->string[length] = '\0';
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * VERTEX
+ *
+ * ===============================================================*/
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+NK_API void
+nk_draw_list_init(struct nk_draw_list *list)
+{
+ nk_size i = 0;
+ NK_ASSERT(list);
+ if (!list) return;
+ nk_zero(list, sizeof(*list));
+ for (i = 0; i < NK_LEN(list->circle_vtx); ++i) {
+ const float a = ((float)i / (float)NK_LEN(list->circle_vtx)) * 2 * NK_PI;
+ list->circle_vtx[i].x = (float)NK_COS(a);
+ list->circle_vtx[i].y = (float)NK_SIN(a);
+ }
+}
+NK_API void
+nk_draw_list_setup(struct nk_draw_list *canvas, const struct nk_convert_config *config,
+ struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements,
+ enum nk_anti_aliasing line_aa, enum nk_anti_aliasing shape_aa)
+{
+ NK_ASSERT(canvas);
+ NK_ASSERT(config);
+ NK_ASSERT(cmds);
+ NK_ASSERT(vertices);
+ NK_ASSERT(elements);
+ if (!canvas || !config || !cmds || !vertices || !elements)
+ return;
+
+ canvas->buffer = cmds;
+ canvas->config = *config;
+ canvas->elements = elements;
+ canvas->vertices = vertices;
+ canvas->line_AA = line_aa;
+ canvas->shape_AA = shape_aa;
+ canvas->clip_rect = nk_null_rect;
+
+ canvas->cmd_offset = 0;
+ canvas->element_count = 0;
+ canvas->vertex_count = 0;
+ canvas->cmd_offset = 0;
+ canvas->cmd_count = 0;
+ canvas->path_count = 0;
+}
+NK_API const struct nk_draw_command*
+nk__draw_list_begin(const struct nk_draw_list *canvas, const struct nk_buffer *buffer)
+{
+ nk_byte *memory;
+ nk_size offset;
+ const struct nk_draw_command *cmd;
+
+ NK_ASSERT(buffer);
+ if (!buffer || !buffer->size || !canvas->cmd_count)
+ return 0;
+
+ memory = (nk_byte*)buffer->memory.ptr;
+ offset = buffer->memory.size - canvas->cmd_offset;
+ cmd = nk_ptr_add(const struct nk_draw_command, memory, offset);
+ return cmd;
+}
+NK_API const struct nk_draw_command*
+nk__draw_list_end(const struct nk_draw_list *canvas, const struct nk_buffer *buffer)
+{
+ nk_size size;
+ nk_size offset;
+ nk_byte *memory;
+ const struct nk_draw_command *end;
+
+ NK_ASSERT(buffer);
+ NK_ASSERT(canvas);
+ if (!buffer || !canvas)
+ return 0;
+
+ memory = (nk_byte*)buffer->memory.ptr;
+ size = buffer->memory.size;
+ offset = size - canvas->cmd_offset;
+ end = nk_ptr_add(const struct nk_draw_command, memory, offset);
+ end -= (canvas->cmd_count-1);
+ return end;
+}
+NK_API const struct nk_draw_command*
+nk__draw_list_next(const struct nk_draw_command *cmd,
+ const struct nk_buffer *buffer, const struct nk_draw_list *canvas)
+{
+ const struct nk_draw_command *end;
+ NK_ASSERT(buffer);
+ NK_ASSERT(canvas);
+ if (!cmd || !buffer || !canvas)
+ return 0;
+
+ end = nk__draw_list_end(canvas, buffer);
+ if (cmd <= end) return 0;
+ return (cmd-1);
+}
+NK_INTERN struct nk_vec2*
+nk_draw_list_alloc_path(struct nk_draw_list *list, int count)
+{
+ struct nk_vec2 *points;
+ NK_STORAGE const nk_size point_align = NK_ALIGNOF(struct nk_vec2);
+ NK_STORAGE const nk_size point_size = sizeof(struct nk_vec2);
+ points = (struct nk_vec2*)
+ nk_buffer_alloc(list->buffer, NK_BUFFER_FRONT,
+ point_size * (nk_size)count, point_align);
+
+ if (!points) return 0;
+ if (!list->path_offset) {
+ void *memory = nk_buffer_memory(list->buffer);
+ list->path_offset = (unsigned int)((nk_byte*)points - (nk_byte*)memory);
+ }
+ list->path_count += (unsigned int)count;
+ return points;
+}
+NK_INTERN struct nk_vec2
+nk_draw_list_path_last(struct nk_draw_list *list)
+{
+ void *memory;
+ struct nk_vec2 *point;
+ NK_ASSERT(list->path_count);
+ memory = nk_buffer_memory(list->buffer);
+ point = nk_ptr_add(struct nk_vec2, memory, list->path_offset);
+ point += (list->path_count-1);
+ return *point;
+}
+NK_INTERN struct nk_draw_command*
+nk_draw_list_push_command(struct nk_draw_list *list, struct nk_rect clip,
+ nk_handle texture)
+{
+ NK_STORAGE const nk_size cmd_align = NK_ALIGNOF(struct nk_draw_command);
+ NK_STORAGE const nk_size cmd_size = sizeof(struct nk_draw_command);
+ struct nk_draw_command *cmd;
+
+ NK_ASSERT(list);
+ cmd = (struct nk_draw_command*)
+ nk_buffer_alloc(list->buffer, NK_BUFFER_BACK, cmd_size, cmd_align);
+
+ if (!cmd) return 0;
+ if (!list->cmd_count) {
+ nk_byte *memory = (nk_byte*)nk_buffer_memory(list->buffer);
+ nk_size total = nk_buffer_total(list->buffer);
+ memory = nk_ptr_add(nk_byte, memory, total);
+ list->cmd_offset = (nk_size)(memory - (nk_byte*)cmd);
+ }
+
+ cmd->elem_count = 0;
+ cmd->clip_rect = clip;
+ cmd->texture = texture;
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ cmd->userdata = list->userdata;
+#endif
+
+ list->cmd_count++;
+ list->clip_rect = clip;
+ return cmd;
+}
+NK_INTERN struct nk_draw_command*
+nk_draw_list_command_last(struct nk_draw_list *list)
+{
+ void *memory;
+ nk_size size;
+ struct nk_draw_command *cmd;
+ NK_ASSERT(list->cmd_count);
+
+ memory = nk_buffer_memory(list->buffer);
+ size = nk_buffer_total(list->buffer);
+ cmd = nk_ptr_add(struct nk_draw_command, memory, size - list->cmd_offset);
+ return (cmd - (list->cmd_count-1));
+}
+NK_INTERN void
+nk_draw_list_add_clip(struct nk_draw_list *list, struct nk_rect rect)
+{
+ NK_ASSERT(list);
+ if (!list) return;
+ if (!list->cmd_count) {
+ nk_draw_list_push_command(list, rect, list->config.tex_null.texture);
+ } else {
+ struct nk_draw_command *prev = nk_draw_list_command_last(list);
+ if (prev->elem_count == 0)
+ prev->clip_rect = rect;
+ nk_draw_list_push_command(list, rect, prev->texture);
+ }
+}
+NK_INTERN void
+nk_draw_list_push_image(struct nk_draw_list *list, nk_handle texture)
+{
+ NK_ASSERT(list);
+ if (!list) return;
+ if (!list->cmd_count) {
+ nk_draw_list_push_command(list, nk_null_rect, texture);
+ } else {
+ struct nk_draw_command *prev = nk_draw_list_command_last(list);
+ if (prev->elem_count == 0) {
+ prev->texture = texture;
+ #ifdef NK_INCLUDE_COMMAND_USERDATA
+ prev->userdata = list->userdata;
+ #endif
+ } else if (prev->texture.id != texture.id
+ #ifdef NK_INCLUDE_COMMAND_USERDATA
+ || prev->userdata.id != list->userdata.id
+ #endif
+ ) nk_draw_list_push_command(list, prev->clip_rect, texture);
+ }
+}
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+NK_API void
+nk_draw_list_push_userdata(struct nk_draw_list *list, nk_handle userdata)
+{
+ list->userdata = userdata;
+}
+#endif
+NK_INTERN void*
+nk_draw_list_alloc_vertices(struct nk_draw_list *list, nk_size count)
+{
+ void *vtx;
+ NK_ASSERT(list);
+ if (!list) return 0;
+ vtx = nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT,
+ list->config.vertex_size*count, list->config.vertex_alignment);
+ if (!vtx) return 0;
+ list->vertex_count += (unsigned int)count;
+
+ /* This assert triggers because your are drawing a lot of stuff and nuklear
+ * defined `nk_draw_index` as `nk_ushort` to safe space be default.
+ *
+ * So you reached the maximum number of indices or rather vertexes.
+ * To solve this issue please change typedef `nk_draw_index` to `nk_uint`
+ * and don't forget to specify the new element size in your drawing
+ * backend (OpenGL, DirectX, ...). For example in OpenGL for `glDrawElements`
+ * instead of specifying `GL_UNSIGNED_SHORT` you have to define `GL_UNSIGNED_INT`.
+ * Sorry for the inconvenience. */
+ if(sizeof(nk_draw_index)==2) NK_ASSERT((list->vertex_count < NK_USHORT_MAX &&
+ "To many vertices for 16-bit vertex indices. Please read comment above on how to solve this problem"));
+ return vtx;
+}
+NK_INTERN nk_draw_index*
+nk_draw_list_alloc_elements(struct nk_draw_list *list, nk_size count)
+{
+ nk_draw_index *ids;
+ struct nk_draw_command *cmd;
+ NK_STORAGE const nk_size elem_align = NK_ALIGNOF(nk_draw_index);
+ NK_STORAGE const nk_size elem_size = sizeof(nk_draw_index);
+ NK_ASSERT(list);
+ if (!list) return 0;
+
+ ids = (nk_draw_index*)
+ nk_buffer_alloc(list->elements, NK_BUFFER_FRONT, elem_size*count, elem_align);
+ if (!ids) return 0;
+ cmd = nk_draw_list_command_last(list);
+ list->element_count += (unsigned int)count;
+ cmd->elem_count += (unsigned int)count;
+ return ids;
+}
+NK_INTERN int
+nk_draw_vertex_layout_element_is_end_of_layout(
+ const struct nk_draw_vertex_layout_element *element)
+{
+ return (element->attribute == NK_VERTEX_ATTRIBUTE_COUNT ||
+ element->format == NK_FORMAT_COUNT);
+}
+NK_INTERN void
+nk_draw_vertex_color(void *attr, const float *vals,
+ enum nk_draw_vertex_layout_format format)
+{
+ /* if this triggers you tried to provide a value format for a color */
+ float val[4];
+ NK_ASSERT(format >= NK_FORMAT_COLOR_BEGIN);
+ NK_ASSERT(format <= NK_FORMAT_COLOR_END);
+ if (format < NK_FORMAT_COLOR_BEGIN || format > NK_FORMAT_COLOR_END) return;
+
+ val[0] = NK_SATURATE(vals[0]);
+ val[1] = NK_SATURATE(vals[1]);
+ val[2] = NK_SATURATE(vals[2]);
+ val[3] = NK_SATURATE(vals[3]);
+
+ switch (format) {
+ default: NK_ASSERT(0 && "Invalid vertex layout color format"); break;
+ case NK_FORMAT_R8G8B8A8:
+ case NK_FORMAT_R8G8B8: {
+ struct nk_color col = nk_rgba_fv(val);
+ NK_MEMCPY(attr, &col.r, sizeof(col));
+ } break;
+ case NK_FORMAT_B8G8R8A8: {
+ struct nk_color col = nk_rgba_fv(val);
+ struct nk_color bgra = nk_rgba(col.b, col.g, col.r, col.a);
+ NK_MEMCPY(attr, &bgra, sizeof(bgra));
+ } break;
+ case NK_FORMAT_R16G15B16: {
+ nk_ushort col[3];
+ col[0] = (nk_ushort)(val[0]*(float)NK_USHORT_MAX);
+ col[1] = (nk_ushort)(val[1]*(float)NK_USHORT_MAX);
+ col[2] = (nk_ushort)(val[2]*(float)NK_USHORT_MAX);
+ NK_MEMCPY(attr, col, sizeof(col));
+ } break;
+ case NK_FORMAT_R16G15B16A16: {
+ nk_ushort col[4];
+ col[0] = (nk_ushort)(val[0]*(float)NK_USHORT_MAX);
+ col[1] = (nk_ushort)(val[1]*(float)NK_USHORT_MAX);
+ col[2] = (nk_ushort)(val[2]*(float)NK_USHORT_MAX);
+ col[3] = (nk_ushort)(val[3]*(float)NK_USHORT_MAX);
+ NK_MEMCPY(attr, col, sizeof(col));
+ } break;
+ case NK_FORMAT_R32G32B32: {
+ nk_uint col[3];
+ col[0] = (nk_uint)(val[0]*(float)NK_UINT_MAX);
+ col[1] = (nk_uint)(val[1]*(float)NK_UINT_MAX);
+ col[2] = (nk_uint)(val[2]*(float)NK_UINT_MAX);
+ NK_MEMCPY(attr, col, sizeof(col));
+ } break;
+ case NK_FORMAT_R32G32B32A32: {
+ nk_uint col[4];
+ col[0] = (nk_uint)(val[0]*(float)NK_UINT_MAX);
+ col[1] = (nk_uint)(val[1]*(float)NK_UINT_MAX);
+ col[2] = (nk_uint)(val[2]*(float)NK_UINT_MAX);
+ col[3] = (nk_uint)(val[3]*(float)NK_UINT_MAX);
+ NK_MEMCPY(attr, col, sizeof(col));
+ } break;
+ case NK_FORMAT_R32G32B32A32_FLOAT:
+ NK_MEMCPY(attr, val, sizeof(float)*4);
+ break;
+ case NK_FORMAT_R32G32B32A32_DOUBLE: {
+ double col[4];
+ col[0] = (double)val[0];
+ col[1] = (double)val[1];
+ col[2] = (double)val[2];
+ col[3] = (double)val[3];
+ NK_MEMCPY(attr, col, sizeof(col));
+ } break;
+ case NK_FORMAT_RGB32:
+ case NK_FORMAT_RGBA32: {
+ struct nk_color col = nk_rgba_fv(val);
+ nk_uint color = nk_color_u32(col);
+ NK_MEMCPY(attr, &color, sizeof(color));
+ } break; }
+}
+NK_INTERN void
+nk_draw_vertex_element(void *dst, const float *values, int value_count,
+ enum nk_draw_vertex_layout_format format)
+{
+ int value_index;
+ void *attribute = dst;
+ /* if this triggers you tried to provide a color format for a value */
+ NK_ASSERT(format < NK_FORMAT_COLOR_BEGIN);
+ if (format >= NK_FORMAT_COLOR_BEGIN && format <= NK_FORMAT_COLOR_END) return;
+ for (value_index = 0; value_index < value_count; ++value_index) {
+ switch (format) {
+ default: NK_ASSERT(0 && "invalid vertex layout format"); break;
+ case NK_FORMAT_SCHAR: {
+ char value = (char)NK_CLAMP((float)NK_SCHAR_MIN, values[value_index], (float)NK_SCHAR_MAX);
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(char));
+ } break;
+ case NK_FORMAT_SSHORT: {
+ nk_short value = (nk_short)NK_CLAMP((float)NK_SSHORT_MIN, values[value_index], (float)NK_SSHORT_MAX);
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(value));
+ } break;
+ case NK_FORMAT_SINT: {
+ nk_int value = (nk_int)NK_CLAMP((float)NK_SINT_MIN, values[value_index], (float)NK_SINT_MAX);
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(nk_int));
+ } break;
+ case NK_FORMAT_UCHAR: {
+ unsigned char value = (unsigned char)NK_CLAMP((float)NK_UCHAR_MIN, values[value_index], (float)NK_UCHAR_MAX);
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(unsigned char));
+ } break;
+ case NK_FORMAT_USHORT: {
+ nk_ushort value = (nk_ushort)NK_CLAMP((float)NK_USHORT_MIN, values[value_index], (float)NK_USHORT_MAX);
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(value));
+ } break;
+ case NK_FORMAT_UINT: {
+ nk_uint value = (nk_uint)NK_CLAMP((float)NK_UINT_MIN, values[value_index], (float)NK_UINT_MAX);
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(nk_uint));
+ } break;
+ case NK_FORMAT_FLOAT:
+ NK_MEMCPY(attribute, &values[value_index], sizeof(values[value_index]));
+ attribute = (void*)((char*)attribute + sizeof(float));
+ break;
+ case NK_FORMAT_DOUBLE: {
+ double value = (double)values[value_index];
+ NK_MEMCPY(attribute, &value, sizeof(value));
+ attribute = (void*)((char*)attribute + sizeof(double));
+ } break;
+ }
+ }
+}
+NK_INTERN void*
+nk_draw_vertex(void *dst, const struct nk_convert_config *config,
+ struct nk_vec2 pos, struct nk_vec2 uv, struct nk_colorf color)
+{
+ void *result = (void*)((char*)dst + config->vertex_size);
+ const struct nk_draw_vertex_layout_element *elem_iter = config->vertex_layout;
+ while (!nk_draw_vertex_layout_element_is_end_of_layout(elem_iter)) {
+ void *address = (void*)((char*)dst + elem_iter->offset);
+ switch (elem_iter->attribute) {
+ case NK_VERTEX_ATTRIBUTE_COUNT:
+ default: NK_ASSERT(0 && "wrong element attribute"); break;
+ case NK_VERTEX_POSITION: nk_draw_vertex_element(address, &pos.x, 2, elem_iter->format); break;
+ case NK_VERTEX_TEXCOORD: nk_draw_vertex_element(address, &uv.x, 2, elem_iter->format); break;
+ case NK_VERTEX_COLOR: nk_draw_vertex_color(address, &color.r, elem_iter->format); break;
+ }
+ elem_iter++;
+ }
+ return result;
+}
+NK_API void
+nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *points,
+ const unsigned int points_count, struct nk_color color, enum nk_draw_list_stroke closed,
+ float thickness, enum nk_anti_aliasing aliasing)
+{
+ nk_size count;
+ int thick_line;
+ struct nk_colorf col;
+ struct nk_colorf col_trans;
+ NK_ASSERT(list);
+ if (!list || points_count < 2) return;
+
+ color.a = (nk_byte)((float)color.a * list->config.global_alpha);
+ count = points_count;
+ if (!closed) count = points_count-1;
+ thick_line = thickness > 1.0f;
+
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ nk_draw_list_push_userdata(list, list->userdata);
+#endif
+
+ color.a = (nk_byte)((float)color.a * list->config.global_alpha);
+ nk_color_fv(&col.r, color);
+ col_trans = col;
+ col_trans.a = 0;
+
+ if (aliasing == NK_ANTI_ALIASING_ON) {
+ /* ANTI-ALIASED STROKE */
+ const float AA_SIZE = 1.0f;
+ NK_STORAGE const nk_size pnt_align = NK_ALIGNOF(struct nk_vec2);
+ NK_STORAGE const nk_size pnt_size = sizeof(struct nk_vec2);
+
+ /* allocate vertices and elements */
+ nk_size i1 = 0;
+ nk_size vertex_offset;
+ nk_size index = list->vertex_count;
+
+ const nk_size idx_count = (thick_line) ? (count * 18) : (count * 12);
+ const nk_size vtx_count = (thick_line) ? (points_count * 4): (points_count *3);
+
+ void *vtx = nk_draw_list_alloc_vertices(list, vtx_count);
+ nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count);
+
+ nk_size size;
+ struct nk_vec2 *normals, *temp;
+ if (!vtx || !ids) return;
+
+ /* temporary allocate normals + points */
+ vertex_offset = (nk_size)((nk_byte*)vtx - (nk_byte*)list->vertices->memory.ptr);
+ nk_buffer_mark(list->vertices, NK_BUFFER_FRONT);
+ size = pnt_size * ((thick_line) ? 5 : 3) * points_count;
+ normals = (struct nk_vec2*) nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, size, pnt_align);
+ if (!normals) return;
+ temp = normals + points_count;
+
+ /* make sure vertex pointer is still correct */
+ vtx = (void*)((nk_byte*)list->vertices->memory.ptr + vertex_offset);
+
+ /* calculate normals */
+ for (i1 = 0; i1 < count; ++i1) {
+ const nk_size i2 = ((i1 + 1) == points_count) ? 0 : (i1 + 1);
+ struct nk_vec2 diff = nk_vec2_sub(points[i2], points[i1]);
+ float len;
+
+ /* vec2 inverted length */
+ len = nk_vec2_len_sqr(diff);
+ if (len != 0.0f)
+ len = NK_INV_SQRT(len);
+ else len = 1.0f;
+
+ diff = nk_vec2_muls(diff, len);
+ normals[i1].x = diff.y;
+ normals[i1].y = -diff.x;
+ }
+
+ if (!closed)
+ normals[points_count-1] = normals[points_count-2];
+
+ if (!thick_line) {
+ nk_size idx1, i;
+ if (!closed) {
+ struct nk_vec2 d;
+ temp[0] = nk_vec2_add(points[0], nk_vec2_muls(normals[0], AA_SIZE));
+ temp[1] = nk_vec2_sub(points[0], nk_vec2_muls(normals[0], AA_SIZE));
+ d = nk_vec2_muls(normals[points_count-1], AA_SIZE);
+ temp[(points_count-1) * 2 + 0] = nk_vec2_add(points[points_count-1], d);
+ temp[(points_count-1) * 2 + 1] = nk_vec2_sub(points[points_count-1], d);
+ }
+
+ /* fill elements */
+ idx1 = index;
+ for (i1 = 0; i1 < count; i1++) {
+ struct nk_vec2 dm;
+ float dmr2;
+ nk_size i2 = ((i1 + 1) == points_count) ? 0 : (i1 + 1);
+ nk_size idx2 = ((i1+1) == points_count) ? index: (idx1 + 3);
+
+ /* average normals */
+ dm = nk_vec2_muls(nk_vec2_add(normals[i1], normals[i2]), 0.5f);
+ dmr2 = dm.x * dm.x + dm.y* dm.y;
+ if (dmr2 > 0.000001f) {
+ float scale = 1.0f/dmr2;
+ scale = NK_MIN(100.0f, scale);
+ dm = nk_vec2_muls(dm, scale);
+ }
+
+ dm = nk_vec2_muls(dm, AA_SIZE);
+ temp[i2*2+0] = nk_vec2_add(points[i2], dm);
+ temp[i2*2+1] = nk_vec2_sub(points[i2], dm);
+
+ ids[0] = (nk_draw_index)(idx2 + 0); ids[1] = (nk_draw_index)(idx1+0);
+ ids[2] = (nk_draw_index)(idx1 + 2); ids[3] = (nk_draw_index)(idx1+2);
+ ids[4] = (nk_draw_index)(idx2 + 2); ids[5] = (nk_draw_index)(idx2+0);
+ ids[6] = (nk_draw_index)(idx2 + 1); ids[7] = (nk_draw_index)(idx1+1);
+ ids[8] = (nk_draw_index)(idx1 + 0); ids[9] = (nk_draw_index)(idx1+0);
+ ids[10]= (nk_draw_index)(idx2 + 0); ids[11]= (nk_draw_index)(idx2+1);
+ ids += 12;
+ idx1 = idx2;
+ }
+
+ /* fill vertices */
+ for (i = 0; i < points_count; ++i) {
+ const struct nk_vec2 uv = list->config.tex_null.uv;
+ vtx = nk_draw_vertex(vtx, &list->config, points[i], uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+0], uv, col_trans);
+ vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+1], uv, col_trans);
+ }
+ } else {
+ nk_size idx1, i;
+ const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f;
+ if (!closed) {
+ struct nk_vec2 d1 = nk_vec2_muls(normals[0], half_inner_thickness + AA_SIZE);
+ struct nk_vec2 d2 = nk_vec2_muls(normals[0], half_inner_thickness);
+
+ temp[0] = nk_vec2_add(points[0], d1);
+ temp[1] = nk_vec2_add(points[0], d2);
+ temp[2] = nk_vec2_sub(points[0], d2);
+ temp[3] = nk_vec2_sub(points[0], d1);
+
+ d1 = nk_vec2_muls(normals[points_count-1], half_inner_thickness + AA_SIZE);
+ d2 = nk_vec2_muls(normals[points_count-1], half_inner_thickness);
+
+ temp[(points_count-1)*4+0] = nk_vec2_add(points[points_count-1], d1);
+ temp[(points_count-1)*4+1] = nk_vec2_add(points[points_count-1], d2);
+ temp[(points_count-1)*4+2] = nk_vec2_sub(points[points_count-1], d2);
+ temp[(points_count-1)*4+3] = nk_vec2_sub(points[points_count-1], d1);
+ }
+
+ /* add all elements */
+ idx1 = index;
+ for (i1 = 0; i1 < count; ++i1) {
+ struct nk_vec2 dm_out, dm_in;
+ const nk_size i2 = ((i1+1) == points_count) ? 0: (i1 + 1);
+ nk_size idx2 = ((i1+1) == points_count) ? index: (idx1 + 4);
+
+ /* average normals */
+ struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(normals[i1], normals[i2]), 0.5f);
+ float dmr2 = dm.x * dm.x + dm.y* dm.y;
+ if (dmr2 > 0.000001f) {
+ float scale = 1.0f/dmr2;
+ scale = NK_MIN(100.0f, scale);
+ dm = nk_vec2_muls(dm, scale);
+ }
+
+ dm_out = nk_vec2_muls(dm, ((half_inner_thickness) + AA_SIZE));
+ dm_in = nk_vec2_muls(dm, half_inner_thickness);
+ temp[i2*4+0] = nk_vec2_add(points[i2], dm_out);
+ temp[i2*4+1] = nk_vec2_add(points[i2], dm_in);
+ temp[i2*4+2] = nk_vec2_sub(points[i2], dm_in);
+ temp[i2*4+3] = nk_vec2_sub(points[i2], dm_out);
+
+ /* add indexes */
+ ids[0] = (nk_draw_index)(idx2 + 1); ids[1] = (nk_draw_index)(idx1+1);
+ ids[2] = (nk_draw_index)(idx1 + 2); ids[3] = (nk_draw_index)(idx1+2);
+ ids[4] = (nk_draw_index)(idx2 + 2); ids[5] = (nk_draw_index)(idx2+1);
+ ids[6] = (nk_draw_index)(idx2 + 1); ids[7] = (nk_draw_index)(idx1+1);
+ ids[8] = (nk_draw_index)(idx1 + 0); ids[9] = (nk_draw_index)(idx1+0);
+ ids[10]= (nk_draw_index)(idx2 + 0); ids[11] = (nk_draw_index)(idx2+1);
+ ids[12]= (nk_draw_index)(idx2 + 2); ids[13] = (nk_draw_index)(idx1+2);
+ ids[14]= (nk_draw_index)(idx1 + 3); ids[15] = (nk_draw_index)(idx1+3);
+ ids[16]= (nk_draw_index)(idx2 + 3); ids[17] = (nk_draw_index)(idx2+2);
+ ids += 18;
+ idx1 = idx2;
+ }
+
+ /* add vertices */
+ for (i = 0; i < points_count; ++i) {
+ const struct nk_vec2 uv = list->config.tex_null.uv;
+ vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+0], uv, col_trans);
+ vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+1], uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+2], uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+3], uv, col_trans);
+ }
+ }
+ /* free temporary normals + points */
+ nk_buffer_reset(list->vertices, NK_BUFFER_FRONT);
+ } else {
+ /* NON ANTI-ALIASED STROKE */
+ nk_size i1 = 0;
+ nk_size idx = list->vertex_count;
+ const nk_size idx_count = count * 6;
+ const nk_size vtx_count = count * 4;
+ void *vtx = nk_draw_list_alloc_vertices(list, vtx_count);
+ nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count);
+ if (!vtx || !ids) return;
+
+ for (i1 = 0; i1 < count; ++i1) {
+ float dx, dy;
+ const struct nk_vec2 uv = list->config.tex_null.uv;
+ const nk_size i2 = ((i1+1) == points_count) ? 0 : i1 + 1;
+ const struct nk_vec2 p1 = points[i1];
+ const struct nk_vec2 p2 = points[i2];
+ struct nk_vec2 diff = nk_vec2_sub(p2, p1);
+ float len;
+
+ /* vec2 inverted length */
+ len = nk_vec2_len_sqr(diff);
+ if (len != 0.0f)
+ len = NK_INV_SQRT(len);
+ else len = 1.0f;
+ diff = nk_vec2_muls(diff, len);
+
+ /* add vertices */
+ dx = diff.x * (thickness * 0.5f);
+ dy = diff.y * (thickness * 0.5f);
+
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p1.x + dy, p1.y - dx), uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p2.x + dy, p2.y - dx), uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p2.x - dy, p2.y + dx), uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p1.x - dy, p1.y + dx), uv, col);
+
+ ids[0] = (nk_draw_index)(idx+0); ids[1] = (nk_draw_index)(idx+1);
+ ids[2] = (nk_draw_index)(idx+2); ids[3] = (nk_draw_index)(idx+0);
+ ids[4] = (nk_draw_index)(idx+2); ids[5] = (nk_draw_index)(idx+3);
+
+ ids += 6;
+ idx += 4;
+ }
+ }
+}
+NK_API void
+nk_draw_list_fill_poly_convex(struct nk_draw_list *list,
+ const struct nk_vec2 *points, const unsigned int points_count,
+ struct nk_color color, enum nk_anti_aliasing aliasing)
+{
+ struct nk_colorf col;
+ struct nk_colorf col_trans;
+
+ NK_STORAGE const nk_size pnt_align = NK_ALIGNOF(struct nk_vec2);
+ NK_STORAGE const nk_size pnt_size = sizeof(struct nk_vec2);
+ NK_ASSERT(list);
+ if (!list || points_count < 3) return;
+
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ nk_draw_list_push_userdata(list, list->userdata);
+#endif
+
+ color.a = (nk_byte)((float)color.a * list->config.global_alpha);
+ nk_color_fv(&col.r, color);
+ col_trans = col;
+ col_trans.a = 0;
+
+ if (aliasing == NK_ANTI_ALIASING_ON) {
+ nk_size i = 0;
+ nk_size i0 = 0;
+ nk_size i1 = 0;
+
+ const float AA_SIZE = 1.0f;
+ nk_size vertex_offset = 0;
+ nk_size index = list->vertex_count;
+
+ const nk_size idx_count = (points_count-2)*3 + points_count*6;
+ const nk_size vtx_count = (points_count*2);
+
+ void *vtx = nk_draw_list_alloc_vertices(list, vtx_count);
+ nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count);
+
+ nk_size size = 0;
+ struct nk_vec2 *normals = 0;
+ unsigned int vtx_inner_idx = (unsigned int)(index + 0);
+ unsigned int vtx_outer_idx = (unsigned int)(index + 1);
+ if (!vtx || !ids) return;
+
+ /* temporary allocate normals */
+ vertex_offset = (nk_size)((nk_byte*)vtx - (nk_byte*)list->vertices->memory.ptr);
+ nk_buffer_mark(list->vertices, NK_BUFFER_FRONT);
+ size = pnt_size * points_count;
+ normals = (struct nk_vec2*) nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, size, pnt_align);
+ if (!normals) return;
+ vtx = (void*)((nk_byte*)list->vertices->memory.ptr + vertex_offset);
+
+ /* add elements */
+ for (i = 2; i < points_count; i++) {
+ ids[0] = (nk_draw_index)(vtx_inner_idx);
+ ids[1] = (nk_draw_index)(vtx_inner_idx + ((i-1) << 1));
+ ids[2] = (nk_draw_index)(vtx_inner_idx + (i << 1));
+ ids += 3;
+ }
+
+ /* compute normals */
+ for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) {
+ struct nk_vec2 p0 = points[i0];
+ struct nk_vec2 p1 = points[i1];
+ struct nk_vec2 diff = nk_vec2_sub(p1, p0);
+
+ /* vec2 inverted length */
+ float len = nk_vec2_len_sqr(diff);
+ if (len != 0.0f)
+ len = NK_INV_SQRT(len);
+ else len = 1.0f;
+ diff = nk_vec2_muls(diff, len);
+
+ normals[i0].x = diff.y;
+ normals[i0].y = -diff.x;
+ }
+
+ /* add vertices + indexes */
+ for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) {
+ const struct nk_vec2 uv = list->config.tex_null.uv;
+ struct nk_vec2 n0 = normals[i0];
+ struct nk_vec2 n1 = normals[i1];
+ struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(n0, n1), 0.5f);
+ float dmr2 = dm.x*dm.x + dm.y*dm.y;
+ if (dmr2 > 0.000001f) {
+ float scale = 1.0f / dmr2;
+ scale = NK_MIN(scale, 100.0f);
+ dm = nk_vec2_muls(dm, scale);
+ }
+ dm = nk_vec2_muls(dm, AA_SIZE * 0.5f);
+
+ /* add vertices */
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2_sub(points[i1], dm), uv, col);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2_add(points[i1], dm), uv, col_trans);
+
+ /* add indexes */
+ ids[0] = (nk_draw_index)(vtx_inner_idx+(i1<<1));
+ ids[1] = (nk_draw_index)(vtx_inner_idx+(i0<<1));
+ ids[2] = (nk_draw_index)(vtx_outer_idx+(i0<<1));
+ ids[3] = (nk_draw_index)(vtx_outer_idx+(i0<<1));
+ ids[4] = (nk_draw_index)(vtx_outer_idx+(i1<<1));
+ ids[5] = (nk_draw_index)(vtx_inner_idx+(i1<<1));
+ ids += 6;
+ }
+ /* free temporary normals + points */
+ nk_buffer_reset(list->vertices, NK_BUFFER_FRONT);
+ } else {
+ nk_size i = 0;
+ nk_size index = list->vertex_count;
+ const nk_size idx_count = (points_count-2)*3;
+ const nk_size vtx_count = points_count;
+ void *vtx = nk_draw_list_alloc_vertices(list, vtx_count);
+ nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count);
+
+ if (!vtx || !ids) return;
+ for (i = 0; i < vtx_count; ++i)
+ vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.tex_null.uv, col);
+ for (i = 2; i < points_count; ++i) {
+ ids[0] = (nk_draw_index)index;
+ ids[1] = (nk_draw_index)(index+ i - 1);
+ ids[2] = (nk_draw_index)(index+i);
+ ids += 3;
+ }
+ }
+}
+NK_API void
+nk_draw_list_path_clear(struct nk_draw_list *list)
+{
+ NK_ASSERT(list);
+ if (!list) return;
+ nk_buffer_reset(list->buffer, NK_BUFFER_FRONT);
+ list->path_count = 0;
+ list->path_offset = 0;
+}
+NK_API void
+nk_draw_list_path_line_to(struct nk_draw_list *list, struct nk_vec2 pos)
+{
+ struct nk_vec2 *points = 0;
+ struct nk_draw_command *cmd = 0;
+ NK_ASSERT(list);
+ if (!list) return;
+ if (!list->cmd_count)
+ nk_draw_list_add_clip(list, nk_null_rect);
+
+ cmd = nk_draw_list_command_last(list);
+ if (cmd && cmd->texture.ptr != list->config.tex_null.texture.ptr)
+ nk_draw_list_push_image(list, list->config.tex_null.texture);
+
+ points = nk_draw_list_alloc_path(list, 1);
+ if (!points) return;
+ points[0] = pos;
+}
+NK_API void
+nk_draw_list_path_arc_to_fast(struct nk_draw_list *list, struct nk_vec2 center,
+ float radius, int a_min, int a_max)
+{
+ int a = 0;
+ NK_ASSERT(list);
+ if (!list) return;
+ if (a_min <= a_max) {
+ for (a = a_min; a <= a_max; a++) {
+ const struct nk_vec2 c = list->circle_vtx[(nk_size)a % NK_LEN(list->circle_vtx)];
+ const float x = center.x + c.x * radius;
+ const float y = center.y + c.y * radius;
+ nk_draw_list_path_line_to(list, nk_vec2(x, y));
+ }
+ }
+}
+NK_API void
+nk_draw_list_path_arc_to(struct nk_draw_list *list, struct nk_vec2 center,
+ float radius, float a_min, float a_max, unsigned int segments)
+{
+ unsigned int i = 0;
+ NK_ASSERT(list);
+ if (!list) return;
+ if (radius == 0.0f) return;
+
+ /* This algorithm for arc drawing relies on these two trigonometric identities[1]:
+ sin(a + b) = sin(a) * cos(b) + cos(a) * sin(b)
+ cos(a + b) = cos(a) * cos(b) - sin(a) * sin(b)
+
+ Two coordinates (x, y) of a point on a circle centered on
+ the origin can be written in polar form as:
+ x = r * cos(a)
+ y = r * sin(a)
+ where r is the radius of the circle,
+ a is the angle between (x, y) and the origin.
+
+ This allows us to rotate the coordinates around the
+ origin by an angle b using the following transformation:
+ x' = r * cos(a + b) = x * cos(b) - y * sin(b)
+ y' = r * sin(a + b) = y * cos(b) + x * sin(b)
+
+ [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Angle_sum_and_difference_identities
+ */
+ {const float d_angle = (a_max - a_min) / (float)segments;
+ const float sin_d = (float)NK_SIN(d_angle);
+ const float cos_d = (float)NK_COS(d_angle);
+
+ float cx = (float)NK_COS(a_min) * radius;
+ float cy = (float)NK_SIN(a_min) * radius;
+ for(i = 0; i <= segments; ++i) {
+ float new_cx, new_cy;
+ const float x = center.x + cx;
+ const float y = center.y + cy;
+ nk_draw_list_path_line_to(list, nk_vec2(x, y));
+
+ new_cx = cx * cos_d - cy * sin_d;
+ new_cy = cy * cos_d + cx * sin_d;
+ cx = new_cx;
+ cy = new_cy;
+ }}
+}
+NK_API void
+nk_draw_list_path_rect_to(struct nk_draw_list *list, struct nk_vec2 a,
+ struct nk_vec2 b, float rounding)
+{
+ float r;
+ NK_ASSERT(list);
+ if (!list) return;
+ r = rounding;
+ r = NK_MIN(r, ((b.x-a.x) < 0) ? -(b.x-a.x): (b.x-a.x));
+ r = NK_MIN(r, ((b.y-a.y) < 0) ? -(b.y-a.y): (b.y-a.y));
+
+ if (r == 0.0f) {
+ nk_draw_list_path_line_to(list, a);
+ nk_draw_list_path_line_to(list, nk_vec2(b.x,a.y));
+ nk_draw_list_path_line_to(list, b);
+ nk_draw_list_path_line_to(list, nk_vec2(a.x,b.y));
+ } else {
+ nk_draw_list_path_arc_to_fast(list, nk_vec2(a.x + r, a.y + r), r, 6, 9);
+ nk_draw_list_path_arc_to_fast(list, nk_vec2(b.x - r, a.y + r), r, 9, 12);
+ nk_draw_list_path_arc_to_fast(list, nk_vec2(b.x - r, b.y - r), r, 0, 3);
+ nk_draw_list_path_arc_to_fast(list, nk_vec2(a.x + r, b.y - r), r, 3, 6);
+ }
+}
+NK_API void
+nk_draw_list_path_curve_to(struct nk_draw_list *list, struct nk_vec2 p2,
+ struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments)
+{
+ float t_step;
+ unsigned int i_step;
+ struct nk_vec2 p1;
+
+ NK_ASSERT(list);
+ NK_ASSERT(list->path_count);
+ if (!list || !list->path_count) return;
+ num_segments = NK_MAX(num_segments, 1);
+
+ p1 = nk_draw_list_path_last(list);
+ t_step = 1.0f/(float)num_segments;
+ for (i_step = 1; i_step <= num_segments; ++i_step) {
+ float t = t_step * (float)i_step;
+ float u = 1.0f - t;
+ float w1 = u*u*u;
+ float w2 = 3*u*u*t;
+ float w3 = 3*u*t*t;
+ float w4 = t * t *t;
+ float x = w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x;
+ float y = w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y;
+ nk_draw_list_path_line_to(list, nk_vec2(x,y));
+ }
+}
+NK_API void
+nk_draw_list_path_fill(struct nk_draw_list *list, struct nk_color color)
+{
+ struct nk_vec2 *points;
+ NK_ASSERT(list);
+ if (!list) return;
+ points = (struct nk_vec2*)nk_buffer_memory(list->buffer);
+ nk_draw_list_fill_poly_convex(list, points, list->path_count, color, list->config.shape_AA);
+ nk_draw_list_path_clear(list);
+}
+NK_API void
+nk_draw_list_path_stroke(struct nk_draw_list *list, struct nk_color color,
+ enum nk_draw_list_stroke closed, float thickness)
+{
+ struct nk_vec2 *points;
+ NK_ASSERT(list);
+ if (!list) return;
+ points = (struct nk_vec2*)nk_buffer_memory(list->buffer);
+ nk_draw_list_stroke_poly_line(list, points, list->path_count, color,
+ closed, thickness, list->config.line_AA);
+ nk_draw_list_path_clear(list);
+}
+NK_API void
+nk_draw_list_stroke_line(struct nk_draw_list *list, struct nk_vec2 a,
+ struct nk_vec2 b, struct nk_color col, float thickness)
+{
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ if (list->line_AA == NK_ANTI_ALIASING_ON) {
+ nk_draw_list_path_line_to(list, a);
+ nk_draw_list_path_line_to(list, b);
+ } else {
+ nk_draw_list_path_line_to(list, nk_vec2_sub(a,nk_vec2(0.5f,0.5f)));
+ nk_draw_list_path_line_to(list, nk_vec2_sub(b,nk_vec2(0.5f,0.5f)));
+ }
+ nk_draw_list_path_stroke(list, col, NK_STROKE_OPEN, thickness);
+}
+NK_API void
+nk_draw_list_fill_rect(struct nk_draw_list *list, struct nk_rect rect,
+ struct nk_color col, float rounding)
+{
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+
+ if (list->line_AA == NK_ANTI_ALIASING_ON) {
+ nk_draw_list_path_rect_to(list, nk_vec2(rect.x, rect.y),
+ nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding);
+ } else {
+ nk_draw_list_path_rect_to(list, nk_vec2(rect.x-0.5f, rect.y-0.5f),
+ nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding);
+ } nk_draw_list_path_fill(list, col);
+}
+NK_API void
+nk_draw_list_stroke_rect(struct nk_draw_list *list, struct nk_rect rect,
+ struct nk_color col, float rounding, float thickness)
+{
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ if (list->line_AA == NK_ANTI_ALIASING_ON) {
+ nk_draw_list_path_rect_to(list, nk_vec2(rect.x, rect.y),
+ nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding);
+ } else {
+ nk_draw_list_path_rect_to(list, nk_vec2(rect.x-0.5f, rect.y-0.5f),
+ nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding);
+ } nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness);
+}
+NK_API void
+nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rect,
+ struct nk_color left, struct nk_color top, struct nk_color right,
+ struct nk_color bottom)
+{
+ void *vtx;
+ struct nk_colorf col_left, col_top;
+ struct nk_colorf col_right, col_bottom;
+ nk_draw_index *idx;
+ nk_draw_index index;
+
+ nk_color_fv(&col_left.r, left);
+ nk_color_fv(&col_right.r, right);
+ nk_color_fv(&col_top.r, top);
+ nk_color_fv(&col_bottom.r, bottom);
+
+ NK_ASSERT(list);
+ if (!list) return;
+
+ nk_draw_list_push_image(list, list->config.tex_null.texture);
+ index = (nk_draw_index)list->vertex_count;
+ vtx = nk_draw_list_alloc_vertices(list, 4);
+ idx = nk_draw_list_alloc_elements(list, 6);
+ if (!vtx || !idx) return;
+
+ idx[0] = (nk_draw_index)(index+0); idx[1] = (nk_draw_index)(index+1);
+ idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0);
+ idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3);
+
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.tex_null.uv, col_left);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.tex_null.uv, col_top);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.tex_null.uv, col_right);
+ vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.tex_null.uv, col_bottom);
+}
+NK_API void
+nk_draw_list_fill_triangle(struct nk_draw_list *list, struct nk_vec2 a,
+ struct nk_vec2 b, struct nk_vec2 c, struct nk_color col)
+{
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ nk_draw_list_path_line_to(list, a);
+ nk_draw_list_path_line_to(list, b);
+ nk_draw_list_path_line_to(list, c);
+ nk_draw_list_path_fill(list, col);
+}
+NK_API void
+nk_draw_list_stroke_triangle(struct nk_draw_list *list, struct nk_vec2 a,
+ struct nk_vec2 b, struct nk_vec2 c, struct nk_color col, float thickness)
+{
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ nk_draw_list_path_line_to(list, a);
+ nk_draw_list_path_line_to(list, b);
+ nk_draw_list_path_line_to(list, c);
+ nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness);
+}
+NK_API void
+nk_draw_list_fill_circle(struct nk_draw_list *list, struct nk_vec2 center,
+ float radius, struct nk_color col, unsigned int segs)
+{
+ float a_max;
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ a_max = NK_PI * 2.0f * ((float)segs - 1.0f) / (float)segs;
+ nk_draw_list_path_arc_to(list, center, radius, 0.0f, a_max, segs);
+ nk_draw_list_path_fill(list, col);
+}
+NK_API void
+nk_draw_list_stroke_circle(struct nk_draw_list *list, struct nk_vec2 center,
+ float radius, struct nk_color col, unsigned int segs, float thickness)
+{
+ float a_max;
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ a_max = NK_PI * 2.0f * ((float)segs - 1.0f) / (float)segs;
+ nk_draw_list_path_arc_to(list, center, radius, 0.0f, a_max, segs);
+ nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness);
+}
+NK_API void
+nk_draw_list_stroke_curve(struct nk_draw_list *list, struct nk_vec2 p0,
+ struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1,
+ struct nk_color col, unsigned int segments, float thickness)
+{
+ NK_ASSERT(list);
+ if (!list || !col.a) return;
+ nk_draw_list_path_line_to(list, p0);
+ nk_draw_list_path_curve_to(list, cp0, cp1, p1, segments);
+ nk_draw_list_path_stroke(list, col, NK_STROKE_OPEN, thickness);
+}
+NK_INTERN void
+nk_draw_list_push_rect_uv(struct nk_draw_list *list, struct nk_vec2 a,
+ struct nk_vec2 c, struct nk_vec2 uva, struct nk_vec2 uvc,
+ struct nk_color color)
+{
+ void *vtx;
+ struct nk_vec2 uvb;
+ struct nk_vec2 uvd;
+ struct nk_vec2 b;
+ struct nk_vec2 d;
+
+ struct nk_colorf col;
+ nk_draw_index *idx;
+ nk_draw_index index;
+ NK_ASSERT(list);
+ if (!list) return;
+
+ nk_color_fv(&col.r, color);
+ uvb = nk_vec2(uvc.x, uva.y);
+ uvd = nk_vec2(uva.x, uvc.y);
+ b = nk_vec2(c.x, a.y);
+ d = nk_vec2(a.x, c.y);
+
+ index = (nk_draw_index)list->vertex_count;
+ vtx = nk_draw_list_alloc_vertices(list, 4);
+ idx = nk_draw_list_alloc_elements(list, 6);
+ if (!vtx || !idx) return;
+
+ idx[0] = (nk_draw_index)(index+0); idx[1] = (nk_draw_index)(index+1);
+ idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0);
+ idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3);
+
+ vtx = nk_draw_vertex(vtx, &list->config, a, uva, col);
+ vtx = nk_draw_vertex(vtx, &list->config, b, uvb, col);
+ vtx = nk_draw_vertex(vtx, &list->config, c, uvc, col);
+ vtx = nk_draw_vertex(vtx, &list->config, d, uvd, col);
+}
+NK_API void
+nk_draw_list_add_image(struct nk_draw_list *list, struct nk_image texture,
+ struct nk_rect rect, struct nk_color color)
+{
+ NK_ASSERT(list);
+ if (!list) return;
+ /* push new command with given texture */
+ nk_draw_list_push_image(list, texture.handle);
+ if (nk_image_is_subimage(&texture)) {
+ /* add region inside of the texture */
+ struct nk_vec2 uv[2];
+ uv[0].x = (float)texture.region[0]/(float)texture.w;
+ uv[0].y = (float)texture.region[1]/(float)texture.h;
+ uv[1].x = (float)(texture.region[0] + texture.region[2])/(float)texture.w;
+ uv[1].y = (float)(texture.region[1] + texture.region[3])/(float)texture.h;
+ nk_draw_list_push_rect_uv(list, nk_vec2(rect.x, rect.y),
+ nk_vec2(rect.x + rect.w, rect.y + rect.h), uv[0], uv[1], color);
+ } else nk_draw_list_push_rect_uv(list, nk_vec2(rect.x, rect.y),
+ nk_vec2(rect.x + rect.w, rect.y + rect.h),
+ nk_vec2(0.0f, 0.0f), nk_vec2(1.0f, 1.0f),color);
+}
+NK_API void
+nk_draw_list_add_text(struct nk_draw_list *list, const struct nk_user_font *font,
+ struct nk_rect rect, const char *text, int len, float font_height,
+ struct nk_color fg)
+{
+ float x = 0;
+ int text_len = 0;
+ nk_rune unicode = 0;
+ nk_rune next = 0;
+ int glyph_len = 0;
+ int next_glyph_len = 0;
+ struct nk_user_font_glyph g;
+
+ NK_ASSERT(list);
+ if (!list || !len || !text) return;
+ if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h,
+ list->clip_rect.x, list->clip_rect.y, list->clip_rect.w, list->clip_rect.h)) return;
+
+ nk_draw_list_push_image(list, font->texture);
+ x = rect.x;
+ glyph_len = nk_utf_decode(text, &unicode, len);
+ if (!glyph_len) return;
+
+ /* draw every glyph image */
+ fg.a = (nk_byte)((float)fg.a * list->config.global_alpha);
+ while (text_len < len && glyph_len) {
+ float gx, gy, gh, gw;
+ float char_width = 0;
+ if (unicode == NK_UTF_INVALID) break;
+
+ /* query currently drawn glyph information */
+ next_glyph_len = nk_utf_decode(text + text_len + glyph_len, &next, (int)len - text_len);
+ font->query(font->userdata, font_height, &g, unicode,
+ (next == NK_UTF_INVALID) ? '\0' : next);
+
+ /* calculate and draw glyph drawing rectangle and image */
+ gx = x + g.offset.x;
+ gy = rect.y + g.offset.y;
+ gw = g.width; gh = g.height;
+ char_width = g.xadvance;
+ nk_draw_list_push_rect_uv(list, nk_vec2(gx,gy), nk_vec2(gx + gw, gy+ gh),
+ g.uv[0], g.uv[1], fg);
+
+ /* offset next glyph */
+ text_len += glyph_len;
+ x += char_width;
+ glyph_len = next_glyph_len;
+ unicode = next;
+ }
+}
+NK_API nk_flags
+nk_convert(struct nk_context *ctx, struct nk_buffer *cmds,
+ struct nk_buffer *vertices, struct nk_buffer *elements,
+ const struct nk_convert_config *config)
+{
+ nk_flags res = NK_CONVERT_SUCCESS;
+ const struct nk_command *cmd;
+ NK_ASSERT(ctx);
+ NK_ASSERT(cmds);
+ NK_ASSERT(vertices);
+ NK_ASSERT(elements);
+ NK_ASSERT(config);
+ NK_ASSERT(config->vertex_layout);
+ NK_ASSERT(config->vertex_size);
+ if (!ctx || !cmds || !vertices || !elements || !config || !config->vertex_layout)
+ return NK_CONVERT_INVALID_PARAM;
+
+ nk_draw_list_setup(&ctx->draw_list, config, cmds, vertices, elements,
+ config->line_AA, config->shape_AA);
+ nk_foreach(cmd, ctx)
+ {
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ ctx->draw_list.userdata = cmd->userdata;
+#endif
+ switch (cmd->type) {
+ case NK_COMMAND_NOP: break;
+ case NK_COMMAND_SCISSOR: {
+ const struct nk_command_scissor *s = (const struct nk_command_scissor*)cmd;
+ nk_draw_list_add_clip(&ctx->draw_list, nk_rect(s->x, s->y, s->w, s->h));
+ } break;
+ case NK_COMMAND_LINE: {
+ const struct nk_command_line *l = (const struct nk_command_line*)cmd;
+ nk_draw_list_stroke_line(&ctx->draw_list, nk_vec2(l->begin.x, l->begin.y),
+ nk_vec2(l->end.x, l->end.y), l->color, l->line_thickness);
+ } break;
+ case NK_COMMAND_CURVE: {
+ const struct nk_command_curve *q = (const struct nk_command_curve*)cmd;
+ nk_draw_list_stroke_curve(&ctx->draw_list, nk_vec2(q->begin.x, q->begin.y),
+ nk_vec2(q->ctrl[0].x, q->ctrl[0].y), nk_vec2(q->ctrl[1].x,
+ q->ctrl[1].y), nk_vec2(q->end.x, q->end.y), q->color,
+ config->curve_segment_count, q->line_thickness);
+ } break;
+ case NK_COMMAND_RECT: {
+ const struct nk_command_rect *r = (const struct nk_command_rect*)cmd;
+ nk_draw_list_stroke_rect(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h),
+ r->color, (float)r->rounding, r->line_thickness);
+ } break;
+ case NK_COMMAND_RECT_FILLED: {
+ const struct nk_command_rect_filled *r = (const struct nk_command_rect_filled*)cmd;
+ nk_draw_list_fill_rect(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h),
+ r->color, (float)r->rounding);
+ } break;
+ case NK_COMMAND_RECT_MULTI_COLOR: {
+ const struct nk_command_rect_multi_color *r = (const struct nk_command_rect_multi_color*)cmd;
+ nk_draw_list_fill_rect_multi_color(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h),
+ r->left, r->top, r->right, r->bottom);
+ } break;
+ case NK_COMMAND_CIRCLE: {
+ const struct nk_command_circle *c = (const struct nk_command_circle*)cmd;
+ nk_draw_list_stroke_circle(&ctx->draw_list, nk_vec2((float)c->x + (float)c->w/2,
+ (float)c->y + (float)c->h/2), (float)c->w/2, c->color,
+ config->circle_segment_count, c->line_thickness);
+ } break;
+ case NK_COMMAND_CIRCLE_FILLED: {
+ const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd;
+ nk_draw_list_fill_circle(&ctx->draw_list, nk_vec2((float)c->x + (float)c->w/2,
+ (float)c->y + (float)c->h/2), (float)c->w/2, c->color,
+ config->circle_segment_count);
+ } break;
+ case NK_COMMAND_ARC: {
+ const struct nk_command_arc *c = (const struct nk_command_arc*)cmd;
+ nk_draw_list_path_line_to(&ctx->draw_list, nk_vec2(c->cx, c->cy));
+ nk_draw_list_path_arc_to(&ctx->draw_list, nk_vec2(c->cx, c->cy), c->r,
+ c->a[0], c->a[1], config->arc_segment_count);
+ nk_draw_list_path_stroke(&ctx->draw_list, c->color, NK_STROKE_CLOSED, c->line_thickness);
+ } break;
+ case NK_COMMAND_ARC_FILLED: {
+ const struct nk_command_arc_filled *c = (const struct nk_command_arc_filled*)cmd;
+ nk_draw_list_path_line_to(&ctx->draw_list, nk_vec2(c->cx, c->cy));
+ nk_draw_list_path_arc_to(&ctx->draw_list, nk_vec2(c->cx, c->cy), c->r,
+ c->a[0], c->a[1], config->arc_segment_count);
+ nk_draw_list_path_fill(&ctx->draw_list, c->color);
+ } break;
+ case NK_COMMAND_TRIANGLE: {
+ const struct nk_command_triangle *t = (const struct nk_command_triangle*)cmd;
+ nk_draw_list_stroke_triangle(&ctx->draw_list, nk_vec2(t->a.x, t->a.y),
+ nk_vec2(t->b.x, t->b.y), nk_vec2(t->c.x, t->c.y), t->color,
+ t->line_thickness);
+ } break;
+ case NK_COMMAND_TRIANGLE_FILLED: {
+ const struct nk_command_triangle_filled *t = (const struct nk_command_triangle_filled*)cmd;
+ nk_draw_list_fill_triangle(&ctx->draw_list, nk_vec2(t->a.x, t->a.y),
+ nk_vec2(t->b.x, t->b.y), nk_vec2(t->c.x, t->c.y), t->color);
+ } break;
+ case NK_COMMAND_POLYGON: {
+ int i;
+ const struct nk_command_polygon*p = (const struct nk_command_polygon*)cmd;
+ for (i = 0; i < p->point_count; ++i) {
+ struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y);
+ nk_draw_list_path_line_to(&ctx->draw_list, pnt);
+ }
+ nk_draw_list_path_stroke(&ctx->draw_list, p->color, NK_STROKE_CLOSED, p->line_thickness);
+ } break;
+ case NK_COMMAND_POLYGON_FILLED: {
+ int i;
+ const struct nk_command_polygon_filled *p = (const struct nk_command_polygon_filled*)cmd;
+ for (i = 0; i < p->point_count; ++i) {
+ struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y);
+ nk_draw_list_path_line_to(&ctx->draw_list, pnt);
+ }
+ nk_draw_list_path_fill(&ctx->draw_list, p->color);
+ } break;
+ case NK_COMMAND_POLYLINE: {
+ int i;
+ const struct nk_command_polyline *p = (const struct nk_command_polyline*)cmd;
+ for (i = 0; i < p->point_count; ++i) {
+ struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y);
+ nk_draw_list_path_line_to(&ctx->draw_list, pnt);
+ }
+ nk_draw_list_path_stroke(&ctx->draw_list, p->color, NK_STROKE_OPEN, p->line_thickness);
+ } break;
+ case NK_COMMAND_TEXT: {
+ const struct nk_command_text *t = (const struct nk_command_text*)cmd;
+ nk_draw_list_add_text(&ctx->draw_list, t->font, nk_rect(t->x, t->y, t->w, t->h),
+ t->string, t->length, t->height, t->foreground);
+ } break;
+ case NK_COMMAND_IMAGE: {
+ const struct nk_command_image *i = (const struct nk_command_image*)cmd;
+ nk_draw_list_add_image(&ctx->draw_list, i->img, nk_rect(i->x, i->y, i->w, i->h), i->col);
+ } break;
+ case NK_COMMAND_CUSTOM: {
+ const struct nk_command_custom *c = (const struct nk_command_custom*)cmd;
+ c->callback(&ctx->draw_list, c->x, c->y, c->w, c->h, c->callback_data);
+ } break;
+ default: break;
+ }
+ }
+ res |= (cmds->needed > cmds->allocated + (cmds->memory.size - cmds->size)) ? NK_CONVERT_COMMAND_BUFFER_FULL: 0;
+ res |= (vertices->needed > vertices->allocated) ? NK_CONVERT_VERTEX_BUFFER_FULL: 0;
+ res |= (elements->needed > elements->allocated) ? NK_CONVERT_ELEMENT_BUFFER_FULL: 0;
+ return res;
+}
+NK_API const struct nk_draw_command*
+nk__draw_begin(const struct nk_context *ctx,
+ const struct nk_buffer *buffer)
+{
+ return nk__draw_list_begin(&ctx->draw_list, buffer);
+}
+NK_API const struct nk_draw_command*
+nk__draw_end(const struct nk_context *ctx, const struct nk_buffer *buffer)
+{
+ return nk__draw_list_end(&ctx->draw_list, buffer);
+}
+NK_API const struct nk_draw_command*
+nk__draw_next(const struct nk_draw_command *cmd,
+ const struct nk_buffer *buffer, const struct nk_context *ctx)
+{
+ return nk__draw_list_next(cmd, buffer, &ctx->draw_list);
+}
+#endif
+
+
+/* stb_rect_pack.h - v1.01 - public domain - rectangle packing */
+/* Sean Barrett 2014 */
+/* */
+/* Useful for e.g. packing rectangular textures into an atlas. */
+/* Does not do rotation. */
+/* */
+/* Before #including, */
+/* */
+/* #define STB_RECT_PACK_IMPLEMENTATION */
+/* */
+/* in the file that you want to have the implementation. */
+/* */
+/* Not necessarily the awesomest packing method, but better than */
+/* the totally naive one in stb_truetype (which is primarily what */
+/* this is meant to replace). */
+/* */
+/* Has only had a few tests run, may have issues. */
+/* */
+/* More docs to come. */
+/* */
+/* No memory allocations; uses qsort() and assert() from stdlib. */
+/* Can override those by defining STBRP_SORT and STBRP_ASSERT. */
+/* */
+/* This library currently uses the Skyline Bottom-Left algorithm. */
+/* */
+/* Please note: better rectangle packers are welcome! Please */
+/* implement them to the same API, but with a different init */
+/* function. */
+/* */
+/* Credits */
+/* */
+/* Library */
+/* Sean Barrett */
+/* Minor features */
+/* Martins Mozeiko */
+/* github:IntellectualKitty */
+/* */
+/* Bugfixes / warning fixes */
+/* Jeremy Jaussaud */
+/* Fabian Giesen */
+/* */
+/* Version history: */
+/* */
+/* 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section */
+/* 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles */
+/* 0.99 (2019-02-07) warning fixes */
+/* 0.11 (2017-03-03) return packing success/fail result */
+/* 0.10 (2016-10-25) remove cast-away-const to avoid warnings */
+/* 0.09 (2016-08-27) fix compiler warnings */
+/* 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) */
+/* 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) */
+/* 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort */
+/* 0.05: added STBRP_ASSERT to allow replacing assert */
+/* 0.04: fixed minor bug in STBRP_LARGE_RECTS support */
+/* 0.01: initial release */
+/* */
+/* LICENSE */
+/* */
+/* See end of file for license information. */
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* INCLUDE SECTION */
+/* */
+
+#ifndef STB_INCLUDE_STB_RECT_PACK_H
+#define STB_INCLUDE_STB_RECT_PACK_H
+
+#define STB_RECT_PACK_VERSION 1
+
+#ifdef STBRP_STATIC
+#define STBRP_DEF static
+#else
+#define STBRP_DEF extern
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct stbrp_context stbrp_context;
+typedef struct stbrp_node stbrp_node;
+typedef struct stbrp_rect stbrp_rect;
+
+typedef int stbrp_coord;
+
+#define STBRP__MAXVAL 0x7fffffff
+/* Mostly for internal use, but this is the maximum supported coordinate value. */
+
+STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
+/* Assign packed locations to rectangles. The rectangles are of type */
+/* 'stbrp_rect' defined below, stored in the array 'rects', and there */
+/* are 'num_rects' many of them. */
+/* */
+/* Rectangles which are successfully packed have the 'was_packed' flag */
+/* set to a non-zero value and 'x' and 'y' store the minimum location */
+/* on each axis (i.e. bottom-left in cartesian coordinates, top-left */
+/* if you imagine y increasing downwards). Rectangles which do not fit */
+/* have the 'was_packed' flag set to 0. */
+/* */
+/* You should not try to access the 'rects' array from another thread */
+/* while this function is running, as the function temporarily reorders */
+/* the array while it executes. */
+/* */
+/* To pack into another rectangle, you need to call stbrp_init_target */
+/* again. To continue packing into the same rectangle, you can call */
+/* this function again. Calling this multiple times with multiple rect */
+/* arrays will probably produce worse packing results than calling it */
+/* a single time with the full rectangle array, but the option is */
+/* available. */
+/* */
+/* The function returns 1 if all of the rectangles were successfully */
+/* packed and 0 otherwise. */
+
+struct stbrp_rect
+{
+ /* reserved for your use: */
+ int id;
+
+ /* input: */
+ stbrp_coord w, h;
+
+ /* output: */
+ stbrp_coord x, y;
+ int was_packed; /* non-zero if valid packing */
+
+}; /* 16 bytes, nominally */
+
+
+STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
+/* Initialize a rectangle packer to: */
+/* pack a rectangle that is 'width' by 'height' in dimensions */
+/* using temporary storage provided by the array 'nodes', which is 'num_nodes' long */
+/* */
+/* You must call this function every time you start packing into a new target. */
+/* */
+/* There is no "shutdown" function. The 'nodes' memory must stay valid for */
+/* the following stbrp_pack_rects() call (or calls), but can be freed after */
+/* the call (or calls) finish. */
+/* */
+/* Note: to guarantee best results, either: */
+/* 1. make sure 'num_nodes' >= 'width' */
+/* or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' */
+/* */
+/* If you don't do either of the above things, widths will be quantized to multiples */
+/* of small integers to guarantee the algorithm doesn't run out of temporary storage. */
+/* */
+/* If you do #2, then the non-quantized algorithm will be used, but the algorithm */
+/* may run out of temporary storage and be unable to pack some rectangles. */
+
+STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
+/* Optionally call this function after init but before doing any packing to */
+/* change the handling of the out-of-temp-memory scenario, described above. */
+/* If you call init again, this will be reset to the default (false). */
+
+
+STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
+/* Optionally select which packing heuristic the library should use. Different */
+/* heuristics will produce better/worse results for different data sets. */
+/* If you call init again, this will be reset to the default. */
+
+enum
+{
+ STBRP_HEURISTIC_Skyline_default=0,
+ STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
+ STBRP_HEURISTIC_Skyline_BF_sortHeight
+};
+
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* the details of the following structures don't matter to you, but they must */
+/* be visible so you can handle the memory allocations for them */
+
+struct stbrp_node
+{
+ stbrp_coord x,y;
+ stbrp_node *next;
+};
+
+struct stbrp_context
+{
+ int width;
+ int height;
+ int align;
+ int init_mode;
+ int heuristic;
+ int num_nodes;
+ stbrp_node *active_head;
+ stbrp_node *free_head;
+ stbrp_node extra[2]; /* we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' */
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* IMPLEMENTATION SECTION */
+/* */
+
+#ifdef STB_RECT_PACK_IMPLEMENTATION
+#ifndef STBRP_SORT
+#include
+#define STBRP_SORT qsort
+#endif
+
+#ifndef STBRP_ASSERT
+#include
+#define STBRP_ASSERT assert
+#endif
+
+#ifdef _MSC_VER
+#define STBRP__NOTUSED(v) (void)(v)
+#define STBRP__CDECL __cdecl
+#else
+#define STBRP__NOTUSED(v) (void)sizeof(v)
+#define STBRP__CDECL
+#endif
+
+enum
+{
+ STBRP__INIT_skyline = 1
+};
+
+STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
+{
+ switch (context->init_mode) {
+ case STBRP__INIT_skyline:
+ STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
+ context->heuristic = heuristic;
+ break;
+ default:
+ STBRP_ASSERT(0);
+ }
+}
+
+STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
+{
+ if (allow_out_of_mem)
+ /* if it's ok to run out of memory, then don't bother aligning them; */
+ /* this gives better packing, but may fail due to OOM (even though */
+ /* the rectangles easily fit). @TODO a smarter approach would be to only */
+ /* quantize once we've hit OOM, then we could get rid of this parameter. */
+ context->align = 1;
+ else {
+ /* if it's not ok to run out of memory, then quantize the widths */
+ /* so that num_nodes is always enough nodes. */
+ /* */
+ /* I.e. num_nodes * align >= width */
+ /* align >= width / num_nodes */
+ /* align = ceil(width/num_nodes) */
+
+ context->align = (context->width + context->num_nodes-1) / context->num_nodes;
+ }
+}
+
+STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
+{
+ int i;
+
+ for (i=0; i < num_nodes-1; ++i)
+ nodes[i].next = &nodes[i+1];
+ nodes[i].next = NULL;
+ context->init_mode = STBRP__INIT_skyline;
+ context->heuristic = STBRP_HEURISTIC_Skyline_default;
+ context->free_head = &nodes[0];
+ context->active_head = &context->extra[0];
+ context->width = width;
+ context->height = height;
+ context->num_nodes = num_nodes;
+ stbrp_setup_allow_out_of_mem(context, 0);
+
+ /* node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) */
+ context->extra[0].x = 0;
+ context->extra[0].y = 0;
+ context->extra[0].next = &context->extra[1];
+ context->extra[1].x = (stbrp_coord) width;
+ context->extra[1].y = (1<<30);
+ context->extra[1].next = NULL;
+}
+
+/* find minimum y position if it starts at x1 */
+static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
+{
+ stbrp_node *node = first;
+ int x1 = x0 + width;
+ int min_y, visited_width, waste_area;
+
+ STBRP__NOTUSED(c);
+
+ STBRP_ASSERT(first->x <= x0);
+
+ #if 0
+ /* skip in case we're past the node */
+ while (node->next->x <= x0)
+ ++node;
+ #else
+ STBRP_ASSERT(node->next->x > x0); /* we ended up handling this in the caller for efficiency */
+ #endif
+
+ STBRP_ASSERT(node->x <= x0);
+
+ min_y = 0;
+ waste_area = 0;
+ visited_width = 0;
+ while (node->x < x1) {
+ if (node->y > min_y) {
+ /* raise min_y higher. */
+ /* we've accounted for all waste up to min_y, */
+ /* but we'll now add more waste for everything we've visited */
+ waste_area += visited_width * (node->y - min_y);
+ min_y = node->y;
+ /* the first time through, visited_width might be reduced */
+ if (node->x < x0)
+ visited_width += node->next->x - x0;
+ else
+ visited_width += node->next->x - node->x;
+ } else {
+ /* add waste area */
+ int under_width = node->next->x - node->x;
+ if (under_width + visited_width > width)
+ under_width = width - visited_width;
+ waste_area += under_width * (min_y - node->y);
+ visited_width += under_width;
+ }
+ node = node->next;
+ }
+
+ *pwaste = waste_area;
+ return min_y;
+}
+
+typedef struct
+{
+ int x,y;
+ stbrp_node **prev_link;
+} stbrp__findresult;
+
+static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
+{
+ int best_waste = (1<<30), best_x, best_y = (1 << 30);
+ stbrp__findresult fr;
+ stbrp_node **prev, *node, *tail, **best = NULL;
+
+ /* align to multiple of c->align */
+ width = (width + c->align - 1);
+ width -= width % c->align;
+ STBRP_ASSERT(width % c->align == 0);
+
+ /* if it can't possibly fit, bail immediately */
+ if (width > c->width || height > c->height) {
+ fr.prev_link = NULL;
+ fr.x = fr.y = 0;
+ return fr;
+ }
+
+ node = c->active_head;
+ prev = &c->active_head;
+ while (node->x + width <= c->width) {
+ int y,waste;
+ y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
+ if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { /* actually just want to test BL */
+ /* bottom left */
+ if (y < best_y) {
+ best_y = y;
+ best = prev;
+ }
+ } else {
+ /* best-fit */
+ if (y + height <= c->height) {
+ /* can only use it if it first vertically */
+ if (y < best_y || (y == best_y && waste < best_waste)) {
+ best_y = y;
+ best_waste = waste;
+ best = prev;
+ }
+ }
+ }
+ prev = &node->next;
+ node = node->next;
+ }
+
+ best_x = (best == NULL) ? 0 : (*best)->x;
+
+ /* if doing best-fit (BF), we also have to try aligning right edge to each node position */
+ /* */
+ /* e.g, if fitting */
+ /* */
+ /* ____________________ */
+ /* |____________________| */
+ /* */
+ /* into */
+ /* */
+ /* | | */
+ /* | ____________| */
+ /* |____________| */
+ /* */
+ /* then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned */
+ /* */
+ /* This makes BF take about 2x the time */
+
+ if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
+ tail = c->active_head;
+ node = c->active_head;
+ prev = &c->active_head;
+ /* find first node that's admissible */
+ while (tail->x < width)
+ tail = tail->next;
+ while (tail) {
+ int xpos = tail->x - width;
+ int y,waste;
+ STBRP_ASSERT(xpos >= 0);
+ /* find the left position that matches this */
+ while (node->next->x <= xpos) {
+ prev = &node->next;
+ node = node->next;
+ }
+ STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
+ y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
+ if (y + height <= c->height) {
+ if (y <= best_y) {
+ if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
+ best_x = xpos;
+ STBRP_ASSERT(y <= best_y);
+ best_y = y;
+ best_waste = waste;
+ best = prev;
+ }
+ }
+ }
+ tail = tail->next;
+ }
+ }
+
+ fr.prev_link = best;
+ fr.x = best_x;
+ fr.y = best_y;
+ return fr;
+}
+
+static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
+{
+ /* find best position according to heuristic */
+ stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
+ stbrp_node *node, *cur;
+
+ /* bail if: */
+ /* 1. it failed */
+ /* 2. the best node doesn't fit (we don't always check this) */
+ /* 3. we're out of memory */
+ if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
+ res.prev_link = NULL;
+ return res;
+ }
+
+ /* on success, create new node */
+ node = context->free_head;
+ node->x = (stbrp_coord) res.x;
+ node->y = (stbrp_coord) (res.y + height);
+
+ context->free_head = node->next;
+
+ /* insert the new node into the right starting point, and */
+ /* let 'cur' point to the remaining nodes needing to be */
+ /* stitched back in */
+
+ cur = *res.prev_link;
+ if (cur->x < res.x) {
+ /* preserve the existing one, so start testing with the next one */
+ stbrp_node *next = cur->next;
+ cur->next = node;
+ cur = next;
+ } else {
+ *res.prev_link = node;
+ }
+
+ /* from here, traverse cur and free the nodes, until we get to one */
+ /* that shouldn't be freed */
+ while (cur->next && cur->next->x <= res.x + width) {
+ stbrp_node *next = cur->next;
+ /* move the current node to the free list */
+ cur->next = context->free_head;
+ context->free_head = cur;
+ cur = next;
+ }
+
+ /* stitch the list back in */
+ node->next = cur;
+
+ if (cur->x < res.x + width)
+ cur->x = (stbrp_coord) (res.x + width);
+
+#ifdef _DEBUG
+ cur = context->active_head;
+ while (cur->x < context->width) {
+ STBRP_ASSERT(cur->x < cur->next->x);
+ cur = cur->next;
+ }
+ STBRP_ASSERT(cur->next == NULL);
+
+ {
+ int count=0;
+ cur = context->active_head;
+ while (cur) {
+ cur = cur->next;
+ ++count;
+ }
+ cur = context->free_head;
+ while (cur) {
+ cur = cur->next;
+ ++count;
+ }
+ STBRP_ASSERT(count == context->num_nodes+2);
+ }
+#endif
+
+ return res;
+}
+
+static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
+{
+ const stbrp_rect *p = (const stbrp_rect *) a;
+ const stbrp_rect *q = (const stbrp_rect *) b;
+ if (p->h > q->h)
+ return -1;
+ if (p->h < q->h)
+ return 1;
+ return (p->w > q->w) ? -1 : (p->w < q->w);
+}
+
+static int STBRP__CDECL rect_original_order(const void *a, const void *b)
+{
+ const stbrp_rect *p = (const stbrp_rect *) a;
+ const stbrp_rect *q = (const stbrp_rect *) b;
+ return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
+}
+
+STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
+{
+ int i, all_rects_packed = 1;
+
+ /* we use the 'was_packed' field internally to allow sorting/unsorting */
+ for (i=0; i < num_rects; ++i) {
+ rects[i].was_packed = i;
+ }
+
+ /* sort according to heuristic */
+ STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
+
+ for (i=0; i < num_rects; ++i) {
+ if (rects[i].w == 0 || rects[i].h == 0) {
+ rects[i].x = rects[i].y = 0; /* empty rect needs no space */
+ } else {
+ stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
+ if (fr.prev_link) {
+ rects[i].x = (stbrp_coord) fr.x;
+ rects[i].y = (stbrp_coord) fr.y;
+ } else {
+ rects[i].x = rects[i].y = STBRP__MAXVAL;
+ }
+ }
+ }
+
+ /* unsort */
+ STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
+
+ /* set was_packed flags and all_rects_packed status */
+ for (i=0; i < num_rects; ++i) {
+ rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
+ if (!rects[i].was_packed)
+ all_rects_packed = 0;
+ }
+
+ /* return the all_rects_packed status */
+ return all_rects_packed;
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
+
+/* stb_truetype.h - v1.26 - public domain */
+/* authored from 2009-2021 by Sean Barrett / RAD Game Tools */
+/* */
+/* ======================================================================= */
+/* */
+/* NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES */
+/* */
+/* This library does no range checking of the offsets found in the file, */
+/* meaning an attacker can use it to read arbitrary memory. */
+/* */
+/* ======================================================================= */
+/* */
+/* This library processes TrueType files: */
+/* parse files */
+/* extract glyph metrics */
+/* extract glyph shapes */
+/* render glyphs to one-channel bitmaps with antialiasing (box filter) */
+/* render glyphs to one-channel SDF bitmaps (signed-distance field/function) */
+/* */
+/* Todo: */
+/* non-MS cmaps */
+/* crashproof on bad data */
+/* hinting? (no longer patented) */
+/* cleartype-style AA? */
+/* optimize: use simple memory allocator for intermediates */
+/* optimize: build edge-list directly from curves */
+/* optimize: rasterize directly from curves? */
+/* */
+/* ADDITIONAL CONTRIBUTORS */
+/* */
+/* Mikko Mononen: compound shape support, more cmap formats */
+/* Tor Andersson: kerning, subpixel rendering */
+/* Dougall Johnson: OpenType / Type 2 font handling */
+/* Daniel Ribeiro Maciel: basic GPOS-based kerning */
+/* */
+/* Misc other: */
+/* Ryan Gordon */
+/* Simon Glass */
+/* github:IntellectualKitty */
+/* Imanol Celaya */
+/* Daniel Ribeiro Maciel */
+/* */
+/* Bug/warning reports/fixes: */
+/* "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe */
+/* Cass Everitt Martins Mozeiko github:aloucks */
+/* stoiko (Haemimont Games) Cap Petschulat github:oyvindjam */
+/* Brian Hook Omar Cornut github:vassvik */
+/* Walter van Niftrik Ryan Griege */
+/* David Gow Peter LaValle */
+/* David Given Sergey Popov */
+/* Ivan-Assen Ivanov Giumo X. Clanjor */
+/* Anthony Pesch Higor Euripedes */
+/* Johan Duparc Thomas Fields */
+/* Hou Qiming Derek Vinyard */
+/* Rob Loach Cort Stratton */
+/* Kenney Phillis Jr. Brian Costabile */
+/* Ken Voskuil (kaesve) */
+/* */
+/* VERSION HISTORY */
+/* */
+/* 1.26 (2021-08-28) fix broken rasterizer */
+/* 1.25 (2021-07-11) many fixes */
+/* 1.24 (2020-02-05) fix warning */
+/* 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) */
+/* 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined */
+/* 1.21 (2019-02-25) fix warning */
+/* 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() */
+/* 1.19 (2018-02-11) GPOS kerning, STBTT_fmod */
+/* 1.18 (2018-01-29) add missing function */
+/* 1.17 (2017-07-23) make more arguments const; doc fix */
+/* 1.16 (2017-07-12) SDF support */
+/* 1.15 (2017-03-03) make more arguments const */
+/* 1.14 (2017-01-16) num-fonts-in-TTC function */
+/* 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts */
+/* 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual */
+/* 1.11 (2016-04-02) fix unused-variable warning */
+/* 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef */
+/* 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly */
+/* 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges */
+/* 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; */
+/* variant PackFontRanges to pack and render in separate phases; */
+/* fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); */
+/* fixed an assert() bug in the new rasterizer */
+/* replace assert() with STBTT_assert() in new rasterizer */
+/* */
+/* Full history can be found at the end of this file. */
+/* */
+/* LICENSE */
+/* */
+/* See end of file for license information. */
+/* */
+/* USAGE */
+/* */
+/* Include this file in whatever places need to refer to it. In ONE C/C++ */
+/* file, write: */
+/* #define STB_TRUETYPE_IMPLEMENTATION */
+/* before the #include of this file. This expands out the actual */
+/* implementation into that C/C++ file. */
+/* */
+/* To make the implementation private to the file that generates the implementation, */
+/* #define STBTT_STATIC */
+/* */
+/* Simple 3D API (don't ship this, but it's fine for tools and quick start) */
+/* stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture */
+/* stbtt_GetBakedQuad() -- compute quad to draw for a given char */
+/* */
+/* Improved 3D API (more shippable): */
+/* #include "stb_rect_pack.h" -- optional, but you really want it */
+/* stbtt_PackBegin() */
+/* stbtt_PackSetOversampling() -- for improved quality on small fonts */
+/* stbtt_PackFontRanges() -- pack and renders */
+/* stbtt_PackEnd() */
+/* stbtt_GetPackedQuad() */
+/* */
+/* "Load" a font file from a memory buffer (you have to keep the buffer loaded) */
+/* stbtt_InitFont() */
+/* stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections */
+/* stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections */
+/* */
+/* Render a unicode codepoint to a bitmap */
+/* stbtt_GetCodepointBitmap() -- allocates and returns a bitmap */
+/* stbtt_MakeCodepointBitmap() -- renders into bitmap you provide */
+/* stbtt_GetCodepointBitmapBox() -- how big the bitmap must be */
+/* */
+/* Character advance/positioning */
+/* stbtt_GetCodepointHMetrics() */
+/* stbtt_GetFontVMetrics() */
+/* stbtt_GetFontVMetricsOS2() */
+/* stbtt_GetCodepointKernAdvance() */
+/* */
+/* Starting with version 1.06, the rasterizer was replaced with a new, */
+/* faster and generally-more-precise rasterizer. The new rasterizer more */
+/* accurately measures pixel coverage for anti-aliasing, except in the case */
+/* where multiple shapes overlap, in which case it overestimates the AA pixel */
+/* coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If */
+/* this turns out to be a problem, you can re-enable the old rasterizer with */
+/* #define STBTT_RASTERIZER_VERSION 1 */
+/* which will incur about a 15% speed hit. */
+/* */
+/* ADDITIONAL DOCUMENTATION */
+/* */
+/* Immediately after this block comment are a series of sample programs. */
+/* */
+/* After the sample programs is the "header file" section. This section */
+/* includes documentation for each API function. */
+/* */
+/* Some important concepts to understand to use this library: */
+/* */
+/* Codepoint */
+/* Characters are defined by unicode codepoints, e.g. 65 is */
+/* uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is */
+/* the hiragana for "ma". */
+/* */
+/* Glyph */
+/* A visual character shape (every codepoint is rendered as */
+/* some glyph) */
+/* */
+/* Glyph index */
+/* A font-specific integer ID representing a glyph */
+/* */
+/* Baseline */
+/* Glyph shapes are defined relative to a baseline, which is the */
+/* bottom of uppercase characters. Characters extend both above */
+/* and below the baseline. */
+/* */
+/* Current Point */
+/* As you draw text to the screen, you keep track of a "current point" */
+/* which is the origin of each character. The current point's vertical */
+/* position is the baseline. Even "baked fonts" use this model. */
+/* */
+/* Vertical Font Metrics */
+/* The vertical qualities of the font, used to vertically position */
+/* and space the characters. See docs for stbtt_GetFontVMetrics. */
+/* */
+/* Font Size in Pixels or Points */
+/* The preferred interface for specifying font sizes in stb_truetype */
+/* is to specify how tall the font's vertical extent should be in pixels. */
+/* If that sounds good enough, skip the next paragraph. */
+/* */
+/* Most font APIs instead use "points", which are a common typographic */
+/* measurement for describing font size, defined as 72 points per inch. */
+/* stb_truetype provides a point API for compatibility. However, true */
+/* "per inch" conventions don't make much sense on computer displays */
+/* since different monitors have different number of pixels per */
+/* inch. For example, Windows traditionally uses a convention that */
+/* there are 96 pixels per inch, thus making 'inch' measurements have */
+/* nothing to do with inches, and thus effectively defining a point to */
+/* be 1.333 pixels. Additionally, the TrueType font data provides */
+/* an explicit scale factor to scale a given font's glyphs to points, */
+/* but the author has observed that this scale factor is often wrong */
+/* for non-commercial fonts, thus making fonts scaled in points */
+/* according to the TrueType spec incoherently sized in practice. */
+/* */
+/* DETAILED USAGE: */
+/* */
+/* Scale: */
+/* Select how high you want the font to be, in points or pixels. */
+/* Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute */
+/* a scale factor SF that will be used by all other functions. */
+/* */
+/* Baseline: */
+/* You need to select a y-coordinate that is the baseline of where */
+/* your text will appear. Call GetFontBoundingBox to get the baseline-relative */
+/* bounding box for all characters. SF*-y0 will be the distance in pixels */
+/* that the worst-case character could extend above the baseline, so if */
+/* you want the top edge of characters to appear at the top of the */
+/* screen where y=0, then you would set the baseline to SF*-y0. */
+/* */
+/* Current point: */
+/* Set the current point where the first character will appear. The */
+/* first character could extend left of the current point; this is font */
+/* dependent. You can either choose a current point that is the leftmost */
+/* point and hope, or add some padding, or check the bounding box or */
+/* left-side-bearing of the first character to be displayed and set */
+/* the current point based on that. */
+/* */
+/* Displaying a character: */
+/* Compute the bounding box of the character. It will contain signed values */
+/* relative to . I.e. if it returns x0,y0,x1,y1, */
+/* then the character should be displayed in the rectangle from */
+/* to = 32 && *text < 128) {
+ stbtt_aligned_quad q;
+ stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);/* 1=opengl & d3d10+,0=d3d9 */
+ glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0);
+ glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0);
+ glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1);
+ glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1);
+ }
+ ++text;
+ }
+ glEnd();
+}
+#endif
+/* */
+/* */
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* Complete program (this compiles): get a single bitmap, print as ASCII art */
+/* */
+#if 0
+#include
+#define STB_TRUETYPE_IMPLEMENTATION /* force following include to generate implementation */
+#include "stb_truetype.h"
+
+char ttf_buffer[1<<25];
+
+int main(int argc, char **argv)
+{
+ stbtt_fontinfo font;
+ unsigned char *bitmap;
+ int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
+
+ fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
+
+ stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
+ bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
+
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i)
+ putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
+ putchar('\n');
+ }
+ return 0;
+}
+#endif
+/* */
+/* Output: */
+/* */
+/* .ii. */
+/* @@@@@@. */
+/* V@Mio@@o */
+/* :i. V@V */
+/* :oM@@M */
+/* :@@@MM@M */
+/* @@o o@M */
+/* :@@. M@M */
+/* @@@o@@@@ */
+/* :M@@V:@@. */
+/* */
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* Complete program: print "Hello World!" banner, with bugs */
+/* */
+#if 0
+char buffer[24<<20];
+unsigned char screen[20][79];
+
+int main(int arg, char **argv)
+{
+ stbtt_fontinfo font;
+ int i,j,ascent,baseline,ch=0;
+ float scale, xpos=2; /* leave a little padding in case the character extends left */
+ char *text = "Heljo World!"; /* intentionally misspelled to show 'lj' brokenness */
+
+ fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
+ stbtt_InitFont(&font, buffer, 0);
+
+ scale = stbtt_ScaleForPixelHeight(&font, 15);
+ stbtt_GetFontVMetrics(&font, &ascent,0,0);
+ baseline = (int) (ascent*scale);
+
+ while (text[ch]) {
+ int advance,lsb,x0,y0,x1,y1;
+ float x_shift = xpos - (float) floor(xpos);
+ stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
+ stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
+ stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
+ /* note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong */
+ /* because this API is really for baking character bitmaps into textures. if you want to render */
+ /* a sequence of characters, you really need to render each bitmap to a temp buffer, then */
+ /* "alpha blend" that into the working buffer */
+ xpos += (advance * scale);
+ if (text[ch+1])
+ xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
+ ++ch;
+ }
+
+ for (j=0; j < 20; ++j) {
+ for (i=0; i < 78; ++i)
+ putchar(" .:ioVM@"[screen[j][i]>>5]);
+ putchar('\n');
+ }
+
+ return 0;
+}
+#endif
+
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* //////////////////////////////////////////////////////////////////////////// */
+/* // */
+/* // INTEGRATION WITH YOUR CODEBASE */
+/* // */
+/* // The following sections allow you to supply alternate definitions */
+/* // of C library functions used by stb_truetype, e.g. if you don't */
+/* // link with the C runtime library. */
+
+#ifdef STB_TRUETYPE_IMPLEMENTATION
+ /* #define your own (u)stbtt_int8/16/32 before including to override this */
+ #ifndef stbtt_uint8
+ typedef unsigned char stbtt_uint8;
+ typedef signed char stbtt_int8;
+ typedef unsigned short stbtt_uint16;
+ typedef signed short stbtt_int16;
+ typedef unsigned int stbtt_uint32;
+ typedef signed int stbtt_int32;
+ #endif
+
+ typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
+ typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
+
+ /* e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h */
+ #ifndef STBTT_ifloor
+ #include
+ #define STBTT_ifloor(x) ((int) floor(x))
+ #define STBTT_iceil(x) ((int) ceil(x))
+ #endif
+
+ #ifndef STBTT_sqrt
+ #include
+ #define STBTT_sqrt(x) sqrt(x)
+ #define STBTT_pow(x,y) pow(x,y)
+ #endif
+
+ #ifndef STBTT_fmod
+ #include
+ #define STBTT_fmod(x,y) fmod(x,y)
+ #endif
+
+ #ifndef STBTT_cos
+ #include
+ #define STBTT_cos(x) cos(x)
+ #define STBTT_acos(x) acos(x)
+ #endif
+
+ #ifndef STBTT_fabs
+ #include
+ #define STBTT_fabs(x) fabs(x)
+ #endif
+
+ /* #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h */
+ #ifndef STBTT_malloc
+ #include
+ #define STBTT_malloc(x,u) ((void)(u),malloc(x))
+ #define STBTT_free(x,u) ((void)(u),free(x))
+ #endif
+
+ #ifndef STBTT_assert
+ #include
+ #define STBTT_assert(x) assert(x)
+ #endif
+
+ #ifndef STBTT_strlen
+ #include
+ #define STBTT_strlen(x) strlen(x)
+ #endif
+
+ #ifndef STBTT_memcpy
+ #include
+ #define STBTT_memcpy memcpy
+ #define STBTT_memset memset
+ #endif
+#endif
+
+/* ///////////////////////////////////////////////////////////////////////////// */
+/* ///////////////////////////////////////////////////////////////////////////// */
+/* // */
+/* // INTERFACE */
+/* // */
+/* // */
+
+#ifndef __STB_INCLUDE_STB_TRUETYPE_H__
+#define __STB_INCLUDE_STB_TRUETYPE_H__
+
+#ifdef STBTT_STATIC
+#define STBTT_DEF static
+#else
+#define STBTT_DEF extern
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* private structure */
+typedef struct
+{
+ unsigned char *data;
+ int cursor;
+ int size;
+} stbtt__buf;
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* TEXTURE BAKING API */
+/* */
+/* If you use this API, you only have to call two functions ever. */
+/* */
+
+typedef struct
+{
+ unsigned short x0,y0,x1,y1; /* coordinates of bbox in bitmap */
+ float xoff,yoff,xadvance;
+} stbtt_bakedchar;
+
+STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, /* font location (use offset=0 for plain .ttf) */
+ float pixel_height, /* height of font in pixels */
+ unsigned char *pixels, int pw, int ph, /* bitmap to be filled in */
+ int first_char, int num_chars, /* characters to bake */
+ stbtt_bakedchar *chardata); /* you allocate this, it's num_chars long */
+/* if return is positive, the first unused row of the bitmap */
+/* if return is negative, returns the negative of the number of characters that fit */
+/* if return is 0, no characters fit and no rows were used */
+/* This uses a very crappy packing. */
+
+typedef struct
+{
+ float x0,y0,s0,t0; /* top-left */
+ float x1,y1,s1,t1; /* bottom-right */
+} stbtt_aligned_quad;
+
+STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, /* same data as above */
+ int char_index, /* character to display */
+ float *xpos, float *ypos, /* pointers to current position in screen pixel space */
+ stbtt_aligned_quad *q, /* output: quad to draw */
+ int opengl_fillrule); /* true if opengl fill rule; false if DX9 or earlier */
+/* Call GetBakedQuad with char_index = 'character - first_char', and it */
+/* creates the quad you need to draw and advances the current position. */
+/* */
+/* The coordinate system used assumes y increases downwards. */
+/* */
+/* Characters will extend both above and below the current position; */
+/* see discussion of "BASELINE" above. */
+/* */
+/* It's inefficient; you might want to c&p it and optimize it. */
+
+STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);
+/* Query the font vertical metrics without having to create a font first. */
+
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* NEW TEXTURE BAKING API */
+/* */
+/* This provides options for packing multiple fonts into one atlas, not */
+/* perfectly but better than nothing. */
+
+typedef struct
+{
+ unsigned short x0,y0,x1,y1; /* coordinates of bbox in bitmap */
+ float xoff,yoff,xadvance;
+ float xoff2,yoff2;
+} stbtt_packedchar;
+
+typedef struct stbtt_pack_context stbtt_pack_context;
+typedef struct stbtt_fontinfo stbtt_fontinfo;
+#ifndef STB_RECT_PACK_VERSION
+typedef struct stbrp_rect stbrp_rect;
+#endif
+
+STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
+/* Initializes a packing context stored in the passed-in stbtt_pack_context. */
+/* Future calls using this context will pack characters into the bitmap passed */
+/* in here: a 1-channel bitmap that is width * height. stride_in_bytes is */
+/* the distance from one row to the next (or 0 to mean they are packed tightly */
+/* together). "padding" is the amount of padding to leave between each */
+/* character (normally you want '1' for bitmaps you'll use as textures with */
+/* bilinear filtering). */
+/* */
+/* Returns 0 on failure, 1 on success. */
+
+STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
+/* Cleans up the packing context and frees all memory. */
+
+#define STBTT_POINT_SIZE(x) (-(x))
+
+STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
+ int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
+/* Creates character bitmaps from the font_index'th font found in fontdata (use */
+/* font_index=0 if you don't know what that is). It creates num_chars_in_range */
+/* bitmaps for characters with unicode values starting at first_unicode_char_in_range */
+/* and increasing. Data for how to render them is stored in chardata_for_range; */
+/* pass these to stbtt_GetPackedQuad to get back renderable quads. */
+/* */
+/* font_size is the full height of the character from ascender to descender, */
+/* as computed by stbtt_ScaleForPixelHeight. To use a point size as computed */
+/* by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() */
+/* and pass that result as 'font_size': */
+/* ..., 20 , ... // font max minus min y is 20 pixels tall */
+/* ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall */
+
+typedef struct
+{
+ float font_size;
+ int first_unicode_codepoint_in_range; /* if non-zero, then the chars are continuous, and this is the first codepoint */
+ int *array_of_unicode_codepoints; /* if non-zero, then this is an array of unicode codepoints */
+ int num_chars;
+ stbtt_packedchar *chardata_for_range; /* output */
+ unsigned char h_oversample, v_oversample; /* don't set these, they're used internally */
+} stbtt_pack_range;
+
+STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
+/* Creates character bitmaps from multiple ranges of characters stored in */
+/* ranges. This will usually create a better-packed bitmap than multiple */
+/* calls to stbtt_PackFontRange. Note that you can call this multiple */
+/* times within a single PackBegin/PackEnd. */
+
+STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
+/* Oversampling a font increases the quality by allowing higher-quality subpixel */
+/* positioning, and is especially valuable at smaller text sizes. */
+/* */
+/* This function sets the amount of oversampling for all following calls to */
+/* stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given */
+/* pack context. The default (no oversampling) is achieved by h_oversample=1 */
+/* and v_oversample=1. The total number of pixels required is */
+/* h_oversample*v_oversample larger than the default; for example, 2x2 */
+/* oversampling requires 4x the storage of 1x1. For best results, render */
+/* oversampled textures with bilinear filtering. Look at the readme in */
+/* stb/tests/oversample for information about oversampled fonts */
+/* */
+/* To use with PackFontRangesGather etc., you must set it before calls */
+/* call to PackFontRangesGatherRects. */
+
+STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);
+/* If skip != 0, this tells stb_truetype to skip any codepoints for which */
+/* there is no corresponding glyph. If skip=0, which is the default, then */
+/* codepoints without a glyph recived the font's "missing character" glyph, */
+/* typically an empty box by convention. */
+
+STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, /* same data as above */
+ int char_index, /* character to display */
+ float *xpos, float *ypos, /* pointers to current position in screen pixel space */
+ stbtt_aligned_quad *q, /* output: quad to draw */
+ int align_to_integer);
+
+STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
+STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
+/* Calling these functions in sequence is roughly equivalent to calling */
+/* stbtt_PackFontRanges(). If you more control over the packing of multiple */
+/* fonts, or if you want to pack custom data into a font texture, take a look */
+/* at the source to of stbtt_PackFontRanges() and create a custom version */
+/* using these functions, e.g. call GatherRects multiple times, */
+/* building up a single array of rects, then call PackRects once, */
+/* then call RenderIntoRects repeatedly. This may result in a */
+/* better packing than calling PackFontRanges multiple times */
+/* (or it may not). */
+
+/* this is an opaque structure that you shouldn't mess with which holds */
+/* all the context needed from PackBegin to PackEnd. */
+struct stbtt_pack_context {
+ void *user_allocator_context;
+ void *pack_info;
+ int width;
+ int height;
+ int stride_in_bytes;
+ int padding;
+ int skip_missing;
+ unsigned int h_oversample, v_oversample;
+ unsigned char *pixels;
+ void *nodes;
+};
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* FONT LOADING */
+/* */
+/* */
+
+STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
+/* This function will determine the number of fonts in a font file. TrueType */
+/* collection (.ttc) files may contain multiple fonts, while TrueType font */
+/* (.ttf) files only contain one font. The number of fonts can be used for */
+/* indexing with the previous function where the index is between zero and one */
+/* less than the total fonts. If an error occurs, -1 is returned. */
+
+STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
+/* Each .ttf/.ttc file may have more than one font. Each font has a sequential */
+/* index number starting from 0. Call this function to get the font offset for */
+/* a given index; it returns -1 if the index is out of range. A regular .ttf */
+/* file will only define one font and it always be at offset 0, so it will */
+/* return '0' for index 0, and -1 for all other indices. */
+
+/* The following structure is defined publicly so you can declare one on */
+/* the stack or as a global or etc, but you should treat it as opaque. */
+struct stbtt_fontinfo
+{
+ void * userdata;
+ unsigned char * data; /* pointer to .ttf file */
+ int fontstart; /* offset of start of font */
+
+ int numGlyphs; /* number of glyphs, needed for range checking */
+
+ int loca,head,glyf,hhea,hmtx,kern,gpos,svg; /* table locations as offset from start of .ttf */
+ int index_map; /* a cmap mapping for our chosen character encoding */
+ int indexToLocFormat; /* format needed to map from glyph index to glyph */
+
+ stbtt__buf cff; /* cff font data */
+ stbtt__buf charstrings; /* the charstring index */
+ stbtt__buf gsubrs; /* global charstring subroutines index */
+ stbtt__buf subrs; /* private charstring subroutines index */
+ stbtt__buf fontdicts; /* array of font dicts */
+ stbtt__buf fdselect; /* map from glyph to fontdict */
+};
+
+STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
+/* Given an offset into the file that defines a font, this function builds */
+/* the necessary cached info for the rest of the system. You must allocate */
+/* the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't */
+/* need to do anything special to free it, because the contents are pure */
+/* value data with no additional data structures. Returns 0 on failure. */
+
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* CHARACTER TO GLYPH-INDEX CONVERSIOn */
+
+STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
+/* If you're going to perform multiple operations on the same character */
+/* and you want a speed-up, call this function with the character you're */
+/* going to process, then use glyph-based functions instead of the */
+/* codepoint-based functions. */
+/* Returns 0 if the character codepoint is not defined in the font. */
+
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* CHARACTER PROPERTIES */
+/* */
+
+STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
+/* computes a scale factor to produce a font whose "height" is 'pixels' tall. */
+/* Height is measured as the distance from the highest ascender to the lowest */
+/* descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics */
+/* and computing: */
+/* scale = pixels / (ascent - descent) */
+/* so if you prefer to measure height by the ascent only, use a similar calculation. */
+
+STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
+/* computes a scale factor to produce a font whose EM size is mapped to */
+/* 'pixels' tall. This is probably what traditional APIs compute, but */
+/* I'm not positive. */
+
+STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
+/* ascent is the coordinate above the baseline the font extends; descent */
+/* is the coordinate below the baseline the font extends (i.e. it is typically negative) */
+/* lineGap is the spacing between one row's descent and the next row's ascent... */
+/* so you should advance the vertical position by "*ascent - *descent + *lineGap" */
+/* these are expressed in unscaled coordinates, so you must multiply by */
+/* the scale factor for a given size */
+
+STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);
+/* analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 */
+/* table (specific to MS/Windows TTF files). */
+/* */
+/* Returns 1 on success (table present), 0 on failure. */
+
+STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
+/* the bounding box around all possible characters */
+
+STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
+/* leftSideBearing is the offset from the current horizontal position to the left edge of the character */
+/* advanceWidth is the offset from the current horizontal position to the next horizontal position */
+/* these are expressed in unscaled coordinates */
+
+STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
+/* an additional amount to add to the 'advance' value between ch1 and ch2 */
+
+STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
+/* Gets the bounding box of the visible part of the glyph, in unscaled coordinates */
+
+STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
+STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
+STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
+/* as above, but takes one or more glyph indices for greater efficiency */
+
+typedef struct stbtt_kerningentry
+{
+ int glyph1; /* use stbtt_FindGlyphIndex */
+ int glyph2;
+ int advance;
+} stbtt_kerningentry;
+
+STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info);
+STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length);
+/* Retrieves a complete list of all of the kerning pairs provided by the font */
+/* stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. */
+/* The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) */
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* GLYPH SHAPES (you probably don't need these, but they have to go before */
+/* the bitmaps for C declaration-order reasons) */
+/* */
+
+#ifndef STBTT_vmove /* you can predefine these to use different values (but why?) */
+ enum {
+ STBTT_vmove=1,
+ STBTT_vline,
+ STBTT_vcurve,
+ STBTT_vcubic
+ };
+#endif
+
+#ifndef stbtt_vertex /* you can predefine this to use different values */
+ /* (we share this with other code at RAD) */
+ #define stbtt_vertex_type short /* can't use stbtt_int16 because that's not visible in the header file */
+ typedef struct
+ {
+ stbtt_vertex_type x,y,cx,cy,cx1,cy1;
+ unsigned char type,padding;
+ } stbtt_vertex;
+#endif
+
+STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
+/* returns non-zero if nothing is drawn for this glyph */
+
+STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
+STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
+/* returns # of vertices and fills *vertices with the pointer to them */
+/* these are expressed in "unscaled" coordinates */
+/* */
+/* The shape is a series of contours. Each one starts with */
+/* a STBTT_moveto, then consists of a series of mixed */
+/* STBTT_lineto and STBTT_curveto segments. A lineto */
+/* draws a line from previous endpoint to its x,y; a curveto */
+/* draws a quadratic bezier from previous endpoint to */
+/* its x,y, using cx,cy as the bezier control point. */
+
+STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
+/* frees the data allocated above */
+
+STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl);
+STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg);
+STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg);
+/* fills svg with the character's SVG data. */
+/* returns data size or 0 if SVG not found. */
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* BITMAP RENDERING */
+/* */
+
+STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
+/* frees the bitmap allocated below */
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
+/* allocates a large-enough single-channel 8bpp bitmap and renders the */
+/* specified character/glyph at the specified scale into it, with */
+/* antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). */
+/* *width & *height are filled out with the width & height of the bitmap, */
+/* which is stored left-to-right, top-to-bottom. */
+/* */
+/* xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap */
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
+/* the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel */
+/* shift for the character */
+
+STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
+/* the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap */
+/* in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap */
+/* is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the */
+/* width and height and positioning info for it first. */
+
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
+/* same as stbtt_MakeCodepointBitmap, but you can specify a subpixel */
+/* shift for the character */
+
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);
+/* same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering */
+/* is performed (see stbtt_PackSetOversampling) */
+
+STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
+/* get the bbox of the bitmap centered around the glyph origin; so the */
+/* bitmap width is ix1-ix0, height is iy1-iy0, and location to place */
+/* the bitmap top left is (leftSideBearing*scale,iy0). */
+/* (Note that the bitmap uses y-increases-down, but the shape uses */
+/* y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) */
+
+STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
+/* same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel */
+/* shift for the character */
+
+/* the following functions are equivalent to the above functions, but operate */
+/* on glyph indices instead of Unicode codepoints (for efficiency) */
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
+STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);
+STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
+STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
+
+
+/* @TODO: don't expose this structure */
+typedef struct
+{
+ int w,h,stride;
+ unsigned char *pixels;
+} stbtt__bitmap;
+
+/* rasterize a shape with quadratic beziers into a bitmap */
+STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, /* 1-channel bitmap to draw into */
+ float flatness_in_pixels, /* allowable error of curve in pixels */
+ stbtt_vertex *vertices, /* array of vertices defining shape */
+ int num_verts, /* number of vertices in above array */
+ float scale_x, float scale_y, /* scale applied to input vertices */
+ float shift_x, float shift_y, /* translation applied to input vertices */
+ int x_off, int y_off, /* another translation applied to input */
+ int invert, /* if non-zero, vertically flip shape */
+ void *userdata); /* context for to STBTT_MALLOC */
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* Signed Distance Function (or Field) rendering */
+
+STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);
+/* frees the SDF bitmap allocated below */
+
+STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
+STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);
+/* These functions compute a discretized SDF field for a single character, suitable for storing */
+/* in a single-channel texture, sampling with bilinear filtering, and testing against */
+/* larger than some threshold to produce scalable fonts. */
+/* info -- the font */
+/* scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap */
+/* glyph/codepoint -- the character to generate the SDF for */
+/* padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), */
+/* which allows effects like bit outlines */
+/* onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) */
+/* pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) */
+/* if positive, > onedge_value is inside; if negative, < onedge_value is inside */
+/* width,height -- output height & width of the SDF bitmap (including padding) */
+/* xoff,yoff -- output origin of the character */
+/* return value -- a 2D array of bytes 0..255, width*height in size */
+/* */
+/* pixel_dist_scale & onedge_value are a scale & bias that allows you to make */
+/* optimal use of the limited 0..255 for your application, trading off precision */
+/* and special effects. SDF values outside the range 0..255 are clamped to 0..255. */
+/* */
+/* Example: */
+/* scale = stbtt_ScaleForPixelHeight(22) */
+/* padding = 5 */
+/* onedge_value = 180 */
+/* pixel_dist_scale = 180/5.0 = 36.0 */
+/* */
+/* This will create an SDF bitmap in which the character is about 22 pixels */
+/* high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled */
+/* shape, sample the SDF at each pixel and fill the pixel if the SDF value */
+/* is greater than or equal to 180/255. (You'll actually want to antialias, */
+/* which is beyond the scope of this example.) Additionally, you can compute */
+/* offset outlines (e.g. to stroke the character border inside & outside, */
+/* or only outside). For example, to fill outside the character up to 3 SDF */
+/* pixels, you would compare against (180-36.0*3)/255 = 72/255. The above */
+/* choice of variables maps a range from 5 pixels outside the shape to */
+/* 2 pixels inside the shape to 0..255; this is intended primarily for apply */
+/* outside effects only (the interior range is needed to allow proper */
+/* antialiasing of the font at *smaller* sizes) */
+/* */
+/* The function computes the SDF analytically at each SDF pixel, not by e.g. */
+/* building a higher-res bitmap and approximating it. In theory the quality */
+/* should be as high as possible for an SDF of this size & representation, but */
+/* unclear if this is true in practice (perhaps building a higher-res bitmap */
+/* and computing from that can allow drop-out prevention). */
+/* */
+/* The algorithm has not been optimized at all, so expect it to be slow */
+/* if computing lots of characters or very large sizes. */
+
+
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* Finding the right font... */
+/* */
+/* You should really just solve this offline, keep your own tables */
+/* of what font is what, and don't try to get it out of the .ttf file. */
+/* That's because getting it out of the .ttf file is really hard, because */
+/* the names in the file can appear in many possible encodings, in many */
+/* possible languages, and e.g. if you need a case-insensitive comparison, */
+/* the details of that depend on the encoding & language in a complex way */
+/* (actually underspecified in truetype, but also gigantic). */
+/* */
+/* But you can use the provided functions in two possible ways: */
+/* stbtt_FindMatchingFont() will use *case-sensitive* comparisons on */
+/* unicode-encoded names to try to find the font you want; */
+/* you can run this before calling stbtt_InitFont() */
+/* */
+/* stbtt_GetFontNameString() lets you get any of the various strings */
+/* from the file yourself and do your own comparisons on them. */
+/* You have to have called stbtt_InitFont() first. */
+
+
+STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
+/* returns the offset (not index) of the font that matches, or -1 if none */
+/* if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". */
+/* if you use any other flag, use a font name like "Arial"; this checks */
+/* the 'macStyle' header field; i don't know if fonts set this consistently */
+#define STBTT_MACSTYLE_DONTCARE 0
+#define STBTT_MACSTYLE_BOLD 1
+#define STBTT_MACSTYLE_ITALIC 2
+#define STBTT_MACSTYLE_UNDERSCORE 4
+#define STBTT_MACSTYLE_NONE 8 /* <= not same as 0, this makes us check the bitfield is 0 */
+
+STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
+/* returns 1/0 whether the first string interpreted as utf8 is identical to */
+/* the second string interpreted as big-endian utf16... useful for strings from next func */
+
+STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
+/* returns the string (which may be big-endian double byte, e.g. for unicode) */
+/* and puts the length in bytes in *length. */
+/* */
+/* some of the values for the IDs are below; for more see the truetype spec: */
+/* http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html */
+/* http://www.microsoft.com/typography/otspec/name.htm */
+
+enum { /* platformID */
+ STBTT_PLATFORM_ID_UNICODE =0,
+ STBTT_PLATFORM_ID_MAC =1,
+ STBTT_PLATFORM_ID_ISO =2,
+ STBTT_PLATFORM_ID_MICROSOFT =3
+};
+
+enum { /* encodingID for STBTT_PLATFORM_ID_UNICODE */
+ STBTT_UNICODE_EID_UNICODE_1_0 =0,
+ STBTT_UNICODE_EID_UNICODE_1_1 =1,
+ STBTT_UNICODE_EID_ISO_10646 =2,
+ STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
+ STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
+};
+
+enum { /* encodingID for STBTT_PLATFORM_ID_MICROSOFT */
+ STBTT_MS_EID_SYMBOL =0,
+ STBTT_MS_EID_UNICODE_BMP =1,
+ STBTT_MS_EID_SHIFTJIS =2,
+ STBTT_MS_EID_UNICODE_FULL =10
+};
+
+enum { /* encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes */
+ STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
+ STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
+ STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
+ STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
+};
+
+enum { /* languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... */
+ /* problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs */
+ STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
+ STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
+ STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
+ STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
+ STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
+ STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
+};
+
+enum { /* languageID for STBTT_PLATFORM_ID_MAC */
+ STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
+ STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
+ STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
+ STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
+ STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
+ STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
+ STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STB_INCLUDE_STB_TRUETYPE_H__ */
+
+/* ///////////////////////////////////////////////////////////////////////////// */
+/* ///////////////////////////////////////////////////////////////////////////// */
+/* // */
+/* // IMPLEMENTATION */
+/* // */
+/* // */
+
+#ifdef STB_TRUETYPE_IMPLEMENTATION
+
+#ifndef STBTT_MAX_OVERSAMPLE
+#define STBTT_MAX_OVERSAMPLE 8
+#endif
+
+#if STBTT_MAX_OVERSAMPLE > 255
+#error "STBTT_MAX_OVERSAMPLE cannot be > 255"
+#endif
+
+typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
+
+#ifndef STBTT_RASTERIZER_VERSION
+#define STBTT_RASTERIZER_VERSION 2
+#endif
+
+#ifdef _MSC_VER
+#define STBTT__NOTUSED(v) (void)(v)
+#else
+#define STBTT__NOTUSED(v) (void)sizeof(v)
+#endif
+
+/* //////////////////////////////////////////////////////////////////////// */
+/* */
+/* stbtt__buf helpers to parse data from file */
+/* */
+
+static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
+{
+ if (b->cursor >= b->size)
+ return 0;
+ return b->data[b->cursor++];
+}
+
+static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
+{
+ if (b->cursor >= b->size)
+ return 0;
+ return b->data[b->cursor];
+}
+
+static void stbtt__buf_seek(stbtt__buf *b, int o)
+{
+ STBTT_assert(!(o > b->size || o < 0));
+ b->cursor = (o > b->size || o < 0) ? b->size : o;
+}
+
+static void stbtt__buf_skip(stbtt__buf *b, int o)
+{
+ stbtt__buf_seek(b, b->cursor + o);
+}
+
+static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
+{
+ stbtt_uint32 v = 0;
+ int i;
+ STBTT_assert(n >= 1 && n <= 4);
+ for (i = 0; i < n; i++)
+ v = (v << 8) | stbtt__buf_get8(b);
+ return v;
+}
+
+static stbtt__buf stbtt__new_buf(const void *p, size_t size)
+{
+ stbtt__buf r;
+ STBTT_assert(size < 0x40000000);
+ r.data = (stbtt_uint8*) p;
+ r.size = (int) size;
+ r.cursor = 0;
+ return r;
+}
+
+#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
+#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
+
+static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
+{
+ stbtt__buf r = stbtt__new_buf(NULL, 0);
+ if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
+ r.data = b->data + o;
+ r.size = s;
+ return r;
+}
+
+static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
+{
+ int count, start, offsize;
+ start = b->cursor;
+ count = stbtt__buf_get16(b);
+ if (count) {
+ offsize = stbtt__buf_get8(b);
+ STBTT_assert(offsize >= 1 && offsize <= 4);
+ stbtt__buf_skip(b, offsize * count);
+ stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
+ }
+ return stbtt__buf_range(b, start, b->cursor - start);
+}
+
+static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
+{
+ int b0 = stbtt__buf_get8(b);
+ if (b0 >= 32 && b0 <= 246) return b0 - 139;
+ else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
+ else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
+ else if (b0 == 28) return stbtt__buf_get16(b);
+ else if (b0 == 29) return stbtt__buf_get32(b);
+ STBTT_assert(0);
+ return 0;
+}
+
+static void stbtt__cff_skip_operand(stbtt__buf *b) {
+ int v, b0 = stbtt__buf_peek8(b);
+ STBTT_assert(b0 >= 28);
+ if (b0 == 30) {
+ stbtt__buf_skip(b, 1);
+ while (b->cursor < b->size) {
+ v = stbtt__buf_get8(b);
+ if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
+ break;
+ }
+ } else {
+ stbtt__cff_int(b);
+ }
+}
+
+static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
+{
+ stbtt__buf_seek(b, 0);
+ while (b->cursor < b->size) {
+ int start = b->cursor, end, op;
+ while (stbtt__buf_peek8(b) >= 28)
+ stbtt__cff_skip_operand(b);
+ end = b->cursor;
+ op = stbtt__buf_get8(b);
+ if (op == 12) op = stbtt__buf_get8(b) | 0x100;
+ if (op == key) return stbtt__buf_range(b, start, end-start);
+ }
+ return stbtt__buf_range(b, 0, 0);
+}
+
+static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
+{
+ int i;
+ stbtt__buf operands = stbtt__dict_get(b, key);
+ for (i = 0; i < outcount && operands.cursor < operands.size; i++)
+ out[i] = stbtt__cff_int(&operands);
+}
+
+static int stbtt__cff_index_count(stbtt__buf *b)
+{
+ stbtt__buf_seek(b, 0);
+ return stbtt__buf_get16(b);
+}
+
+static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
+{
+ int count, offsize, start, end;
+ stbtt__buf_seek(&b, 0);
+ count = stbtt__buf_get16(&b);
+ offsize = stbtt__buf_get8(&b);
+ STBTT_assert(i >= 0 && i < count);
+ STBTT_assert(offsize >= 1 && offsize <= 4);
+ stbtt__buf_skip(&b, i*offsize);
+ start = stbtt__buf_get(&b, offsize);
+ end = stbtt__buf_get(&b, offsize);
+ return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
+}
+
+/* //////////////////////////////////////////////////////////////////////// */
+/* */
+/* accessors to parse data from file */
+/* */
+
+/* on platforms that don't allow misaligned reads, if we want to allow */
+/* truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE */
+
+#define ttBYTE(p) (* (stbtt_uint8 *) (p))
+#define ttCHAR(p) (* (stbtt_int8 *) (p))
+#define ttFixed(p) ttLONG(p)
+
+static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
+static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }
+static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
+static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
+
+#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
+#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
+
+static int stbtt__isfont(stbtt_uint8 *font)
+{
+ /* check the version number */
+ if (stbtt_tag4(font, '1',0,0,0)) return 1; /* TrueType 1 */
+ if (stbtt_tag(font, "typ1")) return 1; /* TrueType with type 1 font -- we don't support this! */
+ if (stbtt_tag(font, "OTTO")) return 1; /* OpenType with CFF */
+ if (stbtt_tag4(font, 0,1,0,0)) return 1; /* OpenType 1.0 */
+ if (stbtt_tag(font, "true")) return 1; /* Apple specification for TrueType fonts */
+ return 0;
+}
+
+/* @OPTIMIZE: binary search */
+static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
+{
+ stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
+ stbtt_uint32 tabledir = fontstart + 12;
+ stbtt_int32 i;
+ for (i=0; i < num_tables; ++i) {
+ stbtt_uint32 loc = tabledir + 16*i;
+ if (stbtt_tag(data+loc+0, tag))
+ return ttULONG(data+loc+8);
+ }
+ return 0;
+}
+
+static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)
+{
+ /* if it's just a font, there's only one valid index */
+ if (stbtt__isfont(font_collection))
+ return index == 0 ? 0 : -1;
+
+ /* check if it's a TTC */
+ if (stbtt_tag(font_collection, "ttcf")) {
+ /* version 1? */
+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
+ stbtt_int32 n = ttLONG(font_collection+8);
+ if (index >= n)
+ return -1;
+ return ttULONG(font_collection+12+index*4);
+ }
+ }
+ return -1;
+}
+
+static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
+{
+ /* if it's just a font, there's only one valid font */
+ if (stbtt__isfont(font_collection))
+ return 1;
+
+ /* check if it's a TTC */
+ if (stbtt_tag(font_collection, "ttcf")) {
+ /* version 1? */
+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
+ return ttLONG(font_collection+8);
+ }
+ }
+ return 0;
+}
+
+static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
+{
+ stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
+ stbtt__buf pdict;
+ stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
+ if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
+ pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
+ stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
+ if (!subrsoff) return stbtt__new_buf(NULL, 0);
+ stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
+ return stbtt__cff_get_index(&cff);
+}
+
+/* since most people won't use this, find this table the first time it's needed */
+static int stbtt__get_svg(stbtt_fontinfo *info)
+{
+ stbtt_uint32 t;
+ if (info->svg < 0) {
+ t = stbtt__find_table(info->data, info->fontstart, "SVG ");
+ if (t) {
+ stbtt_uint32 offset = ttULONG(info->data + t + 2);
+ info->svg = t + offset;
+ } else {
+ info->svg = 0;
+ }
+ }
+ return info->svg;
+}
+
+static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
+{
+ stbtt_uint32 cmap, t;
+ stbtt_int32 i,numTables;
+
+ info->data = data;
+ info->fontstart = fontstart;
+ info->cff = stbtt__new_buf(NULL, 0);
+
+ cmap = stbtt__find_table(data, fontstart, "cmap"); /* required */
+ info->loca = stbtt__find_table(data, fontstart, "loca"); /* required */
+ info->head = stbtt__find_table(data, fontstart, "head"); /* required */
+ info->glyf = stbtt__find_table(data, fontstart, "glyf"); /* required */
+ info->hhea = stbtt__find_table(data, fontstart, "hhea"); /* required */
+ info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); /* required */
+ info->kern = stbtt__find_table(data, fontstart, "kern"); /* not required */
+ info->gpos = stbtt__find_table(data, fontstart, "GPOS"); /* not required */
+
+ if (!cmap || !info->head || !info->hhea || !info->hmtx)
+ return 0;
+ if (info->glyf) {
+ /* required for truetype */
+ if (!info->loca) return 0;
+ } else {
+ /* initialization for CFF / Type2 fonts (OTF) */
+ stbtt__buf b, topdict, topdictidx;
+ stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
+ stbtt_uint32 cff;
+
+ cff = stbtt__find_table(data, fontstart, "CFF ");
+ if (!cff) return 0;
+
+ info->fontdicts = stbtt__new_buf(NULL, 0);
+ info->fdselect = stbtt__new_buf(NULL, 0);
+
+ /* @TODO this should use size from table (not 512MB) */
+ info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
+ b = info->cff;
+
+ /* read the header */
+ stbtt__buf_skip(&b, 2);
+ stbtt__buf_seek(&b, stbtt__buf_get8(&b)); /* hdrsize */
+
+ /* @TODO the name INDEX could list multiple fonts, */
+ /* but we just use the first one. */
+ stbtt__cff_get_index(&b); /* name INDEX */
+ topdictidx = stbtt__cff_get_index(&b);
+ topdict = stbtt__cff_index_get(topdictidx, 0);
+ stbtt__cff_get_index(&b); /* string INDEX */
+ info->gsubrs = stbtt__cff_get_index(&b);
+
+ stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
+ stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
+ stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
+ stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
+ info->subrs = stbtt__get_subrs(b, topdict);
+
+ /* we only support Type 2 charstrings */
+ if (cstype != 2) return 0;
+ if (charstrings == 0) return 0;
+
+ if (fdarrayoff) {
+ /* looks like a CID font */
+ if (!fdselectoff) return 0;
+ stbtt__buf_seek(&b, fdarrayoff);
+ info->fontdicts = stbtt__cff_get_index(&b);
+ info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
+ }
+
+ stbtt__buf_seek(&b, charstrings);
+ info->charstrings = stbtt__cff_get_index(&b);
+ }
+
+ t = stbtt__find_table(data, fontstart, "maxp");
+ if (t)
+ info->numGlyphs = ttUSHORT(data+t+4);
+ else
+ info->numGlyphs = 0xffff;
+
+ info->svg = -1;
+
+ /* find a cmap encoding table we understand *now* to avoid searching */
+ /* later. (todo: could make this installable) */
+ /* the same regardless of glyph. */
+ numTables = ttUSHORT(data + cmap + 2);
+ info->index_map = 0;
+ for (i=0; i < numTables; ++i) {
+ stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
+ /* find an encoding we understand: */
+ switch(ttUSHORT(data+encoding_record)) {
+ case STBTT_PLATFORM_ID_MICROSOFT:
+ switch (ttUSHORT(data+encoding_record+2)) {
+ case STBTT_MS_EID_UNICODE_BMP:
+ case STBTT_MS_EID_UNICODE_FULL:
+ /* MS/Unicode */
+ info->index_map = cmap + ttULONG(data+encoding_record+4);
+ break;
+ }
+ break;
+ case STBTT_PLATFORM_ID_UNICODE:
+ /* Mac/iOS has these */
+ /* all the encodingIDs are unicode, so we don't bother to check it */
+ info->index_map = cmap + ttULONG(data+encoding_record+4);
+ break;
+ }
+ }
+ if (info->index_map == 0)
+ return 0;
+
+ info->indexToLocFormat = ttUSHORT(data+info->head + 50);
+ return 1;
+}
+
+STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
+{
+ stbtt_uint8 *data = info->data;
+ stbtt_uint32 index_map = info->index_map;
+
+ stbtt_uint16 format = ttUSHORT(data + index_map + 0);
+ if (format == 0) { /* apple byte encoding */
+ stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
+ if (unicode_codepoint < bytes-6)
+ return ttBYTE(data + index_map + 6 + unicode_codepoint);
+ return 0;
+ } else if (format == 6) {
+ stbtt_uint32 first = ttUSHORT(data + index_map + 6);
+ stbtt_uint32 count = ttUSHORT(data + index_map + 8);
+ if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
+ return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
+ return 0;
+ } else if (format == 2) {
+ STBTT_assert(0); /* @TODO: high-byte mapping for japanese/chinese/korean */
+ return 0;
+ } else if (format == 4) { /* standard mapping for windows fonts: binary search collection of ranges */
+ stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
+ stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
+ stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
+ stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
+
+ /* do a binary search of the segments */
+ stbtt_uint32 endCount = index_map + 14;
+ stbtt_uint32 search = endCount;
+
+ if (unicode_codepoint > 0xffff)
+ return 0;
+
+ /* they lie from endCount .. endCount + segCount */
+ /* but searchRange is the nearest power of two, so... */
+ if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
+ search += rangeShift*2;
+
+ /* now decrement to bias correctly to find smallest */
+ search -= 2;
+ while (entrySelector) {
+ stbtt_uint16 end;
+ searchRange >>= 1;
+ end = ttUSHORT(data + search + searchRange*2);
+ if (unicode_codepoint > end)
+ search += searchRange*2;
+ --entrySelector;
+ }
+ search += 2;
+
+ {
+ stbtt_uint16 offset, start, last;
+ stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
+
+ start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
+ last = ttUSHORT(data + endCount + 2*item);
+ if (unicode_codepoint < start || unicode_codepoint > last)
+ return 0;
+
+ offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
+ if (offset == 0)
+ return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
+
+ return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
+ }
+ } else if (format == 12 || format == 13) {
+ stbtt_uint32 ngroups = ttULONG(data+index_map+12);
+ stbtt_int32 low,high;
+ low = 0; high = (stbtt_int32)ngroups;
+ /* Binary search the right group. */
+ while (low < high) {
+ stbtt_int32 mid = low + ((high-low) >> 1); /* rounds down, so low <= mid < high */
+ stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
+ stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
+ if ((stbtt_uint32) unicode_codepoint < start_char)
+ high = mid;
+ else if ((stbtt_uint32) unicode_codepoint > end_char)
+ low = mid+1;
+ else {
+ stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
+ if (format == 12)
+ return start_glyph + unicode_codepoint-start_char;
+ else /* format == 13 */
+ return start_glyph;
+ }
+ }
+ return 0; /* not found */
+ }
+ /* @TODO */
+ STBTT_assert(0);
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
+{
+ return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
+}
+
+static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
+{
+ v->type = type;
+ v->x = (stbtt_int16) x;
+ v->y = (stbtt_int16) y;
+ v->cx = (stbtt_int16) cx;
+ v->cy = (stbtt_int16) cy;
+}
+
+static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
+{
+ int g1,g2;
+
+ STBTT_assert(!info->cff.size);
+
+ if (glyph_index >= info->numGlyphs) return -1; /* glyph index out of range */
+ if (info->indexToLocFormat >= 2) return -1; /* unknown index->glyph map format */
+
+ if (info->indexToLocFormat == 0) {
+ g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
+ g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
+ } else {
+ g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
+ g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
+ }
+
+ return g1==g2 ? -1 : g1; /* if length is 0, return -1 */
+}
+
+static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
+
+STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
+{
+ if (info->cff.size) {
+ stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
+ } else {
+ int g = stbtt__GetGlyfOffset(info, glyph_index);
+ if (g < 0) return 0;
+
+ if (x0) *x0 = ttSHORT(info->data + g + 2);
+ if (y0) *y0 = ttSHORT(info->data + g + 4);
+ if (x1) *x1 = ttSHORT(info->data + g + 6);
+ if (y1) *y1 = ttSHORT(info->data + g + 8);
+ }
+ return 1;
+}
+
+STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
+{
+ return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
+}
+
+STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
+{
+ stbtt_int16 numberOfContours;
+ int g;
+ if (info->cff.size)
+ return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
+ g = stbtt__GetGlyfOffset(info, glyph_index);
+ if (g < 0) return 1;
+ numberOfContours = ttSHORT(info->data + g);
+ return numberOfContours == 0;
+}
+
+static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
+ stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
+{
+ if (start_off) {
+ if (was_off)
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
+ } else {
+ if (was_off)
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
+ else
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
+ }
+ return num_vertices;
+}
+
+static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+{
+ stbtt_int16 numberOfContours;
+ stbtt_uint8 *endPtsOfContours;
+ stbtt_uint8 *data = info->data;
+ stbtt_vertex *vertices=0;
+ int num_vertices=0;
+ int g = stbtt__GetGlyfOffset(info, glyph_index);
+
+ *pvertices = NULL;
+
+ if (g < 0) return 0;
+
+ numberOfContours = ttSHORT(data + g);
+
+ if (numberOfContours > 0) {
+ stbtt_uint8 flags=0,flagcount;
+ stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
+ stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
+ stbtt_uint8 *points;
+ endPtsOfContours = (data + g + 10);
+ ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
+ points = data + g + 10 + numberOfContours * 2 + 2 + ins;
+
+ n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
+
+ m = n + 2*numberOfContours; /* a loose bound on how many vertices we might need */
+ vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
+ if (vertices == 0)
+ return 0;
+
+ next_move = 0;
+ flagcount=0;
+
+ /* in first pass, we load uninterpreted data into the allocated array */
+ /* above, shifted to the end of the array so we won't overwrite it when */
+ /* we create our final data starting from the front */
+
+ off = m - n; /* starting offset for uninterpreted data, regardless of how m ends up being calculated */
+
+ /* first load flags */
+
+ for (i=0; i < n; ++i) {
+ if (flagcount == 0) {
+ flags = *points++;
+ if (flags & 8)
+ flagcount = *points++;
+ } else
+ --flagcount;
+ vertices[off+i].type = flags;
+ }
+
+ /* now load x coordinates */
+ x=0;
+ for (i=0; i < n; ++i) {
+ flags = vertices[off+i].type;
+ if (flags & 2) {
+ stbtt_int16 dx = *points++;
+ x += (flags & 16) ? dx : -dx; /* ??? */
+ } else {
+ if (!(flags & 16)) {
+ x = x + (stbtt_int16) (points[0]*256 + points[1]);
+ points += 2;
+ }
+ }
+ vertices[off+i].x = (stbtt_int16) x;
+ }
+
+ /* now load y coordinates */
+ y=0;
+ for (i=0; i < n; ++i) {
+ flags = vertices[off+i].type;
+ if (flags & 4) {
+ stbtt_int16 dy = *points++;
+ y += (flags & 32) ? dy : -dy; /* ??? */
+ } else {
+ if (!(flags & 32)) {
+ y = y + (stbtt_int16) (points[0]*256 + points[1]);
+ points += 2;
+ }
+ }
+ vertices[off+i].y = (stbtt_int16) y;
+ }
+
+ /* now convert them to our format */
+ num_vertices=0;
+ sx = sy = cx = cy = scx = scy = 0;
+ for (i=0; i < n; ++i) {
+ flags = vertices[off+i].type;
+ x = (stbtt_int16) vertices[off+i].x;
+ y = (stbtt_int16) vertices[off+i].y;
+
+ if (next_move == i) {
+ if (i != 0)
+ num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
+
+ /* now start the new one */
+ start_off = !(flags & 1);
+ if (start_off) {
+ /* if we start off with an off-curve point, then when we need to find a point on the curve */
+ /* where we can start, and we need to save some state for when we wraparound. */
+ scx = x;
+ scy = y;
+ if (!(vertices[off+i+1].type & 1)) {
+ /* next point is also a curve point, so interpolate an on-point curve */
+ sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
+ sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
+ } else {
+ /* otherwise just use the next point as our start point */
+ sx = (stbtt_int32) vertices[off+i+1].x;
+ sy = (stbtt_int32) vertices[off+i+1].y;
+ ++i; /* we're using point i+1 as the starting point, so skip it */
+ }
+ } else {
+ sx = x;
+ sy = y;
+ }
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
+ was_off = 0;
+ next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
+ ++j;
+ } else {
+ if (!(flags & 1)) { /* if it's a curve */
+ if (was_off) /* two off-curve control points in a row means interpolate an on-curve midpoint */
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
+ cx = x;
+ cy = y;
+ was_off = 1;
+ } else {
+ if (was_off)
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
+ else
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
+ was_off = 0;
+ }
+ }
+ }
+ num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
+ } else if (numberOfContours < 0) {
+ /* Compound shapes. */
+ int more = 1;
+ stbtt_uint8 *comp = data + g + 10;
+ num_vertices = 0;
+ vertices = 0;
+ while (more) {
+ stbtt_uint16 flags, gidx;
+ int comp_num_verts = 0, i;
+ stbtt_vertex *comp_verts = 0, *tmp = 0;
+ float mtx[6] = {1,0,0,1,0,0}, m, n;
+
+ flags = ttSHORT(comp); comp+=2;
+ gidx = ttSHORT(comp); comp+=2;
+
+ if (flags & 2) { /* XY values */
+ if (flags & 1) { /* shorts */
+ mtx[4] = ttSHORT(comp); comp+=2;
+ mtx[5] = ttSHORT(comp); comp+=2;
+ } else {
+ mtx[4] = ttCHAR(comp); comp+=1;
+ mtx[5] = ttCHAR(comp); comp+=1;
+ }
+ }
+ else {
+ /* @TODO handle matching point */
+ STBTT_assert(0);
+ }
+ if (flags & (1<<3)) { /* WE_HAVE_A_SCALE */
+ mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[1] = mtx[2] = 0;
+ } else if (flags & (1<<6)) { /* WE_HAVE_AN_X_AND_YSCALE */
+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[1] = mtx[2] = 0;
+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
+ } else if (flags & (1<<7)) { /* WE_HAVE_A_TWO_BY_TWO */
+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
+ }
+
+ /* Find transformation scales. */
+ m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
+ n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
+
+ /* Get indexed glyph. */
+ comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
+ if (comp_num_verts > 0) {
+ /* Transform vertices. */
+ for (i = 0; i < comp_num_verts; ++i) {
+ stbtt_vertex* v = &comp_verts[i];
+ stbtt_vertex_type x,y;
+ x=v->x; y=v->y;
+ v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
+ v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
+ x=v->cx; y=v->cy;
+ v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
+ v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
+ }
+ /* Append vertices. */
+ tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
+ if (!tmp) {
+ if (vertices) STBTT_free(vertices, info->userdata);
+ if (comp_verts) STBTT_free(comp_verts, info->userdata);
+ return 0;
+ }
+ if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
+ STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
+ if (vertices) STBTT_free(vertices, info->userdata);
+ vertices = tmp;
+ STBTT_free(comp_verts, info->userdata);
+ num_vertices += comp_num_verts;
+ }
+ /* More components ? */
+ more = flags & (1<<5);
+ }
+ } else {
+ /* numberOfCounters == 0, do nothing */
+ }
+
+ *pvertices = vertices;
+ return num_vertices;
+}
+
+typedef struct
+{
+ int bounds;
+ int started;
+ float first_x, first_y;
+ float x, y;
+ stbtt_int32 min_x, max_x, min_y, max_y;
+
+ stbtt_vertex *pvertices;
+ int num_vertices;
+} stbtt__csctx;
+
+#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
+
+static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
+{
+ if (x > c->max_x || !c->started) c->max_x = x;
+ if (y > c->max_y || !c->started) c->max_y = y;
+ if (x < c->min_x || !c->started) c->min_x = x;
+ if (y < c->min_y || !c->started) c->min_y = y;
+ c->started = 1;
+}
+
+static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
+{
+ if (c->bounds) {
+ stbtt__track_vertex(c, x, y);
+ if (type == STBTT_vcubic) {
+ stbtt__track_vertex(c, cx, cy);
+ stbtt__track_vertex(c, cx1, cy1);
+ }
+ } else {
+ stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
+ c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
+ c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
+ }
+ c->num_vertices++;
+}
+
+static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
+{
+ if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
+ stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
+}
+
+static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
+{
+ stbtt__csctx_close_shape(ctx);
+ ctx->first_x = ctx->x = ctx->x + dx;
+ ctx->first_y = ctx->y = ctx->y + dy;
+ stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
+}
+
+static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
+{
+ ctx->x += dx;
+ ctx->y += dy;
+ stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
+}
+
+static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
+{
+ float cx1 = ctx->x + dx1;
+ float cy1 = ctx->y + dy1;
+ float cx2 = cx1 + dx2;
+ float cy2 = cy1 + dy2;
+ ctx->x = cx2 + dx3;
+ ctx->y = cy2 + dy3;
+ stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
+}
+
+static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
+{
+ int count = stbtt__cff_index_count(&idx);
+ int bias = 107;
+ if (count >= 33900)
+ bias = 32768;
+ else if (count >= 1240)
+ bias = 1131;
+ n += bias;
+ if (n < 0 || n >= count)
+ return stbtt__new_buf(NULL, 0);
+ return stbtt__cff_index_get(idx, n);
+}
+
+static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
+{
+ stbtt__buf fdselect = info->fdselect;
+ int nranges, start, end, v, fmt, fdselector = -1, i;
+
+ stbtt__buf_seek(&fdselect, 0);
+ fmt = stbtt__buf_get8(&fdselect);
+ if (fmt == 0) {
+ /* untested */
+ stbtt__buf_skip(&fdselect, glyph_index);
+ fdselector = stbtt__buf_get8(&fdselect);
+ } else if (fmt == 3) {
+ nranges = stbtt__buf_get16(&fdselect);
+ start = stbtt__buf_get16(&fdselect);
+ for (i = 0; i < nranges; i++) {
+ v = stbtt__buf_get8(&fdselect);
+ end = stbtt__buf_get16(&fdselect);
+ if (glyph_index >= start && glyph_index < end) {
+ fdselector = v;
+ break;
+ }
+ start = end;
+ }
+ }
+ if (fdselector == -1) stbtt__new_buf(NULL, 0);
+ return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
+}
+
+static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
+{
+ int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
+ int has_subrs = 0, clear_stack;
+ float s[48];
+ stbtt__buf subr_stack[10], subrs = info->subrs, b;
+ float f;
+
+#define STBTT__CSERR(s) (0)
+
+ /* this currently ignores the initial width value, which isn't needed if we have hmtx */
+ b = stbtt__cff_index_get(info->charstrings, glyph_index);
+ while (b.cursor < b.size) {
+ i = 0;
+ clear_stack = 1;
+ b0 = stbtt__buf_get8(&b);
+ switch (b0) {
+ /* @TODO implement hinting */
+ case 0x13: /* hintmask */
+ case 0x14: /* cntrmask */
+ if (in_header)
+ maskbits += (sp / 2); /* implicit "vstem" */
+ in_header = 0;
+ stbtt__buf_skip(&b, (maskbits + 7) / 8);
+ break;
+
+ case 0x01: /* hstem */
+ case 0x03: /* vstem */
+ case 0x12: /* hstemhm */
+ case 0x17: /* vstemhm */
+ maskbits += (sp / 2);
+ break;
+
+ case 0x15: /* rmoveto */
+ in_header = 0;
+ if (sp < 2) return STBTT__CSERR("rmoveto stack");
+ stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
+ break;
+ case 0x04: /* vmoveto */
+ in_header = 0;
+ if (sp < 1) return STBTT__CSERR("vmoveto stack");
+ stbtt__csctx_rmove_to(c, 0, s[sp-1]);
+ break;
+ case 0x16: /* hmoveto */
+ in_header = 0;
+ if (sp < 1) return STBTT__CSERR("hmoveto stack");
+ stbtt__csctx_rmove_to(c, s[sp-1], 0);
+ break;
+
+ case 0x05: /* rlineto */
+ if (sp < 2) return STBTT__CSERR("rlineto stack");
+ for (; i + 1 < sp; i += 2)
+ stbtt__csctx_rline_to(c, s[i], s[i+1]);
+ break;
+
+ /* hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical */
+ /* starting from a different place. */
+
+ case 0x07: /* vlineto */
+ if (sp < 1) return STBTT__CSERR("vlineto stack");
+ goto vlineto;
+ case 0x06: /* hlineto */
+ if (sp < 1) return STBTT__CSERR("hlineto stack");
+ for (;;) {
+ if (i >= sp) break;
+ stbtt__csctx_rline_to(c, s[i], 0);
+ i++;
+ vlineto:
+ if (i >= sp) break;
+ stbtt__csctx_rline_to(c, 0, s[i]);
+ i++;
+ }
+ break;
+
+ case 0x1F: /* hvcurveto */
+ if (sp < 4) return STBTT__CSERR("hvcurveto stack");
+ goto hvcurveto;
+ case 0x1E: /* vhcurveto */
+ if (sp < 4) return STBTT__CSERR("vhcurveto stack");
+ for (;;) {
+ if (i + 3 >= sp) break;
+ stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
+ i += 4;
+ hvcurveto:
+ if (i + 3 >= sp) break;
+ stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
+ i += 4;
+ }
+ break;
+
+ case 0x08: /* rrcurveto */
+ if (sp < 6) return STBTT__CSERR("rcurveline stack");
+ for (; i + 5 < sp; i += 6)
+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
+ break;
+
+ case 0x18: /* rcurveline */
+ if (sp < 8) return STBTT__CSERR("rcurveline stack");
+ for (; i + 5 < sp - 2; i += 6)
+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
+ if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
+ stbtt__csctx_rline_to(c, s[i], s[i+1]);
+ break;
+
+ case 0x19: /* rlinecurve */
+ if (sp < 8) return STBTT__CSERR("rlinecurve stack");
+ for (; i + 1 < sp - 6; i += 2)
+ stbtt__csctx_rline_to(c, s[i], s[i+1]);
+ if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
+ break;
+
+ case 0x1A: /* vvcurveto */
+ case 0x1B: /* hhcurveto */
+ if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
+ f = 0.0;
+ if (sp & 1) { f = s[i]; i++; }
+ for (; i + 3 < sp; i += 4) {
+ if (b0 == 0x1B)
+ stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
+ else
+ stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
+ f = 0.0;
+ }
+ break;
+
+ case 0x0A: /* callsubr */
+ if (!has_subrs) {
+ if (info->fdselect.size)
+ subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
+ has_subrs = 1;
+ }
+ /* FALLTHROUGH */
+ case 0x1D: /* callgsubr */
+ if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
+ v = (int) s[--sp];
+ if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
+ subr_stack[subr_stack_height++] = b;
+ b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
+ if (b.size == 0) return STBTT__CSERR("subr not found");
+ b.cursor = 0;
+ clear_stack = 0;
+ break;
+
+ case 0x0B: /* return */
+ if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
+ b = subr_stack[--subr_stack_height];
+ clear_stack = 0;
+ break;
+
+ case 0x0E: /* endchar */
+ stbtt__csctx_close_shape(c);
+ return 1;
+
+ case 0x0C: { /* two-byte escape */
+ float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
+ float dx, dy;
+ int b1 = stbtt__buf_get8(&b);
+ switch (b1) {
+ /* @TODO These "flex" implementations ignore the flex-depth and resolution, */
+ /* and always draw beziers. */
+ case 0x22: /* hflex */
+ if (sp < 7) return STBTT__CSERR("hflex stack");
+ dx1 = s[0];
+ dx2 = s[1];
+ dy2 = s[2];
+ dx3 = s[3];
+ dx4 = s[4];
+ dx5 = s[5];
+ dx6 = s[6];
+ stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
+ stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
+ break;
+
+ case 0x23: /* flex */
+ if (sp < 13) return STBTT__CSERR("flex stack");
+ dx1 = s[0];
+ dy1 = s[1];
+ dx2 = s[2];
+ dy2 = s[3];
+ dx3 = s[4];
+ dy3 = s[5];
+ dx4 = s[6];
+ dy4 = s[7];
+ dx5 = s[8];
+ dy5 = s[9];
+ dx6 = s[10];
+ dy6 = s[11];
+ /* fd is s[12] */
+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
+ stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
+ break;
+
+ case 0x24: /* hflex1 */
+ if (sp < 9) return STBTT__CSERR("hflex1 stack");
+ dx1 = s[0];
+ dy1 = s[1];
+ dx2 = s[2];
+ dy2 = s[3];
+ dx3 = s[4];
+ dx4 = s[5];
+ dx5 = s[6];
+ dy5 = s[7];
+ dx6 = s[8];
+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
+ stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
+ break;
+
+ case 0x25: /* flex1 */
+ if (sp < 11) return STBTT__CSERR("flex1 stack");
+ dx1 = s[0];
+ dy1 = s[1];
+ dx2 = s[2];
+ dy2 = s[3];
+ dx3 = s[4];
+ dy3 = s[5];
+ dx4 = s[6];
+ dy4 = s[7];
+ dx5 = s[8];
+ dy5 = s[9];
+ dx6 = dy6 = s[10];
+ dx = dx1+dx2+dx3+dx4+dx5;
+ dy = dy1+dy2+dy3+dy4+dy5;
+ if (STBTT_fabs(dx) > STBTT_fabs(dy))
+ dy6 = -dy;
+ else
+ dx6 = -dx;
+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
+ stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
+ break;
+
+ default:
+ return STBTT__CSERR("unimplemented");
+ }
+ } break;
+
+ default:
+ if (b0 != 255 && b0 != 28 && b0 < 32)
+ return STBTT__CSERR("reserved operator");
+
+ /* push immediate */
+ if (b0 == 255) {
+ f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
+ } else {
+ stbtt__buf_skip(&b, -1);
+ f = (float)(stbtt_int16)stbtt__cff_int(&b);
+ }
+ if (sp >= 48) return STBTT__CSERR("push stack overflow");
+ s[sp++] = f;
+ clear_stack = 0;
+ break;
+ }
+ if (clear_stack) sp = 0;
+ }
+ return STBTT__CSERR("no endchar");
+
+#undef STBTT__CSERR
+}
+
+static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+{
+ /* runs the charstring twice, once to count and once to output (to avoid realloc) */
+ stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
+ stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
+ if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
+ *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
+ output_ctx.pvertices = *pvertices;
+ if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
+ STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
+ return output_ctx.num_vertices;
+ }
+ }
+ *pvertices = NULL;
+ return 0;
+}
+
+static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
+{
+ stbtt__csctx c = STBTT__CSCTX_INIT(1);
+ int r = stbtt__run_charstring(info, glyph_index, &c);
+ if (x0) *x0 = r ? c.min_x : 0;
+ if (y0) *y0 = r ? c.min_y : 0;
+ if (x1) *x1 = r ? c.max_x : 0;
+ if (y1) *y1 = r ? c.max_y : 0;
+ return r ? c.num_vertices : 0;
+}
+
+STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+{
+ if (!info->cff.size)
+ return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
+ else
+ return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
+}
+
+STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
+{
+ stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
+ if (glyph_index < numOfLongHorMetrics) {
+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
+ } else {
+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
+ }
+}
+
+STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info)
+{
+ stbtt_uint8 *data = info->data + info->kern;
+
+ /* we only look at the first table. it must be 'horizontal' and format 0. */
+ if (!info->kern)
+ return 0;
+ if (ttUSHORT(data+2) < 1) /* number of tables, need at least 1 */
+ return 0;
+ if (ttUSHORT(data+8) != 1) /* horizontal flag must be set in format */
+ return 0;
+
+ return ttUSHORT(data+10);
+}
+
+STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length)
+{
+ stbtt_uint8 *data = info->data + info->kern;
+ int k, length;
+
+ /* we only look at the first table. it must be 'horizontal' and format 0. */
+ if (!info->kern)
+ return 0;
+ if (ttUSHORT(data+2) < 1) /* number of tables, need at least 1 */
+ return 0;
+ if (ttUSHORT(data+8) != 1) /* horizontal flag must be set in format */
+ return 0;
+
+ length = ttUSHORT(data+10);
+ if (table_length < length)
+ length = table_length;
+
+ for (k = 0; k < length; k++)
+ {
+ table[k].glyph1 = ttUSHORT(data+18+(k*6));
+ table[k].glyph2 = ttUSHORT(data+20+(k*6));
+ table[k].advance = ttSHORT(data+22+(k*6));
+ }
+
+ return length;
+}
+
+static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
+{
+ stbtt_uint8 *data = info->data + info->kern;
+ stbtt_uint32 needle, straw;
+ int l, r, m;
+
+ /* we only look at the first table. it must be 'horizontal' and format 0. */
+ if (!info->kern)
+ return 0;
+ if (ttUSHORT(data+2) < 1) /* number of tables, need at least 1 */
+ return 0;
+ if (ttUSHORT(data+8) != 1) /* horizontal flag must be set in format */
+ return 0;
+
+ l = 0;
+ r = ttUSHORT(data+10) - 1;
+ needle = glyph1 << 16 | glyph2;
+ while (l <= r) {
+ m = (l + r) >> 1;
+ straw = ttULONG(data+18+(m*6)); /* note: unaligned read */
+ if (needle < straw)
+ r = m - 1;
+ else if (needle > straw)
+ l = m + 1;
+ else
+ return ttSHORT(data+22+(m*6));
+ }
+ return 0;
+}
+
+static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)
+{
+ stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
+ switch (coverageFormat) {
+ case 1: {
+ stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
+
+ /* Binary search. */
+ stbtt_int32 l=0, r=glyphCount-1, m;
+ int straw, needle=glyph;
+ while (l <= r) {
+ stbtt_uint8 *glyphArray = coverageTable + 4;
+ stbtt_uint16 glyphID;
+ m = (l + r) >> 1;
+ glyphID = ttUSHORT(glyphArray + 2 * m);
+ straw = glyphID;
+ if (needle < straw)
+ r = m - 1;
+ else if (needle > straw)
+ l = m + 1;
+ else {
+ return m;
+ }
+ }
+ break;
+ }
+
+ case 2: {
+ stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
+ stbtt_uint8 *rangeArray = coverageTable + 4;
+
+ /* Binary search. */
+ stbtt_int32 l=0, r=rangeCount-1, m;
+ int strawStart, strawEnd, needle=glyph;
+ while (l <= r) {
+ stbtt_uint8 *rangeRecord;
+ m = (l + r) >> 1;
+ rangeRecord = rangeArray + 6 * m;
+ strawStart = ttUSHORT(rangeRecord);
+ strawEnd = ttUSHORT(rangeRecord + 2);
+ if (needle < strawStart)
+ r = m - 1;
+ else if (needle > strawEnd)
+ l = m + 1;
+ else {
+ stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
+ return startCoverageIndex + glyph - strawStart;
+ }
+ }
+ break;
+ }
+
+ default: return -1; /* unsupported */
+ }
+
+ return -1;
+}
+
+static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)
+{
+ stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
+ switch (classDefFormat)
+ {
+ case 1: {
+ stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
+ stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
+ stbtt_uint8 *classDef1ValueArray = classDefTable + 6;
+
+ if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
+ return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
+ break;
+ }
+
+ case 2: {
+ stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
+ stbtt_uint8 *classRangeRecords = classDefTable + 4;
+
+ /* Binary search. */
+ stbtt_int32 l=0, r=classRangeCount-1, m;
+ int strawStart, strawEnd, needle=glyph;
+ while (l <= r) {
+ stbtt_uint8 *classRangeRecord;
+ m = (l + r) >> 1;
+ classRangeRecord = classRangeRecords + 6 * m;
+ strawStart = ttUSHORT(classRangeRecord);
+ strawEnd = ttUSHORT(classRangeRecord + 2);
+ if (needle < strawStart)
+ r = m - 1;
+ else if (needle > strawEnd)
+ l = m + 1;
+ else
+ return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
+ }
+ break;
+ }
+
+ default:
+ return -1; /* Unsupported definition type, return an error. */
+ }
+
+ /* "All glyphs not assigned to a class fall into class 0". (OpenType spec) */
+ return 0;
+}
+
+/* Define to STBTT_assert(x) if you want to break on unimplemented formats. */
+#define STBTT_GPOS_TODO_assert(x)
+
+static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
+{
+ stbtt_uint16 lookupListOffset;
+ stbtt_uint8 *lookupList;
+ stbtt_uint16 lookupCount;
+ stbtt_uint8 *data;
+ stbtt_int32 i, sti;
+
+ if (!info->gpos) return 0;
+
+ data = info->data + info->gpos;
+
+ if (ttUSHORT(data+0) != 1) return 0; /* Major version 1 */
+ if (ttUSHORT(data+2) != 0) return 0; /* Minor version 0 */
+
+ lookupListOffset = ttUSHORT(data+8);
+ lookupList = data + lookupListOffset;
+ lookupCount = ttUSHORT(lookupList);
+
+ for (i=0; i= pairSetCount) return 0;
+
+ needle=glyph2;
+ r=pairValueCount-1;
+ l=0;
+
+ /* Binary search. */
+ while (l <= r) {
+ stbtt_uint16 secondGlyph;
+ stbtt_uint8 *pairValue;
+ m = (l + r) >> 1;
+ pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
+ secondGlyph = ttUSHORT(pairValue);
+ straw = secondGlyph;
+ if (needle < straw)
+ r = m - 1;
+ else if (needle > straw)
+ l = m + 1;
+ else {
+ stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
+ return xAdvance;
+ }
+ }
+ } else
+ return 0;
+ break;
+ }
+
+ case 2: {
+ stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
+ stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
+ if (valueFormat1 == 4 && valueFormat2 == 0) { /* Support more formats? */
+ stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
+ stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
+ int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
+ int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
+
+ stbtt_uint16 class1Count = ttUSHORT(table + 12);
+ stbtt_uint16 class2Count = ttUSHORT(table + 14);
+ stbtt_uint8 *class1Records, *class2Records;
+ stbtt_int16 xAdvance;
+
+ if (glyph1class < 0 || glyph1class >= class1Count) return 0; /* malformed */
+ if (glyph2class < 0 || glyph2class >= class2Count) return 0; /* malformed */
+
+ class1Records = table + 16;
+ class2Records = class1Records + 2 * (glyph1class * class2Count);
+ xAdvance = ttSHORT(class2Records + 2 * glyph2class);
+ return xAdvance;
+ } else
+ return 0;
+ break;
+ }
+
+ default:
+ return 0; /* Unsupported position format */
+ }
+ }
+ }
+
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)
+{
+ int xAdvance = 0;
+
+ if (info->gpos)
+ xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
+ else if (info->kern)
+ xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
+
+ return xAdvance;
+}
+
+STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
+{
+ if (!info->kern && !info->gpos) /* if no kerning table, don't waste time looking up both codepoint->glyphs */
+ return 0;
+ return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
+}
+
+STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
+{
+ stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
+}
+
+STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
+{
+ if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
+ if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
+ if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
+}
+
+STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)
+{
+ int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
+ if (!tab)
+ return 0;
+ if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68);
+ if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);
+ if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);
+ return 1;
+}
+
+STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
+{
+ *x0 = ttSHORT(info->data + info->head + 36);
+ *y0 = ttSHORT(info->data + info->head + 38);
+ *x1 = ttSHORT(info->data + info->head + 40);
+ *y1 = ttSHORT(info->data + info->head + 42);
+}
+
+STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
+{
+ int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
+ return (float) height / fheight;
+}
+
+STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
+{
+ int unitsPerEm = ttUSHORT(info->data + info->head + 18);
+ return pixels / unitsPerEm;
+}
+
+STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
+{
+ STBTT_free(v, info->userdata);
+}
+
+STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl)
+{
+ int i;
+ stbtt_uint8 *data = info->data;
+ stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info);
+
+ int numEntries = ttUSHORT(svg_doc_list);
+ stbtt_uint8 *svg_docs = svg_doc_list + 2;
+
+ for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2)))
+ return svg_doc;
+ }
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg)
+{
+ stbtt_uint8 *data = info->data;
+ stbtt_uint8 *svg_doc;
+
+ if (info->svg == 0)
+ return 0;
+
+ svg_doc = stbtt_FindSVGDoc(info, gl);
+ if (svg_doc != NULL) {
+ *svg = (char *) data + info->svg + ttULONG(svg_doc + 4);
+ return ttULONG(svg_doc + 8);
+ } else {
+ return 0;
+ }
+}
+
+STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg)
+{
+ return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg);
+}
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* antialiasing software rasterizer */
+/* */
+
+STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ int x0=0,y0=0,x1,y1; /* =0 suppresses compiler warning */
+ if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
+ /* e.g. space character */
+ if (ix0) *ix0 = 0;
+ if (iy0) *iy0 = 0;
+ if (ix1) *ix1 = 0;
+ if (iy1) *iy1 = 0;
+ } else {
+ /* move to integral bboxes (treating pixels as little squares, what pixels get touched)? */
+ if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
+ if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
+ if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
+ if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
+ }
+}
+
+STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
+}
+
+STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
+}
+
+STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
+}
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* Rasterizer */
+
+typedef struct stbtt__hheap_chunk
+{
+ struct stbtt__hheap_chunk *next;
+} stbtt__hheap_chunk;
+
+typedef struct stbtt__hheap
+{
+ struct stbtt__hheap_chunk *head;
+ void *first_free;
+ int num_remaining_in_head_chunk;
+} stbtt__hheap;
+
+static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
+{
+ if (hh->first_free) {
+ void *p = hh->first_free;
+ hh->first_free = * (void **) p;
+ return p;
+ } else {
+ if (hh->num_remaining_in_head_chunk == 0) {
+ int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
+ stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
+ if (c == NULL)
+ return NULL;
+ c->next = hh->head;
+ hh->head = c;
+ hh->num_remaining_in_head_chunk = count;
+ }
+ --hh->num_remaining_in_head_chunk;
+ return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
+ }
+}
+
+static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
+{
+ *(void **) p = hh->first_free;
+ hh->first_free = p;
+}
+
+static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
+{
+ stbtt__hheap_chunk *c = hh->head;
+ while (c) {
+ stbtt__hheap_chunk *n = c->next;
+ STBTT_free(c, userdata);
+ c = n;
+ }
+}
+
+typedef struct stbtt__edge {
+ float x0,y0, x1,y1;
+ int invert;
+} stbtt__edge;
+
+
+typedef struct stbtt__active_edge
+{
+ struct stbtt__active_edge *next;
+ #if STBTT_RASTERIZER_VERSION==1
+ int x,dx;
+ float ey;
+ int direction;
+ #elif STBTT_RASTERIZER_VERSION==2
+ float fx,fdx,fdy;
+ float direction;
+ float sy;
+ float ey;
+ #else
+ #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+ #endif
+} stbtt__active_edge;
+
+#if STBTT_RASTERIZER_VERSION == 1
+#define STBTT_FIXSHIFT 10
+#define STBTT_FIX (1 << STBTT_FIXSHIFT)
+#define STBTT_FIXMASK (STBTT_FIX-1)
+
+static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
+{
+ stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
+ STBTT_assert(z != NULL);
+ if (!z) return z;
+
+ /* round dx down to avoid overshooting */
+ if (dxdy < 0)
+ z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
+ else
+ z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
+
+ z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); /* use z->dx so when we offset later it's by the same amount */
+ z->x -= off_x * STBTT_FIX;
+
+ z->ey = e->y1;
+ z->next = 0;
+ z->direction = e->invert ? 1 : -1;
+ return z;
+}
+#elif STBTT_RASTERIZER_VERSION == 2
+static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
+{
+ stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
+ STBTT_assert(z != NULL);
+ /* STBTT_assert(e->y0 <= start_point); */
+ if (!z) return z;
+ z->fdx = dxdy;
+ z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
+ z->fx = e->x0 + dxdy * (start_point - e->y0);
+ z->fx -= off_x;
+ z->direction = e->invert ? 1.0f : -1.0f;
+ z->sy = e->y0;
+ z->ey = e->y1;
+ z->next = 0;
+ return z;
+}
+#else
+#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+#endif
+
+#if STBTT_RASTERIZER_VERSION == 1
+/* note: this routine clips fills that extend off the edges... ideally this */
+/* wouldn't happen, but it could happen if the truetype glyph bounding boxes */
+/* are wrong, or if the user supplies a too-small bitmap */
+static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
+{
+ /* non-zero winding fill */
+ int x0=0, w=0;
+
+ while (e) {
+ if (w == 0) {
+ /* if we're currently at zero, we need to record the edge start point */
+ x0 = e->x; w += e->direction;
+ } else {
+ int x1 = e->x; w += e->direction;
+ /* if we went to zero, we need to draw */
+ if (w == 0) {
+ int i = x0 >> STBTT_FIXSHIFT;
+ int j = x1 >> STBTT_FIXSHIFT;
+
+ if (i < len && j >= 0) {
+ if (i == j) {
+ /* x0,x1 are the same pixel, so compute combined coverage */
+ scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
+ } else {
+ if (i >= 0) /* add antialiasing for x0 */
+ scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
+ else
+ i = -1; /* clip */
+
+ if (j < len) /* add antialiasing for x1 */
+ scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
+ else
+ j = len; /* clip */
+
+ for (++i; i < j; ++i) /* fill pixels between x0 and x1 */
+ scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
+ }
+ }
+ }
+ }
+
+ e = e->next;
+ }
+}
+
+static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
+{
+ stbtt__hheap hh = { 0, 0, 0 };
+ stbtt__active_edge *active = NULL;
+ int y,j=0;
+ int max_weight = (255 / vsubsample); /* weight per vertical scanline */
+ int s; /* vertical subsample index */
+ unsigned char scanline_data[512], *scanline;
+
+ if (result->w > 512)
+ scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
+ else
+ scanline = scanline_data;
+
+ y = off_y * vsubsample;
+ e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
+
+ while (j < result->h) {
+ STBTT_memset(scanline, 0, result->w);
+ for (s=0; s < vsubsample; ++s) {
+ /* find center of pixel for this scanline */
+ float scan_y = y + 0.5f;
+ stbtt__active_edge **step = &active;
+
+ /* update all active edges; */
+ /* remove all active edges that terminate before the center of this scanline */
+ while (*step) {
+ stbtt__active_edge * z = *step;
+ if (z->ey <= scan_y) {
+ *step = z->next; /* delete from list */
+ STBTT_assert(z->direction);
+ z->direction = 0;
+ stbtt__hheap_free(&hh, z);
+ } else {
+ z->x += z->dx; /* advance to position for current scanline */
+ step = &((*step)->next); /* advance through list */
+ }
+ }
+
+ /* resort the list if needed */
+ for(;;) {
+ int changed=0;
+ step = &active;
+ while (*step && (*step)->next) {
+ if ((*step)->x > (*step)->next->x) {
+ stbtt__active_edge *t = *step;
+ stbtt__active_edge *q = t->next;
+
+ t->next = q->next;
+ q->next = t;
+ *step = q;
+ changed = 1;
+ }
+ step = &(*step)->next;
+ }
+ if (!changed) break;
+ }
+
+ /* insert all edges that start before the center of this scanline -- omit ones that also end on this scanline */
+ while (e->y0 <= scan_y) {
+ if (e->y1 > scan_y) {
+ stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
+ if (z != NULL) {
+ /* find insertion point */
+ if (active == NULL)
+ active = z;
+ else if (z->x < active->x) {
+ /* insert at front */
+ z->next = active;
+ active = z;
+ } else {
+ /* find thing to insert AFTER */
+ stbtt__active_edge *p = active;
+ while (p->next && p->next->x < z->x)
+ p = p->next;
+ /* at this point, p->next->x is NOT < z->x */
+ z->next = p->next;
+ p->next = z;
+ }
+ }
+ }
+ ++e;
+ }
+
+ /* now process all active edges in XOR fashion */
+ if (active)
+ stbtt__fill_active_edges(scanline, result->w, active, max_weight);
+
+ ++y;
+ }
+ STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
+ ++j;
+ }
+
+ stbtt__hheap_cleanup(&hh, userdata);
+
+ if (scanline != scanline_data)
+ STBTT_free(scanline, userdata);
+}
+
+#elif STBTT_RASTERIZER_VERSION == 2
+
+/* the edge passed in here does not cross the vertical line at x or the vertical line at x+1 */
+/* (i.e. it has already been clipped to those) */
+static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
+{
+ if (y0 == y1) return;
+ STBTT_assert(y0 < y1);
+ STBTT_assert(e->sy <= e->ey);
+ if (y0 > e->ey) return;
+ if (y1 < e->sy) return;
+ if (y0 < e->sy) {
+ x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
+ y0 = e->sy;
+ }
+ if (y1 > e->ey) {
+ x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
+ y1 = e->ey;
+ }
+
+ if (x0 == x)
+ STBTT_assert(x1 <= x+1);
+ else if (x0 == x+1)
+ STBTT_assert(x1 >= x);
+ else if (x0 <= x)
+ STBTT_assert(x1 <= x);
+ else if (x0 >= x+1)
+ STBTT_assert(x1 >= x+1);
+ else
+ STBTT_assert(x1 >= x && x1 <= x+1);
+
+ if (x0 <= x && x1 <= x)
+ scanline[x] += e->direction * (y1-y0);
+ else if (x0 >= x+1 && x1 >= x+1)
+ ;
+ else {
+ STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
+ scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); /* coverage = 1 - average x position */
+ }
+}
+
+static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width)
+{
+ STBTT_assert(top_width >= 0);
+ STBTT_assert(bottom_width >= 0);
+ return (top_width + bottom_width) / 2.0f * height;
+}
+
+static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1)
+{
+ return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0);
+}
+
+static float stbtt__sized_triangle_area(float height, float width)
+{
+ return height * width / 2;
+}
+
+static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
+{
+ float y_bottom = y_top+1;
+
+ while (e) {
+ /* brute force every pixel */
+
+ /* compute intersection points with top & bottom */
+ STBTT_assert(e->ey >= y_top);
+
+ if (e->fdx == 0) {
+ float x0 = e->fx;
+ if (x0 < len) {
+ if (x0 >= 0) {
+ stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
+ stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
+ } else {
+ stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
+ }
+ }
+ } else {
+ float x0 = e->fx;
+ float dx = e->fdx;
+ float xb = x0 + dx;
+ float x_top, x_bottom;
+ float sy0,sy1;
+ float dy = e->fdy;
+ STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
+
+ /* compute endpoints of line segment clipped to this scanline (if the */
+ /* line segment starts on this scanline. x0 is the intersection of the */
+ /* line with y_top, but that may be off the line segment. */
+ if (e->sy > y_top) {
+ x_top = x0 + dx * (e->sy - y_top);
+ sy0 = e->sy;
+ } else {
+ x_top = x0;
+ sy0 = y_top;
+ }
+ if (e->ey < y_bottom) {
+ x_bottom = x0 + dx * (e->ey - y_top);
+ sy1 = e->ey;
+ } else {
+ x_bottom = xb;
+ sy1 = y_bottom;
+ }
+
+ if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
+ /* from here on, we don't have to range check x values */
+
+ if ((int) x_top == (int) x_bottom) {
+ float height;
+ /* simple case, only spans one pixel */
+ int x = (int) x_top;
+ height = (sy1 - sy0) * e->direction;
+ STBTT_assert(x >= 0 && x < len);
+ scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f);
+ scanline_fill[x] += height; /* everything right of this pixel is filled */
+ } else {
+ int x,x1,x2;
+ float y_crossing, y_final, step, sign, area;
+ /* covers 2+ pixels */
+ if (x_top > x_bottom) {
+ /* flip scanline vertically; signed area is the same */
+ float t;
+ sy0 = y_bottom - (sy0 - y_top);
+ sy1 = y_bottom - (sy1 - y_top);
+ t = sy0, sy0 = sy1, sy1 = t;
+ t = x_bottom, x_bottom = x_top, x_top = t;
+ dx = -dx;
+ dy = -dy;
+ t = x0, x0 = xb, xb = t;
+ }
+ STBTT_assert(dy >= 0);
+ STBTT_assert(dx >= 0);
+
+ x1 = (int) x_top;
+ x2 = (int) x_bottom;
+ /* compute intersection with y axis at x1+1 */
+ y_crossing = y_top + dy * (x1+1 - x0);
+
+ /* compute intersection with y axis at x2 */
+ y_final = y_top + dy * (x2 - x0);
+
+ /* x1 x_top x2 x_bottom */
+ /* y_top +------|-----+------------+------------+--------|---+------------+ */
+ /* | | | | | | */
+ /* | | | | | | */
+ /* sy0 | Txxxxx|............|............|............|............| */
+ /* y_crossing | *xxxxx.......|............|............|............| */
+ /* | | xxxxx..|............|............|............| */
+ /* | | /- xx*xxxx........|............|............| */
+ /* | | dy < | xxxxxx..|............|............| */
+ /* y_final | | \- | xx*xxx.........|............| */
+ /* sy1 | | | | xxxxxB...|............| */
+ /* | | | | | | */
+ /* | | | | | | */
+ /* y_bottom +------------+------------+------------+------------+------------+ */
+ /* */
+ /* goal is to measure the area covered by '.' in each pixel */
+
+ /* if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 */
+ /* @TODO: maybe test against sy1 rather than y_bottom? */
+ if (y_crossing > y_bottom)
+ y_crossing = y_bottom;
+
+ sign = e->direction;
+
+ /* area of the rectangle covered from sy0..y_crossing */
+ area = sign * (y_crossing-sy0);
+
+ /* area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) */
+ scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top);
+
+ /* check if final y_crossing is blown up; no test case for this */
+ if (y_final > y_bottom) {
+ y_final = y_bottom;
+ dy = (y_final - y_crossing ) / (x2 - (x1+1)); /* if denom=0, y_final = y_crossing, so y_final <= y_bottom */
+ }
+
+ /* in second pixel, area covered by line segment found in first pixel */
+ /* is always a rectangle 1 wide * the height of that line segment; this */
+ /* is exactly what the variable 'area' stores. it also gets a contribution */
+ /* from the line segment within it. the THIRD pixel will get the first */
+ /* pixel's rectangle contribution, the second pixel's rectangle contribution, */
+ /* and its own contribution. the 'own contribution' is the same in every pixel except */
+ /* the leftmost and rightmost, a trapezoid that slides down in each pixel. */
+ /* the second pixel's contribution to the third pixel will be the */
+ /* rectangle 1 wide times the height change in the second pixel, which is dy. */
+
+ step = sign * dy * 1; /* dy is dy/dx, change in y for every 1 change in x, */
+ /* which multiplied by 1-pixel-width is how much pixel area changes for each step in x */
+ /* so the area advances by 'step' every time */
+
+ for (x = x1+1; x < x2; ++x) {
+ scanline[x] += area + step/2; /* area of trapezoid is 1*step/2 */
+ area += step;
+ }
+ STBTT_assert(STBTT_fabs(area) <= 1.01f); /* accumulated error from area += step unless we round step down */
+ STBTT_assert(sy1 > y_final-0.01f);
+
+ /* area covered in the last pixel is the rectangle from all the pixels to the left, */
+ /* plus the trapezoid filled by the line segment in this pixel all the way to the right edge */
+ scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f);
+
+ /* the rest of the line is filled based on the total height of the line segment in this pixel */
+ scanline_fill[x2] += sign * (sy1-sy0);
+ }
+ } else {
+ /* if edge goes outside of box we're drawing, we require */
+ /* clipping logic. since this does not match the intended use */
+ /* of this library, we use a different, very slow brute */
+ /* force implementation */
+ /* note though that this does happen some of the time because */
+ /* x_top and x_bottom can be extrapolated at the top & bottom of */
+ /* the shape and actually lie outside the bounding box */
+ int x;
+ for (x=0; x < len; ++x) {
+ /* cases: */
+ /* */
+ /* there can be up to two intersections with the pixel. any intersection */
+ /* with left or right edges can be handled by splitting into two (or three) */
+ /* regions. intersections with top & bottom do not necessitate case-wise logic. */
+ /* */
+ /* the old way of doing this found the intersections with the left & right edges, */
+ /* then used some simple logic to produce up to three segments in sorted order */
+ /* from top-to-bottom. however, this had a problem: if an x edge was epsilon */
+ /* across the x border, then the corresponding y position might not be distinct */
+ /* from the other y segment, and it might ignored as an empty segment. to avoid */
+ /* that, we need to explicitly produce segments based on x positions. */
+
+ /* rename variables to clearly-defined pairs */
+ float y0 = y_top;
+ float x1 = (float) (x);
+ float x2 = (float) (x+1);
+ float x3 = xb;
+ float y3 = y_bottom;
+
+ /* x = e->x + e->dx * (y-y_top) */
+ /* (y-y_top) = (x - e->x) / e->dx */
+ /* y = (x - e->x) / e->dx + y_top */
+ float y1 = (x - x0) / dx + y_top;
+ float y2 = (x+1 - x0) / dx + y_top;
+
+ if (x0 < x1 && x3 > x2) { /* three segments descending down-right */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
+ } else if (x3 < x1 && x0 > x2) { /* three segments descending down-left */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
+ } else if (x0 < x1 && x3 > x1) { /* two segments across x, down-right */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
+ } else if (x3 < x1 && x0 > x1) { /* two segments across x, down-left */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
+ } else if (x0 < x2 && x3 > x2) { /* two segments across x+1, down-right */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
+ } else if (x3 < x2 && x0 > x2) { /* two segments across x+1, down-left */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
+ } else { /* one segment */
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
+ }
+ }
+ }
+ }
+ e = e->next;
+ }
+}
+
+/* directly AA rasterize edges w/o supersampling */
+static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
+{
+ stbtt__hheap hh = { 0, 0, 0 };
+ stbtt__active_edge *active = NULL;
+ int y,j=0, i;
+ float scanline_data[129], *scanline, *scanline2;
+
+ STBTT__NOTUSED(vsubsample);
+
+ if (result->w > 64)
+ scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
+ else
+ scanline = scanline_data;
+
+ scanline2 = scanline + result->w;
+
+ y = off_y;
+ e[n].y0 = (float) (off_y + result->h) + 1;
+
+ while (j < result->h) {
+ /* find center of pixel for this scanline */
+ float scan_y_top = y + 0.0f;
+ float scan_y_bottom = y + 1.0f;
+ stbtt__active_edge **step = &active;
+
+ STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
+ STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
+
+ /* update all active edges; */
+ /* remove all active edges that terminate before the top of this scanline */
+ while (*step) {
+ stbtt__active_edge * z = *step;
+ if (z->ey <= scan_y_top) {
+ *step = z->next; /* delete from list */
+ STBTT_assert(z->direction);
+ z->direction = 0;
+ stbtt__hheap_free(&hh, z);
+ } else {
+ step = &((*step)->next); /* advance through list */
+ }
+ }
+
+ /* insert all edges that start before the bottom of this scanline */
+ while (e->y0 <= scan_y_bottom) {
+ if (e->y0 != e->y1) {
+ stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
+ if (z != NULL) {
+ if (j == 0 && off_y != 0) {
+ if (z->ey < scan_y_top) {
+ /* this can happen due to subpixel positioning and some kind of fp rounding error i think */
+ z->ey = scan_y_top;
+ }
+ }
+ STBTT_assert(z->ey >= scan_y_top); /* if we get really unlucky a tiny bit of an edge can be out of bounds */
+ /* insert at front */
+ z->next = active;
+ active = z;
+ }
+ }
+ ++e;
+ }
+
+ /* now process all active edges */
+ if (active)
+ stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
+
+ {
+ float sum = 0;
+ for (i=0; i < result->w; ++i) {
+ float k;
+ int m;
+ sum += scanline2[i];
+ k = scanline[i] + sum;
+ k = (float) STBTT_fabs(k)*255 + 0.5f;
+ m = (int) k;
+ if (m > 255) m = 255;
+ result->pixels[j*result->stride + i] = (unsigned char) m;
+ }
+ }
+ /* advance all the edges */
+ step = &active;
+ while (*step) {
+ stbtt__active_edge *z = *step;
+ z->fx += z->fdx; /* advance to position for current scanline */
+ step = &((*step)->next); /* advance through list */
+ }
+
+ ++y;
+ ++j;
+ }
+
+ stbtt__hheap_cleanup(&hh, userdata);
+
+ if (scanline != scanline_data)
+ STBTT_free(scanline, userdata);
+}
+#else
+#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+#endif
+
+#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
+
+static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
+{
+ int i,j;
+ for (i=1; i < n; ++i) {
+ stbtt__edge t = p[i], *a = &t;
+ j = i;
+ while (j > 0) {
+ stbtt__edge *b = &p[j-1];
+ int c = STBTT__COMPARE(a,b);
+ if (!c) break;
+ p[j] = p[j-1];
+ --j;
+ }
+ if (i != j)
+ p[j] = t;
+ }
+}
+
+static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
+{
+ /* threshold for transitioning to insertion sort */
+ while (n > 12) {
+ stbtt__edge t;
+ int c01,c12,c,m,i,j;
+
+ /* compute median of three */
+ m = n >> 1;
+ c01 = STBTT__COMPARE(&p[0],&p[m]);
+ c12 = STBTT__COMPARE(&p[m],&p[n-1]);
+ /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
+ if (c01 != c12) {
+ /* otherwise, we'll need to swap something else to middle */
+ int z;
+ c = STBTT__COMPARE(&p[0],&p[n-1]);
+ /* 0>mid && midn => n; 0 0 */
+ /* 0n: 0>n => 0; 0 n */
+ z = (c == c12) ? 0 : n-1;
+ t = p[z];
+ p[z] = p[m];
+ p[m] = t;
+ }
+ /* now p[m] is the median-of-three */
+ /* swap it to the beginning so it won't move around */
+ t = p[0];
+ p[0] = p[m];
+ p[m] = t;
+
+ /* partition loop */
+ i=1;
+ j=n-1;
+ for(;;) {
+ /* handling of equality is crucial here */
+ /* for sentinels & efficiency with duplicates */
+ for (;;++i) {
+ if (!STBTT__COMPARE(&p[i], &p[0])) break;
+ }
+ for (;;--j) {
+ if (!STBTT__COMPARE(&p[0], &p[j])) break;
+ }
+ /* make sure we haven't crossed */
+ if (i >= j) break;
+ t = p[i];
+ p[i] = p[j];
+ p[j] = t;
+
+ ++i;
+ --j;
+ }
+ /* recurse on smaller side, iterate on larger */
+ if (j < (n-i)) {
+ stbtt__sort_edges_quicksort(p,j);
+ p = p+i;
+ n = n-i;
+ } else {
+ stbtt__sort_edges_quicksort(p+i, n-i);
+ n = j;
+ }
+ }
+}
+
+static void stbtt__sort_edges(stbtt__edge *p, int n)
+{
+ stbtt__sort_edges_quicksort(p, n);
+ stbtt__sort_edges_ins_sort(p, n);
+}
+
+typedef struct
+{
+ float x,y;
+} stbtt__point;
+
+static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)
+{
+ float y_scale_inv = invert ? -scale_y : scale_y;
+ stbtt__edge *e;
+ int n,i,j,k,m;
+#if STBTT_RASTERIZER_VERSION == 1
+ int vsubsample = result->h < 8 ? 15 : 5;
+#elif STBTT_RASTERIZER_VERSION == 2
+ int vsubsample = 1;
+#else
+ #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+#endif
+ /* vsubsample should divide 255 evenly; otherwise we won't reach full opacity */
+
+ /* now we have to blow out the windings into explicit edge lists */
+ n = 0;
+ for (i=0; i < windings; ++i)
+ n += wcount[i];
+
+ e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); /* add an extra one as a sentinel */
+ if (e == 0) return;
+ n = 0;
+
+ m=0;
+ for (i=0; i < windings; ++i) {
+ stbtt__point *p = pts + m;
+ m += wcount[i];
+ j = wcount[i]-1;
+ for (k=0; k < wcount[i]; j=k++) {
+ int a=k,b=j;
+ /* skip the edge if horizontal */
+ if (p[j].y == p[k].y)
+ continue;
+ /* add edge from j to k to the list */
+ e[n].invert = 0;
+ if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
+ e[n].invert = 1;
+ a=j,b=k;
+ }
+ e[n].x0 = p[a].x * scale_x + shift_x;
+ e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
+ e[n].x1 = p[b].x * scale_x + shift_x;
+ e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
+ ++n;
+ }
+ }
+
+ /* now sort the edges by their highest point (should snap to integer, and then by x) */
+ /* STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); */
+ stbtt__sort_edges(e, n);
+
+ /* now, traverse the scanlines and find the intersections on each scanline, use xor winding rule */
+ stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
+
+ STBTT_free(e, userdata);
+}
+
+static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
+{
+ if (!points) return; /* during first pass, it's unallocated */
+ points[n].x = x;
+ points[n].y = y;
+}
+
+/* tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching */
+static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)
+{
+ /* midpoint */
+ float mx = (x0 + 2*x1 + x2)/4;
+ float my = (y0 + 2*y1 + y2)/4;
+ /* versus directly drawn line */
+ float dx = (x0+x2)/2 - mx;
+ float dy = (y0+y2)/2 - my;
+ if (n > 16) /* 65536 segments on one curve better be enough! */
+ return 1;
+ if (dx*dx+dy*dy > objspace_flatness_squared) { /* half-pixel error allowed... need to be smaller if AA */
+ stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
+ stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
+ } else {
+ stbtt__add_point(points, *num_points,x2,y2);
+ *num_points = *num_points+1;
+ }
+ return 1;
+}
+
+static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
+{
+ /* @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough */
+ float dx0 = x1-x0;
+ float dy0 = y1-y0;
+ float dx1 = x2-x1;
+ float dy1 = y2-y1;
+ float dx2 = x3-x2;
+ float dy2 = y3-y2;
+ float dx = x3-x0;
+ float dy = y3-y0;
+ float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
+ float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
+ float flatness_squared = longlen*longlen-shortlen*shortlen;
+
+ if (n > 16) /* 65536 segments on one curve better be enough! */
+ return;
+
+ if (flatness_squared > objspace_flatness_squared) {
+ float x01 = (x0+x1)/2;
+ float y01 = (y0+y1)/2;
+ float x12 = (x1+x2)/2;
+ float y12 = (y1+y2)/2;
+ float x23 = (x2+x3)/2;
+ float y23 = (y2+y3)/2;
+
+ float xa = (x01+x12)/2;
+ float ya = (y01+y12)/2;
+ float xb = (x12+x23)/2;
+ float yb = (y12+y23)/2;
+
+ float mx = (xa+xb)/2;
+ float my = (ya+yb)/2;
+
+ stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
+ stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
+ } else {
+ stbtt__add_point(points, *num_points,x3,y3);
+ *num_points = *num_points+1;
+ }
+}
+
+/* returns number of contours */
+static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
+{
+ stbtt__point *points=0;
+ int num_points=0;
+
+ float objspace_flatness_squared = objspace_flatness * objspace_flatness;
+ int i,n=0,start=0, pass;
+
+ /* count how many "moves" there are to get the contour count */
+ for (i=0; i < num_verts; ++i)
+ if (vertices[i].type == STBTT_vmove)
+ ++n;
+
+ *num_contours = n;
+ if (n == 0) return 0;
+
+ *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
+
+ if (*contour_lengths == 0) {
+ *num_contours = 0;
+ return 0;
+ }
+
+ /* make two passes through the points so we don't need to realloc */
+ for (pass=0; pass < 2; ++pass) {
+ float x=0,y=0;
+ if (pass == 1) {
+ points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
+ if (points == NULL) goto error;
+ }
+ num_points = 0;
+ n= -1;
+ for (i=0; i < num_verts; ++i) {
+ switch (vertices[i].type) {
+ case STBTT_vmove:
+ /* start the next contour */
+ if (n >= 0)
+ (*contour_lengths)[n] = num_points - start;
+ ++n;
+ start = num_points;
+
+ x = vertices[i].x, y = vertices[i].y;
+ stbtt__add_point(points, num_points++, x,y);
+ break;
+ case STBTT_vline:
+ x = vertices[i].x, y = vertices[i].y;
+ stbtt__add_point(points, num_points++, x, y);
+ break;
+ case STBTT_vcurve:
+ stbtt__tesselate_curve(points, &num_points, x,y,
+ vertices[i].cx, vertices[i].cy,
+ vertices[i].x, vertices[i].y,
+ objspace_flatness_squared, 0);
+ x = vertices[i].x, y = vertices[i].y;
+ break;
+ case STBTT_vcubic:
+ stbtt__tesselate_cubic(points, &num_points, x,y,
+ vertices[i].cx, vertices[i].cy,
+ vertices[i].cx1, vertices[i].cy1,
+ vertices[i].x, vertices[i].y,
+ objspace_flatness_squared, 0);
+ x = vertices[i].x, y = vertices[i].y;
+ break;
+ }
+ }
+ (*contour_lengths)[n] = num_points - start;
+ }
+
+ return points;
+error:
+ STBTT_free(points, userdata);
+ STBTT_free(*contour_lengths, userdata);
+ *contour_lengths = 0;
+ *num_contours = 0;
+ return NULL;
+}
+
+STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
+{
+ float scale = scale_x > scale_y ? scale_y : scale_x;
+ int winding_count = 0;
+ int *winding_lengths = NULL;
+ stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
+ if (windings) {
+ stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
+ STBTT_free(winding_lengths, userdata);
+ STBTT_free(windings, userdata);
+ }
+}
+
+STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
+{
+ STBTT_free(bitmap, userdata);
+}
+
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)
+{
+ int ix0,iy0,ix1,iy1;
+ stbtt__bitmap gbm;
+ stbtt_vertex *vertices;
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
+
+ if (scale_x == 0) scale_x = scale_y;
+ if (scale_y == 0) {
+ if (scale_x == 0) {
+ STBTT_free(vertices, info->userdata);
+ return NULL;
+ }
+ scale_y = scale_x;
+ }
+
+ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
+
+ /* now we get the size */
+ gbm.w = (ix1 - ix0);
+ gbm.h = (iy1 - iy0);
+ gbm.pixels = NULL; /* in case we error */
+
+ if (width ) *width = gbm.w;
+ if (height) *height = gbm.h;
+ if (xoff ) *xoff = ix0;
+ if (yoff ) *yoff = iy0;
+
+ if (gbm.w && gbm.h) {
+ gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
+ if (gbm.pixels) {
+ gbm.stride = gbm.w;
+
+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
+ }
+ }
+ STBTT_free(vertices, info->userdata);
+ return gbm.pixels;
+}
+
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
+}
+
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
+{
+ int ix0,iy0;
+ stbtt_vertex *vertices;
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
+ stbtt__bitmap gbm;
+
+ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
+ gbm.pixels = output;
+ gbm.w = out_w;
+ gbm.h = out_h;
+ gbm.stride = out_stride;
+
+ if (gbm.w && gbm.h)
+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
+
+ STBTT_free(vertices, info->userdata);
+}
+
+STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
+{
+ stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
+}
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
+}
+
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)
+{
+ stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));
+}
+
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
+{
+ stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
+}
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
+}
+
+STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
+{
+ stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
+}
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* bitmap baking */
+/* */
+/* This is SUPER-CRAPPY packing to keep source code small */
+
+static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, /* font location (use offset=0 for plain .ttf) */
+ float pixel_height, /* height of font in pixels */
+ unsigned char *pixels, int pw, int ph, /* bitmap to be filled in */
+ int first_char, int num_chars, /* characters to bake */
+ stbtt_bakedchar *chardata)
+{
+ float scale;
+ int x,y,bottom_y, i;
+ stbtt_fontinfo f;
+ f.userdata = NULL;
+ if (!stbtt_InitFont(&f, data, offset))
+ return -1;
+ STBTT_memset(pixels, 0, pw*ph); /* background of 0 around pixels */
+ x=y=1;
+ bottom_y = 1;
+
+ scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
+
+ for (i=0; i < num_chars; ++i) {
+ int advance, lsb, x0,y0,x1,y1,gw,gh;
+ int g = stbtt_FindGlyphIndex(&f, first_char + i);
+ stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
+ stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
+ gw = x1-x0;
+ gh = y1-y0;
+ if (x + gw + 1 >= pw)
+ y = bottom_y, x = 1; /* advance to next row */
+ if (y + gh + 1 >= ph) /* check if it fits vertically AFTER potentially moving to next row */
+ return -i;
+ STBTT_assert(x+gw < pw);
+ STBTT_assert(y+gh < ph);
+ stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
+ chardata[i].x0 = (stbtt_int16) x;
+ chardata[i].y0 = (stbtt_int16) y;
+ chardata[i].x1 = (stbtt_int16) (x + gw);
+ chardata[i].y1 = (stbtt_int16) (y + gh);
+ chardata[i].xadvance = scale * advance;
+ chardata[i].xoff = (float) x0;
+ chardata[i].yoff = (float) y0;
+ x = x + gw + 1;
+ if (y+gh+1 > bottom_y)
+ bottom_y = y+gh+1;
+ }
+ return bottom_y;
+}
+
+STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
+{
+ float d3d_bias = opengl_fillrule ? 0 : -0.5f;
+ float ipw = 1.0f / pw, iph = 1.0f / ph;
+ const stbtt_bakedchar *b = chardata + char_index;
+ int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
+ int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
+
+ q->x0 = round_x + d3d_bias;
+ q->y0 = round_y + d3d_bias;
+ q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
+ q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
+
+ q->s0 = b->x0 * ipw;
+ q->t0 = b->y0 * iph;
+ q->s1 = b->x1 * ipw;
+ q->t1 = b->y1 * iph;
+
+ *xpos += b->xadvance;
+}
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* rectangle packing replacement routines if you don't have stb_rect_pack.h */
+/* */
+
+#ifndef STB_RECT_PACK_VERSION
+
+typedef int stbrp_coord;
+
+/* ////////////////////////////////////////////////////////////////////////////////// */
+/* // */
+/* // */
+/* COMPILER WARNING ?!?!? // */
+/* // */
+/* // */
+/* if you get a compile warning due to these symbols being defined more than // */
+/* once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // */
+/* // */
+/* ////////////////////////////////////////////////////////////////////////////////// */
+
+typedef struct
+{
+ int width,height;
+ int x,y,bottom_y;
+} stbrp_context;
+
+typedef struct
+{
+ unsigned char x;
+} stbrp_node;
+
+struct stbrp_rect
+{
+ stbrp_coord x,y;
+ int id,w,h,was_packed;
+};
+
+static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
+{
+ con->width = pw;
+ con->height = ph;
+ con->x = 0;
+ con->y = 0;
+ con->bottom_y = 0;
+ STBTT__NOTUSED(nodes);
+ STBTT__NOTUSED(num_nodes);
+}
+
+static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
+{
+ int i;
+ for (i=0; i < num_rects; ++i) {
+ if (con->x + rects[i].w > con->width) {
+ con->x = 0;
+ con->y = con->bottom_y;
+ }
+ if (con->y + rects[i].h > con->height)
+ break;
+ rects[i].x = con->x;
+ rects[i].y = con->y;
+ rects[i].was_packed = 1;
+ con->x += rects[i].w;
+ if (con->y + rects[i].h > con->bottom_y)
+ con->bottom_y = con->y + rects[i].h;
+ }
+ for ( ; i < num_rects; ++i)
+ rects[i].was_packed = 0;
+}
+#endif
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* bitmap baking */
+/* */
+/* This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If */
+/* stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. */
+
+STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
+{
+ stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);
+ int num_nodes = pw - padding;
+ stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);
+
+ if (context == NULL || nodes == NULL) {
+ if (context != NULL) STBTT_free(context, alloc_context);
+ if (nodes != NULL) STBTT_free(nodes , alloc_context);
+ return 0;
+ }
+
+ spc->user_allocator_context = alloc_context;
+ spc->width = pw;
+ spc->height = ph;
+ spc->pixels = pixels;
+ spc->pack_info = context;
+ spc->nodes = nodes;
+ spc->padding = padding;
+ spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
+ spc->h_oversample = 1;
+ spc->v_oversample = 1;
+ spc->skip_missing = 0;
+
+ stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
+
+ if (pixels)
+ STBTT_memset(pixels, 0, pw*ph); /* background of 0 around pixels */
+
+ return 1;
+}
+
+STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)
+{
+ STBTT_free(spc->nodes , spc->user_allocator_context);
+ STBTT_free(spc->pack_info, spc->user_allocator_context);
+}
+
+STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
+{
+ STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
+ STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
+ if (h_oversample <= STBTT_MAX_OVERSAMPLE)
+ spc->h_oversample = h_oversample;
+ if (v_oversample <= STBTT_MAX_OVERSAMPLE)
+ spc->v_oversample = v_oversample;
+}
+
+STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)
+{
+ spc->skip_missing = skip;
+}
+
+#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
+
+static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
+{
+ unsigned char buffer[STBTT_MAX_OVERSAMPLE];
+ int safe_w = w - kernel_width;
+ int j;
+ STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); /* suppress bogus warning from VS2013 -analyze */
+ for (j=0; j < h; ++j) {
+ int i;
+ unsigned int total;
+ STBTT_memset(buffer, 0, kernel_width);
+
+ total = 0;
+
+ /* make kernel_width a constant in common cases so compiler can optimize out the divide */
+ switch (kernel_width) {
+ case 2:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 2);
+ }
+ break;
+ case 3:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 3);
+ }
+ break;
+ case 4:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 4);
+ }
+ break;
+ case 5:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 5);
+ }
+ break;
+ default:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / kernel_width);
+ }
+ break;
+ }
+
+ for (; i < w; ++i) {
+ STBTT_assert(pixels[i] == 0);
+ total -= buffer[i & STBTT__OVER_MASK];
+ pixels[i] = (unsigned char) (total / kernel_width);
+ }
+
+ pixels += stride_in_bytes;
+ }
+}
+
+static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
+{
+ unsigned char buffer[STBTT_MAX_OVERSAMPLE];
+ int safe_h = h - kernel_width;
+ int j;
+ STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); /* suppress bogus warning from VS2013 -analyze */
+ for (j=0; j < w; ++j) {
+ int i;
+ unsigned int total;
+ STBTT_memset(buffer, 0, kernel_width);
+
+ total = 0;
+
+ /* make kernel_width a constant in common cases so compiler can optimize out the divide */
+ switch (kernel_width) {
+ case 2:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
+ }
+ break;
+ case 3:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
+ }
+ break;
+ case 4:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
+ }
+ break;
+ case 5:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
+ }
+ break;
+ default:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
+ }
+ break;
+ }
+
+ for (; i < h; ++i) {
+ STBTT_assert(pixels[i*stride_in_bytes] == 0);
+ total -= buffer[i & STBTT__OVER_MASK];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
+ }
+
+ pixels += 1;
+ }
+}
+
+static float stbtt__oversample_shift(int oversample)
+{
+ if (!oversample)
+ return 0.0f;
+
+ /* The prefilter is a box filter of width "oversample", */
+ /* which shifts phase by (oversample - 1)/2 pixels in */
+ /* oversampled space. We want to shift in the opposite */
+ /* direction to counter this. */
+ return (float)-(oversample - 1) / (2.0f * (float)oversample);
+}
+
+/* rects array must be big enough to accommodate all characters in the given ranges */
+STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
+{
+ int i,j,k;
+ int missing_glyph_added = 0;
+
+ k=0;
+ for (i=0; i < num_ranges; ++i) {
+ float fh = ranges[i].font_size;
+ float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
+ ranges[i].h_oversample = (unsigned char) spc->h_oversample;
+ ranges[i].v_oversample = (unsigned char) spc->v_oversample;
+ for (j=0; j < ranges[i].num_chars; ++j) {
+ int x0,y0,x1,y1;
+ int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
+ int glyph = stbtt_FindGlyphIndex(info, codepoint);
+ if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) {
+ rects[k].w = rects[k].h = 0;
+ } else {
+ stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
+ scale * spc->h_oversample,
+ scale * spc->v_oversample,
+ 0,0,
+ &x0,&y0,&x1,&y1);
+ rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
+ rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
+ if (glyph == 0)
+ missing_glyph_added = 1;
+ }
+ ++k;
+ }
+ }
+
+ return k;
+}
+
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)
+{
+ stbtt_MakeGlyphBitmapSubpixel(info,
+ output,
+ out_w - (prefilter_x - 1),
+ out_h - (prefilter_y - 1),
+ out_stride,
+ scale_x,
+ scale_y,
+ shift_x,
+ shift_y,
+ glyph);
+
+ if (prefilter_x > 1)
+ stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
+
+ if (prefilter_y > 1)
+ stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
+
+ *sub_x = stbtt__oversample_shift(prefilter_x);
+ *sub_y = stbtt__oversample_shift(prefilter_y);
+}
+
+/* rects array must be big enough to accommodate all characters in the given ranges */
+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
+{
+ int i,j,k, missing_glyph = -1, return_value = 1;
+
+ /* save current values */
+ int old_h_over = spc->h_oversample;
+ int old_v_over = spc->v_oversample;
+
+ k = 0;
+ for (i=0; i < num_ranges; ++i) {
+ float fh = ranges[i].font_size;
+ float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
+ float recip_h,recip_v,sub_x,sub_y;
+ spc->h_oversample = ranges[i].h_oversample;
+ spc->v_oversample = ranges[i].v_oversample;
+ recip_h = 1.0f / spc->h_oversample;
+ recip_v = 1.0f / spc->v_oversample;
+ sub_x = stbtt__oversample_shift(spc->h_oversample);
+ sub_y = stbtt__oversample_shift(spc->v_oversample);
+ for (j=0; j < ranges[i].num_chars; ++j) {
+ stbrp_rect *r = &rects[k];
+ if (r->was_packed && r->w != 0 && r->h != 0) {
+ stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
+ int advance, lsb, x0,y0,x1,y1;
+ int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
+ int glyph = stbtt_FindGlyphIndex(info, codepoint);
+ stbrp_coord pad = (stbrp_coord) spc->padding;
+
+ /* pad on left and top */
+ r->x += pad;
+ r->y += pad;
+ r->w -= pad;
+ r->h -= pad;
+ stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
+ stbtt_GetGlyphBitmapBox(info, glyph,
+ scale * spc->h_oversample,
+ scale * spc->v_oversample,
+ &x0,&y0,&x1,&y1);
+ stbtt_MakeGlyphBitmapSubpixel(info,
+ spc->pixels + r->x + r->y*spc->stride_in_bytes,
+ r->w - spc->h_oversample+1,
+ r->h - spc->v_oversample+1,
+ spc->stride_in_bytes,
+ scale * spc->h_oversample,
+ scale * spc->v_oversample,
+ 0,0,
+ glyph);
+
+ if (spc->h_oversample > 1)
+ stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
+ r->w, r->h, spc->stride_in_bytes,
+ spc->h_oversample);
+
+ if (spc->v_oversample > 1)
+ stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
+ r->w, r->h, spc->stride_in_bytes,
+ spc->v_oversample);
+
+ bc->x0 = (stbtt_int16) r->x;
+ bc->y0 = (stbtt_int16) r->y;
+ bc->x1 = (stbtt_int16) (r->x + r->w);
+ bc->y1 = (stbtt_int16) (r->y + r->h);
+ bc->xadvance = scale * advance;
+ bc->xoff = (float) x0 * recip_h + sub_x;
+ bc->yoff = (float) y0 * recip_v + sub_y;
+ bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
+ bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
+
+ if (glyph == 0)
+ missing_glyph = j;
+ } else if (spc->skip_missing) {
+ return_value = 0;
+ } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) {
+ ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph];
+ } else {
+ return_value = 0; /* if any fail, report failure */
+ }
+
+ ++k;
+ }
+ }
+
+ /* restore original values */
+ spc->h_oversample = old_h_over;
+ spc->v_oversample = old_v_over;
+
+ return return_value;
+}
+
+STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
+{
+ stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
+}
+
+STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
+{
+ stbtt_fontinfo info;
+ int i,j,n, return_value = 1;
+ /* stbrp_context *context = (stbrp_context *) spc->pack_info; */
+ stbrp_rect *rects;
+
+ /* flag all characters as NOT packed */
+ for (i=0; i < num_ranges; ++i)
+ for (j=0; j < ranges[i].num_chars; ++j)
+ ranges[i].chardata_for_range[j].x0 =
+ ranges[i].chardata_for_range[j].y0 =
+ ranges[i].chardata_for_range[j].x1 =
+ ranges[i].chardata_for_range[j].y1 = 0;
+
+ n = 0;
+ for (i=0; i < num_ranges; ++i)
+ n += ranges[i].num_chars;
+
+ rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
+ if (rects == NULL)
+ return 0;
+
+ info.userdata = spc->user_allocator_context;
+ stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
+
+ n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
+
+ stbtt_PackFontRangesPackRects(spc, rects, n);
+
+ return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
+
+ STBTT_free(rects, spc->user_allocator_context);
+ return return_value;
+}
+
+STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,
+ int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
+{
+ stbtt_pack_range range;
+ range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
+ range.array_of_unicode_codepoints = NULL;
+ range.num_chars = num_chars_in_range;
+ range.chardata_for_range = chardata_for_range;
+ range.font_size = font_size;
+ return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
+}
+
+STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)
+{
+ int i_ascent, i_descent, i_lineGap;
+ float scale;
+ stbtt_fontinfo info;
+ stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));
+ scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);
+ stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);
+ *ascent = (float) i_ascent * scale;
+ *descent = (float) i_descent * scale;
+ *lineGap = (float) i_lineGap * scale;
+}
+
+STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
+{
+ float ipw = 1.0f / pw, iph = 1.0f / ph;
+ const stbtt_packedchar *b = chardata + char_index;
+
+ if (align_to_integer) {
+ float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
+ float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
+ q->x0 = x;
+ q->y0 = y;
+ q->x1 = x + b->xoff2 - b->xoff;
+ q->y1 = y + b->yoff2 - b->yoff;
+ } else {
+ q->x0 = *xpos + b->xoff;
+ q->y0 = *ypos + b->yoff;
+ q->x1 = *xpos + b->xoff2;
+ q->y1 = *ypos + b->yoff2;
+ }
+
+ q->s0 = b->x0 * ipw;
+ q->t0 = b->y0 * iph;
+ q->s1 = b->x1 * ipw;
+ q->t1 = b->y1 * iph;
+
+ *xpos += b->xadvance;
+}
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* sdf computation */
+/* */
+
+#define STBTT_min(a,b) ((a) < (b) ? (a) : (b))
+#define STBTT_max(a,b) ((a) < (b) ? (b) : (a))
+
+static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
+{
+ float q0perp = q0[1]*ray[0] - q0[0]*ray[1];
+ float q1perp = q1[1]*ray[0] - q1[0]*ray[1];
+ float q2perp = q2[1]*ray[0] - q2[0]*ray[1];
+ float roperp = orig[1]*ray[0] - orig[0]*ray[1];
+
+ float a = q0perp - 2*q1perp + q2perp;
+ float b = q1perp - q0perp;
+ float c = q0perp - roperp;
+
+ float s0 = 0., s1 = 0.;
+ int num_s = 0;
+
+ if (a != 0.0) {
+ float discr = b*b - a*c;
+ if (discr > 0.0) {
+ float rcpna = -1 / a;
+ float d = (float) STBTT_sqrt(discr);
+ s0 = (b+d) * rcpna;
+ s1 = (b-d) * rcpna;
+ if (s0 >= 0.0 && s0 <= 1.0)
+ num_s = 1;
+ if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {
+ if (num_s == 0) s0 = s1;
+ ++num_s;
+ }
+ }
+ } else {
+ /* 2*b*s + c = 0 */
+ /* s = -c / (2*b) */
+ s0 = c / (-2 * b);
+ if (s0 >= 0.0 && s0 <= 1.0)
+ num_s = 1;
+ }
+
+ if (num_s == 0)
+ return 0;
+ else {
+ float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);
+ float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
+
+ float q0d = q0[0]*rayn_x + q0[1]*rayn_y;
+ float q1d = q1[0]*rayn_x + q1[1]*rayn_y;
+ float q2d = q2[0]*rayn_x + q2[1]*rayn_y;
+ float rod = orig[0]*rayn_x + orig[1]*rayn_y;
+
+ float q10d = q1d - q0d;
+ float q20d = q2d - q0d;
+ float q0rd = q0d - rod;
+
+ hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;
+ hits[0][1] = a*s0+b;
+
+ if (num_s > 1) {
+ hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;
+ hits[1][1] = a*s1+b;
+ return 2;
+ } else {
+ return 1;
+ }
+ }
+}
+
+static int equal(float *a, float *b)
+{
+ return (a[0] == b[0] && a[1] == b[1]);
+}
+
+static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)
+{
+ int i;
+ float orig[2], ray[2] = { 1, 0 };
+ float y_frac;
+ int winding = 0;
+
+ /* make sure y never passes through a vertex of the shape */
+ y_frac = (float) STBTT_fmod(y, 1.0f);
+ if (y_frac < 0.01f)
+ y += 0.01f;
+ else if (y_frac > 0.99f)
+ y -= 0.01f;
+
+ orig[0] = x;
+ orig[1] = y;
+
+ /* test a ray from (-infinity,y) to (x,y) */
+ for (i=0; i < nverts; ++i) {
+ if (verts[i].type == STBTT_vline) {
+ int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;
+ int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y;
+ if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
+ float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
+ if (x_inter < x)
+ winding += (y0 < y1) ? 1 : -1;
+ }
+ }
+ if (verts[i].type == STBTT_vcurve) {
+ int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;
+ int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy;
+ int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ;
+ int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));
+ int by = STBTT_max(y0,STBTT_max(y1,y2));
+ if (y > ay && y < by && x > ax) {
+ float q0[2],q1[2],q2[2];
+ float hits[2][2];
+ q0[0] = (float)x0;
+ q0[1] = (float)y0;
+ q1[0] = (float)x1;
+ q1[1] = (float)y1;
+ q2[0] = (float)x2;
+ q2[1] = (float)y2;
+ if (equal(q0,q1) || equal(q1,q2)) {
+ x0 = (int)verts[i-1].x;
+ y0 = (int)verts[i-1].y;
+ x1 = (int)verts[i ].x;
+ y1 = (int)verts[i ].y;
+ if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {
+ float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;
+ if (x_inter < x)
+ winding += (y0 < y1) ? 1 : -1;
+ }
+ } else {
+ int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
+ if (num_hits >= 1)
+ if (hits[0][0] < 0)
+ winding += (hits[0][1] < 0 ? -1 : 1);
+ if (num_hits >= 2)
+ if (hits[1][0] < 0)
+ winding += (hits[1][1] < 0 ? -1 : 1);
+ }
+ }
+ }
+ }
+ return winding;
+}
+
+static float stbtt__cuberoot( float x )
+{
+ if (x<0)
+ return -(float) STBTT_pow(-x,1.0f/3.0f);
+ else
+ return (float) STBTT_pow( x,1.0f/3.0f);
+}
+
+/* x^3 + a*x^2 + b*x + c = 0 */
+static int stbtt__solve_cubic(float a, float b, float c, float* r)
+{
+ float s = -a / 3;
+ float p = b - a*a / 3;
+ float q = a * (2*a*a - 9*b) / 27 + c;
+ float p3 = p*p*p;
+ float d = q*q + 4*p3 / 27;
+ if (d >= 0) {
+ float z = (float) STBTT_sqrt(d);
+ float u = (-q + z) / 2;
+ float v = (-q - z) / 2;
+ u = stbtt__cuberoot(u);
+ v = stbtt__cuberoot(v);
+ r[0] = s + u + v;
+ return 1;
+ } else {
+ float u = (float) STBTT_sqrt(-p/3);
+ float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; /* p3 must be negative, since d is negative */
+ float m = (float) STBTT_cos(v);
+ float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;
+ r[0] = s + u * 2 * m;
+ r[1] = s - u * (m + n);
+ r[2] = s - u * (m - n);
+
+ /* STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? */
+ /* STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); */
+ /* STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); */
+ return 3;
+ }
+}
+
+STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
+{
+ float scale_x = scale, scale_y = scale;
+ int ix0,iy0,ix1,iy1;
+ int w,h;
+ unsigned char *data;
+
+ if (scale == 0) return NULL;
+
+ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);
+
+ /* if empty, return NULL */
+ if (ix0 == ix1 || iy0 == iy1)
+ return NULL;
+
+ ix0 -= padding;
+ iy0 -= padding;
+ ix1 += padding;
+ iy1 += padding;
+
+ w = (ix1 - ix0);
+ h = (iy1 - iy0);
+
+ if (width ) *width = w;
+ if (height) *height = h;
+ if (xoff ) *xoff = ix0;
+ if (yoff ) *yoff = iy0;
+
+ /* invert for y-downwards bitmaps */
+ scale_y = -scale_y;
+
+ {
+ int x,y,i,j;
+ float *precompute;
+ stbtt_vertex *verts;
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
+ data = (unsigned char *) STBTT_malloc(w * h, info->userdata);
+ precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);
+
+ for (i=0,j=num_verts-1; i < num_verts; j=i++) {
+ if (verts[i].type == STBTT_vline) {
+ float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
+ float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;
+ float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
+ precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
+ } else if (verts[i].type == STBTT_vcurve) {
+ float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;
+ float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;
+ float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;
+ float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
+ float len2 = bx*bx + by*by;
+ if (len2 != 0.0f)
+ precompute[i] = 1.0f / (bx*bx + by*by);
+ else
+ precompute[i] = 0.0f;
+ } else
+ precompute[i] = 0.0f;
+ }
+
+ for (y=iy0; y < iy1; ++y) {
+ for (x=ix0; x < ix1; ++x) {
+ float val;
+ float min_dist = 999999.0f;
+ float sx = (float) x + 0.5f;
+ float sy = (float) y + 0.5f;
+ float x_gspace = (sx / scale_x);
+ float y_gspace = (sy / scale_y);
+
+ int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); /* @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path */
+
+ for (i=0; i < num_verts; ++i) {
+ float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;
+
+ if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) {
+ float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;
+
+ float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
+ if (dist2 < min_dist*min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+
+ /* coarse culling against bbox */
+ /* if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && */
+ /* sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) */
+ dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];
+ STBTT_assert(i != 0);
+ if (dist < min_dist) {
+ /* check position along line */
+ /* x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) */
+ /* minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) */
+ float dx = x1-x0, dy = y1-y0;
+ float px = x0-sx, py = y0-sy;
+ /* minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy */
+ /* derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve */
+ float t = -(px*dx + py*dy) / (dx*dx + dy*dy);
+ if (t >= 0.0f && t <= 1.0f)
+ min_dist = dist;
+ }
+ } else if (verts[i].type == STBTT_vcurve) {
+ float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;
+ float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y;
+ float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);
+ float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);
+ float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);
+ float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);
+ /* coarse culling against bbox to avoid computing cubic unnecessarily */
+ if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {
+ int num=0;
+ float ax = x1-x0, ay = y1-y0;
+ float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;
+ float mx = x0 - sx, my = y0 - sy;
+ float res[3] = {0.f,0.f,0.f};
+ float px,py,t,it,dist2;
+ float a_inv = precompute[i];
+ if (a_inv == 0.0) { /* if a_inv is 0, it's 2nd degree so use quadratic formula */
+ float a = 3*(ax*bx + ay*by);
+ float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);
+ float c = mx*ax+my*ay;
+ if (a == 0.0) { /* if a is 0, it's linear */
+ if (b != 0.0) {
+ res[num++] = -c/b;
+ }
+ } else {
+ float discriminant = b*b - 4*a*c;
+ if (discriminant < 0)
+ num = 0;
+ else {
+ float root = (float) STBTT_sqrt(discriminant);
+ res[0] = (-b - root)/(2*a);
+ res[1] = (-b + root)/(2*a);
+ num = 2; /* don't bother distinguishing 1-solution case, as code below will still work */
+ }
+ }
+ } else {
+ float b = 3*(ax*bx + ay*by) * a_inv; /* could precompute this as it doesn't depend on sample point */
+ float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;
+ float d = (mx*ax+my*ay) * a_inv;
+ num = stbtt__solve_cubic(b, c, d, res);
+ }
+ dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);
+ if (dist2 < min_dist*min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+
+ if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {
+ t = res[0], it = 1.0f - t;
+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;
+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;
+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
+ if (dist2 < min_dist * min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+ }
+ if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {
+ t = res[1], it = 1.0f - t;
+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;
+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;
+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
+ if (dist2 < min_dist * min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+ }
+ if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {
+ t = res[2], it = 1.0f - t;
+ px = it*it*x0 + 2*t*it*x1 + t*t*x2;
+ py = it*it*y0 + 2*t*it*y1 + t*t*y2;
+ dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);
+ if (dist2 < min_dist * min_dist)
+ min_dist = (float) STBTT_sqrt(dist2);
+ }
+ }
+ }
+ }
+ if (winding == 0)
+ min_dist = -min_dist; /* if outside the shape, value is negative */
+ val = onedge_value + pixel_dist_scale * min_dist;
+ if (val < 0)
+ val = 0;
+ else if (val > 255)
+ val = 255;
+ data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;
+ }
+ }
+ STBTT_free(precompute, info->userdata);
+ STBTT_free(verts, info->userdata);
+ }
+ return data;
+}
+
+STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
+}
+
+STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)
+{
+ STBTT_free(bitmap, userdata);
+}
+
+/* //////////////////////////////////////////////////////////////////////////// */
+/* */
+/* font name matching -- recommended not to use this */
+/* */
+
+/* check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string */
+static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)
+{
+ stbtt_int32 i=0;
+
+ /* convert utf16 to utf8 and compare the results while converting */
+ while (len2) {
+ stbtt_uint16 ch = s2[0]*256 + s2[1];
+ if (ch < 0x80) {
+ if (i >= len1) return -1;
+ if (s1[i++] != ch) return -1;
+ } else if (ch < 0x800) {
+ if (i+1 >= len1) return -1;
+ if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
+ if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
+ } else if (ch >= 0xd800 && ch < 0xdc00) {
+ stbtt_uint32 c;
+ stbtt_uint16 ch2 = s2[2]*256 + s2[3];
+ if (i+3 >= len1) return -1;
+ c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
+ if (s1[i++] != 0xf0 + (c >> 18)) return -1;
+ if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
+ if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
+ if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
+ s2 += 2; /* plus another 2 below */
+ len2 -= 2;
+ } else if (ch >= 0xdc00 && ch < 0xe000) {
+ return -1;
+ } else {
+ if (i+2 >= len1) return -1;
+ if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
+ if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
+ if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
+ }
+ s2 += 2;
+ len2 -= 2;
+ }
+ return i;
+}
+
+static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)
+{
+ return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);
+}
+
+/* returns results in whatever encoding you request... but note that 2-byte encodings */
+/* will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare */
+STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
+{
+ stbtt_int32 i,count,stringOffset;
+ stbtt_uint8 *fc = font->data;
+ stbtt_uint32 offset = font->fontstart;
+ stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
+ if (!nm) return NULL;
+
+ count = ttUSHORT(fc+nm+2);
+ stringOffset = nm + ttUSHORT(fc+nm+4);
+ for (i=0; i < count; ++i) {
+ stbtt_uint32 loc = nm + 6 + 12 * i;
+ if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
+ && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
+ *length = ttUSHORT(fc+loc+8);
+ return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
+ }
+ }
+ return NULL;
+}
+
+static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
+{
+ stbtt_int32 i;
+ stbtt_int32 count = ttUSHORT(fc+nm+2);
+ stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
+
+ for (i=0; i < count; ++i) {
+ stbtt_uint32 loc = nm + 6 + 12 * i;
+ stbtt_int32 id = ttUSHORT(fc+loc+6);
+ if (id == target_id) {
+ /* find the encoding */
+ stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
+
+ /* is this a Unicode encoding? */
+ if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
+ stbtt_int32 slen = ttUSHORT(fc+loc+8);
+ stbtt_int32 off = ttUSHORT(fc+loc+10);
+
+ /* check if there's a prefix match */
+ stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
+ if (matchlen >= 0) {
+ /* check for target_id+1 immediately following, with same encoding & language */
+ if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {
+ slen = ttUSHORT(fc+loc+12+8);
+ off = ttUSHORT(fc+loc+12+10);
+ if (slen == 0) {
+ if (matchlen == nlen)
+ return 1;
+ } else if (matchlen < nlen && name[matchlen] == ' ') {
+ ++matchlen;
+ if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
+ return 1;
+ }
+ } else {
+ /* if nothing immediately following */
+ if (matchlen == nlen)
+ return 1;
+ }
+ }
+ }
+
+ /* @TODO handle other encodings */
+ }
+ }
+ return 0;
+}
+
+static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
+{
+ stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
+ stbtt_uint32 nm,hd;
+ if (!stbtt__isfont(fc+offset)) return 0;
+
+ /* check italics/bold/underline flags in macStyle... */
+ if (flags) {
+ hd = stbtt__find_table(fc, offset, "head");
+ if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
+ }
+
+ nm = stbtt__find_table(fc, offset, "name");
+ if (!nm) return 0;
+
+ if (flags) {
+ /* if we checked the macStyle flags, then just check the family and ignore the subfamily */
+ if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
+ } else {
+ if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
+ }
+
+ return 0;
+}
+
+static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)
+{
+ stbtt_int32 i;
+ for (i=0;;++i) {
+ stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
+ if (off < 0) return off;
+ if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
+ return off;
+ }
+}
+
+#if defined(__GNUC__) || defined(__clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wcast-qual"
+#endif
+
+STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,
+ float pixel_height, unsigned char *pixels, int pw, int ph,
+ int first_char, int num_chars, stbtt_bakedchar *chardata)
+{
+ return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
+}
+
+STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
+{
+ return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);
+}
+
+STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
+{
+ return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
+}
+
+STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
+{
+ return stbtt_InitFont_internal(info, (unsigned char *) data, offset);
+}
+
+STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)
+{
+ return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);
+}
+
+STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
+{
+ return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);
+}
+
+#if defined(__GNUC__) || defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
+
+#endif /* STB_TRUETYPE_IMPLEMENTATION */
+
+
+/* FULL VERSION HISTORY */
+/* */
+/* 1.25 (2021-07-11) many fixes */
+/* 1.24 (2020-02-05) fix warning */
+/* 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) */
+/* 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined */
+/* 1.21 (2019-02-25) fix warning */
+/* 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() */
+/* 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod */
+/* 1.18 (2018-01-29) add missing function */
+/* 1.17 (2017-07-23) make more arguments const; doc fix */
+/* 1.16 (2017-07-12) SDF support */
+/* 1.15 (2017-03-03) make more arguments const */
+/* 1.14 (2017-01-16) num-fonts-in-TTC function */
+/* 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts */
+/* 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual */
+/* 1.11 (2016-04-02) fix unused-variable warning */
+/* 1.10 (2016-04-02) allow user-defined fabs() replacement */
+/* fix memory leak if fontsize=0.0 */
+/* fix warning from duplicate typedef */
+/* 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges */
+/* 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges */
+/* 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; */
+/* allow PackFontRanges to pack and render in separate phases; */
+/* fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); */
+/* fixed an assert() bug in the new rasterizer */
+/* replace assert() with STBTT_assert() in new rasterizer */
+/* 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) */
+/* also more precise AA rasterizer, except if shapes overlap */
+/* remove need for STBTT_sort */
+/* 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC */
+/* 1.04 (2015-04-15) typo in example */
+/* 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes */
+/* 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ */
+/* 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match */
+/* non-oversampled; STBTT_POINT_SIZE for packed case only */
+/* 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling */
+/* 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) */
+/* 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID */
+/* 0.8b (2014-07-07) fix a warning */
+/* 0.8 (2014-05-25) fix a few more warnings */
+/* 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back */
+/* 0.6c (2012-07-24) improve documentation */
+/* 0.6b (2012-07-20) fix a few more warnings */
+/* 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, */
+/* stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty */
+/* 0.5 (2011-12-09) bugfixes: */
+/* subpixel glyph renderer computed wrong bounding box */
+/* first vertex of shape can be off-curve (FreeSans) */
+/* 0.4b (2011-12-03) fixed an error in the font baking example */
+/* 0.4 (2011-12-01) kerning, subpixel rendering (tor) */
+/* bugfixes for: */
+/* codepoint-to-glyph conversion using table fmt=12 */
+/* codepoint-to-glyph conversion using table fmt=4 */
+/* stbtt_GetBakedQuad with non-square texture (Zer) */
+/* updated Hello World! sample to use kerning and subpixel */
+/* fixed some warnings */
+/* 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) */
+/* userdata, malloc-from-userdata, non-zero fill (stb) */
+/* 0.2 (2009-03-11) Fix unsigned/signed char warnings */
+/* 0.1 (2009-03-09) First public release */
+/* */
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
+
+
+
+
+#ifdef NK_INCLUDE_FONT_BAKING
+/* -------------------------------------------------------------
+ *
+ * RECT PACK
+ *
+ * --------------------------------------------------------------*/
+
+
+
+/*
+ * ==============================================================
+ *
+ * TRUETYPE
+ *
+ * ===============================================================
+ */
+#define STBTT_MAX_OVERSAMPLE 8
+
+
+/* -------------------------------------------------------------
+ *
+ * FONT BAKING
+ *
+ * --------------------------------------------------------------*/
+struct nk_font_bake_data {
+ struct stbtt_fontinfo info;
+ struct stbrp_rect *rects;
+ stbtt_pack_range *ranges;
+ nk_rune range_count;
+};
+
+struct nk_font_baker {
+ struct nk_allocator alloc;
+ struct stbtt_pack_context spc;
+ struct nk_font_bake_data *build;
+ stbtt_packedchar *packed_chars;
+ struct stbrp_rect *rects;
+ stbtt_pack_range *ranges;
+};
+
+NK_GLOBAL const nk_size nk_rect_align = NK_ALIGNOF(struct stbrp_rect);
+NK_GLOBAL const nk_size nk_range_align = NK_ALIGNOF(stbtt_pack_range);
+NK_GLOBAL const nk_size nk_char_align = NK_ALIGNOF(stbtt_packedchar);
+NK_GLOBAL const nk_size nk_build_align = NK_ALIGNOF(struct nk_font_bake_data);
+NK_GLOBAL const nk_size nk_baker_align = NK_ALIGNOF(struct nk_font_baker);
+
+NK_INTERN int
+nk_range_count(const nk_rune *range)
+{
+ const nk_rune *iter = range;
+ NK_ASSERT(range);
+ if (!range) return 0;
+ while (*(iter++) != 0);
+ return (iter == range) ? 0 : (int)((iter - range)/2);
+}
+NK_INTERN int
+nk_range_glyph_count(const nk_rune *range, int count)
+{
+ int i = 0;
+ int total_glyphs = 0;
+ for (i = 0; i < count; ++i) {
+ int diff;
+ nk_rune f = range[(i*2)+0];
+ nk_rune t = range[(i*2)+1];
+ NK_ASSERT(t >= f);
+ diff = (int)((t - f) + 1);
+ total_glyphs += diff;
+ }
+ return total_glyphs;
+}
+NK_API const nk_rune*
+nk_font_default_glyph_ranges(void)
+{
+ NK_STORAGE const nk_rune ranges[] = {0x0020, 0x00FF, 0};
+ return ranges;
+}
+NK_API const nk_rune*
+nk_font_chinese_glyph_ranges(void)
+{
+ NK_STORAGE const nk_rune ranges[] = {
+ 0x0020, 0x00FF,
+ 0x3000, 0x30FF,
+ 0x31F0, 0x31FF,
+ 0xFF00, 0xFFEF,
+ 0x4E00, 0x9FAF,
+ 0
+ };
+ return ranges;
+}
+NK_API const nk_rune*
+nk_font_cyrillic_glyph_ranges(void)
+{
+ NK_STORAGE const nk_rune ranges[] = {
+ 0x0020, 0x00FF,
+ 0x0400, 0x052F,
+ 0x2DE0, 0x2DFF,
+ 0xA640, 0xA69F,
+ 0
+ };
+ return ranges;
+}
+NK_API const nk_rune*
+nk_font_korean_glyph_ranges(void)
+{
+ NK_STORAGE const nk_rune ranges[] = {
+ 0x0020, 0x00FF,
+ 0x3131, 0x3163,
+ 0xAC00, 0xD79D,
+ 0
+ };
+ return ranges;
+}
+NK_INTERN void
+nk_font_baker_memory(nk_size *temp, int *glyph_count,
+ struct nk_font_config *config_list, int count)
+{
+ int range_count = 0;
+ int total_range_count = 0;
+ struct nk_font_config *iter, *i;
+
+ NK_ASSERT(config_list);
+ NK_ASSERT(glyph_count);
+ if (!config_list) {
+ *temp = 0;
+ *glyph_count = 0;
+ return;
+ }
+ *glyph_count = 0;
+ for (iter = config_list; iter; iter = iter->next) {
+ i = iter;
+ do {if (!i->range) iter->range = nk_font_default_glyph_ranges();
+ range_count = nk_range_count(i->range);
+ total_range_count += range_count;
+ *glyph_count += nk_range_glyph_count(i->range, range_count);
+ } while ((i = i->n) != iter);
+ }
+ *temp = (nk_size)*glyph_count * sizeof(struct stbrp_rect);
+ *temp += (nk_size)total_range_count * sizeof(stbtt_pack_range);
+ *temp += (nk_size)*glyph_count * sizeof(stbtt_packedchar);
+ *temp += (nk_size)count * sizeof(struct nk_font_bake_data);
+ *temp += sizeof(struct nk_font_baker);
+ *temp += nk_rect_align + nk_range_align + nk_char_align;
+ *temp += nk_build_align + nk_baker_align;
+}
+NK_INTERN struct nk_font_baker*
+nk_font_baker(void *memory, int glyph_count, int count, struct nk_allocator *alloc)
+{
+ struct nk_font_baker *baker;
+ if (!memory) return 0;
+ /* setup baker inside a memory block */
+ baker = (struct nk_font_baker*)NK_ALIGN_PTR(memory, nk_baker_align);
+ baker->build = (struct nk_font_bake_data*)NK_ALIGN_PTR((baker + 1), nk_build_align);
+ baker->packed_chars = (stbtt_packedchar*)NK_ALIGN_PTR((baker->build + count), nk_char_align);
+ baker->rects = (struct stbrp_rect*)NK_ALIGN_PTR((baker->packed_chars + glyph_count), nk_rect_align);
+ baker->ranges = (stbtt_pack_range*)NK_ALIGN_PTR((baker->rects + glyph_count), nk_range_align);
+ baker->alloc = *alloc;
+ return baker;
+}
+NK_INTERN int
+nk_font_bake_pack(struct nk_font_baker *baker,
+ nk_size *image_memory, int *width, int *height, struct nk_recti *custom,
+ const struct nk_font_config *config_list, int count,
+ struct nk_allocator *alloc)
+{
+ NK_STORAGE const nk_size max_height = 1024 * 32;
+ const struct nk_font_config *config_iter, *it;
+ int total_glyph_count = 0;
+ int total_range_count = 0;
+ int range_count = 0;
+ int i = 0;
+
+ NK_ASSERT(image_memory);
+ NK_ASSERT(width);
+ NK_ASSERT(height);
+ NK_ASSERT(config_list);
+ NK_ASSERT(count);
+ NK_ASSERT(alloc);
+
+ if (!image_memory || !width || !height || !config_list || !count) return nk_false;
+ for (config_iter = config_list; config_iter; config_iter = config_iter->next) {
+ it = config_iter;
+ do {range_count = nk_range_count(it->range);
+ total_range_count += range_count;
+ total_glyph_count += nk_range_glyph_count(it->range, range_count);
+ } while ((it = it->n) != config_iter);
+ }
+ /* setup font baker from temporary memory */
+ for (config_iter = config_list; config_iter; config_iter = config_iter->next) {
+ it = config_iter;
+ do {
+ struct stbtt_fontinfo *font_info = &baker->build[i++].info;
+ font_info->userdata = alloc;
+
+ if (!stbtt_InitFont(font_info, (const unsigned char*)it->ttf_blob, stbtt_GetFontOffsetForIndex((const unsigned char*)it->ttf_blob, 0)))
+ return nk_false;
+ } while ((it = it->n) != config_iter);
+ }
+ *height = 0;
+ *width = (total_glyph_count > 1000) ? 1024 : 512;
+ stbtt_PackBegin(&baker->spc, 0, (int)*width, (int)max_height, 0, 1, alloc);
+ {
+ int input_i = 0;
+ int range_n = 0;
+ int rect_n = 0;
+ int char_n = 0;
+
+ if (custom) {
+ /* pack custom user data first so it will be in the upper left corner*/
+ struct stbrp_rect custom_space;
+ nk_zero(&custom_space, sizeof(custom_space));
+ custom_space.w = (stbrp_coord)(custom->w);
+ custom_space.h = (stbrp_coord)(custom->h);
+
+ stbtt_PackSetOversampling(&baker->spc, 1, 1);
+ stbrp_pack_rects((struct stbrp_context*)baker->spc.pack_info, &custom_space, 1);
+ *height = NK_MAX(*height, (int)(custom_space.y + custom_space.h));
+
+ custom->x = (short)custom_space.x;
+ custom->y = (short)custom_space.y;
+ custom->w = (short)custom_space.w;
+ custom->h = (short)custom_space.h;
+ }
+
+ /* first font pass: pack all glyphs */
+ for (input_i = 0, config_iter = config_list; input_i < count && config_iter;
+ config_iter = config_iter->next) {
+ it = config_iter;
+ do {int n = 0;
+ int glyph_count;
+ const nk_rune *in_range;
+ const struct nk_font_config *cfg = it;
+ struct nk_font_bake_data *tmp = &baker->build[input_i++];
+
+ /* count glyphs + ranges in current font */
+ glyph_count = 0; range_count = 0;
+ for (in_range = cfg->range; in_range[0] && in_range[1]; in_range += 2) {
+ glyph_count += (int)(in_range[1] - in_range[0]) + 1;
+ range_count++;
+ }
+
+ /* setup ranges */
+ tmp->ranges = baker->ranges + range_n;
+ tmp->range_count = (nk_rune)range_count;
+ range_n += range_count;
+ for (i = 0; i < range_count; ++i) {
+ in_range = &cfg->range[i * 2];
+ tmp->ranges[i].font_size = cfg->size;
+ tmp->ranges[i].first_unicode_codepoint_in_range = (int)in_range[0];
+ tmp->ranges[i].num_chars = (int)(in_range[1]- in_range[0]) + 1;
+ tmp->ranges[i].chardata_for_range = baker->packed_chars + char_n;
+ char_n += tmp->ranges[i].num_chars;
+ }
+
+ /* pack */
+ tmp->rects = baker->rects + rect_n;
+ rect_n += glyph_count;
+ stbtt_PackSetOversampling(&baker->spc, cfg->oversample_h, cfg->oversample_v);
+ n = stbtt_PackFontRangesGatherRects(&baker->spc, &tmp->info,
+ tmp->ranges, (int)tmp->range_count, tmp->rects);
+ stbrp_pack_rects((struct stbrp_context*)baker->spc.pack_info, tmp->rects, (int)n);
+
+ /* texture height */
+ for (i = 0; i < n; ++i) {
+ if (tmp->rects[i].was_packed)
+ *height = NK_MAX(*height, tmp->rects[i].y + tmp->rects[i].h);
+ }
+ } while ((it = it->n) != config_iter);
+ }
+ NK_ASSERT(rect_n == total_glyph_count);
+ NK_ASSERT(char_n == total_glyph_count);
+ NK_ASSERT(range_n == total_range_count);
+ }
+ *height = (int)nk_round_up_pow2((nk_uint)*height);
+ *image_memory = (nk_size)(*width) * (nk_size)(*height);
+ return nk_true;
+}
+NK_INTERN void
+nk_font_bake(struct nk_font_baker *baker, void *image_memory, int width, int height,
+ struct nk_font_glyph *glyphs, int glyphs_count,
+ const struct nk_font_config *config_list, int font_count)
+{
+ int input_i = 0;
+ nk_rune glyph_n = 0;
+ const struct nk_font_config *config_iter;
+ const struct nk_font_config *it;
+
+ NK_ASSERT(image_memory);
+ NK_ASSERT(width);
+ NK_ASSERT(height);
+ NK_ASSERT(config_list);
+ NK_ASSERT(baker);
+ NK_ASSERT(font_count);
+ NK_ASSERT(glyphs_count);
+ if (!image_memory || !width || !height || !config_list ||
+ !font_count || !glyphs || !glyphs_count)
+ return;
+
+ /* second font pass: render glyphs */
+ nk_zero(image_memory, (nk_size)((nk_size)width * (nk_size)height));
+ baker->spc.pixels = (unsigned char*)image_memory;
+ baker->spc.height = (int)height;
+ for (input_i = 0, config_iter = config_list; input_i < font_count && config_iter;
+ config_iter = config_iter->next) {
+ it = config_iter;
+ do {const struct nk_font_config *cfg = it;
+ struct nk_font_bake_data *tmp = &baker->build[input_i++];
+ stbtt_PackSetOversampling(&baker->spc, cfg->oversample_h, cfg->oversample_v);
+ stbtt_PackFontRangesRenderIntoRects(&baker->spc, &tmp->info, tmp->ranges, (int)tmp->range_count, tmp->rects);
+ } while ((it = it->n) != config_iter);
+ } stbtt_PackEnd(&baker->spc);
+
+ /* third pass: setup font and glyphs */
+ for (input_i = 0, config_iter = config_list; input_i < font_count && config_iter;
+ config_iter = config_iter->next) {
+ it = config_iter;
+ do {nk_size i = 0;
+ int char_idx = 0;
+ nk_rune glyph_count = 0;
+ const struct nk_font_config *cfg = it;
+ struct nk_font_bake_data *tmp = &baker->build[input_i++];
+ struct nk_baked_font *dst_font = cfg->font;
+
+ float font_scale = stbtt_ScaleForPixelHeight(&tmp->info, cfg->size);
+ int unscaled_ascent, unscaled_descent, unscaled_line_gap;
+ stbtt_GetFontVMetrics(&tmp->info, &unscaled_ascent, &unscaled_descent,
+ &unscaled_line_gap);
+
+ /* fill baked font */
+ if (!cfg->merge_mode) {
+ dst_font->ranges = cfg->range;
+ dst_font->height = cfg->size;
+ dst_font->ascent = ((float)unscaled_ascent * font_scale);
+ dst_font->descent = ((float)unscaled_descent * font_scale);
+ dst_font->glyph_offset = glyph_n;
+ /*
+ Need to zero this, or it will carry over from a previous
+ bake, and cause a segfault when accessing glyphs[].
+ */
+ dst_font->glyph_count = 0;
+ }
+
+ /* fill own baked font glyph array */
+ for (i = 0; i < tmp->range_count; ++i) {
+ stbtt_pack_range *range = &tmp->ranges[i];
+ for (char_idx = 0; char_idx < range->num_chars; char_idx++)
+ {
+ nk_rune codepoint = 0;
+ float dummy_x = 0, dummy_y = 0;
+ stbtt_aligned_quad q;
+ struct nk_font_glyph *glyph;
+
+ /* query glyph bounds from stb_truetype */
+ const stbtt_packedchar *pc = &range->chardata_for_range[char_idx];
+ codepoint = (nk_rune)(range->first_unicode_codepoint_in_range + char_idx);
+ stbtt_GetPackedQuad(range->chardata_for_range, (int)width,
+ (int)height, char_idx, &dummy_x, &dummy_y, &q, 0);
+
+ /* fill own glyph type with data */
+ glyph = &glyphs[dst_font->glyph_offset + dst_font->glyph_count + (unsigned int)glyph_count];
+ glyph->codepoint = codepoint;
+ glyph->x0 = q.x0; glyph->y0 = q.y0;
+ glyph->x1 = q.x1; glyph->y1 = q.y1;
+ glyph->y0 += (dst_font->ascent + 0.5f);
+ glyph->y1 += (dst_font->ascent + 0.5f);
+ glyph->w = glyph->x1 - glyph->x0 + 0.5f;
+ glyph->h = glyph->y1 - glyph->y0;
+
+ if (cfg->coord_type == NK_COORD_PIXEL) {
+ glyph->u0 = q.s0 * (float)width;
+ glyph->v0 = q.t0 * (float)height;
+ glyph->u1 = q.s1 * (float)width;
+ glyph->v1 = q.t1 * (float)height;
+ } else {
+ glyph->u0 = q.s0;
+ glyph->v0 = q.t0;
+ glyph->u1 = q.s1;
+ glyph->v1 = q.t1;
+ }
+ glyph->xadvance = (pc->xadvance + cfg->spacing.x);
+ if (cfg->pixel_snap)
+ glyph->xadvance = (float)(int)(glyph->xadvance + 0.5f);
+ glyph_count++;
+ }
+ }
+ dst_font->glyph_count += glyph_count;
+ glyph_n += glyph_count;
+ } while ((it = it->n) != config_iter);
+ }
+}
+NK_INTERN void
+nk_font_bake_custom_data(void *img_memory, int img_width, int img_height,
+ struct nk_recti img_dst, const char *texture_data_mask, int tex_width,
+ int tex_height, char white, char black)
+{
+ nk_byte *pixels;
+ int y = 0;
+ int x = 0;
+ int n = 0;
+
+ NK_ASSERT(img_memory);
+ NK_ASSERT(img_width);
+ NK_ASSERT(img_height);
+ NK_ASSERT(texture_data_mask);
+ NK_UNUSED(tex_height);
+ if (!img_memory || !img_width || !img_height || !texture_data_mask)
+ return;
+
+ pixels = (nk_byte*)img_memory;
+ for (y = 0, n = 0; y < tex_height; ++y) {
+ for (x = 0; x < tex_width; ++x, ++n) {
+ const int off0 = ((img_dst.x + x) + (img_dst.y + y) * img_width);
+ const int off1 = off0 + 1 + tex_width;
+ pixels[off0] = (texture_data_mask[n] == white) ? 0xFF : 0x00;
+ pixels[off1] = (texture_data_mask[n] == black) ? 0xFF : 0x00;
+ }
+ }
+}
+NK_INTERN void
+nk_font_bake_convert(void *out_memory, int img_width, int img_height,
+ const void *in_memory)
+{
+ int n = 0;
+ nk_rune *dst;
+ const nk_byte *src;
+
+ NK_ASSERT(out_memory);
+ NK_ASSERT(in_memory);
+ NK_ASSERT(img_width);
+ NK_ASSERT(img_height);
+ if (!out_memory || !in_memory || !img_height || !img_width) return;
+
+ dst = (nk_rune*)out_memory;
+ src = (const nk_byte*)in_memory;
+ for (n = (int)(img_width * img_height); n > 0; n--)
+ *dst++ = ((nk_rune)(*src++) << 24) | 0x00FFFFFF;
+}
+
+/* -------------------------------------------------------------
+ *
+ * FONT
+ *
+ * --------------------------------------------------------------*/
+NK_INTERN float
+nk_font_text_width(nk_handle handle, float height, const char *text, int len)
+{
+ nk_rune unicode;
+ int text_len = 0;
+ float text_width = 0;
+ int glyph_len = 0;
+ float scale = 0;
+
+ struct nk_font *font = (struct nk_font*)handle.ptr;
+ NK_ASSERT(font);
+ NK_ASSERT(font->glyphs);
+ if (!font || !text || !len)
+ return 0;
+
+ scale = height/font->info.height;
+ glyph_len = text_len = nk_utf_decode(text, &unicode, (int)len);
+ if (!glyph_len) return 0;
+ while (text_len <= (int)len && glyph_len) {
+ const struct nk_font_glyph *g;
+ if (unicode == NK_UTF_INVALID) break;
+
+ /* query currently drawn glyph information */
+ g = nk_font_find_glyph(font, unicode);
+ text_width += g->xadvance * scale;
+
+ /* offset next glyph */
+ glyph_len = nk_utf_decode(text + text_len, &unicode, (int)len - text_len);
+ text_len += glyph_len;
+ }
+ return text_width;
+}
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+NK_INTERN void
+nk_font_query_font_glyph(nk_handle handle, float height,
+ struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint)
+{
+ float scale;
+ const struct nk_font_glyph *g;
+ struct nk_font *font;
+
+ NK_ASSERT(glyph);
+ NK_UNUSED(next_codepoint);
+
+ font = (struct nk_font*)handle.ptr;
+ NK_ASSERT(font);
+ NK_ASSERT(font->glyphs);
+ if (!font || !glyph)
+ return;
+
+ scale = height/font->info.height;
+ g = nk_font_find_glyph(font, codepoint);
+ glyph->width = (g->x1 - g->x0) * scale;
+ glyph->height = (g->y1 - g->y0) * scale;
+ glyph->offset = nk_vec2(g->x0 * scale, g->y0 * scale);
+ glyph->xadvance = (g->xadvance * scale);
+ glyph->uv[0] = nk_vec2(g->u0, g->v0);
+ glyph->uv[1] = nk_vec2(g->u1, g->v1);
+}
+#endif
+NK_API const struct nk_font_glyph*
+nk_font_find_glyph(struct nk_font *font, nk_rune unicode)
+{
+ int i = 0;
+ int count;
+ int total_glyphs = 0;
+ const struct nk_font_glyph *glyph = 0;
+ const struct nk_font_config *iter = 0;
+
+ NK_ASSERT(font);
+ NK_ASSERT(font->glyphs);
+ NK_ASSERT(font->info.ranges);
+ if (!font || !font->glyphs) return 0;
+
+ glyph = font->fallback;
+ iter = font->config;
+ do {count = nk_range_count(iter->range);
+ for (i = 0; i < count; ++i) {
+ nk_rune f = iter->range[(i*2)+0];
+ nk_rune t = iter->range[(i*2)+1];
+ int diff = (int)((t - f) + 1);
+ if (unicode >= f && unicode <= t)
+ return &font->glyphs[((nk_rune)total_glyphs + (unicode - f))];
+ total_glyphs += diff;
+ }
+ } while ((iter = iter->n) != font->config);
+ return glyph;
+}
+NK_INTERN void
+nk_font_init(struct nk_font *font, float pixel_height,
+ nk_rune fallback_codepoint, struct nk_font_glyph *glyphs,
+ const struct nk_baked_font *baked_font, nk_handle atlas)
+{
+ struct nk_baked_font baked;
+ NK_ASSERT(font);
+ NK_ASSERT(glyphs);
+ NK_ASSERT(baked_font);
+ if (!font || !glyphs || !baked_font)
+ return;
+
+ baked = *baked_font;
+ font->fallback = 0;
+ font->info = baked;
+ font->scale = (float)pixel_height / (float)font->info.height;
+ font->glyphs = &glyphs[baked_font->glyph_offset];
+ font->texture = atlas;
+ font->fallback_codepoint = fallback_codepoint;
+ font->fallback = nk_font_find_glyph(font, fallback_codepoint);
+
+ font->handle.height = font->info.height * font->scale;
+ font->handle.width = nk_font_text_width;
+ font->handle.userdata.ptr = font;
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+ font->handle.query = nk_font_query_font_glyph;
+ font->handle.texture = font->texture;
+#endif
+}
+
+/* ---------------------------------------------------------------------------
+ *
+ * DEFAULT FONT
+ *
+ * ProggyClean.ttf
+ * Copyright (c) 2004, 2005 Tristan Grimmer
+ * MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip)
+ * Download and more information at http://upperbounds.net
+ *-----------------------------------------------------------------------------*/
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Woverlength-strings"
+#elif defined(__GNUC__) || defined(__GNUG__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Woverlength-strings"
+#endif
+
+#ifdef NK_INCLUDE_DEFAULT_FONT
+
+NK_GLOBAL const char nk_proggy_clean_ttf_compressed_data_base85[11980+1] =
+ "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/"
+ "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N"
+ "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`j@'DbG^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc."
+ "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G"
+ "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)"
+ "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#"
+ "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM"
+ "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu"
+ "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/"
+ "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO"
+ "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:Fce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%"
+ "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]"
+ "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et"
+ "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:"
+ "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>QWIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M"
+ "D?@f&1'BW-)Ju#bmmWCMkkTR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX("
+ "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs"
+ "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q"
+ "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-"
+ "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCFB^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i"
+ "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7"
+ ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@"
+ "$&)WHtPm*5_rO0&e%K-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*"
+ "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u"
+ "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae"
+ "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s-aFRNQv>o8lKN%5/$(vdfq7+ebA#"
+ "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8"
+ "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c"
+ "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hLSfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5"
+ "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%"
+ "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJAYJ//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;"
+ "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:"
+ "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-"
+ "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*"
+ "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-"
+ "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj"
+ "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa"
+ ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>"
+ "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`Peb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I"
+ "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)"
+ "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuGVf1398/pVo"
+ "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P"
+ "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO"
+ "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#"
+ ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T"
+ "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4"
+ "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#"
+ "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP"
+ "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp"
+ "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#";
+
+#endif /* NK_INCLUDE_DEFAULT_FONT */
+
+#define NK_CURSOR_DATA_W 90
+#define NK_CURSOR_DATA_H 27
+NK_GLOBAL const char nk_custom_cursor_data[NK_CURSOR_DATA_W * NK_CURSOR_DATA_H + 1] =
+{
+ "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX"
+ "..- -X.....X- X.X - X.X -X.....X - X.....X"
+ "--- -XXX.XXX- X...X - X...X -X....X - X....X"
+ "X - X.X - X.....X - X.....X -X...X - X...X"
+ "XX - X.X -X.......X- X.......X -X..X.X - X.X..X"
+ "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X"
+ "X..X - X.X - X.X - X.X -XX X.X - X.X XX"
+ "X...X - X.X - X.X - XX X.X XX - X.X - X.X "
+ "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X "
+ "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X "
+ "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X "
+ "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X "
+ "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X "
+ "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X "
+ "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X "
+ "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X "
+ "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX "
+ "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------"
+ "X.X X..X - -X.......X- X.......X - XX XX - "
+ "XX X..X - - X.....X - X.....X - X.X X.X - "
+ " X..X - X...X - X...X - X..X X..X - "
+ " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - "
+ "------------ - X - X -X.....................X- "
+ " ----------------------------------- X...XXXXXXXXXXXXX...X - "
+ " - X..X X..X - "
+ " - X.X X.X - "
+ " - XX XX - "
+};
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#elif defined(__GNUC__) || defined(__GNUG__)
+#pragma GCC diagnostic pop
+#endif
+
+NK_GLOBAL unsigned char *nk__barrier;
+NK_GLOBAL unsigned char *nk__barrier2;
+NK_GLOBAL unsigned char *nk__barrier3;
+NK_GLOBAL unsigned char *nk__barrier4;
+NK_GLOBAL unsigned char *nk__dout;
+
+NK_INTERN unsigned int
+nk_decompress_length(unsigned char *input)
+{
+ return (unsigned int)((input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]);
+}
+NK_INTERN void
+nk__match(unsigned char *data, unsigned int length)
+{
+ /* INVERSE of memmove... write each byte before copying the next...*/
+ NK_ASSERT (nk__dout + length <= nk__barrier);
+ if (nk__dout + length > nk__barrier) { nk__dout += length; return; }
+ if (data < nk__barrier4) { nk__dout = nk__barrier+1; return; }
+ while (length--) *nk__dout++ = *data++;
+}
+NK_INTERN void
+nk__lit(unsigned char *data, unsigned int length)
+{
+ NK_ASSERT (nk__dout + length <= nk__barrier);
+ if (nk__dout + length > nk__barrier) { nk__dout += length; return; }
+ if (data < nk__barrier2) { nk__dout = nk__barrier+1; return; }
+ NK_MEMCPY(nk__dout, data, length);
+ nk__dout += length;
+}
+NK_INTERN unsigned char*
+nk_decompress_token(unsigned char *i)
+{
+ #define nk__in2(x) ((i[x] << 8) + i[(x)+1])
+ #define nk__in3(x) ((i[x] << 16) + nk__in2((x)+1))
+ #define nk__in4(x) ((i[x] << 24) + nk__in3((x)+1))
+
+ if (*i >= 0x20) { /* use fewer if's for cases that expand small */
+ if (*i >= 0x80) nk__match(nk__dout-i[1]-1, (unsigned int)i[0] - 0x80 + 1), i += 2;
+ else if (*i >= 0x40) nk__match(nk__dout-(nk__in2(0) - 0x4000 + 1), (unsigned int)i[2]+1), i += 3;
+ else /* *i >= 0x20 */ nk__lit(i+1, (unsigned int)i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);
+ } else { /* more ifs for cases that expand large, since overhead is amortized */
+ if (*i >= 0x18) nk__match(nk__dout-(unsigned int)(nk__in3(0) - 0x180000 + 1), (unsigned int)i[3]+1), i += 4;
+ else if (*i >= 0x10) nk__match(nk__dout-(unsigned int)(nk__in3(0) - 0x100000 + 1), (unsigned int)nk__in2(3)+1), i += 5;
+ else if (*i >= 0x08) nk__lit(i+2, (unsigned int)nk__in2(0) - 0x0800 + 1), i += 2 + (nk__in2(0) - 0x0800 + 1);
+ else if (*i == 0x07) nk__lit(i+3, (unsigned int)nk__in2(1) + 1), i += 3 + (nk__in2(1) + 1);
+ else if (*i == 0x06) nk__match(nk__dout-(unsigned int)(nk__in3(1)+1), i[4]+1u), i += 5;
+ else if (*i == 0x04) nk__match(nk__dout-(unsigned int)(nk__in3(1)+1), (unsigned int)nk__in2(4)+1u), i += 6;
+ }
+ return i;
+}
+NK_INTERN unsigned int
+nk_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen)
+{
+ const unsigned long ADLER_MOD = 65521;
+ unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
+ unsigned long blocklen, i;
+
+ blocklen = buflen % 5552;
+ while (buflen) {
+ for (i=0; i + 7 < blocklen; i += 8) {
+ s1 += buffer[0]; s2 += s1;
+ s1 += buffer[1]; s2 += s1;
+ s1 += buffer[2]; s2 += s1;
+ s1 += buffer[3]; s2 += s1;
+ s1 += buffer[4]; s2 += s1;
+ s1 += buffer[5]; s2 += s1;
+ s1 += buffer[6]; s2 += s1;
+ s1 += buffer[7]; s2 += s1;
+ buffer += 8;
+ }
+ for (; i < blocklen; ++i) {
+ s1 += *buffer++; s2 += s1;
+ }
+
+ s1 %= ADLER_MOD; s2 %= ADLER_MOD;
+ buflen -= (unsigned int)blocklen;
+ blocklen = 5552;
+ }
+ return (unsigned int)(s2 << 16) + (unsigned int)s1;
+}
+NK_INTERN unsigned int
+nk_decompress(unsigned char *output, unsigned char *i, unsigned int length)
+{
+ unsigned int olen;
+ if (nk__in4(0) != 0x57bC0000) return 0;
+ if (nk__in4(4) != 0) return 0; /* error! stream is > 4GB */
+ olen = nk_decompress_length(i);
+ nk__barrier2 = i;
+ nk__barrier3 = i+length;
+ nk__barrier = output + olen;
+ nk__barrier4 = output;
+ i += 16;
+
+ nk__dout = output;
+ for (;;) {
+ unsigned char *old_i = i;
+ i = nk_decompress_token(i);
+ if (i == old_i) {
+ if (*i == 0x05 && i[1] == 0xfa) {
+ NK_ASSERT(nk__dout == output + olen);
+ if (nk__dout != output + olen) return 0;
+ if (nk_adler32(1, output, olen) != (unsigned int) nk__in4(2))
+ return 0;
+ return olen;
+ } else {
+ NK_ASSERT(0); /* NOTREACHED */
+ return 0;
+ }
+ }
+ NK_ASSERT(nk__dout <= output + olen);
+ if (nk__dout > output + olen)
+ return 0;
+ }
+}
+NK_INTERN unsigned int
+nk_decode_85_byte(char c)
+{
+ return (unsigned int)((c >= '\\') ? c-36 : c-35);
+}
+NK_INTERN void
+nk_decode_85(unsigned char* dst, const unsigned char* src)
+{
+ while (*src)
+ {
+ unsigned int tmp =
+ nk_decode_85_byte((char)src[0]) +
+ 85 * (nk_decode_85_byte((char)src[1]) +
+ 85 * (nk_decode_85_byte((char)src[2]) +
+ 85 * (nk_decode_85_byte((char)src[3]) +
+ 85 * nk_decode_85_byte((char)src[4]))));
+
+ /* we can't assume little-endianess. */
+ dst[0] = (unsigned char)((tmp >> 0) & 0xFF);
+ dst[1] = (unsigned char)((tmp >> 8) & 0xFF);
+ dst[2] = (unsigned char)((tmp >> 16) & 0xFF);
+ dst[3] = (unsigned char)((tmp >> 24) & 0xFF);
+
+ src += 5;
+ dst += 4;
+ }
+}
+
+/* -------------------------------------------------------------
+ *
+ * FONT ATLAS
+ *
+ * --------------------------------------------------------------*/
+NK_API struct nk_font_config
+nk_font_config(float pixel_height)
+{
+ struct nk_font_config cfg;
+ nk_zero_struct(cfg);
+ cfg.ttf_blob = 0;
+ cfg.ttf_size = 0;
+ cfg.ttf_data_owned_by_atlas = 0;
+ cfg.size = pixel_height;
+ cfg.oversample_h = 3;
+ cfg.oversample_v = 1;
+ cfg.pixel_snap = 0;
+ cfg.coord_type = NK_COORD_UV;
+ cfg.spacing = nk_vec2(0,0);
+ cfg.range = nk_font_default_glyph_ranges();
+ cfg.merge_mode = 0;
+ cfg.fallback_glyph = '?';
+ cfg.font = 0;
+ cfg.n = 0;
+ return cfg;
+}
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void
+nk_font_atlas_init_default(struct nk_font_atlas *atlas)
+{
+ NK_ASSERT(atlas);
+ if (!atlas) return;
+ nk_zero_struct(*atlas);
+ atlas->temporary.userdata.ptr = 0;
+ atlas->temporary.alloc = nk_malloc;
+ atlas->temporary.free = nk_mfree;
+ atlas->permanent.userdata.ptr = 0;
+ atlas->permanent.alloc = nk_malloc;
+ atlas->permanent.free = nk_mfree;
+}
+#endif
+NK_API void
+nk_font_atlas_init(struct nk_font_atlas *atlas, struct nk_allocator *alloc)
+{
+ NK_ASSERT(atlas);
+ NK_ASSERT(alloc);
+ if (!atlas || !alloc) return;
+ nk_zero_struct(*atlas);
+ atlas->permanent = *alloc;
+ atlas->temporary = *alloc;
+}
+NK_API void
+nk_font_atlas_init_custom(struct nk_font_atlas *atlas,
+ struct nk_allocator *permanent, struct nk_allocator *temporary)
+{
+ NK_ASSERT(atlas);
+ NK_ASSERT(permanent);
+ NK_ASSERT(temporary);
+ if (!atlas || !permanent || !temporary) return;
+ nk_zero_struct(*atlas);
+ atlas->permanent = *permanent;
+ atlas->temporary = *temporary;
+}
+NK_API void
+nk_font_atlas_begin(struct nk_font_atlas *atlas)
+{
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc && atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc && atlas->permanent.free);
+ if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free ||
+ !atlas->temporary.alloc || !atlas->temporary.free) return;
+ if (atlas->glyphs) {
+ atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs);
+ atlas->glyphs = 0;
+ }
+ if (atlas->pixel) {
+ atlas->permanent.free(atlas->permanent.userdata, atlas->pixel);
+ atlas->pixel = 0;
+ }
+}
+NK_API struct nk_font*
+nk_font_atlas_add(struct nk_font_atlas *atlas, const struct nk_font_config *config)
+{
+ struct nk_font *font = 0;
+ struct nk_font_config *cfg;
+
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+
+ NK_ASSERT(config);
+ NK_ASSERT(config->ttf_blob);
+ NK_ASSERT(config->ttf_size);
+ NK_ASSERT(config->size > 0.0f);
+
+ if (!atlas || !config || !config->ttf_blob || !config->ttf_size || config->size <= 0.0f||
+ !atlas->permanent.alloc || !atlas->permanent.free ||
+ !atlas->temporary.alloc || !atlas->temporary.free)
+ return 0;
+
+ /* allocate font config */
+ cfg = (struct nk_font_config*)
+ atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font_config));
+ NK_MEMCPY(cfg, config, sizeof(*config));
+ cfg->n = cfg;
+ cfg->p = cfg;
+
+ if (!config->merge_mode) {
+ /* insert font config into list */
+ if (!atlas->config) {
+ atlas->config = cfg;
+ cfg->next = 0;
+ } else {
+ struct nk_font_config *i = atlas->config;
+ while (i->next) i = i->next;
+ i->next = cfg;
+ cfg->next = 0;
+ }
+ /* allocate new font */
+ font = (struct nk_font*)
+ atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font));
+ NK_ASSERT(font);
+ nk_zero(font, sizeof(*font));
+ if (!font) return 0;
+ font->config = cfg;
+
+ /* insert font into list */
+ if (!atlas->fonts) {
+ atlas->fonts = font;
+ font->next = 0;
+ } else {
+ struct nk_font *i = atlas->fonts;
+ while (i->next) i = i->next;
+ i->next = font;
+ font->next = 0;
+ }
+ cfg->font = &font->info;
+ } else {
+ /* extend previously added font */
+ struct nk_font *f = 0;
+ struct nk_font_config *c = 0;
+ NK_ASSERT(atlas->font_num);
+ f = atlas->fonts;
+ c = f->config;
+ cfg->font = &f->info;
+
+ cfg->n = c;
+ cfg->p = c->p;
+ c->p->n = cfg;
+ c->p = cfg;
+ }
+ /* create own copy of .TTF font blob */
+ if (!config->ttf_data_owned_by_atlas) {
+ cfg->ttf_blob = atlas->permanent.alloc(atlas->permanent.userdata,0, cfg->ttf_size);
+ NK_ASSERT(cfg->ttf_blob);
+ if (!cfg->ttf_blob) {
+ atlas->font_num++;
+ return 0;
+ }
+ NK_MEMCPY(cfg->ttf_blob, config->ttf_blob, cfg->ttf_size);
+ cfg->ttf_data_owned_by_atlas = 1;
+ }
+ atlas->font_num++;
+ return font;
+}
+NK_API struct nk_font*
+nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory,
+ nk_size size, float height, const struct nk_font_config *config)
+{
+ struct nk_font_config cfg;
+ NK_ASSERT(memory);
+ NK_ASSERT(size);
+
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+ if (!atlas || !atlas->temporary.alloc || !atlas->temporary.free || !memory || !size ||
+ !atlas->permanent.alloc || !atlas->permanent.free)
+ return 0;
+
+ cfg = (config) ? *config: nk_font_config(height);
+ cfg.ttf_blob = memory;
+ cfg.ttf_size = size;
+ cfg.size = height;
+ cfg.ttf_data_owned_by_atlas = 0;
+ return nk_font_atlas_add(atlas, &cfg);
+}
+#ifdef NK_INCLUDE_STANDARD_IO
+NK_API struct nk_font*
+nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path,
+ float height, const struct nk_font_config *config)
+{
+ nk_size size;
+ char *memory;
+ struct nk_font_config cfg;
+
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+
+ if (!atlas || !file_path) return 0;
+ memory = nk_file_load(file_path, &size, &atlas->permanent);
+ if (!memory) return 0;
+
+ cfg = (config) ? *config: nk_font_config(height);
+ cfg.ttf_blob = memory;
+ cfg.ttf_size = size;
+ cfg.size = height;
+ cfg.ttf_data_owned_by_atlas = 1;
+ return nk_font_atlas_add(atlas, &cfg);
+}
+#endif
+NK_API struct nk_font*
+nk_font_atlas_add_compressed(struct nk_font_atlas *atlas,
+ void *compressed_data, nk_size compressed_size, float height,
+ const struct nk_font_config *config)
+{
+ unsigned int decompressed_size;
+ void *decompressed_data;
+ struct nk_font_config cfg;
+
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+
+ NK_ASSERT(compressed_data);
+ NK_ASSERT(compressed_size);
+ if (!atlas || !compressed_data || !atlas->temporary.alloc || !atlas->temporary.free ||
+ !atlas->permanent.alloc || !atlas->permanent.free)
+ return 0;
+
+ decompressed_size = nk_decompress_length((unsigned char*)compressed_data);
+ decompressed_data = atlas->permanent.alloc(atlas->permanent.userdata,0,decompressed_size);
+ NK_ASSERT(decompressed_data);
+ if (!decompressed_data) return 0;
+ nk_decompress((unsigned char*)decompressed_data, (unsigned char*)compressed_data,
+ (unsigned int)compressed_size);
+
+ cfg = (config) ? *config: nk_font_config(height);
+ cfg.ttf_blob = decompressed_data;
+ cfg.ttf_size = decompressed_size;
+ cfg.size = height;
+ cfg.ttf_data_owned_by_atlas = 1;
+ return nk_font_atlas_add(atlas, &cfg);
+}
+NK_API struct nk_font*
+nk_font_atlas_add_compressed_base85(struct nk_font_atlas *atlas,
+ const char *data_base85, float height, const struct nk_font_config *config)
+{
+ int compressed_size;
+ void *compressed_data;
+ struct nk_font *font;
+
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+
+ NK_ASSERT(data_base85);
+ if (!atlas || !data_base85 || !atlas->temporary.alloc || !atlas->temporary.free ||
+ !atlas->permanent.alloc || !atlas->permanent.free)
+ return 0;
+
+ compressed_size = (((int)nk_strlen(data_base85) + 4) / 5) * 4;
+ compressed_data = atlas->temporary.alloc(atlas->temporary.userdata,0, (nk_size)compressed_size);
+ NK_ASSERT(compressed_data);
+ if (!compressed_data) return 0;
+ nk_decode_85((unsigned char*)compressed_data, (const unsigned char*)data_base85);
+ font = nk_font_atlas_add_compressed(atlas, compressed_data,
+ (nk_size)compressed_size, height, config);
+ atlas->temporary.free(atlas->temporary.userdata, compressed_data);
+ return font;
+}
+
+#ifdef NK_INCLUDE_DEFAULT_FONT
+NK_API struct nk_font*
+nk_font_atlas_add_default(struct nk_font_atlas *atlas,
+ float pixel_height, const struct nk_font_config *config)
+{
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+ return nk_font_atlas_add_compressed_base85(atlas,
+ nk_proggy_clean_ttf_compressed_data_base85, pixel_height, config);
+}
+#endif
+NK_API const void*
+nk_font_atlas_bake(struct nk_font_atlas *atlas, int *width, int *height,
+ enum nk_font_atlas_format fmt)
+{
+ int i = 0;
+ void *tmp = 0;
+ nk_size tmp_size, img_size;
+ struct nk_font *font_iter;
+ struct nk_font_baker *baker;
+
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+
+ NK_ASSERT(width);
+ NK_ASSERT(height);
+ if (!atlas || !width || !height ||
+ !atlas->temporary.alloc || !atlas->temporary.free ||
+ !atlas->permanent.alloc || !atlas->permanent.free)
+ return 0;
+
+#ifdef NK_INCLUDE_DEFAULT_FONT
+ /* no font added so just use default font */
+ if (!atlas->font_num)
+ atlas->default_font = nk_font_atlas_add_default(atlas, 13.0f, 0);
+#endif
+ NK_ASSERT(atlas->font_num);
+ if (!atlas->font_num) return 0;
+
+ /* allocate temporary baker memory required for the baking process */
+ nk_font_baker_memory(&tmp_size, &atlas->glyph_count, atlas->config, atlas->font_num);
+ tmp = atlas->temporary.alloc(atlas->temporary.userdata,0, tmp_size);
+ NK_ASSERT(tmp);
+ if (!tmp) goto failed;
+ NK_MEMSET(tmp,0,tmp_size);
+
+ /* allocate glyph memory for all fonts */
+ baker = nk_font_baker(tmp, atlas->glyph_count, atlas->font_num, &atlas->temporary);
+ atlas->glyphs = (struct nk_font_glyph*)atlas->permanent.alloc(
+ atlas->permanent.userdata,0, sizeof(struct nk_font_glyph)*(nk_size)atlas->glyph_count);
+ NK_ASSERT(atlas->glyphs);
+ if (!atlas->glyphs)
+ goto failed;
+
+ /* pack all glyphs into a tight fit space */
+ atlas->custom.w = (NK_CURSOR_DATA_W*2)+1;
+ atlas->custom.h = NK_CURSOR_DATA_H + 1;
+ if (!nk_font_bake_pack(baker, &img_size, width, height, &atlas->custom,
+ atlas->config, atlas->font_num, &atlas->temporary))
+ goto failed;
+
+ /* allocate memory for the baked image font atlas */
+ atlas->pixel = atlas->temporary.alloc(atlas->temporary.userdata,0, img_size);
+ NK_ASSERT(atlas->pixel);
+ if (!atlas->pixel)
+ goto failed;
+
+ /* bake glyphs and custom white pixel into image */
+ nk_font_bake(baker, atlas->pixel, *width, *height,
+ atlas->glyphs, atlas->glyph_count, atlas->config, atlas->font_num);
+ nk_font_bake_custom_data(atlas->pixel, *width, *height, atlas->custom,
+ nk_custom_cursor_data, NK_CURSOR_DATA_W, NK_CURSOR_DATA_H, '.', 'X');
+
+ if (fmt == NK_FONT_ATLAS_RGBA32) {
+ /* convert alpha8 image into rgba32 image */
+ void *img_rgba = atlas->temporary.alloc(atlas->temporary.userdata,0,
+ (nk_size)(*width * *height * 4));
+ NK_ASSERT(img_rgba);
+ if (!img_rgba) goto failed;
+ nk_font_bake_convert(img_rgba, *width, *height, atlas->pixel);
+ atlas->temporary.free(atlas->temporary.userdata, atlas->pixel);
+ atlas->pixel = img_rgba;
+ }
+ atlas->tex_width = *width;
+ atlas->tex_height = *height;
+
+ /* initialize each font */
+ for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) {
+ struct nk_font *font = font_iter;
+ struct nk_font_config *config = font->config;
+ nk_font_init(font, config->size, config->fallback_glyph, atlas->glyphs,
+ config->font, nk_handle_ptr(0));
+ }
+
+ /* initialize each cursor */
+ {NK_STORAGE const struct nk_vec2 nk_cursor_data[NK_CURSOR_COUNT][3] = {
+ /* Pos Size Offset */
+ {{ 0, 3}, {12,19}, { 0, 0}},
+ {{13, 0}, { 7,16}, { 4, 8}},
+ {{31, 0}, {23,23}, {11,11}},
+ {{21, 0}, { 9, 23}, { 5,11}},
+ {{55,18}, {23, 9}, {11, 5}},
+ {{73, 0}, {17,17}, { 9, 9}},
+ {{55, 0}, {17,17}, { 9, 9}}
+ };
+ for (i = 0; i < NK_CURSOR_COUNT; ++i) {
+ struct nk_cursor *cursor = &atlas->cursors[i];
+ cursor->img.w = (unsigned short)*width;
+ cursor->img.h = (unsigned short)*height;
+ cursor->img.region[0] = (unsigned short)(atlas->custom.x + nk_cursor_data[i][0].x);
+ cursor->img.region[1] = (unsigned short)(atlas->custom.y + nk_cursor_data[i][0].y);
+ cursor->img.region[2] = (unsigned short)nk_cursor_data[i][1].x;
+ cursor->img.region[3] = (unsigned short)nk_cursor_data[i][1].y;
+ cursor->size = nk_cursor_data[i][1];
+ cursor->offset = nk_cursor_data[i][2];
+ }}
+ /* free temporary memory */
+ atlas->temporary.free(atlas->temporary.userdata, tmp);
+ return atlas->pixel;
+
+failed:
+ /* error so cleanup all memory */
+ if (tmp) atlas->temporary.free(atlas->temporary.userdata, tmp);
+ if (atlas->glyphs) {
+ atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs);
+ atlas->glyphs = 0;
+ }
+ if (atlas->pixel) {
+ atlas->temporary.free(atlas->temporary.userdata, atlas->pixel);
+ atlas->pixel = 0;
+ }
+ return 0;
+}
+NK_API void
+nk_font_atlas_end(struct nk_font_atlas *atlas, nk_handle texture,
+ struct nk_draw_null_texture *tex_null)
+{
+ int i = 0;
+ struct nk_font *font_iter;
+ NK_ASSERT(atlas);
+ if (!atlas) {
+ if (!tex_null) return;
+ tex_null->texture = texture;
+ tex_null->uv = nk_vec2(0.5f,0.5f);
+ }
+ if (tex_null) {
+ tex_null->texture = texture;
+ tex_null->uv.x = (atlas->custom.x + 0.5f)/(float)atlas->tex_width;
+ tex_null->uv.y = (atlas->custom.y + 0.5f)/(float)atlas->tex_height;
+ }
+ for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) {
+ font_iter->texture = texture;
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+ font_iter->handle.texture = texture;
+#endif
+ }
+ for (i = 0; i < NK_CURSOR_COUNT; ++i)
+ atlas->cursors[i].img.handle = texture;
+
+ atlas->temporary.free(atlas->temporary.userdata, atlas->pixel);
+ atlas->pixel = 0;
+ atlas->tex_width = 0;
+ atlas->tex_height = 0;
+ atlas->custom.x = 0;
+ atlas->custom.y = 0;
+ atlas->custom.w = 0;
+ atlas->custom.h = 0;
+}
+NK_API void
+nk_font_atlas_cleanup(struct nk_font_atlas *atlas)
+{
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+ if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free) return;
+ if (atlas->config) {
+ struct nk_font_config *iter;
+ for (iter = atlas->config; iter; iter = iter->next) {
+ struct nk_font_config *i;
+ for (i = iter->n; i != iter; i = i->n) {
+ atlas->permanent.free(atlas->permanent.userdata, i->ttf_blob);
+ i->ttf_blob = 0;
+ }
+ atlas->permanent.free(atlas->permanent.userdata, iter->ttf_blob);
+ iter->ttf_blob = 0;
+ }
+ }
+}
+NK_API void
+nk_font_atlas_clear(struct nk_font_atlas *atlas)
+{
+ NK_ASSERT(atlas);
+ NK_ASSERT(atlas->temporary.alloc);
+ NK_ASSERT(atlas->temporary.free);
+ NK_ASSERT(atlas->permanent.alloc);
+ NK_ASSERT(atlas->permanent.free);
+ if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free) return;
+
+ if (atlas->config) {
+ struct nk_font_config *iter, *next;
+ for (iter = atlas->config; iter; iter = next) {
+ struct nk_font_config *i, *n;
+ for (i = iter->n; i != iter; i = n) {
+ n = i->n;
+ if (i->ttf_blob)
+ atlas->permanent.free(atlas->permanent.userdata, i->ttf_blob);
+ atlas->permanent.free(atlas->permanent.userdata, i);
+ }
+ next = iter->next;
+ if (i->ttf_blob)
+ atlas->permanent.free(atlas->permanent.userdata, iter->ttf_blob);
+ atlas->permanent.free(atlas->permanent.userdata, iter);
+ }
+ atlas->config = 0;
+ }
+ if (atlas->fonts) {
+ struct nk_font *iter, *next;
+ for (iter = atlas->fonts; iter; iter = next) {
+ next = iter->next;
+ atlas->permanent.free(atlas->permanent.userdata, iter);
+ }
+ atlas->fonts = 0;
+ }
+ if (atlas->glyphs)
+ atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs);
+ nk_zero_struct(*atlas);
+}
+#endif
+
+
+
+
+
+/* ===============================================================
+ *
+ * INPUT
+ *
+ * ===============================================================*/
+NK_API void
+nk_input_begin(struct nk_context *ctx)
+{
+ int i;
+ struct nk_input *in;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ in = &ctx->input;
+ for (i = 0; i < NK_BUTTON_MAX; ++i)
+ in->mouse.buttons[i].clicked = 0;
+
+ in->keyboard.text_len = 0;
+ in->mouse.scroll_delta = nk_vec2(0,0);
+ in->mouse.prev.x = in->mouse.pos.x;
+ in->mouse.prev.y = in->mouse.pos.y;
+ in->mouse.delta.x = 0;
+ in->mouse.delta.y = 0;
+ for (i = 0; i < NK_KEY_MAX; i++)
+ in->keyboard.keys[i].clicked = 0;
+}
+NK_API void
+nk_input_end(struct nk_context *ctx)
+{
+ struct nk_input *in;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ in = &ctx->input;
+ if (in->mouse.grab)
+ in->mouse.grab = 0;
+ if (in->mouse.ungrab) {
+ in->mouse.grabbed = 0;
+ in->mouse.ungrab = 0;
+ in->mouse.grab = 0;
+ }
+}
+NK_API void
+nk_input_motion(struct nk_context *ctx, int x, int y)
+{
+ struct nk_input *in;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ in = &ctx->input;
+ in->mouse.pos.x = (float)x;
+ in->mouse.pos.y = (float)y;
+ in->mouse.delta.x = in->mouse.pos.x - in->mouse.prev.x;
+ in->mouse.delta.y = in->mouse.pos.y - in->mouse.prev.y;
+}
+NK_API void
+nk_input_key(struct nk_context *ctx, enum nk_keys key, nk_bool down)
+{
+ struct nk_input *in;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ in = &ctx->input;
+#ifdef NK_KEYSTATE_BASED_INPUT
+ if (in->keyboard.keys[key].down != down)
+ in->keyboard.keys[key].clicked++;
+#else
+ in->keyboard.keys[key].clicked++;
+#endif
+ in->keyboard.keys[key].down = down;
+}
+NK_API void
+nk_input_button(struct nk_context *ctx, enum nk_buttons id, int x, int y, nk_bool down)
+{
+ struct nk_mouse_button *btn;
+ struct nk_input *in;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ in = &ctx->input;
+ if (in->mouse.buttons[id].down == down) return;
+
+ btn = &in->mouse.buttons[id];
+ btn->clicked_pos.x = (float)x;
+ btn->clicked_pos.y = (float)y;
+ btn->down = down;
+ btn->clicked++;
+
+ /* Fix Click-Drag for touch events. */
+ in->mouse.delta.x = 0;
+ in->mouse.delta.y = 0;
+#ifdef NK_BUTTON_TRIGGER_ON_RELEASE
+ if (down == 1 && id == NK_BUTTON_LEFT)
+ {
+ in->mouse.down_pos.x = btn->clicked_pos.x;
+ in->mouse.down_pos.y = btn->clicked_pos.y;
+ }
+#endif
+}
+NK_API void
+nk_input_scroll(struct nk_context *ctx, struct nk_vec2 val)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ ctx->input.mouse.scroll_delta.x += val.x;
+ ctx->input.mouse.scroll_delta.y += val.y;
+}
+NK_API void
+nk_input_glyph(struct nk_context *ctx, const nk_glyph glyph)
+{
+ int len = 0;
+ nk_rune unicode;
+ struct nk_input *in;
+
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ in = &ctx->input;
+
+ len = nk_utf_decode(glyph, &unicode, NK_UTF_SIZE);
+ if (len && ((in->keyboard.text_len + len) < NK_INPUT_MAX)) {
+ nk_utf_encode(unicode, &in->keyboard.text[in->keyboard.text_len],
+ NK_INPUT_MAX - in->keyboard.text_len);
+ in->keyboard.text_len += len;
+ }
+}
+NK_API void
+nk_input_char(struct nk_context *ctx, char c)
+{
+ nk_glyph glyph;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ glyph[0] = c;
+ nk_input_glyph(ctx, glyph);
+}
+NK_API void
+nk_input_unicode(struct nk_context *ctx, nk_rune unicode)
+{
+ nk_glyph rune;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ nk_utf_encode(unicode, rune, NK_UTF_SIZE);
+ nk_input_glyph(ctx, rune);
+}
+NK_API nk_bool
+nk_input_has_mouse_click(const struct nk_input *i, enum nk_buttons id)
+{
+ const struct nk_mouse_button *btn;
+ if (!i) return nk_false;
+ btn = &i->mouse.buttons[id];
+ return (btn->clicked && btn->down == nk_false) ? nk_true : nk_false;
+}
+NK_API nk_bool
+nk_input_has_mouse_click_in_rect(const struct nk_input *i, enum nk_buttons id,
+ struct nk_rect b)
+{
+ const struct nk_mouse_button *btn;
+ if (!i) return nk_false;
+ btn = &i->mouse.buttons[id];
+ if (!NK_INBOX(btn->clicked_pos.x,btn->clicked_pos.y,b.x,b.y,b.w,b.h))
+ return nk_false;
+ return nk_true;
+}
+NK_API nk_bool
+nk_input_has_mouse_click_in_button_rect(const struct nk_input *i, enum nk_buttons id,
+ struct nk_rect b)
+{
+ const struct nk_mouse_button *btn;
+ if (!i) return nk_false;
+ btn = &i->mouse.buttons[id];
+#ifdef NK_BUTTON_TRIGGER_ON_RELEASE
+ if (!NK_INBOX(btn->clicked_pos.x,btn->clicked_pos.y,b.x,b.y,b.w,b.h)
+ || !NK_INBOX(i->mouse.down_pos.x,i->mouse.down_pos.y,b.x,b.y,b.w,b.h))
+#else
+ if (!NK_INBOX(btn->clicked_pos.x,btn->clicked_pos.y,b.x,b.y,b.w,b.h))
+#endif
+ return nk_false;
+ return nk_true;
+}
+NK_API nk_bool
+nk_input_has_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id,
+ struct nk_rect b, nk_bool down)
+{
+ const struct nk_mouse_button *btn;
+ if (!i) return nk_false;
+ btn = &i->mouse.buttons[id];
+ return nk_input_has_mouse_click_in_rect(i, id, b) && (btn->down == down);
+}
+NK_API nk_bool
+nk_input_is_mouse_click_in_rect(const struct nk_input *i, enum nk_buttons id,
+ struct nk_rect b)
+{
+ const struct nk_mouse_button *btn;
+ if (!i) return nk_false;
+ btn = &i->mouse.buttons[id];
+ return (nk_input_has_mouse_click_down_in_rect(i, id, b, nk_false) &&
+ btn->clicked) ? nk_true : nk_false;
+}
+NK_API nk_bool
+nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id,
+ struct nk_rect b, nk_bool down)
+{
+ const struct nk_mouse_button *btn;
+ if (!i) return nk_false;
+ btn = &i->mouse.buttons[id];
+ return (nk_input_has_mouse_click_down_in_rect(i, id, b, down) &&
+ btn->clicked) ? nk_true : nk_false;
+}
+NK_API nk_bool
+nk_input_any_mouse_click_in_rect(const struct nk_input *in, struct nk_rect b)
+{
+ int i, down = 0;
+ for (i = 0; i < NK_BUTTON_MAX; ++i)
+ down = down || nk_input_is_mouse_click_in_rect(in, (enum nk_buttons)i, b);
+ return down;
+}
+NK_API nk_bool
+nk_input_is_mouse_hovering_rect(const struct nk_input *i, struct nk_rect rect)
+{
+ if (!i) return nk_false;
+ return NK_INBOX(i->mouse.pos.x, i->mouse.pos.y, rect.x, rect.y, rect.w, rect.h);
+}
+NK_API nk_bool
+nk_input_is_mouse_prev_hovering_rect(const struct nk_input *i, struct nk_rect rect)
+{
+ if (!i) return nk_false;
+ return NK_INBOX(i->mouse.prev.x, i->mouse.prev.y, rect.x, rect.y, rect.w, rect.h);
+}
+NK_API nk_bool
+nk_input_mouse_clicked(const struct nk_input *i, enum nk_buttons id, struct nk_rect rect)
+{
+ if (!i) return nk_false;
+ if (!nk_input_is_mouse_hovering_rect(i, rect)) return nk_false;
+ return nk_input_is_mouse_click_in_rect(i, id, rect);
+}
+NK_API nk_bool
+nk_input_is_mouse_down(const struct nk_input *i, enum nk_buttons id)
+{
+ if (!i) return nk_false;
+ return i->mouse.buttons[id].down;
+}
+NK_API nk_bool
+nk_input_is_mouse_pressed(const struct nk_input *i, enum nk_buttons id)
+{
+ const struct nk_mouse_button *b;
+ if (!i) return nk_false;
+ b = &i->mouse.buttons[id];
+ if (b->down && b->clicked)
+ return nk_true;
+ return nk_false;
+}
+NK_API nk_bool
+nk_input_is_mouse_released(const struct nk_input *i, enum nk_buttons id)
+{
+ if (!i) return nk_false;
+ return (!i->mouse.buttons[id].down && i->mouse.buttons[id].clicked);
+}
+NK_API nk_bool
+nk_input_is_key_pressed(const struct nk_input *i, enum nk_keys key)
+{
+ const struct nk_key *k;
+ if (!i) return nk_false;
+ k = &i->keyboard.keys[key];
+ if ((k->down && k->clicked) || (!k->down && k->clicked >= 2))
+ return nk_true;
+ return nk_false;
+}
+NK_API nk_bool
+nk_input_is_key_released(const struct nk_input *i, enum nk_keys key)
+{
+ const struct nk_key *k;
+ if (!i) return nk_false;
+ k = &i->keyboard.keys[key];
+ if ((!k->down && k->clicked) || (k->down && k->clicked >= 2))
+ return nk_true;
+ return nk_false;
+}
+NK_API nk_bool
+nk_input_is_key_down(const struct nk_input *i, enum nk_keys key)
+{
+ const struct nk_key *k;
+ if (!i) return nk_false;
+ k = &i->keyboard.keys[key];
+ if (k->down) return nk_true;
+ return nk_false;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * STYLE
+ *
+ * ===============================================================*/
+NK_API void nk_style_default(struct nk_context *ctx){nk_style_from_table(ctx, 0);}
+#define NK_COLOR_MAP(NK_COLOR)\
+ NK_COLOR(NK_COLOR_TEXT, 175,175,175,255) \
+ NK_COLOR(NK_COLOR_WINDOW, 45, 45, 45, 255) \
+ NK_COLOR(NK_COLOR_HEADER, 40, 40, 40, 255) \
+ NK_COLOR(NK_COLOR_BORDER, 65, 65, 65, 255) \
+ NK_COLOR(NK_COLOR_BUTTON, 50, 50, 50, 255) \
+ NK_COLOR(NK_COLOR_BUTTON_HOVER, 40, 40, 40, 255) \
+ NK_COLOR(NK_COLOR_BUTTON_ACTIVE, 35, 35, 35, 255) \
+ NK_COLOR(NK_COLOR_TOGGLE, 100,100,100,255) \
+ NK_COLOR(NK_COLOR_TOGGLE_HOVER, 120,120,120,255) \
+ NK_COLOR(NK_COLOR_TOGGLE_CURSOR, 45, 45, 45, 255) \
+ NK_COLOR(NK_COLOR_SELECT, 45, 45, 45, 255) \
+ NK_COLOR(NK_COLOR_SELECT_ACTIVE, 35, 35, 35,255) \
+ NK_COLOR(NK_COLOR_SLIDER, 38, 38, 38, 255) \
+ NK_COLOR(NK_COLOR_SLIDER_CURSOR, 100,100,100,255) \
+ NK_COLOR(NK_COLOR_SLIDER_CURSOR_HOVER, 120,120,120,255) \
+ NK_COLOR(NK_COLOR_SLIDER_CURSOR_ACTIVE, 150,150,150,255) \
+ NK_COLOR(NK_COLOR_PROPERTY, 38, 38, 38, 255) \
+ NK_COLOR(NK_COLOR_EDIT, 38, 38, 38, 255) \
+ NK_COLOR(NK_COLOR_EDIT_CURSOR, 175,175,175,255) \
+ NK_COLOR(NK_COLOR_COMBO, 45, 45, 45, 255) \
+ NK_COLOR(NK_COLOR_CHART, 120,120,120,255) \
+ NK_COLOR(NK_COLOR_CHART_COLOR, 45, 45, 45, 255) \
+ NK_COLOR(NK_COLOR_CHART_COLOR_HIGHLIGHT, 255, 0, 0, 255) \
+ NK_COLOR(NK_COLOR_SCROLLBAR, 40, 40, 40, 255) \
+ NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR, 100,100,100,255) \
+ NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR_HOVER, 120,120,120,255) \
+ NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR_ACTIVE, 150,150,150,255) \
+ NK_COLOR(NK_COLOR_TAB_HEADER, 40, 40, 40,255)
+
+NK_GLOBAL const struct nk_color
+nk_default_color_style[NK_COLOR_COUNT] = {
+#define NK_COLOR(a,b,c,d,e) {b,c,d,e},
+ NK_COLOR_MAP(NK_COLOR)
+#undef NK_COLOR
+};
+NK_GLOBAL const char *nk_color_names[NK_COLOR_COUNT] = {
+#define NK_COLOR(a,b,c,d,e) #a,
+ NK_COLOR_MAP(NK_COLOR)
+#undef NK_COLOR
+};
+
+NK_API const char*
+nk_style_get_color_by_name(enum nk_style_colors c)
+{
+ return nk_color_names[c];
+}
+NK_API struct nk_style_item
+nk_style_item_color(struct nk_color col)
+{
+ struct nk_style_item i;
+ i.type = NK_STYLE_ITEM_COLOR;
+ i.data.color = col;
+ return i;
+}
+NK_API struct nk_style_item
+nk_style_item_image(struct nk_image img)
+{
+ struct nk_style_item i;
+ i.type = NK_STYLE_ITEM_IMAGE;
+ i.data.image = img;
+ return i;
+}
+NK_API struct nk_style_item
+nk_style_item_nine_slice(struct nk_nine_slice slice)
+{
+ struct nk_style_item i;
+ i.type = NK_STYLE_ITEM_NINE_SLICE;
+ i.data.slice = slice;
+ return i;
+}
+NK_API struct nk_style_item
+nk_style_item_hide(void)
+{
+ struct nk_style_item i;
+ i.type = NK_STYLE_ITEM_COLOR;
+ i.data.color = nk_rgba(0,0,0,0);
+ return i;
+}
+NK_API void
+nk_style_from_table(struct nk_context *ctx, const struct nk_color *table)
+{
+ struct nk_style *style;
+ struct nk_style_text *text;
+ struct nk_style_button *button;
+ struct nk_style_toggle *toggle;
+ struct nk_style_selectable *select;
+ struct nk_style_slider *slider;
+ struct nk_style_progress *prog;
+ struct nk_style_scrollbar *scroll;
+ struct nk_style_edit *edit;
+ struct nk_style_property *property;
+ struct nk_style_combo *combo;
+ struct nk_style_chart *chart;
+ struct nk_style_tab *tab;
+ struct nk_style_window *win;
+
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ style = &ctx->style;
+ table = (!table) ? nk_default_color_style: table;
+
+ /* default text */
+ text = &style->text;
+ text->color = table[NK_COLOR_TEXT];
+ text->padding = nk_vec2(0,0);
+ text->color_factor = 1.0f;
+ text->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* default button */
+ button = &style->button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]);
+ button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]);
+ button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]);
+ button->border_color = table[NK_COLOR_BORDER];
+ button->text_background = table[NK_COLOR_BUTTON];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(2.0f,2.0f);
+ button->image_padding = nk_vec2(0.0f,0.0f);
+ button->touch_padding = nk_vec2(0.0f, 0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 1.0f;
+ button->rounding = 4.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+
+ /* contextual button */
+ button = &style->contextual_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]);
+ button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]);
+ button->border_color = table[NK_COLOR_WINDOW];
+ button->text_background = table[NK_COLOR_WINDOW];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(2.0f,2.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+
+ /* menu button */
+ button = &style->menu_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->hover = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->active = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->border_color = table[NK_COLOR_WINDOW];
+ button->text_background = table[NK_COLOR_WINDOW];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(2.0f,2.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 1.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+
+ /* checkbox toggle */
+ toggle = &style->checkbox;
+ nk_zero_struct(*toggle);
+ toggle->normal = nk_style_item_color(table[NK_COLOR_TOGGLE]);
+ toggle->hover = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]);
+ toggle->active = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]);
+ toggle->cursor_normal = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]);
+ toggle->cursor_hover = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]);
+ toggle->userdata = nk_handle_ptr(0);
+ toggle->text_background = table[NK_COLOR_WINDOW];
+ toggle->text_normal = table[NK_COLOR_TEXT];
+ toggle->text_hover = table[NK_COLOR_TEXT];
+ toggle->text_active = table[NK_COLOR_TEXT];
+ toggle->padding = nk_vec2(2.0f, 2.0f);
+ toggle->touch_padding = nk_vec2(0,0);
+ toggle->border_color = nk_rgba(0,0,0,0);
+ toggle->border = 0.0f;
+ toggle->spacing = 4;
+ toggle->color_factor = 1.0f;
+ toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* option toggle */
+ toggle = &style->option;
+ nk_zero_struct(*toggle);
+ toggle->normal = nk_style_item_color(table[NK_COLOR_TOGGLE]);
+ toggle->hover = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]);
+ toggle->active = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]);
+ toggle->cursor_normal = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]);
+ toggle->cursor_hover = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]);
+ toggle->userdata = nk_handle_ptr(0);
+ toggle->text_background = table[NK_COLOR_WINDOW];
+ toggle->text_normal = table[NK_COLOR_TEXT];
+ toggle->text_hover = table[NK_COLOR_TEXT];
+ toggle->text_active = table[NK_COLOR_TEXT];
+ toggle->padding = nk_vec2(3.0f, 3.0f);
+ toggle->touch_padding = nk_vec2(0,0);
+ toggle->border_color = nk_rgba(0,0,0,0);
+ toggle->border = 0.0f;
+ toggle->spacing = 4;
+ toggle->color_factor = 1.0f;
+ toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* selectable */
+ select = &style->selectable;
+ nk_zero_struct(*select);
+ select->normal = nk_style_item_color(table[NK_COLOR_SELECT]);
+ select->hover = nk_style_item_color(table[NK_COLOR_SELECT]);
+ select->pressed = nk_style_item_color(table[NK_COLOR_SELECT]);
+ select->normal_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]);
+ select->hover_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]);
+ select->pressed_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]);
+ select->text_normal = table[NK_COLOR_TEXT];
+ select->text_hover = table[NK_COLOR_TEXT];
+ select->text_pressed = table[NK_COLOR_TEXT];
+ select->text_normal_active = table[NK_COLOR_TEXT];
+ select->text_hover_active = table[NK_COLOR_TEXT];
+ select->text_pressed_active = table[NK_COLOR_TEXT];
+ select->padding = nk_vec2(2.0f,2.0f);
+ select->image_padding = nk_vec2(2.0f,2.0f);
+ select->touch_padding = nk_vec2(0,0);
+ select->userdata = nk_handle_ptr(0);
+ select->rounding = 0.0f;
+ select->color_factor = 1.0f;
+ select->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ select->draw_begin = 0;
+ select->draw_end = 0;
+
+ /* slider */
+ slider = &style->slider;
+ nk_zero_struct(*slider);
+ slider->normal = nk_style_item_hide();
+ slider->hover = nk_style_item_hide();
+ slider->active = nk_style_item_hide();
+ slider->bar_normal = table[NK_COLOR_SLIDER];
+ slider->bar_hover = table[NK_COLOR_SLIDER];
+ slider->bar_active = table[NK_COLOR_SLIDER];
+ slider->bar_filled = table[NK_COLOR_SLIDER_CURSOR];
+ slider->cursor_normal = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR]);
+ slider->cursor_hover = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_HOVER]);
+ slider->cursor_active = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_ACTIVE]);
+ slider->inc_symbol = NK_SYMBOL_TRIANGLE_RIGHT;
+ slider->dec_symbol = NK_SYMBOL_TRIANGLE_LEFT;
+ slider->cursor_size = nk_vec2(16,16);
+ slider->padding = nk_vec2(2,2);
+ slider->spacing = nk_vec2(2,2);
+ slider->userdata = nk_handle_ptr(0);
+ slider->show_buttons = nk_false;
+ slider->bar_height = 8;
+ slider->rounding = 0;
+ slider->color_factor = 1.0f;
+ slider->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ slider->draw_begin = 0;
+ slider->draw_end = 0;
+
+ /* slider buttons */
+ button = &style->slider.inc_button;
+ button->normal = nk_style_item_color(nk_rgb(40,40,40));
+ button->hover = nk_style_item_color(nk_rgb(42,42,42));
+ button->active = nk_style_item_color(nk_rgb(44,44,44));
+ button->border_color = nk_rgb(65,65,65);
+ button->text_background = nk_rgb(40,40,40);
+ button->text_normal = nk_rgb(175,175,175);
+ button->text_hover = nk_rgb(175,175,175);
+ button->text_active = nk_rgb(175,175,175);
+ button->padding = nk_vec2(8.0f,8.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 1.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+ style->slider.dec_button = style->slider.inc_button;
+
+ /* progressbar */
+ prog = &style->progress;
+ nk_zero_struct(*prog);
+ prog->normal = nk_style_item_color(table[NK_COLOR_SLIDER]);
+ prog->hover = nk_style_item_color(table[NK_COLOR_SLIDER]);
+ prog->active = nk_style_item_color(table[NK_COLOR_SLIDER]);
+ prog->cursor_normal = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR]);
+ prog->cursor_hover = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_HOVER]);
+ prog->cursor_active = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_ACTIVE]);
+ prog->border_color = nk_rgba(0,0,0,0);
+ prog->cursor_border_color = nk_rgba(0,0,0,0);
+ prog->userdata = nk_handle_ptr(0);
+ prog->padding = nk_vec2(4,4);
+ prog->rounding = 0;
+ prog->border = 0;
+ prog->cursor_rounding = 0;
+ prog->cursor_border = 0;
+ prog->color_factor = 1.0f;
+ prog->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ prog->draw_begin = 0;
+ prog->draw_end = 0;
+
+ /* scrollbars */
+ scroll = &style->scrollh;
+ nk_zero_struct(*scroll);
+ scroll->normal = nk_style_item_color(table[NK_COLOR_SCROLLBAR]);
+ scroll->hover = nk_style_item_color(table[NK_COLOR_SCROLLBAR]);
+ scroll->active = nk_style_item_color(table[NK_COLOR_SCROLLBAR]);
+ scroll->cursor_normal = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR]);
+ scroll->cursor_hover = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR_HOVER]);
+ scroll->cursor_active = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR_ACTIVE]);
+ scroll->dec_symbol = NK_SYMBOL_CIRCLE_SOLID;
+ scroll->inc_symbol = NK_SYMBOL_CIRCLE_SOLID;
+ scroll->userdata = nk_handle_ptr(0);
+ scroll->border_color = table[NK_COLOR_SCROLLBAR];
+ scroll->cursor_border_color = table[NK_COLOR_SCROLLBAR];
+ scroll->padding = nk_vec2(0,0);
+ scroll->show_buttons = nk_false;
+ scroll->border = 0;
+ scroll->rounding = 0;
+ scroll->border_cursor = 0;
+ scroll->rounding_cursor = 0;
+ scroll->color_factor = 1.0f;
+ scroll->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ scroll->draw_begin = 0;
+ scroll->draw_end = 0;
+ style->scrollv = style->scrollh;
+
+ /* scrollbars buttons */
+ button = &style->scrollh.inc_button;
+ button->normal = nk_style_item_color(nk_rgb(40,40,40));
+ button->hover = nk_style_item_color(nk_rgb(42,42,42));
+ button->active = nk_style_item_color(nk_rgb(44,44,44));
+ button->border_color = nk_rgb(65,65,65);
+ button->text_background = nk_rgb(40,40,40);
+ button->text_normal = nk_rgb(175,175,175);
+ button->text_hover = nk_rgb(175,175,175);
+ button->text_active = nk_rgb(175,175,175);
+ button->padding = nk_vec2(4.0f,4.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 1.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+ style->scrollh.dec_button = style->scrollh.inc_button;
+ style->scrollv.inc_button = style->scrollh.inc_button;
+ style->scrollv.dec_button = style->scrollh.inc_button;
+
+ /* edit */
+ edit = &style->edit;
+ nk_zero_struct(*edit);
+ edit->normal = nk_style_item_color(table[NK_COLOR_EDIT]);
+ edit->hover = nk_style_item_color(table[NK_COLOR_EDIT]);
+ edit->active = nk_style_item_color(table[NK_COLOR_EDIT]);
+ edit->cursor_normal = table[NK_COLOR_TEXT];
+ edit->cursor_hover = table[NK_COLOR_TEXT];
+ edit->cursor_text_normal= table[NK_COLOR_EDIT];
+ edit->cursor_text_hover = table[NK_COLOR_EDIT];
+ edit->border_color = table[NK_COLOR_BORDER];
+ edit->text_normal = table[NK_COLOR_TEXT];
+ edit->text_hover = table[NK_COLOR_TEXT];
+ edit->text_active = table[NK_COLOR_TEXT];
+ edit->selected_normal = table[NK_COLOR_TEXT];
+ edit->selected_hover = table[NK_COLOR_TEXT];
+ edit->selected_text_normal = table[NK_COLOR_EDIT];
+ edit->selected_text_hover = table[NK_COLOR_EDIT];
+ edit->scrollbar_size = nk_vec2(10,10);
+ edit->scrollbar = style->scrollv;
+ edit->padding = nk_vec2(4,4);
+ edit->row_padding = 2;
+ edit->cursor_size = 4;
+ edit->border = 1;
+ edit->rounding = 0;
+ edit->color_factor = 1.0f;
+ edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* property */
+ property = &style->property;
+ nk_zero_struct(*property);
+ property->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ property->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ property->active = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ property->border_color = table[NK_COLOR_BORDER];
+ property->label_normal = table[NK_COLOR_TEXT];
+ property->label_hover = table[NK_COLOR_TEXT];
+ property->label_active = table[NK_COLOR_TEXT];
+ property->sym_left = NK_SYMBOL_TRIANGLE_LEFT;
+ property->sym_right = NK_SYMBOL_TRIANGLE_RIGHT;
+ property->userdata = nk_handle_ptr(0);
+ property->padding = nk_vec2(4,4);
+ property->border = 1;
+ property->rounding = 10;
+ property->draw_begin = 0;
+ property->draw_end = 0;
+ property->color_factor = 1.0f;
+ property->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* property buttons */
+ button = &style->property.dec_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ button->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ button->active = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ button->border_color = nk_rgba(0,0,0,0);
+ button->text_background = table[NK_COLOR_PROPERTY];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(0.0f,0.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+ style->property.inc_button = style->property.dec_button;
+
+ /* property edit */
+ edit = &style->property.edit;
+ nk_zero_struct(*edit);
+ edit->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ edit->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ edit->active = nk_style_item_color(table[NK_COLOR_PROPERTY]);
+ edit->border_color = nk_rgba(0,0,0,0);
+ edit->cursor_normal = table[NK_COLOR_TEXT];
+ edit->cursor_hover = table[NK_COLOR_TEXT];
+ edit->cursor_text_normal= table[NK_COLOR_EDIT];
+ edit->cursor_text_hover = table[NK_COLOR_EDIT];
+ edit->text_normal = table[NK_COLOR_TEXT];
+ edit->text_hover = table[NK_COLOR_TEXT];
+ edit->text_active = table[NK_COLOR_TEXT];
+ edit->selected_normal = table[NK_COLOR_TEXT];
+ edit->selected_hover = table[NK_COLOR_TEXT];
+ edit->selected_text_normal = table[NK_COLOR_EDIT];
+ edit->selected_text_hover = table[NK_COLOR_EDIT];
+ edit->padding = nk_vec2(0,0);
+ edit->cursor_size = 8;
+ edit->border = 0;
+ edit->rounding = 0;
+ edit->color_factor = 1.0f;
+ edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* chart */
+ chart = &style->chart;
+ nk_zero_struct(*chart);
+ chart->background = nk_style_item_color(table[NK_COLOR_CHART]);
+ chart->border_color = table[NK_COLOR_BORDER];
+ chart->selected_color = table[NK_COLOR_CHART_COLOR_HIGHLIGHT];
+ chart->color = table[NK_COLOR_CHART_COLOR];
+ chart->padding = nk_vec2(4,4);
+ chart->border = 0;
+ chart->rounding = 0;
+ chart->color_factor = 1.0f;
+ chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ chart->show_markers = nk_true;
+
+ /* combo */
+ combo = &style->combo;
+ combo->normal = nk_style_item_color(table[NK_COLOR_COMBO]);
+ combo->hover = nk_style_item_color(table[NK_COLOR_COMBO]);
+ combo->active = nk_style_item_color(table[NK_COLOR_COMBO]);
+ combo->border_color = table[NK_COLOR_BORDER];
+ combo->label_normal = table[NK_COLOR_TEXT];
+ combo->label_hover = table[NK_COLOR_TEXT];
+ combo->label_active = table[NK_COLOR_TEXT];
+ combo->sym_normal = NK_SYMBOL_TRIANGLE_DOWN;
+ combo->sym_hover = NK_SYMBOL_TRIANGLE_DOWN;
+ combo->sym_active = NK_SYMBOL_TRIANGLE_DOWN;
+ combo->content_padding = nk_vec2(4,4);
+ combo->button_padding = nk_vec2(0,4);
+ combo->spacing = nk_vec2(4,0);
+ combo->border = 1;
+ combo->rounding = 0;
+ combo->color_factor = 1.0f;
+ combo->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* combo button */
+ button = &style->combo.button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_COMBO]);
+ button->hover = nk_style_item_color(table[NK_COLOR_COMBO]);
+ button->active = nk_style_item_color(table[NK_COLOR_COMBO]);
+ button->border_color = nk_rgba(0,0,0,0);
+ button->text_background = table[NK_COLOR_COMBO];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(2.0f,2.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+
+ /* tab */
+ tab = &style->tab;
+ tab->background = nk_style_item_color(table[NK_COLOR_TAB_HEADER]);
+ tab->border_color = table[NK_COLOR_BORDER];
+ tab->text = table[NK_COLOR_TEXT];
+ tab->sym_minimize = NK_SYMBOL_TRIANGLE_RIGHT;
+ tab->sym_maximize = NK_SYMBOL_TRIANGLE_DOWN;
+ tab->padding = nk_vec2(4,4);
+ tab->spacing = nk_vec2(4,4);
+ tab->indent = 10.0f;
+ tab->border = 1;
+ tab->rounding = 0;
+ tab->color_factor = 1.0f;
+ tab->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+
+ /* tab button */
+ button = &style->tab.tab_minimize_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_TAB_HEADER]);
+ button->hover = nk_style_item_color(table[NK_COLOR_TAB_HEADER]);
+ button->active = nk_style_item_color(table[NK_COLOR_TAB_HEADER]);
+ button->border_color = nk_rgba(0,0,0,0);
+ button->text_background = table[NK_COLOR_TAB_HEADER];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(2.0f,2.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+ style->tab.tab_maximize_button =*button;
+
+ /* node button */
+ button = &style->tab.node_minimize_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->hover = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->active = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ button->border_color = nk_rgba(0,0,0,0);
+ button->text_background = table[NK_COLOR_TAB_HEADER];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(2.0f,2.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+ style->tab.node_maximize_button =*button;
+
+ /* window header */
+ win = &style->window;
+ win->header.align = NK_HEADER_RIGHT;
+ win->header.close_symbol = NK_SYMBOL_X;
+ win->header.minimize_symbol = NK_SYMBOL_MINUS;
+ win->header.maximize_symbol = NK_SYMBOL_PLUS;
+ win->header.normal = nk_style_item_color(table[NK_COLOR_HEADER]);
+ win->header.hover = nk_style_item_color(table[NK_COLOR_HEADER]);
+ win->header.active = nk_style_item_color(table[NK_COLOR_HEADER]);
+ win->header.label_normal = table[NK_COLOR_TEXT];
+ win->header.label_hover = table[NK_COLOR_TEXT];
+ win->header.label_active = table[NK_COLOR_TEXT];
+ win->header.label_padding = nk_vec2(4,4);
+ win->header.padding = nk_vec2(4,4);
+ win->header.spacing = nk_vec2(0,0);
+
+ /* window header close button */
+ button = &style->window.header.close_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_HEADER]);
+ button->hover = nk_style_item_color(table[NK_COLOR_HEADER]);
+ button->active = nk_style_item_color(table[NK_COLOR_HEADER]);
+ button->border_color = nk_rgba(0,0,0,0);
+ button->text_background = table[NK_COLOR_HEADER];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(0.0f,0.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+
+ /* window header minimize button */
+ button = &style->window.header.minimize_button;
+ nk_zero_struct(*button);
+ button->normal = nk_style_item_color(table[NK_COLOR_HEADER]);
+ button->hover = nk_style_item_color(table[NK_COLOR_HEADER]);
+ button->active = nk_style_item_color(table[NK_COLOR_HEADER]);
+ button->border_color = nk_rgba(0,0,0,0);
+ button->text_background = table[NK_COLOR_HEADER];
+ button->text_normal = table[NK_COLOR_TEXT];
+ button->text_hover = table[NK_COLOR_TEXT];
+ button->text_active = table[NK_COLOR_TEXT];
+ button->padding = nk_vec2(0.0f,0.0f);
+ button->touch_padding = nk_vec2(0.0f,0.0f);
+ button->userdata = nk_handle_ptr(0);
+ button->text_alignment = NK_TEXT_CENTERED;
+ button->border = 0.0f;
+ button->rounding = 0.0f;
+ button->color_factor_text = 1.0f;
+ button->color_factor_background = 1.0f;
+ button->disabled_factor = NK_WIDGET_DISABLED_FACTOR;
+ button->draw_begin = 0;
+ button->draw_end = 0;
+
+ /* window */
+ win->background = table[NK_COLOR_WINDOW];
+ win->fixed_background = nk_style_item_color(table[NK_COLOR_WINDOW]);
+ win->border_color = table[NK_COLOR_BORDER];
+ win->popup_border_color = table[NK_COLOR_BORDER];
+ win->combo_border_color = table[NK_COLOR_BORDER];
+ win->contextual_border_color = table[NK_COLOR_BORDER];
+ win->menu_border_color = table[NK_COLOR_BORDER];
+ win->group_border_color = table[NK_COLOR_BORDER];
+ win->tooltip_border_color = table[NK_COLOR_BORDER];
+ win->scaler = nk_style_item_color(table[NK_COLOR_TEXT]);
+
+ win->rounding = 0.0f;
+ win->spacing = nk_vec2(4,4);
+ win->scrollbar_size = nk_vec2(10,10);
+ win->min_size = nk_vec2(64,64);
+
+ win->combo_border = 1.0f;
+ win->contextual_border = 1.0f;
+ win->menu_border = 1.0f;
+ win->group_border = 1.0f;
+ win->tooltip_border = 1.0f;
+ win->popup_border = 1.0f;
+ win->border = 2.0f;
+ win->min_row_height_padding = 8;
+
+ win->padding = nk_vec2(4,4);
+ win->group_padding = nk_vec2(4,4);
+ win->popup_padding = nk_vec2(4,4);
+ win->combo_padding = nk_vec2(4,4);
+ win->contextual_padding = nk_vec2(4,4);
+ win->menu_padding = nk_vec2(4,4);
+ win->tooltip_padding = nk_vec2(4,4);
+}
+NK_API void
+nk_style_set_font(struct nk_context *ctx, const struct nk_user_font *font)
+{
+ struct nk_style *style;
+ NK_ASSERT(ctx);
+
+ if (!ctx) return;
+ style = &ctx->style;
+ style->font = font;
+ ctx->stacks.fonts.head = 0;
+ if (ctx->current)
+ nk_layout_reset_min_row_height(ctx);
+}
+NK_API nk_bool
+nk_style_push_font(struct nk_context *ctx, const struct nk_user_font *font)
+{
+ struct nk_config_stack_user_font *font_stack;
+ struct nk_config_stack_user_font_element *element;
+
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+
+ font_stack = &ctx->stacks.fonts;
+ NK_ASSERT(font_stack->head < (int)NK_LEN(font_stack->elements));
+ if (font_stack->head >= (int)NK_LEN(font_stack->elements))
+ return 0;
+
+ element = &font_stack->elements[font_stack->head++];
+ element->address = &ctx->style.font;
+ element->old_value = ctx->style.font;
+ ctx->style.font = font;
+ return 1;
+}
+NK_API nk_bool
+nk_style_pop_font(struct nk_context *ctx)
+{
+ struct nk_config_stack_user_font *font_stack;
+ struct nk_config_stack_user_font_element *element;
+
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+
+ font_stack = &ctx->stacks.fonts;
+ NK_ASSERT(font_stack->head > 0);
+ if (font_stack->head < 1)
+ return 0;
+
+ element = &font_stack->elements[--font_stack->head];
+ *element->address = element->old_value;
+ return 1;
+}
+#define NK_STYLE_PUSH_IMPLEMENATION(prefix, type, stack) \
+nk_style_push_##type(struct nk_context *ctx, prefix##_##type *address, prefix##_##type value)\
+{\
+ struct nk_config_stack_##type * type_stack;\
+ struct nk_config_stack_##type##_element *element;\
+ NK_ASSERT(ctx);\
+ if (!ctx) return 0;\
+ type_stack = &ctx->stacks.stack;\
+ NK_ASSERT(type_stack->head < (int)NK_LEN(type_stack->elements));\
+ if (type_stack->head >= (int)NK_LEN(type_stack->elements))\
+ return 0;\
+ element = &type_stack->elements[type_stack->head++];\
+ element->address = address;\
+ element->old_value = *address;\
+ *address = value;\
+ return 1;\
+}
+#define NK_STYLE_POP_IMPLEMENATION(type, stack) \
+nk_style_pop_##type(struct nk_context *ctx)\
+{\
+ struct nk_config_stack_##type *type_stack;\
+ struct nk_config_stack_##type##_element *element;\
+ NK_ASSERT(ctx);\
+ if (!ctx) return 0;\
+ type_stack = &ctx->stacks.stack;\
+ NK_ASSERT(type_stack->head > 0);\
+ if (type_stack->head < 1)\
+ return 0;\
+ element = &type_stack->elements[--type_stack->head];\
+ *element->address = element->old_value;\
+ return 1;\
+}
+NK_API nk_bool NK_STYLE_PUSH_IMPLEMENATION(struct nk, style_item, style_items)
+NK_API nk_bool NK_STYLE_PUSH_IMPLEMENATION(nk,float, floats)
+NK_API nk_bool NK_STYLE_PUSH_IMPLEMENATION(struct nk, vec2, vectors)
+NK_API nk_bool NK_STYLE_PUSH_IMPLEMENATION(nk,flags, flags)
+NK_API nk_bool NK_STYLE_PUSH_IMPLEMENATION(struct nk,color, colors)
+
+NK_API nk_bool NK_STYLE_POP_IMPLEMENATION(style_item, style_items)
+NK_API nk_bool NK_STYLE_POP_IMPLEMENATION(float,floats)
+NK_API nk_bool NK_STYLE_POP_IMPLEMENATION(vec2, vectors)
+NK_API nk_bool NK_STYLE_POP_IMPLEMENATION(flags,flags)
+NK_API nk_bool NK_STYLE_POP_IMPLEMENATION(color,colors)
+
+NK_API nk_bool
+nk_style_set_cursor(struct nk_context *ctx, enum nk_style_cursor c)
+{
+ struct nk_style *style;
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ style = &ctx->style;
+ if (style->cursors[c]) {
+ style->cursor_active = style->cursors[c];
+ return 1;
+ }
+ return 0;
+}
+NK_API void
+nk_style_show_cursor(struct nk_context *ctx)
+{
+ ctx->style.cursor_visible = nk_true;
+}
+NK_API void
+nk_style_hide_cursor(struct nk_context *ctx)
+{
+ ctx->style.cursor_visible = nk_false;
+}
+NK_API void
+nk_style_load_cursor(struct nk_context *ctx, enum nk_style_cursor cursor,
+ const struct nk_cursor *c)
+{
+ struct nk_style *style;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ style = &ctx->style;
+ style->cursors[cursor] = c;
+}
+NK_API void
+nk_style_load_all_cursors(struct nk_context *ctx, struct nk_cursor *cursors)
+{
+ int i = 0;
+ struct nk_style *style;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ style = &ctx->style;
+ for (i = 0; i < NK_CURSOR_COUNT; ++i)
+ style->cursors[i] = &cursors[i];
+ style->cursor_visible = nk_true;
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * CONTEXT
+ *
+ * ===============================================================*/
+NK_INTERN void
+nk_setup(struct nk_context *ctx, const struct nk_user_font *font)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ nk_zero_struct(*ctx);
+ nk_style_default(ctx);
+ ctx->seq = 1;
+ if (font) ctx->style.font = font;
+#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
+ nk_draw_list_init(&ctx->draw_list);
+#endif
+}
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API nk_bool
+nk_init_default(struct nk_context *ctx, const struct nk_user_font *font)
+{
+ struct nk_allocator alloc;
+ alloc.userdata.ptr = 0;
+ alloc.alloc = nk_malloc;
+ alloc.free = nk_mfree;
+ return nk_init(ctx, &alloc, font);
+}
+#endif
+NK_API nk_bool
+nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size,
+ const struct nk_user_font *font)
+{
+ NK_ASSERT(memory);
+ if (!memory) return 0;
+ nk_setup(ctx, font);
+ nk_buffer_init_fixed(&ctx->memory, memory, size);
+ ctx->use_pool = nk_false;
+ return 1;
+}
+NK_API nk_bool
+nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds,
+ struct nk_buffer *pool, const struct nk_user_font *font)
+{
+ NK_ASSERT(cmds);
+ NK_ASSERT(pool);
+ if (!cmds || !pool) return 0;
+
+ nk_setup(ctx, font);
+ ctx->memory = *cmds;
+ if (pool->type == NK_BUFFER_FIXED) {
+ /* take memory from buffer and alloc fixed pool */
+ nk_pool_init_fixed(&ctx->pool, pool->memory.ptr, pool->memory.size);
+ } else {
+ /* create dynamic pool from buffer allocator */
+ struct nk_allocator *alloc = &pool->pool;
+ nk_pool_init(&ctx->pool, alloc, NK_POOL_DEFAULT_CAPACITY);
+ }
+ ctx->use_pool = nk_true;
+ return 1;
+}
+NK_API nk_bool
+nk_init(struct nk_context *ctx, struct nk_allocator *alloc,
+ const struct nk_user_font *font)
+{
+ NK_ASSERT(alloc);
+ if (!alloc) return 0;
+ nk_setup(ctx, font);
+ nk_buffer_init(&ctx->memory, alloc, NK_DEFAULT_COMMAND_BUFFER_SIZE);
+ nk_pool_init(&ctx->pool, alloc, NK_POOL_DEFAULT_CAPACITY);
+ ctx->use_pool = nk_true;
+ return 1;
+}
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+NK_API void
+nk_set_user_data(struct nk_context *ctx, nk_handle handle)
+{
+ if (!ctx) return;
+ ctx->userdata = handle;
+ if (ctx->current)
+ ctx->current->buffer.userdata = handle;
+}
+#endif
+NK_API void
+nk_free(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ nk_buffer_free(&ctx->memory);
+ if (ctx->use_pool)
+ nk_pool_free(&ctx->pool);
+
+ nk_zero(&ctx->input, sizeof(ctx->input));
+ nk_zero(&ctx->style, sizeof(ctx->style));
+ nk_zero(&ctx->memory, sizeof(ctx->memory));
+
+ ctx->seq = 0;
+ ctx->build = 0;
+ ctx->begin = 0;
+ ctx->end = 0;
+ ctx->active = 0;
+ ctx->current = 0;
+ ctx->freelist = 0;
+ ctx->count = 0;
+}
+NK_API void
+nk_clear(struct nk_context *ctx)
+{
+ struct nk_window *iter;
+ struct nk_window *next;
+ NK_ASSERT(ctx);
+
+ if (!ctx) return;
+ if (ctx->use_pool)
+ nk_buffer_clear(&ctx->memory);
+ else nk_buffer_reset(&ctx->memory, NK_BUFFER_FRONT);
+
+ ctx->build = 0;
+ ctx->memory.calls = 0;
+ ctx->last_widget_state = 0;
+ ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_ARROW];
+ NK_MEMSET(&ctx->overlay, 0, sizeof(ctx->overlay));
+
+ /* garbage collector */
+ iter = ctx->begin;
+ while (iter) {
+ /* make sure valid minimized windows do not get removed */
+ if ((iter->flags & NK_WINDOW_MINIMIZED) &&
+ !(iter->flags & NK_WINDOW_CLOSED) &&
+ iter->seq == ctx->seq) {
+ iter = iter->next;
+ continue;
+ }
+ /* remove hotness from hidden or closed windows*/
+ if (((iter->flags & NK_WINDOW_HIDDEN) ||
+ (iter->flags & NK_WINDOW_CLOSED)) &&
+ iter == ctx->active) {
+ ctx->active = iter->prev;
+ ctx->end = iter->prev;
+ if (!ctx->end)
+ ctx->begin = 0;
+ if (ctx->active)
+ ctx->active->flags &= ~(unsigned)NK_WINDOW_ROM;
+ }
+ /* free unused popup windows */
+ if (iter->popup.win && iter->popup.win->seq != ctx->seq) {
+ nk_free_window(ctx, iter->popup.win);
+ iter->popup.win = 0;
+ }
+ /* remove unused window state tables */
+ {struct nk_table *n, *it = iter->tables;
+ while (it) {
+ n = it->next;
+ if (it->seq != ctx->seq) {
+ nk_remove_table(iter, it);
+ nk_zero(it, sizeof(union nk_page_data));
+ nk_free_table(ctx, it);
+ if (it == iter->tables)
+ iter->tables = n;
+ } it = n;
+ }}
+ /* window itself is not used anymore so free */
+ if (iter->seq != ctx->seq || iter->flags & NK_WINDOW_CLOSED) {
+ next = iter->next;
+ nk_remove_window(ctx, iter);
+ nk_free_window(ctx, iter);
+ iter = next;
+ } else iter = iter->next;
+ }
+ ctx->seq++;
+}
+NK_LIB void
+nk_start_buffer(struct nk_context *ctx, struct nk_command_buffer *buffer)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(buffer);
+ if (!ctx || !buffer) return;
+ buffer->begin = ctx->memory.allocated;
+ buffer->end = buffer->begin;
+ buffer->last = buffer->begin;
+ buffer->clip = nk_null_rect;
+}
+NK_LIB void
+nk_start(struct nk_context *ctx, struct nk_window *win)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(win);
+ nk_start_buffer(ctx, &win->buffer);
+}
+NK_LIB void
+nk_start_popup(struct nk_context *ctx, struct nk_window *win)
+{
+ struct nk_popup_buffer *buf;
+ NK_ASSERT(ctx);
+ NK_ASSERT(win);
+ if (!ctx || !win) return;
+
+ /* save buffer fill state for popup */
+ buf = &win->popup.buf;
+ buf->begin = win->buffer.end;
+ buf->end = win->buffer.end;
+ buf->parent = win->buffer.last;
+ buf->last = buf->begin;
+ buf->active = nk_true;
+}
+NK_LIB void
+nk_finish_popup(struct nk_context *ctx, struct nk_window *win)
+{
+ struct nk_popup_buffer *buf;
+ NK_ASSERT(ctx);
+ NK_ASSERT(win);
+ if (!ctx || !win) return;
+
+ buf = &win->popup.buf;
+ buf->last = win->buffer.last;
+ buf->end = win->buffer.end;
+}
+NK_LIB void
+nk_finish_buffer(struct nk_context *ctx, struct nk_command_buffer *buffer)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(buffer);
+ if (!ctx || !buffer) return;
+ buffer->end = ctx->memory.allocated;
+}
+NK_LIB void
+nk_finish(struct nk_context *ctx, struct nk_window *win)
+{
+ struct nk_popup_buffer *buf;
+ struct nk_command *parent_last;
+ void *memory;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(win);
+ if (!ctx || !win) return;
+ nk_finish_buffer(ctx, &win->buffer);
+ if (!win->popup.buf.active) return;
+
+ buf = &win->popup.buf;
+ memory = ctx->memory.memory.ptr;
+ parent_last = nk_ptr_add(struct nk_command, memory, buf->parent);
+ parent_last->next = buf->end;
+}
+NK_LIB void
+nk_build(struct nk_context *ctx)
+{
+ struct nk_window *it = 0;
+ struct nk_command *cmd = 0;
+ nk_byte *buffer = 0;
+
+ /* draw cursor overlay */
+ if (!ctx->style.cursor_active)
+ ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_ARROW];
+ if (ctx->style.cursor_active && !ctx->input.mouse.grabbed && ctx->style.cursor_visible) {
+ struct nk_rect mouse_bounds;
+ const struct nk_cursor *cursor = ctx->style.cursor_active;
+ nk_command_buffer_init(&ctx->overlay, &ctx->memory, NK_CLIPPING_OFF);
+ nk_start_buffer(ctx, &ctx->overlay);
+
+ mouse_bounds.x = ctx->input.mouse.pos.x - cursor->offset.x;
+ mouse_bounds.y = ctx->input.mouse.pos.y - cursor->offset.y;
+ mouse_bounds.w = cursor->size.x;
+ mouse_bounds.h = cursor->size.y;
+
+ nk_draw_image(&ctx->overlay, mouse_bounds, &cursor->img, nk_white);
+ nk_finish_buffer(ctx, &ctx->overlay);
+ }
+ /* build one big draw command list out of all window buffers */
+ it = ctx->begin;
+ buffer = (nk_byte*)ctx->memory.memory.ptr;
+ while (it != 0) {
+ struct nk_window *next = it->next;
+ if (it->buffer.last == it->buffer.begin || (it->flags & NK_WINDOW_HIDDEN)||
+ it->seq != ctx->seq)
+ goto cont;
+
+ cmd = nk_ptr_add(struct nk_command, buffer, it->buffer.last);
+ while (next && ((next->buffer.last == next->buffer.begin) ||
+ (next->flags & NK_WINDOW_HIDDEN) || next->seq != ctx->seq))
+ next = next->next; /* skip empty command buffers */
+
+ if (next) cmd->next = next->buffer.begin;
+ cont: it = next;
+ }
+ /* append all popup draw commands into lists */
+ it = ctx->begin;
+ while (it != 0) {
+ struct nk_window *next = it->next;
+ struct nk_popup_buffer *buf;
+ if (!it->popup.buf.active)
+ goto skip;
+
+ buf = &it->popup.buf;
+ cmd->next = buf->begin;
+ cmd = nk_ptr_add(struct nk_command, buffer, buf->last);
+ buf->active = nk_false;
+ skip: it = next;
+ }
+ if (cmd) {
+ /* append overlay commands */
+ if (ctx->overlay.end != ctx->overlay.begin)
+ cmd->next = ctx->overlay.begin;
+ else cmd->next = ctx->memory.allocated;
+ }
+}
+NK_API const struct nk_command*
+nk__begin(struct nk_context *ctx)
+{
+ struct nk_window *iter;
+ nk_byte *buffer;
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ if (!ctx->count) return 0;
+
+ buffer = (nk_byte*)ctx->memory.memory.ptr;
+ if (!ctx->build) {
+ nk_build(ctx);
+ ctx->build = nk_true;
+ }
+ iter = ctx->begin;
+ while (iter && ((iter->buffer.begin == iter->buffer.end) ||
+ (iter->flags & NK_WINDOW_HIDDEN) || iter->seq != ctx->seq))
+ iter = iter->next;
+ if (!iter) return 0;
+ return nk_ptr_add_const(struct nk_command, buffer, iter->buffer.begin);
+}
+
+NK_API const struct nk_command*
+nk__next(struct nk_context *ctx, const struct nk_command *cmd)
+{
+ nk_byte *buffer;
+ const struct nk_command *next;
+ NK_ASSERT(ctx);
+ if (!ctx || !cmd || !ctx->count) return 0;
+ if (cmd->next >= ctx->memory.allocated) return 0;
+ buffer = (nk_byte*)ctx->memory.memory.ptr;
+ next = nk_ptr_add_const(struct nk_command, buffer, cmd->next);
+ return next;
+}
+
+
+
+
+
+
+/* ===============================================================
+ *
+ * POOL
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_pool_init(struct nk_pool *pool, struct nk_allocator *alloc,
+ unsigned int capacity)
+{
+ NK_ASSERT(capacity >= 1);
+ nk_zero(pool, sizeof(*pool));
+ pool->alloc = *alloc;
+ pool->capacity = capacity;
+ pool->type = NK_BUFFER_DYNAMIC;
+ pool->pages = 0;
+}
+NK_LIB void
+nk_pool_free(struct nk_pool *pool)
+{
+ struct nk_page *iter;
+ if (!pool) return;
+ iter = pool->pages;
+ if (pool->type == NK_BUFFER_FIXED) return;
+ while (iter) {
+ struct nk_page *next = iter->next;
+ pool->alloc.free(pool->alloc.userdata, iter);
+ iter = next;
+ }
+}
+NK_LIB void
+nk_pool_init_fixed(struct nk_pool *pool, void *memory, nk_size size)
+{
+ nk_zero(pool, sizeof(*pool));
+ NK_ASSERT(size >= sizeof(struct nk_page));
+ if (size < sizeof(struct nk_page)) return;
+ /* first nk_page_element is embedded in nk_page, additional elements follow in adjacent space */
+ pool->capacity = (unsigned)(1 + (size - sizeof(struct nk_page)) / sizeof(struct nk_page_element));
+ pool->pages = (struct nk_page*)memory;
+ pool->type = NK_BUFFER_FIXED;
+ pool->size = size;
+}
+NK_LIB struct nk_page_element*
+nk_pool_alloc(struct nk_pool *pool)
+{
+ if (!pool->pages || pool->pages->size >= pool->capacity) {
+ /* allocate new page */
+ struct nk_page *page;
+ if (pool->type == NK_BUFFER_FIXED) {
+ NK_ASSERT(pool->pages);
+ if (!pool->pages) return 0;
+ NK_ASSERT(pool->pages->size < pool->capacity);
+ return 0;
+ } else {
+ nk_size size = sizeof(struct nk_page);
+ size += (pool->capacity - 1) * sizeof(struct nk_page_element);
+ page = (struct nk_page*)pool->alloc.alloc(pool->alloc.userdata,0, size);
+ page->next = pool->pages;
+ pool->pages = page;
+ page->size = 0;
+ }
+ } return &pool->pages->win[pool->pages->size++];
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * PAGE ELEMENT
+ *
+ * ===============================================================*/
+NK_LIB struct nk_page_element*
+nk_create_page_element(struct nk_context *ctx)
+{
+ struct nk_page_element *elem;
+ if (ctx->freelist) {
+ /* unlink page element from free list */
+ elem = ctx->freelist;
+ ctx->freelist = elem->next;
+ } else if (ctx->use_pool) {
+ /* allocate page element from memory pool */
+ elem = nk_pool_alloc(&ctx->pool);
+ NK_ASSERT(elem);
+ if (!elem) return 0;
+ } else {
+ /* allocate new page element from back of fixed size memory buffer */
+ NK_STORAGE const nk_size size = sizeof(struct nk_page_element);
+ NK_STORAGE const nk_size align = NK_ALIGNOF(struct nk_page_element);
+ elem = (struct nk_page_element*)nk_buffer_alloc(&ctx->memory, NK_BUFFER_BACK, size, align);
+ NK_ASSERT(elem);
+ if (!elem) return 0;
+ }
+ nk_zero_struct(*elem);
+ elem->next = 0;
+ elem->prev = 0;
+ return elem;
+}
+NK_LIB void
+nk_link_page_element_into_freelist(struct nk_context *ctx,
+ struct nk_page_element *elem)
+{
+ /* link table into freelist */
+ if (!ctx->freelist) {
+ ctx->freelist = elem;
+ } else {
+ elem->next = ctx->freelist;
+ ctx->freelist = elem;
+ }
+}
+NK_LIB void
+nk_free_page_element(struct nk_context *ctx, struct nk_page_element *elem)
+{
+ /* we have a pool so just add to free list */
+ if (ctx->use_pool) {
+ nk_link_page_element_into_freelist(ctx, elem);
+ return;
+ }
+ /* if possible remove last element from back of fixed memory buffer */
+ {void *elem_end = (void*)(elem + 1);
+ void *buffer_end = (nk_byte*)ctx->memory.memory.ptr + ctx->memory.size;
+ if (elem_end == buffer_end)
+ ctx->memory.size -= sizeof(struct nk_page_element);
+ else nk_link_page_element_into_freelist(ctx, elem);}
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * TABLE
+ *
+ * ===============================================================*/
+NK_LIB struct nk_table*
+nk_create_table(struct nk_context *ctx)
+{
+ struct nk_page_element *elem;
+ elem = nk_create_page_element(ctx);
+ if (!elem) return 0;
+ nk_zero_struct(*elem);
+ return &elem->data.tbl;
+}
+NK_LIB void
+nk_free_table(struct nk_context *ctx, struct nk_table *tbl)
+{
+ union nk_page_data *pd = NK_CONTAINER_OF(tbl, union nk_page_data, tbl);
+ struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data);
+ nk_free_page_element(ctx, pe);
+}
+NK_LIB void
+nk_push_table(struct nk_window *win, struct nk_table *tbl)
+{
+ if (!win->tables) {
+ win->tables = tbl;
+ tbl->next = 0;
+ tbl->prev = 0;
+ tbl->size = 0;
+ win->table_count = 1;
+ return;
+ }
+ win->tables->prev = tbl;
+ tbl->next = win->tables;
+ tbl->prev = 0;
+ tbl->size = 0;
+ win->tables = tbl;
+ win->table_count++;
+}
+NK_LIB void
+nk_remove_table(struct nk_window *win, struct nk_table *tbl)
+{
+ if (win->tables == tbl)
+ win->tables = tbl->next;
+ if (tbl->next)
+ tbl->next->prev = tbl->prev;
+ if (tbl->prev)
+ tbl->prev->next = tbl->next;
+ tbl->next = 0;
+ tbl->prev = 0;
+}
+NK_LIB nk_uint*
+nk_add_value(struct nk_context *ctx, struct nk_window *win,
+ nk_hash name, nk_uint value)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(win);
+ if (!win || !ctx) return 0;
+ if (!win->tables || win->tables->size >= NK_VALUE_PAGE_CAPACITY) {
+ struct nk_table *tbl = nk_create_table(ctx);
+ NK_ASSERT(tbl);
+ if (!tbl) return 0;
+ nk_push_table(win, tbl);
+ }
+ win->tables->seq = win->seq;
+ win->tables->keys[win->tables->size] = name;
+ win->tables->values[win->tables->size] = value;
+ return &win->tables->values[win->tables->size++];
+}
+NK_LIB nk_uint*
+nk_find_value(struct nk_window *win, nk_hash name)
+{
+ struct nk_table *iter = win->tables;
+ while (iter) {
+ unsigned int i = 0;
+ unsigned int size = iter->size;
+ for (i = 0; i < size; ++i) {
+ if (iter->keys[i] == name) {
+ iter->seq = win->seq;
+ return &iter->values[i];
+ }
+ } size = NK_VALUE_PAGE_CAPACITY;
+ iter = iter->next;
+ }
+ return 0;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * PANEL
+ *
+ * ===============================================================*/
+NK_LIB void*
+nk_create_panel(struct nk_context *ctx)
+{
+ struct nk_page_element *elem;
+ elem = nk_create_page_element(ctx);
+ if (!elem) return 0;
+ nk_zero_struct(*elem);
+ return &elem->data.pan;
+}
+NK_LIB void
+nk_free_panel(struct nk_context *ctx, struct nk_panel *pan)
+{
+ union nk_page_data *pd = NK_CONTAINER_OF(pan, union nk_page_data, pan);
+ struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data);
+ nk_free_page_element(ctx, pe);
+}
+NK_LIB nk_bool
+nk_panel_has_header(nk_flags flags, const char *title)
+{
+ nk_bool active = 0;
+ active = (flags & (NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE));
+ active = active || (flags & NK_WINDOW_TITLE);
+ active = active && !(flags & NK_WINDOW_HIDDEN) && title;
+ return active;
+}
+NK_LIB struct nk_vec2
+nk_panel_get_padding(const struct nk_style *style, enum nk_panel_type type)
+{
+ switch (type) {
+ default:
+ case NK_PANEL_WINDOW: return style->window.padding;
+ case NK_PANEL_GROUP: return style->window.group_padding;
+ case NK_PANEL_POPUP: return style->window.popup_padding;
+ case NK_PANEL_CONTEXTUAL: return style->window.contextual_padding;
+ case NK_PANEL_COMBO: return style->window.combo_padding;
+ case NK_PANEL_MENU: return style->window.menu_padding;
+ case NK_PANEL_TOOLTIP: return style->window.menu_padding;}
+}
+NK_LIB float
+nk_panel_get_border(const struct nk_style *style, nk_flags flags,
+ enum nk_panel_type type)
+{
+ if (flags & NK_WINDOW_BORDER) {
+ switch (type) {
+ default:
+ case NK_PANEL_WINDOW: return style->window.border;
+ case NK_PANEL_GROUP: return style->window.group_border;
+ case NK_PANEL_POPUP: return style->window.popup_border;
+ case NK_PANEL_CONTEXTUAL: return style->window.contextual_border;
+ case NK_PANEL_COMBO: return style->window.combo_border;
+ case NK_PANEL_MENU: return style->window.menu_border;
+ case NK_PANEL_TOOLTIP: return style->window.menu_border;
+ }} else return 0;
+}
+NK_LIB struct nk_color
+nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type)
+{
+ switch (type) {
+ default:
+ case NK_PANEL_WINDOW: return style->window.border_color;
+ case NK_PANEL_GROUP: return style->window.group_border_color;
+ case NK_PANEL_POPUP: return style->window.popup_border_color;
+ case NK_PANEL_CONTEXTUAL: return style->window.contextual_border_color;
+ case NK_PANEL_COMBO: return style->window.combo_border_color;
+ case NK_PANEL_MENU: return style->window.menu_border_color;
+ case NK_PANEL_TOOLTIP: return style->window.menu_border_color;}
+}
+NK_LIB nk_bool
+nk_panel_is_sub(enum nk_panel_type type)
+{
+ return ((int)type & (int)NK_PANEL_SET_SUB)?1:0;
+}
+NK_LIB nk_bool
+nk_panel_is_nonblock(enum nk_panel_type type)
+{
+ return ((int)type & (int)NK_PANEL_SET_NONBLOCK)?1:0;
+}
+NK_LIB nk_bool
+nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type)
+{
+ struct nk_input *in;
+ struct nk_window *win;
+ struct nk_panel *layout;
+ struct nk_command_buffer *out;
+ const struct nk_style *style;
+ const struct nk_user_font *font;
+
+ struct nk_vec2 scrollbar_size;
+ struct nk_vec2 panel_padding;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) return 0;
+ nk_zero(ctx->current->layout, sizeof(*ctx->current->layout));
+ if ((ctx->current->flags & NK_WINDOW_HIDDEN) || (ctx->current->flags & NK_WINDOW_CLOSED)) {
+ nk_zero(ctx->current->layout, sizeof(struct nk_panel));
+ ctx->current->layout->type = panel_type;
+ return 0;
+ }
+ /* pull state into local stack */
+ style = &ctx->style;
+ font = style->font;
+ win = ctx->current;
+ layout = win->layout;
+ out = &win->buffer;
+ in = (win->flags & NK_WINDOW_NO_INPUT) ? 0: &ctx->input;
+#ifdef NK_INCLUDE_COMMAND_USERDATA
+ win->buffer.userdata = ctx->userdata;
+#endif
+ /* pull style configuration into local stack */
+ scrollbar_size = style->window.scrollbar_size;
+ panel_padding = nk_panel_get_padding(style, panel_type);
+
+ /* window movement */
+ if ((win->flags & NK_WINDOW_MOVABLE) && !(win->flags & NK_WINDOW_ROM)) {
+ nk_bool left_mouse_down;
+ unsigned int left_mouse_clicked;
+ int left_mouse_click_in_cursor;
+
+ /* calculate draggable window space */
+ struct nk_rect header;
+ header.x = win->bounds.x;
+ header.y = win->bounds.y;
+ header.w = win->bounds.w;
+ if (nk_panel_has_header(win->flags, title)) {
+ header.h = font->height + 2.0f * style->window.header.padding.y;
+ header.h += 2.0f * style->window.header.label_padding.y;
+ } else header.h = panel_padding.y;
+
+ /* window movement by dragging */
+ left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down;
+ left_mouse_clicked = in->mouse.buttons[NK_BUTTON_LEFT].clicked;
+ left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in,
+ NK_BUTTON_LEFT, header, nk_true);
+ if (left_mouse_down && left_mouse_click_in_cursor && !left_mouse_clicked) {
+ win->bounds.x = win->bounds.x + in->mouse.delta.x;
+ win->bounds.y = win->bounds.y + in->mouse.delta.y;
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x += in->mouse.delta.x;
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y += in->mouse.delta.y;
+ ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_MOVE];
+ }
+ }
+
+ /* setup panel */
+ layout->type = panel_type;
+ layout->flags = win->flags;
+ layout->bounds = win->bounds;
+ layout->bounds.x += panel_padding.x;
+ layout->bounds.w -= 2*panel_padding.x;
+ if (win->flags & NK_WINDOW_BORDER) {
+ layout->border = nk_panel_get_border(style, win->flags, panel_type);
+ layout->bounds = nk_shrink_rect(layout->bounds, layout->border);
+ } else layout->border = 0;
+ layout->at_y = layout->bounds.y;
+ layout->at_x = layout->bounds.x;
+ layout->max_x = 0;
+ layout->header_height = 0;
+ layout->footer_height = 0;
+ nk_layout_reset_min_row_height(ctx);
+ layout->row.index = 0;
+ layout->row.columns = 0;
+ layout->row.ratio = 0;
+ layout->row.item_width = 0;
+ layout->row.tree_depth = 0;
+ layout->row.height = panel_padding.y;
+ layout->has_scrolling = nk_true;
+ if (!(win->flags & NK_WINDOW_NO_SCROLLBAR))
+ layout->bounds.w -= scrollbar_size.x;
+ if (!nk_panel_is_nonblock(panel_type)) {
+ layout->footer_height = 0;
+ if (!(win->flags & NK_WINDOW_NO_SCROLLBAR) || win->flags & NK_WINDOW_SCALABLE)
+ layout->footer_height = scrollbar_size.y;
+ layout->bounds.h -= layout->footer_height;
+ }
+
+ /* panel header */
+ if (nk_panel_has_header(win->flags, title))
+ {
+ struct nk_text text;
+ struct nk_rect header;
+ const struct nk_style_item *background = 0;
+
+ /* calculate header bounds */
+ header.x = win->bounds.x;
+ header.y = win->bounds.y;
+ header.w = win->bounds.w;
+ header.h = font->height + 2.0f * style->window.header.padding.y;
+ header.h += (2.0f * style->window.header.label_padding.y);
+
+ /* shrink panel by header */
+ layout->header_height = header.h;
+ layout->bounds.y += header.h;
+ layout->bounds.h -= header.h;
+ layout->at_y += header.h;
+
+ /* select correct header background and text color */
+ if (ctx->active == win) {
+ background = &style->window.header.active;
+ text.text = style->window.header.label_active;
+ } else if (nk_input_is_mouse_hovering_rect(&ctx->input, header)) {
+ background = &style->window.header.hover;
+ text.text = style->window.header.label_hover;
+ } else {
+ background = &style->window.header.normal;
+ text.text = style->window.header.label_normal;
+ }
+
+ /* draw header background */
+ header.h += 1.0f;
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ text.background = nk_rgba(0,0,0,0);
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_white);
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white);
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ text.background = background->data.color;
+ nk_fill_rect(out, header, 0, background->data.color);
+ break;
+ }
+
+ /* window close button */
+ {struct nk_rect button;
+ button.y = header.y + style->window.header.padding.y;
+ button.h = header.h - 2 * style->window.header.padding.y;
+ button.w = button.h;
+ if (win->flags & NK_WINDOW_CLOSABLE) {
+ nk_flags ws = 0;
+ if (style->window.header.align == NK_HEADER_RIGHT) {
+ button.x = (header.w + header.x) - (button.w + style->window.header.padding.x);
+ header.w -= button.w + style->window.header.spacing.x + style->window.header.padding.x;
+ } else {
+ button.x = header.x + style->window.header.padding.x;
+ header.x += button.w + style->window.header.spacing.x + style->window.header.padding.x;
+ }
+
+ if (nk_do_button_symbol(&ws, &win->buffer, button,
+ style->window.header.close_symbol, NK_BUTTON_DEFAULT,
+ &style->window.header.close_button, in, style->font) && !(win->flags & NK_WINDOW_ROM))
+ {
+ layout->flags |= NK_WINDOW_HIDDEN;
+ layout->flags &= (nk_flags)~NK_WINDOW_MINIMIZED;
+ }
+ }
+
+ /* window minimize button */
+ if (win->flags & NK_WINDOW_MINIMIZABLE) {
+ nk_flags ws = 0;
+ if (style->window.header.align == NK_HEADER_RIGHT) {
+ button.x = (header.w + header.x) - button.w;
+ if (!(win->flags & NK_WINDOW_CLOSABLE)) {
+ button.x -= style->window.header.padding.x;
+ header.w -= style->window.header.padding.x;
+ }
+ header.w -= button.w + style->window.header.spacing.x;
+ } else {
+ button.x = header.x;
+ header.x += button.w + style->window.header.spacing.x + style->window.header.padding.x;
+ }
+ if (nk_do_button_symbol(&ws, &win->buffer, button, (layout->flags & NK_WINDOW_MINIMIZED)?
+ style->window.header.maximize_symbol: style->window.header.minimize_symbol,
+ NK_BUTTON_DEFAULT, &style->window.header.minimize_button, in, style->font) && !(win->flags & NK_WINDOW_ROM))
+ layout->flags = (layout->flags & NK_WINDOW_MINIMIZED) ?
+ layout->flags & (nk_flags)~NK_WINDOW_MINIMIZED:
+ layout->flags | NK_WINDOW_MINIMIZED;
+ }}
+
+ {/* window header title */
+ int text_len = nk_strlen(title);
+ struct nk_rect label = {0,0,0,0};
+ float t = font->width(font->userdata, font->height, title, text_len);
+ text.padding = nk_vec2(0,0);
+
+ label.x = header.x + style->window.header.padding.x;
+ label.x += style->window.header.label_padding.x;
+ label.y = header.y + style->window.header.label_padding.y;
+ label.h = font->height + 2 * style->window.header.label_padding.y;
+ label.w = t + 2 * style->window.header.spacing.x;
+ label.w = NK_CLAMP(0, label.w, header.x + header.w - label.x);
+ nk_widget_text(out, label, (const char*)title, text_len, &text, NK_TEXT_LEFT, font);}
+ }
+
+ /* draw window background */
+ if (!(layout->flags & NK_WINDOW_MINIMIZED) && !(layout->flags & NK_WINDOW_DYNAMIC)) {
+ struct nk_rect body;
+ body.x = win->bounds.x;
+ body.w = win->bounds.w;
+ body.y = (win->bounds.y + layout->header_height);
+ body.h = (win->bounds.h - layout->header_height);
+
+ switch(style->window.fixed_background.type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, body, &style->window.fixed_background.data.image, nk_white);
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, body, &style->window.fixed_background.data.slice, nk_white);
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, body, 0, style->window.fixed_background.data.color);
+ break;
+ }
+ }
+
+ /* set clipping rectangle */
+ {struct nk_rect clip;
+ layout->clip = layout->bounds;
+ nk_unify(&clip, &win->buffer.clip, layout->clip.x, layout->clip.y,
+ layout->clip.x + layout->clip.w, layout->clip.y + layout->clip.h);
+ nk_push_scissor(out, clip);
+ layout->clip = clip;}
+ return !(layout->flags & NK_WINDOW_HIDDEN) && !(layout->flags & NK_WINDOW_MINIMIZED);
+}
+NK_LIB void
+nk_panel_end(struct nk_context *ctx)
+{
+ struct nk_input *in;
+ struct nk_window *window;
+ struct nk_panel *layout;
+ const struct nk_style *style;
+ struct nk_command_buffer *out;
+
+ struct nk_vec2 scrollbar_size;
+ struct nk_vec2 panel_padding;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ window = ctx->current;
+ layout = window->layout;
+ style = &ctx->style;
+ out = &window->buffer;
+ in = (layout->flags & NK_WINDOW_ROM || layout->flags & NK_WINDOW_NO_INPUT) ? 0 :&ctx->input;
+ if (!nk_panel_is_sub(layout->type))
+ nk_push_scissor(out, nk_null_rect);
+
+ /* cache configuration data */
+ scrollbar_size = style->window.scrollbar_size;
+ panel_padding = nk_panel_get_padding(style, layout->type);
+
+ /* update the current cursor Y-position to point over the last added widget */
+ layout->at_y += layout->row.height;
+
+ /* dynamic panels */
+ if (layout->flags & NK_WINDOW_DYNAMIC && !(layout->flags & NK_WINDOW_MINIMIZED))
+ {
+ /* update panel height to fit dynamic growth */
+ struct nk_rect empty_space;
+ if (layout->at_y < (layout->bounds.y + layout->bounds.h))
+ layout->bounds.h = layout->at_y - layout->bounds.y;
+
+ /* fill top empty space */
+ empty_space.x = window->bounds.x;
+ empty_space.y = layout->bounds.y;
+ empty_space.h = panel_padding.y;
+ empty_space.w = window->bounds.w;
+ nk_fill_rect(out, empty_space, 0, style->window.background);
+
+ /* fill left empty space */
+ empty_space.x = window->bounds.x;
+ empty_space.y = layout->bounds.y;
+ empty_space.w = panel_padding.x + layout->border;
+ empty_space.h = layout->bounds.h;
+ nk_fill_rect(out, empty_space, 0, style->window.background);
+
+ /* fill right empty space */
+ empty_space.x = layout->bounds.x + layout->bounds.w;
+ empty_space.y = layout->bounds.y;
+ empty_space.w = panel_padding.x + layout->border;
+ empty_space.h = layout->bounds.h;
+ if (*layout->offset_y == 0 && !(layout->flags & NK_WINDOW_NO_SCROLLBAR))
+ empty_space.w += scrollbar_size.x;
+ nk_fill_rect(out, empty_space, 0, style->window.background);
+
+ /* fill bottom empty space */
+ if (layout->footer_height > 0) {
+ empty_space.x = window->bounds.x;
+ empty_space.y = layout->bounds.y + layout->bounds.h;
+ empty_space.w = window->bounds.w;
+ empty_space.h = layout->footer_height;
+ nk_fill_rect(out, empty_space, 0, style->window.background);
+ }
+ }
+
+ /* scrollbars */
+ if (!(layout->flags & NK_WINDOW_NO_SCROLLBAR) &&
+ !(layout->flags & NK_WINDOW_MINIMIZED) &&
+ window->scrollbar_hiding_timer < NK_SCROLLBAR_HIDING_TIMEOUT)
+ {
+ struct nk_rect scroll;
+ int scroll_has_scrolling;
+ float scroll_target;
+ float scroll_offset;
+ float scroll_step;
+ float scroll_inc;
+
+ /* mouse wheel scrolling */
+ if (nk_panel_is_sub(layout->type))
+ {
+ /* sub-window mouse wheel scrolling */
+ struct nk_window *root_window = window;
+ struct nk_panel *root_panel = window->layout;
+ while (root_panel->parent)
+ root_panel = root_panel->parent;
+ while (root_window->parent)
+ root_window = root_window->parent;
+
+ /* only allow scrolling if parent window is active */
+ scroll_has_scrolling = 0;
+ if ((root_window == ctx->active) && layout->has_scrolling) {
+ /* and panel is being hovered and inside clip rect*/
+ if (nk_input_is_mouse_hovering_rect(in, layout->bounds) &&
+ NK_INTERSECT(layout->bounds.x, layout->bounds.y, layout->bounds.w, layout->bounds.h,
+ root_panel->clip.x, root_panel->clip.y, root_panel->clip.w, root_panel->clip.h))
+ {
+ /* deactivate all parent scrolling */
+ root_panel = window->layout;
+ while (root_panel->parent) {
+ root_panel->has_scrolling = nk_false;
+ root_panel = root_panel->parent;
+ }
+ root_panel->has_scrolling = nk_false;
+ scroll_has_scrolling = nk_true;
+ }
+ }
+ } else if (!nk_panel_is_sub(layout->type)) {
+ /* window mouse wheel scrolling */
+ scroll_has_scrolling = (window == ctx->active) && layout->has_scrolling;
+ if (in && (in->mouse.scroll_delta.y > 0 || in->mouse.scroll_delta.x > 0) && scroll_has_scrolling)
+ window->scrolled = nk_true;
+ else window->scrolled = nk_false;
+ } else scroll_has_scrolling = nk_false;
+
+ {
+ /* vertical scrollbar */
+ nk_flags state = 0;
+ scroll.x = layout->bounds.x + layout->bounds.w + panel_padding.x;
+ scroll.y = layout->bounds.y;
+ scroll.w = scrollbar_size.x;
+ scroll.h = layout->bounds.h;
+
+ scroll_offset = (float)*layout->offset_y;
+ scroll_step = scroll.h * 0.10f;
+ scroll_inc = scroll.h * 0.01f;
+ scroll_target = (float)(int)(layout->at_y - scroll.y);
+ scroll_offset = nk_do_scrollbarv(&state, out, scroll, scroll_has_scrolling,
+ scroll_offset, scroll_target, scroll_step, scroll_inc,
+ &ctx->style.scrollv, in, style->font);
+ *layout->offset_y = (nk_uint)scroll_offset;
+ if (in && scroll_has_scrolling)
+ in->mouse.scroll_delta.y = 0;
+ }
+ {
+ /* horizontal scrollbar */
+ nk_flags state = 0;
+ scroll.x = layout->bounds.x;
+ scroll.y = layout->bounds.y + layout->bounds.h;
+ scroll.w = layout->bounds.w;
+ scroll.h = scrollbar_size.y;
+
+ scroll_offset = (float)*layout->offset_x;
+ scroll_target = (float)(int)(layout->max_x - scroll.x);
+ scroll_step = layout->max_x * 0.05f;
+ scroll_inc = layout->max_x * 0.005f;
+ scroll_offset = nk_do_scrollbarh(&state, out, scroll, scroll_has_scrolling,
+ scroll_offset, scroll_target, scroll_step, scroll_inc,
+ &ctx->style.scrollh, in, style->font);
+ *layout->offset_x = (nk_uint)scroll_offset;
+ }
+ }
+
+ /* hide scroll if no user input */
+ if (window->flags & NK_WINDOW_SCROLL_AUTO_HIDE) {
+ int has_input = ctx->input.mouse.delta.x != 0 || ctx->input.mouse.delta.y != 0 || ctx->input.mouse.scroll_delta.y != 0;
+ int is_window_hovered = nk_window_is_hovered(ctx);
+ int any_item_active = (ctx->last_widget_state & NK_WIDGET_STATE_MODIFIED);
+ if ((!has_input && is_window_hovered) || (!is_window_hovered && !any_item_active))
+ window->scrollbar_hiding_timer += ctx->delta_time_seconds;
+ else window->scrollbar_hiding_timer = 0;
+ } else window->scrollbar_hiding_timer = 0;
+
+ /* window border */
+ if (layout->flags & NK_WINDOW_BORDER)
+ {
+ struct nk_color border_color = nk_panel_get_border_color(style, layout->type);
+ const float padding_y = (layout->flags & NK_WINDOW_MINIMIZED)
+ ? (style->window.border + window->bounds.y + layout->header_height)
+ : ((layout->flags & NK_WINDOW_DYNAMIC)
+ ? (layout->bounds.y + layout->bounds.h + layout->footer_height)
+ : (window->bounds.y + window->bounds.h));
+ struct nk_rect b = window->bounds;
+ b.h = padding_y - window->bounds.y;
+ nk_stroke_rect(out, b, 0, layout->border, border_color);
+ }
+
+ /* scaler */
+ if ((layout->flags & NK_WINDOW_SCALABLE) && in && !(layout->flags & NK_WINDOW_MINIMIZED))
+ {
+ /* calculate scaler bounds */
+ struct nk_rect scaler;
+ scaler.w = scrollbar_size.x;
+ scaler.h = scrollbar_size.y;
+ scaler.y = layout->bounds.y + layout->bounds.h;
+ if (layout->flags & NK_WINDOW_SCALE_LEFT)
+ scaler.x = layout->bounds.x - panel_padding.x * 0.5f;
+ else scaler.x = layout->bounds.x + layout->bounds.w + panel_padding.x;
+ if (layout->flags & NK_WINDOW_NO_SCROLLBAR)
+ scaler.x -= scaler.w;
+
+ /* draw scaler */
+ {const struct nk_style_item *item = &style->window.scaler;
+ if (item->type == NK_STYLE_ITEM_IMAGE)
+ nk_draw_image(out, scaler, &item->data.image, nk_white);
+ else {
+ if (layout->flags & NK_WINDOW_SCALE_LEFT) {
+ nk_fill_triangle(out, scaler.x, scaler.y, scaler.x,
+ scaler.y + scaler.h, scaler.x + scaler.w,
+ scaler.y + scaler.h, item->data.color);
+ } else {
+ nk_fill_triangle(out, scaler.x + scaler.w, scaler.y, scaler.x + scaler.w,
+ scaler.y + scaler.h, scaler.x, scaler.y + scaler.h, item->data.color);
+ }
+ }}
+
+ /* do window scaling */
+ if (!(window->flags & NK_WINDOW_ROM)) {
+ struct nk_vec2 window_size = style->window.min_size;
+ int left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down;
+ int left_mouse_click_in_scaler = nk_input_has_mouse_click_down_in_rect(in,
+ NK_BUTTON_LEFT, scaler, nk_true);
+
+ if (left_mouse_down && left_mouse_click_in_scaler) {
+ float delta_x = in->mouse.delta.x;
+ if (layout->flags & NK_WINDOW_SCALE_LEFT) {
+ delta_x = -delta_x;
+ window->bounds.x += in->mouse.delta.x;
+ }
+ /* dragging in x-direction */
+ if (window->bounds.w + delta_x >= window_size.x) {
+ if ((delta_x < 0) || (delta_x > 0 && in->mouse.pos.x >= scaler.x)) {
+ window->bounds.w = window->bounds.w + delta_x;
+ scaler.x += in->mouse.delta.x;
+ }
+ }
+ /* dragging in y-direction (only possible if static window) */
+ if (!(layout->flags & NK_WINDOW_DYNAMIC)) {
+ if (window_size.y < window->bounds.h + in->mouse.delta.y) {
+ if ((in->mouse.delta.y < 0) || (in->mouse.delta.y > 0 && in->mouse.pos.y >= scaler.y)) {
+ window->bounds.h = window->bounds.h + in->mouse.delta.y;
+ scaler.y += in->mouse.delta.y;
+ }
+ }
+ }
+ ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT];
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = scaler.x + scaler.w/2.0f;
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y = scaler.y + scaler.h/2.0f;
+ }
+ }
+ }
+ if (!nk_panel_is_sub(layout->type)) {
+ /* window is hidden so clear command buffer */
+ if (layout->flags & NK_WINDOW_HIDDEN)
+ nk_command_buffer_reset(&window->buffer);
+ /* window is visible and not tab */
+ else nk_finish(ctx, window);
+ }
+
+ /* NK_WINDOW_REMOVE_ROM flag was set so remove NK_WINDOW_ROM */
+ if (layout->flags & NK_WINDOW_REMOVE_ROM) {
+ layout->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ layout->flags &= ~(nk_flags)NK_WINDOW_REMOVE_ROM;
+ }
+ window->flags = layout->flags;
+
+ /* property garbage collector */
+ if (window->property.active && window->property.old != window->property.seq &&
+ window->property.active == window->property.prev) {
+ nk_zero(&window->property, sizeof(window->property));
+ } else {
+ window->property.old = window->property.seq;
+ window->property.prev = window->property.active;
+ window->property.seq = 0;
+ }
+ /* edit garbage collector */
+ if (window->edit.active && window->edit.old != window->edit.seq &&
+ window->edit.active == window->edit.prev) {
+ nk_zero(&window->edit, sizeof(window->edit));
+ } else {
+ window->edit.old = window->edit.seq;
+ window->edit.prev = window->edit.active;
+ window->edit.seq = 0;
+ }
+ /* contextual garbage collector */
+ if (window->popup.active_con && window->popup.con_old != window->popup.con_count) {
+ window->popup.con_count = 0;
+ window->popup.con_old = 0;
+ window->popup.active_con = 0;
+ } else {
+ window->popup.con_old = window->popup.con_count;
+ window->popup.con_count = 0;
+ }
+ window->popup.combo_count = 0;
+ /* helper to make sure you have a 'nk_tree_push' for every 'nk_tree_pop' */
+ NK_ASSERT(!layout->row.tree_depth);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * WINDOW
+ *
+ * ===============================================================*/
+NK_LIB void*
+nk_create_window(struct nk_context *ctx)
+{
+ struct nk_page_element *elem;
+ elem = nk_create_page_element(ctx);
+ if (!elem) return 0;
+ elem->data.win.seq = ctx->seq;
+ return &elem->data.win;
+}
+NK_LIB void
+nk_free_window(struct nk_context *ctx, struct nk_window *win)
+{
+ /* unlink windows from list */
+ struct nk_table *it = win->tables;
+ if (win->popup.win) {
+ nk_free_window(ctx, win->popup.win);
+ win->popup.win = 0;
+ }
+ win->next = 0;
+ win->prev = 0;
+
+ while (it) {
+ /*free window state tables */
+ struct nk_table *n = it->next;
+ nk_remove_table(win, it);
+ nk_free_table(ctx, it);
+ if (it == win->tables)
+ win->tables = n;
+ it = n;
+ }
+
+ /* link windows into freelist */
+ {union nk_page_data *pd = NK_CONTAINER_OF(win, union nk_page_data, win);
+ struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data);
+ nk_free_page_element(ctx, pe);}
+}
+NK_LIB struct nk_window*
+nk_find_window(struct nk_context *ctx, nk_hash hash, const char *name)
+{
+ struct nk_window *iter;
+ iter = ctx->begin;
+ while (iter) {
+ NK_ASSERT(iter != iter->next);
+ if (iter->name == hash) {
+ int max_len = nk_strlen(iter->name_string);
+ if (!nk_stricmpn(iter->name_string, name, max_len))
+ return iter;
+ }
+ iter = iter->next;
+ }
+ return 0;
+}
+NK_LIB void
+nk_insert_window(struct nk_context *ctx, struct nk_window *win,
+ enum nk_window_insert_location loc)
+{
+ const struct nk_window *iter;
+ NK_ASSERT(ctx);
+ NK_ASSERT(win);
+ if (!win || !ctx) return;
+
+ iter = ctx->begin;
+ while (iter) {
+ NK_ASSERT(iter != iter->next);
+ NK_ASSERT(iter != win);
+ if (iter == win) return;
+ iter = iter->next;
+ }
+
+ if (!ctx->begin) {
+ win->next = 0;
+ win->prev = 0;
+ ctx->begin = win;
+ ctx->end = win;
+ ctx->count = 1;
+ return;
+ }
+ if (loc == NK_INSERT_BACK) {
+ struct nk_window *end;
+ end = ctx->end;
+ end->flags |= NK_WINDOW_ROM;
+ end->next = win;
+ win->prev = ctx->end;
+ win->next = 0;
+ ctx->end = win;
+ ctx->active = ctx->end;
+ ctx->end->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ } else {
+ /*ctx->end->flags |= NK_WINDOW_ROM;*/
+ ctx->begin->prev = win;
+ win->next = ctx->begin;
+ win->prev = 0;
+ ctx->begin = win;
+ ctx->begin->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ }
+ ctx->count++;
+}
+NK_LIB void
+nk_remove_window(struct nk_context *ctx, struct nk_window *win)
+{
+ if (win == ctx->begin || win == ctx->end) {
+ if (win == ctx->begin) {
+ ctx->begin = win->next;
+ if (win->next)
+ win->next->prev = 0;
+ }
+ if (win == ctx->end) {
+ ctx->end = win->prev;
+ if (win->prev)
+ win->prev->next = 0;
+ }
+ } else {
+ if (win->next)
+ win->next->prev = win->prev;
+ if (win->prev)
+ win->prev->next = win->next;
+ }
+ if (win == ctx->active || !ctx->active) {
+ ctx->active = ctx->end;
+ if (ctx->end)
+ ctx->end->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ }
+ win->next = 0;
+ win->prev = 0;
+ ctx->count--;
+}
+NK_API nk_bool
+nk_begin(struct nk_context *ctx, const char *title,
+ struct nk_rect bounds, nk_flags flags)
+{
+ return nk_begin_titled(ctx, title, title, bounds, flags);
+}
+NK_API nk_bool
+nk_begin_titled(struct nk_context *ctx, const char *name, const char *title,
+ struct nk_rect bounds, nk_flags flags)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ nk_hash name_hash;
+ int name_len;
+ int ret = 0;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+ NK_ASSERT(title);
+ NK_ASSERT(ctx->style.font && ctx->style.font->width && "if this triggers you forgot to add a font");
+ NK_ASSERT(!ctx->current && "if this triggers you missed a `nk_end` call");
+ if (!ctx || ctx->current || !title || !name)
+ return 0;
+
+ /* find or create window */
+ style = &ctx->style;
+ name_len = (int)nk_strlen(name);
+ name_hash = nk_murmur_hash(name, (int)name_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, name_hash, name);
+ if (!win) {
+ /* create new window */
+ nk_size name_length = (nk_size)name_len;
+ win = (struct nk_window*)nk_create_window(ctx);
+ NK_ASSERT(win);
+ if (!win) return 0;
+
+ if (flags & NK_WINDOW_BACKGROUND)
+ nk_insert_window(ctx, win, NK_INSERT_FRONT);
+ else nk_insert_window(ctx, win, NK_INSERT_BACK);
+ nk_command_buffer_init(&win->buffer, &ctx->memory, NK_CLIPPING_ON);
+
+ win->flags = flags;
+ win->bounds = bounds;
+ win->name = name_hash;
+ name_length = NK_MIN(name_length, NK_WINDOW_MAX_NAME-1);
+ NK_MEMCPY(win->name_string, name, name_length);
+ win->name_string[name_length] = 0;
+ win->popup.win = 0;
+ win->widgets_disabled = nk_false;
+ if (!ctx->active)
+ ctx->active = win;
+ } else {
+ /* update window */
+ win->flags &= ~(nk_flags)(NK_WINDOW_PRIVATE-1);
+ win->flags |= flags;
+ if (!(win->flags & (NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE)))
+ win->bounds = bounds;
+ /* If this assert triggers you either:
+ *
+ * I.) Have more than one window with the same name or
+ * II.) You forgot to actually draw the window.
+ * More specific you did not call `nk_clear` (nk_clear will be
+ * automatically called for you if you are using one of the
+ * provided demo backends). */
+ NK_ASSERT(win->seq != ctx->seq);
+ win->seq = ctx->seq;
+ if (!ctx->active && !(win->flags & NK_WINDOW_HIDDEN)) {
+ ctx->active = win;
+ ctx->end = win;
+ }
+ }
+ if (win->flags & NK_WINDOW_HIDDEN) {
+ ctx->current = win;
+ win->layout = 0;
+ return 0;
+ } else nk_start(ctx, win);
+
+ /* window overlapping */
+ if (!(win->flags & NK_WINDOW_HIDDEN) && !(win->flags & NK_WINDOW_NO_INPUT))
+ {
+ int inpanel, ishovered;
+ struct nk_window *iter = win;
+ float h = ctx->style.font->height + 2.0f * style->window.header.padding.y +
+ (2.0f * style->window.header.label_padding.y);
+ struct nk_rect win_bounds = (!(win->flags & NK_WINDOW_MINIMIZED))?
+ win->bounds: nk_rect(win->bounds.x, win->bounds.y, win->bounds.w, h);
+
+ /* activate window if hovered and no other window is overlapping this window */
+ inpanel = nk_input_has_mouse_click_down_in_rect(&ctx->input, NK_BUTTON_LEFT, win_bounds, nk_true);
+ inpanel = inpanel && ctx->input.mouse.buttons[NK_BUTTON_LEFT].clicked;
+ ishovered = nk_input_is_mouse_hovering_rect(&ctx->input, win_bounds);
+ if ((win != ctx->active) && ishovered && !ctx->input.mouse.buttons[NK_BUTTON_LEFT].down) {
+ iter = win->next;
+ while (iter) {
+ struct nk_rect iter_bounds = (!(iter->flags & NK_WINDOW_MINIMIZED))?
+ iter->bounds: nk_rect(iter->bounds.x, iter->bounds.y, iter->bounds.w, h);
+ if (NK_INTERSECT(win_bounds.x, win_bounds.y, win_bounds.w, win_bounds.h,
+ iter_bounds.x, iter_bounds.y, iter_bounds.w, iter_bounds.h) &&
+ (!(iter->flags & NK_WINDOW_HIDDEN)))
+ break;
+
+ if (iter->popup.win && iter->popup.active && !(iter->flags & NK_WINDOW_HIDDEN) &&
+ NK_INTERSECT(win->bounds.x, win_bounds.y, win_bounds.w, win_bounds.h,
+ iter->popup.win->bounds.x, iter->popup.win->bounds.y,
+ iter->popup.win->bounds.w, iter->popup.win->bounds.h))
+ break;
+ iter = iter->next;
+ }
+ }
+
+ /* activate window if clicked */
+ if (iter && inpanel && (win != ctx->end)) {
+ iter = win->next;
+ while (iter) {
+ /* try to find a panel with higher priority in the same position */
+ struct nk_rect iter_bounds = (!(iter->flags & NK_WINDOW_MINIMIZED))?
+ iter->bounds: nk_rect(iter->bounds.x, iter->bounds.y, iter->bounds.w, h);
+ if (NK_INBOX(ctx->input.mouse.pos.x, ctx->input.mouse.pos.y,
+ iter_bounds.x, iter_bounds.y, iter_bounds.w, iter_bounds.h) &&
+ !(iter->flags & NK_WINDOW_HIDDEN))
+ break;
+ if (iter->popup.win && iter->popup.active && !(iter->flags & NK_WINDOW_HIDDEN) &&
+ NK_INTERSECT(win_bounds.x, win_bounds.y, win_bounds.w, win_bounds.h,
+ iter->popup.win->bounds.x, iter->popup.win->bounds.y,
+ iter->popup.win->bounds.w, iter->popup.win->bounds.h))
+ break;
+ iter = iter->next;
+ }
+ }
+ if (iter && !(win->flags & NK_WINDOW_ROM) && (win->flags & NK_WINDOW_BACKGROUND)) {
+ win->flags |= (nk_flags)NK_WINDOW_ROM;
+ iter->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ ctx->active = iter;
+ if (!(iter->flags & NK_WINDOW_BACKGROUND)) {
+ /* current window is active in that position so transfer to top
+ * at the highest priority in stack */
+ nk_remove_window(ctx, iter);
+ nk_insert_window(ctx, iter, NK_INSERT_BACK);
+ }
+ } else {
+ if (!iter && ctx->end != win) {
+ if (!(win->flags & NK_WINDOW_BACKGROUND)) {
+ /* current window is active in that position so transfer to top
+ * at the highest priority in stack */
+ nk_remove_window(ctx, win);
+ nk_insert_window(ctx, win, NK_INSERT_BACK);
+ }
+ win->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ ctx->active = win;
+ }
+ if (ctx->end != win && !(win->flags & NK_WINDOW_BACKGROUND))
+ win->flags |= NK_WINDOW_ROM;
+ }
+ }
+ win->layout = (struct nk_panel*)nk_create_panel(ctx);
+ ctx->current = win;
+ ret = nk_panel_begin(ctx, title, NK_PANEL_WINDOW);
+ win->layout->offset_x = &win->scrollbar.x;
+ win->layout->offset_y = &win->scrollbar.y;
+ return ret;
+}
+NK_API void
+nk_end(struct nk_context *ctx)
+{
+ struct nk_panel *layout;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current && "if this triggers you forgot to call `nk_begin`");
+ if (!ctx || !ctx->current)
+ return;
+
+ layout = ctx->current->layout;
+ if (!layout || (layout->type == NK_PANEL_WINDOW && (ctx->current->flags & NK_WINDOW_HIDDEN))) {
+ ctx->current = 0;
+ return;
+ }
+ nk_panel_end(ctx);
+ nk_free_panel(ctx, ctx->current->layout);
+ ctx->current = 0;
+}
+NK_API struct nk_rect
+nk_window_get_bounds(const struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return nk_rect(0,0,0,0);
+ return ctx->current->bounds;
+}
+NK_API struct nk_vec2
+nk_window_get_position(const struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return nk_vec2(0,0);
+ return nk_vec2(ctx->current->bounds.x, ctx->current->bounds.y);
+}
+NK_API struct nk_vec2
+nk_window_get_size(const struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return nk_vec2(0,0);
+ return nk_vec2(ctx->current->bounds.w, ctx->current->bounds.h);
+}
+NK_API float
+nk_window_get_width(const struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return 0;
+ return ctx->current->bounds.w;
+}
+NK_API float
+nk_window_get_height(const struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return 0;
+ return ctx->current->bounds.h;
+}
+NK_API struct nk_rect
+nk_window_get_content_region(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return nk_rect(0,0,0,0);
+ return ctx->current->layout->clip;
+}
+NK_API struct nk_vec2
+nk_window_get_content_region_min(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current) return nk_vec2(0,0);
+ return nk_vec2(ctx->current->layout->clip.x, ctx->current->layout->clip.y);
+}
+NK_API struct nk_vec2
+nk_window_get_content_region_max(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current) return nk_vec2(0,0);
+ return nk_vec2(ctx->current->layout->clip.x + ctx->current->layout->clip.w,
+ ctx->current->layout->clip.y + ctx->current->layout->clip.h);
+}
+NK_API struct nk_vec2
+nk_window_get_content_region_size(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current) return nk_vec2(0,0);
+ return nk_vec2(ctx->current->layout->clip.w, ctx->current->layout->clip.h);
+}
+NK_API struct nk_command_buffer*
+nk_window_get_canvas(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current) return 0;
+ return &ctx->current->buffer;
+}
+NK_API struct nk_panel*
+nk_window_get_panel(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return 0;
+ return ctx->current->layout;
+}
+NK_API void
+nk_window_get_scroll(struct nk_context *ctx, nk_uint *offset_x, nk_uint *offset_y)
+{
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return ;
+ win = ctx->current;
+ if (offset_x)
+ *offset_x = win->scrollbar.x;
+ if (offset_y)
+ *offset_y = win->scrollbar.y;
+}
+NK_API nk_bool
+nk_window_has_focus(const struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current) return 0;
+ return ctx->current == ctx->active;
+}
+NK_API nk_bool
+nk_window_is_hovered(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current || (ctx->current->flags & NK_WINDOW_HIDDEN))
+ return 0;
+ else {
+ struct nk_rect actual_bounds = ctx->current->bounds;
+ if (ctx->begin->flags & NK_WINDOW_MINIMIZED) {
+ actual_bounds.h = ctx->current->layout->header_height;
+ }
+ return nk_input_is_mouse_hovering_rect(&ctx->input, actual_bounds);
+ }
+}
+NK_API nk_bool
+nk_window_is_any_hovered(struct nk_context *ctx)
+{
+ struct nk_window *iter;
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ iter = ctx->begin;
+ while (iter) {
+ /* check if window is being hovered */
+ if(!(iter->flags & NK_WINDOW_HIDDEN)) {
+ /* check if window popup is being hovered */
+ if (iter->popup.active && iter->popup.win && nk_input_is_mouse_hovering_rect(&ctx->input, iter->popup.win->bounds))
+ return 1;
+
+ if (iter->flags & NK_WINDOW_MINIMIZED) {
+ struct nk_rect header = iter->bounds;
+ header.h = ctx->style.font->height + 2 * ctx->style.window.header.padding.y;
+ if (nk_input_is_mouse_hovering_rect(&ctx->input, header))
+ return 1;
+ } else if (nk_input_is_mouse_hovering_rect(&ctx->input, iter->bounds)) {
+ return 1;
+ }
+ }
+ iter = iter->next;
+ }
+ return 0;
+}
+NK_API nk_bool
+nk_item_is_any_active(struct nk_context *ctx)
+{
+ int any_hovered = nk_window_is_any_hovered(ctx);
+ int any_active = (ctx->last_widget_state & NK_WIDGET_STATE_MODIFIED);
+ return any_hovered || any_active;
+}
+NK_API nk_bool
+nk_window_is_collapsed(struct nk_context *ctx, const char *name)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (!win) return 0;
+ return win->flags & NK_WINDOW_MINIMIZED;
+}
+NK_API nk_bool
+nk_window_is_closed(struct nk_context *ctx, const char *name)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return 1;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (!win) return 1;
+ return (win->flags & NK_WINDOW_CLOSED);
+}
+NK_API nk_bool
+nk_window_is_hidden(struct nk_context *ctx, const char *name)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return 1;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (!win) return 1;
+ return (win->flags & NK_WINDOW_HIDDEN);
+}
+NK_API nk_bool
+nk_window_is_active(struct nk_context *ctx, const char *name)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (!win) return 0;
+ return win == ctx->active;
+}
+NK_API struct nk_window*
+nk_window_find(struct nk_context *ctx, const char *name)
+{
+ int title_len;
+ nk_hash title_hash;
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ return nk_find_window(ctx, title_hash, name);
+}
+NK_API void
+nk_window_close(struct nk_context *ctx, const char *name)
+{
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ win = nk_window_find(ctx, name);
+ if (!win) return;
+ NK_ASSERT(ctx->current != win && "You cannot close a currently active window");
+ if (ctx->current == win) return;
+ win->flags |= NK_WINDOW_HIDDEN;
+ win->flags |= NK_WINDOW_CLOSED;
+}
+NK_API void
+nk_window_set_bounds(struct nk_context *ctx,
+ const char *name, struct nk_rect bounds)
+{
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ win = nk_window_find(ctx, name);
+ if (!win) return;
+ NK_ASSERT(ctx->current != win && "You cannot update a currently in procecss window");
+ win->bounds = bounds;
+}
+NK_API void
+nk_window_set_position(struct nk_context *ctx,
+ const char *name, struct nk_vec2 pos)
+{
+ struct nk_window *win = nk_window_find(ctx, name);
+ if (!win) return;
+ win->bounds.x = pos.x;
+ win->bounds.y = pos.y;
+}
+NK_API void
+nk_window_set_size(struct nk_context *ctx,
+ const char *name, struct nk_vec2 size)
+{
+ struct nk_window *win = nk_window_find(ctx, name);
+ if (!win) return;
+ win->bounds.w = size.x;
+ win->bounds.h = size.y;
+}
+NK_API void
+nk_window_set_scroll(struct nk_context *ctx, nk_uint offset_x, nk_uint offset_y)
+{
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return;
+ win = ctx->current;
+ win->scrollbar.x = offset_x;
+ win->scrollbar.y = offset_y;
+}
+NK_API void
+nk_window_collapse(struct nk_context *ctx, const char *name,
+ enum nk_collapse_states c)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (!win) return;
+ if (c == NK_MINIMIZED)
+ win->flags |= NK_WINDOW_MINIMIZED;
+ else win->flags &= ~(nk_flags)NK_WINDOW_MINIMIZED;
+}
+NK_API void
+nk_window_collapse_if(struct nk_context *ctx, const char *name,
+ enum nk_collapse_states c, int cond)
+{
+ NK_ASSERT(ctx);
+ if (!ctx || !cond) return;
+ nk_window_collapse(ctx, name, c);
+}
+NK_API void
+nk_window_show(struct nk_context *ctx, const char *name, enum nk_show_states s)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (!win) return;
+ if (s == NK_HIDDEN) {
+ win->flags |= NK_WINDOW_HIDDEN;
+ } else win->flags &= ~(nk_flags)NK_WINDOW_HIDDEN;
+}
+NK_API void
+nk_window_show_if(struct nk_context *ctx, const char *name,
+ enum nk_show_states s, int cond)
+{
+ NK_ASSERT(ctx);
+ if (!ctx || !cond) return;
+ nk_window_show(ctx, name, s);
+}
+
+NK_API void
+nk_window_set_focus(struct nk_context *ctx, const char *name)
+{
+ int title_len;
+ nk_hash title_hash;
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+
+ title_len = (int)nk_strlen(name);
+ title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE);
+ win = nk_find_window(ctx, title_hash, name);
+ if (win && ctx->end != win) {
+ nk_remove_window(ctx, win);
+ nk_insert_window(ctx, win, NK_INSERT_BACK);
+ }
+ ctx->active = win;
+}
+NK_API void
+nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk_bool rounding)
+{
+ struct nk_rect space;
+ enum nk_widget_layout_states state = nk_widget(&space, ctx);
+ struct nk_command_buffer *canvas = nk_window_get_canvas(ctx);
+ if (!state) return;
+ nk_fill_rect(canvas, space, rounding && space.h > 1.5f ? space.h / 2.0f : 0, color);
+}
+
+
+
+
+/* ===============================================================
+ *
+ * POPUP
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_popup_begin(struct nk_context *ctx, enum nk_popup_type type,
+ const char *title, nk_flags flags, struct nk_rect rect)
+{
+ struct nk_window *popup;
+ struct nk_window *win;
+ struct nk_panel *panel;
+
+ int title_len;
+ nk_hash title_hash;
+ nk_size allocated;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(title);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ panel = win->layout;
+ NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP) && "popups are not allowed to have popups");
+ (void)panel;
+ title_len = (int)nk_strlen(title);
+ title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP);
+
+ popup = win->popup.win;
+ if (!popup) {
+ popup = (struct nk_window*)nk_create_window(ctx);
+ popup->parent = win;
+ win->popup.win = popup;
+ win->popup.active = 0;
+ win->popup.type = NK_PANEL_POPUP;
+ }
+
+ /* make sure we have correct popup */
+ if (win->popup.name != title_hash) {
+ if (!win->popup.active) {
+ nk_zero(popup, sizeof(*popup));
+ win->popup.name = title_hash;
+ win->popup.active = 1;
+ win->popup.type = NK_PANEL_POPUP;
+ } else return 0;
+ }
+
+ /* popup position is local to window */
+ ctx->current = popup;
+ rect.x += win->layout->clip.x;
+ rect.y += win->layout->clip.y;
+
+ /* setup popup data */
+ popup->parent = win;
+ popup->bounds = rect;
+ popup->seq = ctx->seq;
+ popup->layout = (struct nk_panel*)nk_create_panel(ctx);
+ popup->flags = flags;
+ popup->flags |= NK_WINDOW_BORDER;
+ if (type == NK_POPUP_DYNAMIC)
+ popup->flags |= NK_WINDOW_DYNAMIC;
+
+ popup->buffer = win->buffer;
+ nk_start_popup(ctx, win);
+ allocated = ctx->memory.allocated;
+ nk_push_scissor(&popup->buffer, nk_null_rect);
+
+ if (nk_panel_begin(ctx, title, NK_PANEL_POPUP)) {
+ /* popup is running therefore invalidate parent panels */
+ struct nk_panel *root;
+ root = win->layout;
+ while (root) {
+ root->flags |= NK_WINDOW_ROM;
+ root->flags &= ~(nk_flags)NK_WINDOW_REMOVE_ROM;
+ root = root->parent;
+ }
+ win->popup.active = 1;
+ popup->layout->offset_x = &popup->scrollbar.x;
+ popup->layout->offset_y = &popup->scrollbar.y;
+ popup->layout->parent = win->layout;
+ return 1;
+ } else {
+ /* popup was closed/is invalid so cleanup */
+ struct nk_panel *root;
+ root = win->layout;
+ while (root) {
+ root->flags |= NK_WINDOW_REMOVE_ROM;
+ root = root->parent;
+ }
+ win->popup.buf.active = 0;
+ win->popup.active = 0;
+ ctx->memory.allocated = allocated;
+ ctx->current = win;
+ nk_free_panel(ctx, popup->layout);
+ popup->layout = 0;
+ return 0;
+ }
+}
+NK_LIB nk_bool
+nk_nonblock_begin(struct nk_context *ctx,
+ nk_flags flags, struct nk_rect body, struct nk_rect header,
+ enum nk_panel_type panel_type)
+{
+ struct nk_window *popup;
+ struct nk_window *win;
+ struct nk_panel *panel;
+ int is_active = nk_true;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ /* popups cannot have popups */
+ win = ctx->current;
+ panel = win->layout;
+ NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP));
+ (void)panel;
+ popup = win->popup.win;
+ if (!popup) {
+ /* create window for nonblocking popup */
+ popup = (struct nk_window*)nk_create_window(ctx);
+ popup->parent = win;
+ win->popup.win = popup;
+ win->popup.type = panel_type;
+ nk_command_buffer_init(&popup->buffer, &ctx->memory, NK_CLIPPING_ON);
+ } else {
+ /* close the popup if user pressed outside or in the header */
+ int pressed, in_body, in_header;
+#ifdef NK_BUTTON_TRIGGER_ON_RELEASE
+ pressed = nk_input_is_mouse_released(&ctx->input, NK_BUTTON_LEFT);
+#else
+ pressed = nk_input_is_mouse_pressed(&ctx->input, NK_BUTTON_LEFT);
+#endif
+ in_body = nk_input_is_mouse_hovering_rect(&ctx->input, body);
+ in_header = nk_input_is_mouse_hovering_rect(&ctx->input, header);
+ if (pressed && (!in_body || in_header))
+ is_active = nk_false;
+ }
+ win->popup.header = header;
+
+ if (!is_active) {
+ /* remove read only mode from all parent panels */
+ struct nk_panel *root = win->layout;
+ while (root) {
+ root->flags |= NK_WINDOW_REMOVE_ROM;
+ root = root->parent;
+ }
+ return is_active;
+ }
+ popup->bounds = body;
+ popup->parent = win;
+ popup->layout = (struct nk_panel*)nk_create_panel(ctx);
+ popup->flags = flags;
+ popup->flags |= NK_WINDOW_BORDER;
+ popup->flags |= NK_WINDOW_DYNAMIC;
+ popup->seq = ctx->seq;
+ win->popup.active = 1;
+ NK_ASSERT(popup->layout);
+
+ nk_start_popup(ctx, win);
+ popup->buffer = win->buffer;
+ nk_push_scissor(&popup->buffer, nk_null_rect);
+ ctx->current = popup;
+
+ nk_panel_begin(ctx, 0, panel_type);
+ win->buffer = popup->buffer;
+ popup->layout->parent = win->layout;
+ popup->layout->offset_x = &popup->scrollbar.x;
+ popup->layout->offset_y = &popup->scrollbar.y;
+
+ /* set read only mode to all parent panels */
+ {struct nk_panel *root;
+ root = win->layout;
+ while (root) {
+ root->flags |= NK_WINDOW_ROM;
+ root = root->parent;
+ }}
+ return is_active;
+}
+NK_API void
+nk_popup_close(struct nk_context *ctx)
+{
+ struct nk_window *popup;
+ NK_ASSERT(ctx);
+ if (!ctx || !ctx->current) return;
+
+ popup = ctx->current;
+ NK_ASSERT(popup->parent);
+ NK_ASSERT((int)popup->layout->type & (int)NK_PANEL_SET_POPUP);
+ popup->flags |= NK_WINDOW_HIDDEN;
+}
+NK_API void
+nk_popup_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_window *popup;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ popup = ctx->current;
+ if (!popup->parent) return;
+ win = popup->parent;
+ if (popup->flags & NK_WINDOW_HIDDEN) {
+ struct nk_panel *root;
+ root = win->layout;
+ while (root) {
+ root->flags |= NK_WINDOW_REMOVE_ROM;
+ root = root->parent;
+ }
+ win->popup.active = 0;
+ }
+ nk_push_scissor(&popup->buffer, nk_null_rect);
+ nk_end(ctx);
+
+ win->buffer = popup->buffer;
+ nk_finish_popup(ctx, win);
+ ctx->current = win;
+ nk_push_scissor(&win->buffer, win->layout->clip);
+}
+NK_API void
+nk_popup_get_scroll(struct nk_context *ctx, nk_uint *offset_x, nk_uint *offset_y)
+{
+ struct nk_window *popup;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ popup = ctx->current;
+ if (offset_x)
+ *offset_x = popup->scrollbar.x;
+ if (offset_y)
+ *offset_y = popup->scrollbar.y;
+}
+NK_API void
+nk_popup_set_scroll(struct nk_context *ctx, nk_uint offset_x, nk_uint offset_y)
+{
+ struct nk_window *popup;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ popup = ctx->current;
+ popup->scrollbar.x = offset_x;
+ popup->scrollbar.y = offset_y;
+}
+
+
+
+
+/* ==============================================================
+ *
+ * CONTEXTUAL
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size,
+ struct nk_rect trigger_bounds)
+{
+ struct nk_window *win;
+ struct nk_window *popup;
+ struct nk_rect body;
+ struct nk_input* in;
+
+ NK_STORAGE const struct nk_rect null_rect = {-1,-1,0,0};
+ int is_clicked = 0;
+ int is_open = 0;
+ int ret = 0;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ ++win->popup.con_count;
+ if (ctx->current != ctx->active)
+ return 0;
+
+ /* check if currently active contextual is active */
+ popup = win->popup.win;
+ is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL);
+ in = win->widgets_disabled ? 0 : &ctx->input;
+ if (in) {
+ is_clicked = nk_input_mouse_clicked(in, NK_BUTTON_RIGHT, trigger_bounds);
+ if (win->popup.active_con && win->popup.con_count != win->popup.active_con)
+ return 0;
+ if (!is_open && win->popup.active_con)
+ win->popup.active_con = 0;
+ if ((!is_open && !is_clicked))
+ return 0;
+
+ /* calculate contextual position on click */
+ win->popup.active_con = win->popup.con_count;
+ if (is_clicked) {
+ body.x = in->mouse.pos.x;
+ body.y = in->mouse.pos.y;
+ } else {
+ body.x = popup->bounds.x;
+ body.y = popup->bounds.y;
+ }
+
+ body.w = size.x;
+ body.h = size.y;
+
+ /* start nonblocking contextual popup */
+ ret = nk_nonblock_begin(ctx, flags | NK_WINDOW_NO_SCROLLBAR, body,
+ null_rect, NK_PANEL_CONTEXTUAL);
+ if (ret) win->popup.type = NK_PANEL_CONTEXTUAL;
+ else {
+ win->popup.active_con = 0;
+ win->popup.type = NK_PANEL_NONE;
+ if (win->popup.win)
+ win->popup.win->flags = 0;
+ }
+ }
+ return ret;
+}
+NK_API nk_bool
+nk_contextual_item_text(struct nk_context *ctx, const char *text, int len,
+ nk_flags alignment)
+{
+ struct nk_window *win;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding);
+ if (!state) return nk_false;
+
+ in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds,
+ text, len, alignment, NK_BUTTON_DEFAULT, &style->contextual_button, in, style->font)) {
+ nk_contextual_close(ctx);
+ return nk_true;
+ }
+ return nk_false;
+}
+NK_API nk_bool
+nk_contextual_item_label(struct nk_context *ctx, const char *label, nk_flags align)
+{
+ return nk_contextual_item_text(ctx, label, nk_strlen(label), align);
+}
+NK_API nk_bool
+nk_contextual_item_image_text(struct nk_context *ctx, struct nk_image img,
+ const char *text, int len, nk_flags align)
+{
+ struct nk_window *win;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding);
+ if (!state) return nk_false;
+
+ in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds,
+ img, text, len, align, NK_BUTTON_DEFAULT, &style->contextual_button, style->font, in)){
+ nk_contextual_close(ctx);
+ return nk_true;
+ }
+ return nk_false;
+}
+NK_API nk_bool
+nk_contextual_item_image_label(struct nk_context *ctx, struct nk_image img,
+ const char *label, nk_flags align)
+{
+ return nk_contextual_item_image_text(ctx, img, label, nk_strlen(label), align);
+}
+NK_API nk_bool
+nk_contextual_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type symbol,
+ const char *text, int len, nk_flags align)
+{
+ struct nk_window *win;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding);
+ if (!state) return nk_false;
+
+ in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds,
+ symbol, text, len, align, NK_BUTTON_DEFAULT, &style->contextual_button, style->font, in)) {
+ nk_contextual_close(ctx);
+ return nk_true;
+ }
+ return nk_false;
+}
+NK_API nk_bool
+nk_contextual_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type symbol,
+ const char *text, nk_flags align)
+{
+ return nk_contextual_item_symbol_text(ctx, symbol, text, nk_strlen(text), align);
+}
+NK_API void
+nk_contextual_close(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) return;
+ nk_popup_close(ctx);
+}
+NK_API void
+nk_contextual_end(struct nk_context *ctx)
+{
+ struct nk_window *popup;
+ struct nk_panel *panel;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return;
+
+ popup = ctx->current;
+ panel = popup->layout;
+ NK_ASSERT(popup->parent);
+ NK_ASSERT((int)panel->type & (int)NK_PANEL_SET_POPUP);
+ if (panel->flags & NK_WINDOW_DYNAMIC) {
+ /* Close behavior
+ This is a bit of a hack solution since we do not know before we end our popup
+ how big it will be. We therefore do not directly know when a
+ click outside the non-blocking popup must close it at that direct frame.
+ Instead it will be closed in the next frame.*/
+ struct nk_rect body = {0,0,0,0};
+ if (panel->at_y < (panel->bounds.y + panel->bounds.h)) {
+ struct nk_vec2 padding = nk_panel_get_padding(&ctx->style, panel->type);
+ body = panel->bounds;
+ body.y = (panel->at_y + panel->footer_height + panel->border + padding.y + panel->row.height);
+ body.h = (panel->bounds.y + panel->bounds.h) - body.y;
+ }
+ {int pressed = nk_input_is_mouse_pressed(&ctx->input, NK_BUTTON_LEFT);
+ int in_body = nk_input_is_mouse_hovering_rect(&ctx->input, body);
+ if (pressed && in_body)
+ popup->flags |= NK_WINDOW_HIDDEN;
+ }
+ }
+ if (popup->flags & NK_WINDOW_HIDDEN)
+ popup->seq = 0;
+ nk_popup_end(ctx);
+ return;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * MENU
+ *
+ * ===============================================================*/
+NK_API void
+nk_menubar_begin(struct nk_context *ctx)
+{
+ struct nk_panel *layout;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ layout = ctx->current->layout;
+ NK_ASSERT(layout->at_y == layout->bounds.y);
+ /* if this assert triggers you allocated space between nk_begin and nk_menubar_begin.
+ If you want a menubar the first nuklear function after `nk_begin` has to be a
+ `nk_menubar_begin` call. Inside the menubar you then have to allocate space for
+ widgets (also supports multiple rows).
+ Example:
+ if (nk_begin(...)) {
+ nk_menubar_begin(...);
+ nk_layout_xxxx(...);
+ nk_button(...);
+ nk_layout_xxxx(...);
+ nk_button(...);
+ nk_menubar_end(...);
+ }
+ nk_end(...);
+ */
+ if (layout->flags & NK_WINDOW_HIDDEN || layout->flags & NK_WINDOW_MINIMIZED)
+ return;
+
+ layout->menu.x = layout->at_x;
+ layout->menu.y = layout->at_y + layout->row.height;
+ layout->menu.w = layout->bounds.w;
+ layout->menu.offset.x = *layout->offset_x;
+ layout->menu.offset.y = *layout->offset_y;
+ *layout->offset_y = 0;
+}
+NK_API void
+nk_menubar_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ struct nk_command_buffer *out;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ out = &win->buffer;
+ layout = win->layout;
+ if (layout->flags & NK_WINDOW_HIDDEN || layout->flags & NK_WINDOW_MINIMIZED)
+ return;
+
+ layout->menu.h = layout->at_y - layout->menu.y;
+ layout->menu.h += layout->row.height + ctx->style.window.spacing.y;
+
+ layout->bounds.y += layout->menu.h;
+ layout->bounds.h -= layout->menu.h;
+
+ *layout->offset_x = layout->menu.offset.x;
+ *layout->offset_y = layout->menu.offset.y;
+ layout->at_y = layout->bounds.y - layout->row.height;
+
+ layout->clip.y = layout->bounds.y;
+ layout->clip.h = layout->bounds.h;
+ nk_push_scissor(out, layout->clip);
+}
+NK_INTERN int
+nk_menu_begin(struct nk_context *ctx, struct nk_window *win,
+ const char *id, int is_clicked, struct nk_rect header, struct nk_vec2 size)
+{
+ int is_open = 0;
+ int is_active = 0;
+ struct nk_rect body;
+ struct nk_window *popup;
+ nk_hash hash = nk_murmur_hash(id, (int)nk_strlen(id), NK_PANEL_MENU);
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ body.x = header.x;
+ body.w = size.x;
+ body.y = header.y + header.h;
+ body.h = size.y;
+
+ popup = win->popup.win;
+ is_open = popup ? nk_true : nk_false;
+ is_active = (popup && (win->popup.name == hash) && win->popup.type == NK_PANEL_MENU);
+ if ((is_clicked && is_open && !is_active) || (is_open && !is_active) ||
+ (!is_open && !is_active && !is_clicked)) return 0;
+ if (!nk_nonblock_begin(ctx, NK_WINDOW_NO_SCROLLBAR, body, header, NK_PANEL_MENU))
+ return 0;
+
+ win->popup.type = NK_PANEL_MENU;
+ win->popup.name = hash;
+ return 1;
+}
+NK_API nk_bool
+nk_menu_begin_text(struct nk_context *ctx, const char *title, int len,
+ nk_flags align, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ const struct nk_input *in;
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ nk_flags state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ state = nk_widget(&header, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header,
+ title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font))
+ is_clicked = nk_true;
+ return nk_menu_begin(ctx, win, title, is_clicked, header, size);
+}
+NK_API nk_bool nk_menu_begin_label(struct nk_context *ctx,
+ const char *text, nk_flags align, struct nk_vec2 size)
+{
+ return nk_menu_begin_text(ctx, text, nk_strlen(text), align, size);
+}
+NK_API nk_bool
+nk_menu_begin_image(struct nk_context *ctx, const char *id, struct nk_image img,
+ struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_rect header;
+ const struct nk_input *in;
+ int is_clicked = nk_false;
+ nk_flags state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ state = nk_widget(&header, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header,
+ img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in))
+ is_clicked = nk_true;
+ return nk_menu_begin(ctx, win, id, is_clicked, header, size);
+}
+NK_API nk_bool
+nk_menu_begin_symbol(struct nk_context *ctx, const char *id,
+ enum nk_symbol_type sym, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ const struct nk_input *in;
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ nk_flags state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ state = nk_widget(&header, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header,
+ sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font))
+ is_clicked = nk_true;
+ return nk_menu_begin(ctx, win, id, is_clicked, header, size);
+}
+NK_API nk_bool
+nk_menu_begin_image_text(struct nk_context *ctx, const char *title, int len,
+ nk_flags align, struct nk_image img, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_rect header;
+ const struct nk_input *in;
+ int is_clicked = nk_false;
+ nk_flags state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ state = nk_widget(&header, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer,
+ header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button,
+ ctx->style.font, in))
+ is_clicked = nk_true;
+ return nk_menu_begin(ctx, win, title, is_clicked, header, size);
+}
+NK_API nk_bool
+nk_menu_begin_image_label(struct nk_context *ctx,
+ const char *title, nk_flags align, struct nk_image img, struct nk_vec2 size)
+{
+ return nk_menu_begin_image_text(ctx, title, nk_strlen(title), align, img, size);
+}
+NK_API nk_bool
+nk_menu_begin_symbol_text(struct nk_context *ctx, const char *title, int len,
+ nk_flags align, enum nk_symbol_type sym, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_rect header;
+ const struct nk_input *in;
+ int is_clicked = nk_false;
+ nk_flags state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ state = nk_widget(&header, ctx);
+ if (!state) return 0;
+
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer,
+ header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button,
+ ctx->style.font, in)) is_clicked = nk_true;
+ return nk_menu_begin(ctx, win, title, is_clicked, header, size);
+}
+NK_API nk_bool
+nk_menu_begin_symbol_label(struct nk_context *ctx,
+ const char *title, nk_flags align, enum nk_symbol_type sym, struct nk_vec2 size )
+{
+ return nk_menu_begin_symbol_text(ctx, title, nk_strlen(title), align,sym,size);
+}
+NK_API nk_bool
+nk_menu_item_text(struct nk_context *ctx, const char *title, int len, nk_flags align)
+{
+ return nk_contextual_item_text(ctx, title, len, align);
+}
+NK_API nk_bool
+nk_menu_item_label(struct nk_context *ctx, const char *label, nk_flags align)
+{
+ return nk_contextual_item_label(ctx, label, align);
+}
+NK_API nk_bool
+nk_menu_item_image_label(struct nk_context *ctx, struct nk_image img,
+ const char *label, nk_flags align)
+{
+ return nk_contextual_item_image_label(ctx, img, label, align);
+}
+NK_API nk_bool
+nk_menu_item_image_text(struct nk_context *ctx, struct nk_image img,
+ const char *text, int len, nk_flags align)
+{
+ return nk_contextual_item_image_text(ctx, img, text, len, align);
+}
+NK_API nk_bool nk_menu_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *text, int len, nk_flags align)
+{
+ return nk_contextual_item_symbol_text(ctx, sym, text, len, align);
+}
+NK_API nk_bool nk_menu_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *label, nk_flags align)
+{
+ return nk_contextual_item_symbol_label(ctx, sym, label, align);
+}
+NK_API void nk_menu_close(struct nk_context *ctx)
+{
+ nk_contextual_close(ctx);
+}
+NK_API void
+nk_menu_end(struct nk_context *ctx)
+{
+ nk_contextual_end(ctx);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * LAYOUT
+ *
+ * ===============================================================*/
+NK_API void
+nk_layout_set_min_row_height(struct nk_context *ctx, float height)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ layout->row.min_height = height;
+}
+NK_API void
+nk_layout_reset_min_row_height(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ layout->row.min_height = ctx->style.font->height;
+ layout->row.min_height += ctx->style.text.padding.y*2;
+ layout->row.min_height += ctx->style.window.min_row_height_padding*2;
+}
+NK_LIB float
+nk_layout_row_calculate_usable_space(const struct nk_style *style, enum nk_panel_type type,
+ float total_space, int columns)
+{
+ float panel_spacing;
+ float panel_space;
+
+ struct nk_vec2 spacing;
+
+ NK_UNUSED(type);
+
+ spacing = style->window.spacing;
+
+ /* calculate the usable panel space */
+ panel_spacing = (float)NK_MAX(columns - 1, 0) * spacing.x;
+ panel_space = total_space - panel_spacing;
+ return panel_space;
+}
+NK_LIB void
+nk_panel_layout(const struct nk_context *ctx, struct nk_window *win,
+ float height, int cols)
+{
+ struct nk_panel *layout;
+ const struct nk_style *style;
+ struct nk_command_buffer *out;
+
+ struct nk_vec2 item_spacing;
+ struct nk_color color;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ /* prefetch some configuration data */
+ layout = win->layout;
+ style = &ctx->style;
+ out = &win->buffer;
+ color = style->window.background;
+ item_spacing = style->window.spacing;
+
+ /* if one of these triggers you forgot to add an `if` condition around either
+ a window, group, popup, combobox or contextual menu `begin` and `end` block.
+ Example:
+ if (nk_begin(...) {...} nk_end(...); or
+ if (nk_group_begin(...) { nk_group_end(...);} */
+ NK_ASSERT(!(layout->flags & NK_WINDOW_MINIMIZED));
+ NK_ASSERT(!(layout->flags & NK_WINDOW_HIDDEN));
+ NK_ASSERT(!(layout->flags & NK_WINDOW_CLOSED));
+
+ /* update the current row and set the current row layout */
+ layout->row.index = 0;
+ layout->at_y += layout->row.height;
+ layout->row.columns = cols;
+ if (height == 0.0f)
+ layout->row.height = NK_MAX(height, layout->row.min_height) + item_spacing.y;
+ else layout->row.height = height + item_spacing.y;
+
+ layout->row.item_offset = 0;
+ if (layout->flags & NK_WINDOW_DYNAMIC) {
+ /* draw background for dynamic panels */
+ struct nk_rect background;
+ background.x = win->bounds.x;
+ background.w = win->bounds.w;
+ background.y = layout->at_y - 1.0f;
+ background.h = layout->row.height + 1.0f;
+ nk_fill_rect(out, background, 0, color);
+ }
+}
+NK_LIB void
+nk_row_layout(struct nk_context *ctx, enum nk_layout_format fmt,
+ float height, int cols, int width)
+{
+ /* update the current row and set the current row layout */
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ nk_panel_layout(ctx, win, height, cols);
+ if (fmt == NK_DYNAMIC)
+ win->layout->row.type = NK_LAYOUT_DYNAMIC_FIXED;
+ else win->layout->row.type = NK_LAYOUT_STATIC_FIXED;
+
+ win->layout->row.ratio = 0;
+ win->layout->row.filled = 0;
+ win->layout->row.item_offset = 0;
+ win->layout->row.item_width = (float)width;
+}
+NK_API float
+nk_layout_ratio_from_pixel(struct nk_context *ctx, float pixel_width)
+{
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ NK_ASSERT(pixel_width);
+ if (!ctx || !ctx->current || !ctx->current->layout) return 0;
+ win = ctx->current;
+ return NK_CLAMP(0.0f, pixel_width/win->bounds.x, 1.0f);
+}
+NK_API void
+nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols)
+{
+ nk_row_layout(ctx, NK_DYNAMIC, height, cols, 0);
+}
+NK_API void
+nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols)
+{
+ nk_row_layout(ctx, NK_STATIC, height, cols, item_width);
+}
+NK_API void
+nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt,
+ float row_height, int cols)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ nk_panel_layout(ctx, win, row_height, cols);
+ if (fmt == NK_DYNAMIC)
+ layout->row.type = NK_LAYOUT_DYNAMIC_ROW;
+ else layout->row.type = NK_LAYOUT_STATIC_ROW;
+
+ layout->row.ratio = 0;
+ layout->row.filled = 0;
+ layout->row.item_width = 0;
+ layout->row.item_offset = 0;
+ layout->row.columns = cols;
+}
+NK_API void
+nk_layout_row_push(struct nk_context *ctx, float ratio_or_width)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ NK_ASSERT(layout->row.type == NK_LAYOUT_STATIC_ROW || layout->row.type == NK_LAYOUT_DYNAMIC_ROW);
+ if (layout->row.type != NK_LAYOUT_STATIC_ROW && layout->row.type != NK_LAYOUT_DYNAMIC_ROW)
+ return;
+
+ if (layout->row.type == NK_LAYOUT_DYNAMIC_ROW) {
+ float ratio = ratio_or_width;
+ if ((ratio + layout->row.filled) > 1.0f) return;
+ if (ratio > 0.0f)
+ layout->row.item_width = NK_SATURATE(ratio);
+ else layout->row.item_width = 1.0f - layout->row.filled;
+ } else layout->row.item_width = ratio_or_width;
+}
+NK_API void
+nk_layout_row_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ NK_ASSERT(layout->row.type == NK_LAYOUT_STATIC_ROW || layout->row.type == NK_LAYOUT_DYNAMIC_ROW);
+ if (layout->row.type != NK_LAYOUT_STATIC_ROW && layout->row.type != NK_LAYOUT_DYNAMIC_ROW)
+ return;
+ layout->row.item_width = 0;
+ layout->row.item_offset = 0;
+}
+NK_API void
+nk_layout_row(struct nk_context *ctx, enum nk_layout_format fmt,
+ float height, int cols, const float *ratio)
+{
+ int i;
+ int n_undef = 0;
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ nk_panel_layout(ctx, win, height, cols);
+ if (fmt == NK_DYNAMIC) {
+ /* calculate width of undefined widget ratios */
+ float r = 0;
+ layout->row.ratio = ratio;
+ for (i = 0; i < cols; ++i) {
+ if (ratio[i] < 0.0f)
+ n_undef++;
+ else r += ratio[i];
+ }
+ r = NK_SATURATE(1.0f - r);
+ layout->row.type = NK_LAYOUT_DYNAMIC;
+ layout->row.item_width = (r > 0 && n_undef > 0) ? (r / (float)n_undef):0;
+ } else {
+ layout->row.ratio = ratio;
+ layout->row.type = NK_LAYOUT_STATIC;
+ layout->row.item_width = 0;
+ layout->row.item_offset = 0;
+ }
+ layout->row.item_offset = 0;
+ layout->row.filled = 0;
+}
+NK_API void
+nk_layout_row_template_begin(struct nk_context *ctx, float height)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ nk_panel_layout(ctx, win, height, 1);
+ layout->row.type = NK_LAYOUT_TEMPLATE;
+ layout->row.columns = 0;
+ layout->row.ratio = 0;
+ layout->row.item_width = 0;
+ layout->row.item_height = 0;
+ layout->row.item_offset = 0;
+ layout->row.filled = 0;
+ layout->row.item.x = 0;
+ layout->row.item.y = 0;
+ layout->row.item.w = 0;
+ layout->row.item.h = 0;
+}
+NK_API void
+nk_layout_row_template_push_dynamic(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE);
+ NK_ASSERT(layout->row.columns < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS);
+ if (layout->row.type != NK_LAYOUT_TEMPLATE) return;
+ if (layout->row.columns >= NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS) return;
+ layout->row.templates[layout->row.columns++] = -1.0f;
+}
+NK_API void
+nk_layout_row_template_push_variable(struct nk_context *ctx, float min_width)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE);
+ NK_ASSERT(layout->row.columns < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS);
+ if (layout->row.type != NK_LAYOUT_TEMPLATE) return;
+ if (layout->row.columns >= NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS) return;
+ layout->row.templates[layout->row.columns++] = -min_width;
+}
+NK_API void
+nk_layout_row_template_push_static(struct nk_context *ctx, float width)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE);
+ NK_ASSERT(layout->row.columns < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS);
+ if (layout->row.type != NK_LAYOUT_TEMPLATE) return;
+ if (layout->row.columns >= NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS) return;
+ layout->row.templates[layout->row.columns++] = width;
+}
+NK_API void
+nk_layout_row_template_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ int i = 0;
+ int variable_count = 0;
+ int min_variable_count = 0;
+ float min_fixed_width = 0.0f;
+ float total_fixed_width = 0.0f;
+ float max_variable_width = 0.0f;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE);
+ if (layout->row.type != NK_LAYOUT_TEMPLATE) return;
+ for (i = 0; i < layout->row.columns; ++i) {
+ float width = layout->row.templates[i];
+ if (width >= 0.0f) {
+ total_fixed_width += width;
+ min_fixed_width += width;
+ } else if (width < -1.0f) {
+ width = -width;
+ total_fixed_width += width;
+ max_variable_width = NK_MAX(max_variable_width, width);
+ variable_count++;
+ } else {
+ min_variable_count++;
+ variable_count++;
+ }
+ }
+ if (variable_count) {
+ float space = nk_layout_row_calculate_usable_space(&ctx->style, layout->type,
+ layout->bounds.w, layout->row.columns);
+ float var_width = (NK_MAX(space-min_fixed_width,0.0f)) / (float)variable_count;
+ int enough_space = var_width >= max_variable_width;
+ if (!enough_space)
+ var_width = (NK_MAX(space-total_fixed_width,0)) / (float)min_variable_count;
+ for (i = 0; i < layout->row.columns; ++i) {
+ float *width = &layout->row.templates[i];
+ *width = (*width >= 0.0f)? *width: (*width < -1.0f && !enough_space)? -(*width): var_width;
+ }
+ }
+}
+NK_API void
+nk_layout_space_begin(struct nk_context *ctx, enum nk_layout_format fmt,
+ float height, int widget_count)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ nk_panel_layout(ctx, win, height, widget_count);
+ if (fmt == NK_STATIC)
+ layout->row.type = NK_LAYOUT_STATIC_FREE;
+ else layout->row.type = NK_LAYOUT_DYNAMIC_FREE;
+
+ layout->row.ratio = 0;
+ layout->row.filled = 0;
+ layout->row.item_width = 0;
+ layout->row.item_offset = 0;
+}
+NK_API void
+nk_layout_space_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ layout->row.item_width = 0;
+ layout->row.item_height = 0;
+ layout->row.item_offset = 0;
+ nk_zero(&layout->row.item, sizeof(layout->row.item));
+}
+NK_API void
+nk_layout_space_push(struct nk_context *ctx, struct nk_rect rect)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ layout->row.item = rect;
+}
+NK_API struct nk_rect
+nk_layout_space_bounds(struct nk_context *ctx)
+{
+ struct nk_rect ret;
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ win = ctx->current;
+ layout = win->layout;
+
+ ret.x = layout->clip.x;
+ ret.y = layout->clip.y;
+ ret.w = layout->clip.w;
+ ret.h = layout->row.height;
+ return ret;
+}
+NK_API struct nk_rect
+nk_layout_widget_bounds(struct nk_context *ctx)
+{
+ struct nk_rect ret;
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ win = ctx->current;
+ layout = win->layout;
+
+ ret.x = layout->at_x;
+ ret.y = layout->at_y;
+ ret.w = layout->bounds.w - NK_MAX(layout->at_x - layout->bounds.x,0);
+ ret.h = layout->row.height;
+ return ret;
+}
+NK_API struct nk_vec2
+nk_layout_space_to_screen(struct nk_context *ctx, struct nk_vec2 ret)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ win = ctx->current;
+ layout = win->layout;
+
+ ret.x += layout->at_x - (float)*layout->offset_x;
+ ret.y += layout->at_y - (float)*layout->offset_y;
+ return ret;
+}
+NK_API struct nk_vec2
+nk_layout_space_to_local(struct nk_context *ctx, struct nk_vec2 ret)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ win = ctx->current;
+ layout = win->layout;
+
+ ret.x += -layout->at_x + (float)*layout->offset_x;
+ ret.y += -layout->at_y + (float)*layout->offset_y;
+ return ret;
+}
+NK_API struct nk_rect
+nk_layout_space_rect_to_screen(struct nk_context *ctx, struct nk_rect ret)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ win = ctx->current;
+ layout = win->layout;
+
+ ret.x += layout->at_x - (float)*layout->offset_x;
+ ret.y += layout->at_y - (float)*layout->offset_y;
+ return ret;
+}
+NK_API struct nk_rect
+nk_layout_space_rect_to_local(struct nk_context *ctx, struct nk_rect ret)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ win = ctx->current;
+ layout = win->layout;
+
+ ret.x += -layout->at_x + (float)*layout->offset_x;
+ ret.y += -layout->at_y + (float)*layout->offset_y;
+ return ret;
+}
+NK_LIB void
+nk_panel_alloc_row(const struct nk_context *ctx, struct nk_window *win)
+{
+ struct nk_panel *layout = win->layout;
+ struct nk_vec2 spacing = ctx->style.window.spacing;
+ const float row_height = layout->row.height - spacing.y;
+ nk_panel_layout(ctx, win, row_height, layout->row.columns);
+}
+NK_LIB void
+nk_layout_widget_space(struct nk_rect *bounds, const struct nk_context *ctx,
+ struct nk_window *win, int modify)
+{
+ struct nk_panel *layout;
+ const struct nk_style *style;
+
+ struct nk_vec2 spacing;
+
+ float item_offset = 0;
+ float item_width = 0;
+ float item_spacing = 0;
+ float panel_space = 0;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ style = &ctx->style;
+ NK_ASSERT(bounds);
+
+ spacing = style->window.spacing;
+ panel_space = nk_layout_row_calculate_usable_space(&ctx->style, layout->type,
+ layout->bounds.w, layout->row.columns);
+
+ #define NK_FRAC(x) (x - (float)(int)x) /* will be used to remove fookin gaps */
+ /* calculate the width of one item inside the current layout space */
+ switch (layout->row.type) {
+ case NK_LAYOUT_DYNAMIC_FIXED: {
+ /* scaling fixed size widgets item width */
+ float w = NK_MAX(1.0f,panel_space) / (float)layout->row.columns;
+ item_offset = (float)layout->row.index * w;
+ item_width = w + NK_FRAC(item_offset);
+ item_spacing = (float)layout->row.index * spacing.x;
+ } break;
+ case NK_LAYOUT_DYNAMIC_ROW: {
+ /* scaling single ratio widget width */
+ float w = layout->row.item_width * panel_space;
+ item_offset = layout->row.item_offset;
+ item_width = w + NK_FRAC(item_offset);
+ item_spacing = 0;
+
+ if (modify) {
+ layout->row.item_offset += w + spacing.x;
+ layout->row.filled += layout->row.item_width;
+ layout->row.index = 0;
+ }
+ } break;
+ case NK_LAYOUT_DYNAMIC_FREE: {
+ /* panel width depended free widget placing */
+ bounds->x = layout->at_x + (layout->bounds.w * layout->row.item.x);
+ bounds->x -= (float)*layout->offset_x;
+ bounds->y = layout->at_y + (layout->row.height * layout->row.item.y);
+ bounds->y -= (float)*layout->offset_y;
+ bounds->w = layout->bounds.w * layout->row.item.w + NK_FRAC(bounds->x);
+ bounds->h = layout->row.height * layout->row.item.h + NK_FRAC(bounds->y);
+ return;
+ }
+ case NK_LAYOUT_DYNAMIC: {
+ /* scaling arrays of panel width ratios for every widget */
+ float ratio, w;
+ NK_ASSERT(layout->row.ratio);
+ ratio = (layout->row.ratio[layout->row.index] < 0) ?
+ layout->row.item_width : layout->row.ratio[layout->row.index];
+
+ w = (ratio * panel_space);
+ item_spacing = (float)layout->row.index * spacing.x;
+ item_offset = layout->row.item_offset;
+ item_width = w + NK_FRAC(item_offset);
+
+ if (modify) {
+ layout->row.item_offset += w;
+ layout->row.filled += ratio;
+ }
+ } break;
+ case NK_LAYOUT_STATIC_FIXED: {
+ /* non-scaling fixed widgets item width */
+ item_width = layout->row.item_width;
+ item_offset = (float)layout->row.index * item_width;
+ item_spacing = (float)layout->row.index * spacing.x;
+ } break;
+ case NK_LAYOUT_STATIC_ROW: {
+ /* scaling single ratio widget width */
+ item_width = layout->row.item_width;
+ item_offset = layout->row.item_offset;
+ item_spacing = (float)layout->row.index * spacing.x;
+ if (modify) layout->row.item_offset += item_width;
+ } break;
+ case NK_LAYOUT_STATIC_FREE: {
+ /* free widget placing */
+ bounds->x = layout->at_x + layout->row.item.x;
+ bounds->w = layout->row.item.w;
+ if (((bounds->x + bounds->w) > layout->max_x) && modify)
+ layout->max_x = (bounds->x + bounds->w);
+ bounds->x -= (float)*layout->offset_x;
+ bounds->y = layout->at_y + layout->row.item.y;
+ bounds->y -= (float)*layout->offset_y;
+ bounds->h = layout->row.item.h;
+ return;
+ }
+ case NK_LAYOUT_STATIC: {
+ /* non-scaling array of panel pixel width for every widget */
+ item_spacing = (float)layout->row.index * spacing.x;
+ item_width = layout->row.ratio[layout->row.index];
+ item_offset = layout->row.item_offset;
+ if (modify) layout->row.item_offset += item_width;
+ } break;
+ case NK_LAYOUT_TEMPLATE: {
+ /* stretchy row layout with combined dynamic/static widget width*/
+ float w;
+ NK_ASSERT(layout->row.index < layout->row.columns);
+ NK_ASSERT(layout->row.index < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS);
+ w = layout->row.templates[layout->row.index];
+ item_offset = layout->row.item_offset;
+ item_width = w + NK_FRAC(item_offset);
+ item_spacing = (float)layout->row.index * spacing.x;
+ if (modify) layout->row.item_offset += w;
+ } break;
+ #undef NK_FRAC
+ default: NK_ASSERT(0); break;
+ };
+
+ /* set the bounds of the newly allocated widget */
+ bounds->w = item_width;
+ bounds->h = layout->row.height - spacing.y;
+ bounds->y = layout->at_y - (float)*layout->offset_y;
+ bounds->x = layout->at_x + item_offset + item_spacing;
+ if (((bounds->x + bounds->w) > layout->max_x) && modify)
+ layout->max_x = bounds->x + bounds->w;
+ bounds->x -= (float)*layout->offset_x;
+}
+NK_LIB void
+nk_panel_alloc_space(struct nk_rect *bounds, const struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ /* check if the end of the row has been hit and begin new row if so */
+ win = ctx->current;
+ layout = win->layout;
+ if (layout->row.index >= layout->row.columns)
+ nk_panel_alloc_row(ctx, win);
+
+ /* calculate widget position and size */
+ nk_layout_widget_space(bounds, ctx, win, nk_true);
+ layout->row.index++;
+}
+NK_LIB void
+nk_layout_peek(struct nk_rect *bounds, struct nk_context *ctx)
+{
+ float y;
+ int index;
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) {
+ *bounds = nk_rect(0,0,0,0);
+ return;
+ }
+
+ win = ctx->current;
+ layout = win->layout;
+ y = layout->at_y;
+ index = layout->row.index;
+ if (layout->row.index >= layout->row.columns) {
+ layout->at_y += layout->row.height;
+ layout->row.index = 0;
+ }
+ nk_layout_widget_space(bounds, ctx, win, nk_false);
+ if (!layout->row.index) {
+ bounds->x -= layout->row.item_offset;
+ }
+ layout->at_y = y;
+ layout->row.index = index;
+}
+NK_API void
+nk_spacer(struct nk_context *ctx )
+{
+ struct nk_rect dummy_rect = { 0, 0, 0, 0 };
+ nk_panel_alloc_space( &dummy_rect, ctx );
+}
+
+
+
+
+/* ===============================================================
+ *
+ * TREE
+ *
+ * ===============================================================*/
+NK_INTERN int
+nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image *img, const char *title, enum nk_collapse_states *state)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_style *style;
+ struct nk_command_buffer *out;
+ const struct nk_input *in;
+ const struct nk_style_button *button;
+ enum nk_symbol_type symbol;
+ float row_height;
+
+ struct nk_vec2 item_spacing;
+ struct nk_rect header = {0,0,0,0};
+ struct nk_rect sym = {0,0,0,0};
+ struct nk_text text;
+
+ nk_flags ws = 0;
+ enum nk_widget_layout_states widget_state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ /* cache some data */
+ win = ctx->current;
+ layout = win->layout;
+ out = &win->buffer;
+ style = &ctx->style;
+ item_spacing = style->window.spacing;
+
+ /* calculate header bounds and draw background */
+ row_height = style->font->height + 2 * style->tab.padding.y;
+ nk_layout_set_min_row_height(ctx, row_height);
+ nk_layout_row_dynamic(ctx, row_height, 1);
+ nk_layout_reset_min_row_height(ctx);
+
+ widget_state = nk_widget(&header, ctx);
+ if (type == NK_TREE_TAB) {
+ const struct nk_style_item *background = &style->tab.background;
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor));
+ nk_fill_rect(out, nk_shrink_rect(header, style->tab.border),
+ style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor));
+ break;
+ }
+ } else text.background = style->window.background;
+
+ /* update node state */
+ in = (!(layout->flags & NK_WINDOW_ROM)) ? &ctx->input: 0;
+ in = (in && widget_state == NK_WIDGET_VALID) ? &ctx->input : 0;
+ if (nk_button_behavior(&ws, header, in, NK_BUTTON_DEFAULT))
+ *state = (*state == NK_MAXIMIZED) ? NK_MINIMIZED : NK_MAXIMIZED;
+
+ /* select correct button style */
+ if (*state == NK_MAXIMIZED) {
+ symbol = style->tab.sym_maximize;
+ if (type == NK_TREE_TAB)
+ button = &style->tab.tab_maximize_button;
+ else button = &style->tab.node_maximize_button;
+ } else {
+ symbol = style->tab.sym_minimize;
+ if (type == NK_TREE_TAB)
+ button = &style->tab.tab_minimize_button;
+ else button = &style->tab.node_minimize_button;
+ }
+
+ {/* draw triangle button */
+ sym.w = sym.h = style->font->height;
+ sym.y = header.y + style->tab.padding.y;
+ sym.x = header.x + style->tab.padding.x;
+ nk_do_button_symbol(&ws, &win->buffer, sym, symbol, NK_BUTTON_DEFAULT,
+ button, 0, style->font);
+
+ if (img) {
+ /* draw optional image icon */
+ sym.x = sym.x + sym.w + 4 * item_spacing.x;
+ nk_draw_image(&win->buffer, sym, img, nk_white);
+ sym.w = style->font->height + style->tab.spacing.x;}
+ }
+
+ {/* draw label */
+ struct nk_rect label;
+ header.w = NK_MAX(header.w, sym.w + item_spacing.x);
+ label.x = sym.x + sym.w + item_spacing.x;
+ label.y = sym.y;
+ label.w = header.w - (sym.w + item_spacing.y + style->tab.indent);
+ label.h = style->font->height;
+ text.text = nk_rgb_factor(style->tab.text, style->tab.color_factor);
+ text.padding = nk_vec2(0,0);
+ nk_widget_text(out, label, title, nk_strlen(title), &text,
+ NK_TEXT_LEFT, style->font);}
+
+ /* increase x-axis cursor widget position pointer */
+ if (*state == NK_MAXIMIZED) {
+ layout->at_x = header.x + (float)*layout->offset_x + style->tab.indent;
+ layout->bounds.w = NK_MAX(layout->bounds.w, style->tab.indent);
+ layout->bounds.w -= (style->tab.indent + style->window.padding.x);
+ layout->row.tree_depth++;
+ return nk_true;
+ } else return nk_false;
+}
+NK_INTERN int
+nk_tree_base(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image *img, const char *title, enum nk_collapse_states initial_state,
+ const char *hash, int len, int line)
+{
+ struct nk_window *win = ctx->current;
+ int title_len = 0;
+ nk_hash tree_hash = 0;
+ nk_uint *state = 0;
+
+ /* retrieve tree state from internal widget state tables */
+ if (!hash) {
+ title_len = (int)nk_strlen(title);
+ tree_hash = nk_murmur_hash(title, (int)title_len, (nk_hash)line);
+ } else tree_hash = nk_murmur_hash(hash, len, (nk_hash)line);
+ state = nk_find_value(win, tree_hash);
+ if (!state) {
+ state = nk_add_value(ctx, win, tree_hash, 0);
+ *state = initial_state;
+ }
+ return nk_tree_state_base(ctx, type, img, title, (enum nk_collapse_states*)state);
+}
+NK_API nk_bool
+nk_tree_state_push(struct nk_context *ctx, enum nk_tree_type type,
+ const char *title, enum nk_collapse_states *state)
+{
+ return nk_tree_state_base(ctx, type, 0, title, state);
+}
+NK_API nk_bool
+nk_tree_state_image_push(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image img, const char *title, enum nk_collapse_states *state)
+{
+ return nk_tree_state_base(ctx, type, &img, title, state);
+}
+NK_API void
+nk_tree_state_pop(struct nk_context *ctx)
+{
+ struct nk_window *win = 0;
+ struct nk_panel *layout = 0;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ layout->at_x -= ctx->style.tab.indent + (float)*layout->offset_x;
+ layout->bounds.w += ctx->style.tab.indent + ctx->style.window.padding.x;
+ NK_ASSERT(layout->row.tree_depth);
+ layout->row.tree_depth--;
+}
+NK_API nk_bool
+nk_tree_push_hashed(struct nk_context *ctx, enum nk_tree_type type,
+ const char *title, enum nk_collapse_states initial_state,
+ const char *hash, int len, int line)
+{
+ return nk_tree_base(ctx, type, 0, title, initial_state, hash, len, line);
+}
+NK_API nk_bool
+nk_tree_image_push_hashed(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image img, const char *title, enum nk_collapse_states initial_state,
+ const char *hash, int len,int seed)
+{
+ return nk_tree_base(ctx, type, &img, title, initial_state, hash, len, seed);
+}
+NK_API void
+nk_tree_pop(struct nk_context *ctx)
+{
+ nk_tree_state_pop(ctx);
+}
+NK_INTERN int
+nk_tree_element_image_push_hashed_base(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image *img, const char *title, int title_len,
+ enum nk_collapse_states *state, nk_bool *selected)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_style *style;
+ struct nk_command_buffer *out;
+ const struct nk_input *in;
+ const struct nk_style_button *button;
+ enum nk_symbol_type symbol;
+ float row_height;
+ struct nk_vec2 padding;
+
+ int text_len;
+ float text_width;
+
+ struct nk_vec2 item_spacing;
+ struct nk_rect header = {0,0,0,0};
+ struct nk_rect sym = {0,0,0,0};
+
+ nk_flags ws = 0;
+ enum nk_widget_layout_states widget_state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ /* cache some data */
+ win = ctx->current;
+ layout = win->layout;
+ out = &win->buffer;
+ style = &ctx->style;
+ item_spacing = style->window.spacing;
+ padding = style->selectable.padding;
+
+ /* calculate header bounds and draw background */
+ row_height = style->font->height + 2 * style->tab.padding.y;
+ nk_layout_set_min_row_height(ctx, row_height);
+ nk_layout_row_dynamic(ctx, row_height, 1);
+ nk_layout_reset_min_row_height(ctx);
+
+ widget_state = nk_widget(&header, ctx);
+ if (type == NK_TREE_TAB) {
+ const struct nk_style_item *background = &style->tab.background;
+
+ switch (background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor));
+ nk_fill_rect(out, nk_shrink_rect(header, style->tab.border),
+ style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor));
+
+ break;
+ }
+ }
+
+ in = (!(layout->flags & NK_WINDOW_ROM)) ? &ctx->input: 0;
+ in = (in && widget_state == NK_WIDGET_VALID) ? &ctx->input : 0;
+
+ /* select correct button style */
+ if (*state == NK_MAXIMIZED) {
+ symbol = style->tab.sym_maximize;
+ if (type == NK_TREE_TAB)
+ button = &style->tab.tab_maximize_button;
+ else button = &style->tab.node_maximize_button;
+ } else {
+ symbol = style->tab.sym_minimize;
+ if (type == NK_TREE_TAB)
+ button = &style->tab.tab_minimize_button;
+ else button = &style->tab.node_minimize_button;
+ }
+ {/* draw triangle button */
+ sym.w = sym.h = style->font->height;
+ sym.y = header.y + style->tab.padding.y;
+ sym.x = header.x + style->tab.padding.x;
+ if (nk_do_button_symbol(&ws, &win->buffer, sym, symbol, NK_BUTTON_DEFAULT, button, in, style->font))
+ *state = (*state == NK_MAXIMIZED) ? NK_MINIMIZED : NK_MAXIMIZED;}
+
+ /* draw label */
+ {nk_flags dummy = 0;
+ struct nk_rect label;
+ /* calculate size of the text and tooltip */
+ text_len = nk_strlen(title);
+ text_width = style->font->width(style->font->userdata, style->font->height, title, text_len);
+ text_width += (4 * padding.x);
+
+ header.w = NK_MAX(header.w, sym.w + item_spacing.x);
+ label.x = sym.x + sym.w + item_spacing.x;
+ label.y = sym.y;
+ label.w = NK_MIN(header.w - (sym.w + item_spacing.y + style->tab.indent), text_width);
+ label.h = style->font->height;
+
+ if (img) {
+ nk_do_selectable_image(&dummy, &win->buffer, label, title, title_len, NK_TEXT_LEFT,
+ selected, img, &style->selectable, in, style->font);
+ } else nk_do_selectable(&dummy, &win->buffer, label, title, title_len, NK_TEXT_LEFT,
+ selected, &style->selectable, in, style->font);
+ }
+ /* increase x-axis cursor widget position pointer */
+ if (*state == NK_MAXIMIZED) {
+ layout->at_x = header.x + (float)*layout->offset_x + style->tab.indent;
+ layout->bounds.w = NK_MAX(layout->bounds.w, style->tab.indent);
+ layout->bounds.w -= (style->tab.indent + style->window.padding.x);
+ layout->row.tree_depth++;
+ return nk_true;
+ } else return nk_false;
+}
+NK_INTERN int
+nk_tree_element_base(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image *img, const char *title, enum nk_collapse_states initial_state,
+ nk_bool *selected, const char *hash, int len, int line)
+{
+ struct nk_window *win = ctx->current;
+ int title_len = 0;
+ nk_hash tree_hash = 0;
+ nk_uint *state = 0;
+
+ /* retrieve tree state from internal widget state tables */
+ if (!hash) {
+ title_len = (int)nk_strlen(title);
+ tree_hash = nk_murmur_hash(title, (int)title_len, (nk_hash)line);
+ } else tree_hash = nk_murmur_hash(hash, len, (nk_hash)line);
+ state = nk_find_value(win, tree_hash);
+ if (!state) {
+ state = nk_add_value(ctx, win, tree_hash, 0);
+ *state = initial_state;
+ } return nk_tree_element_image_push_hashed_base(ctx, type, img, title,
+ nk_strlen(title), (enum nk_collapse_states*)state, selected);
+}
+NK_API nk_bool
+nk_tree_element_push_hashed(struct nk_context *ctx, enum nk_tree_type type,
+ const char *title, enum nk_collapse_states initial_state,
+ nk_bool *selected, const char *hash, int len, int seed)
+{
+ return nk_tree_element_base(ctx, type, 0, title, initial_state, selected, hash, len, seed);
+}
+NK_API nk_bool
+nk_tree_element_image_push_hashed(struct nk_context *ctx, enum nk_tree_type type,
+ struct nk_image img, const char *title, enum nk_collapse_states initial_state,
+ nk_bool *selected, const char *hash, int len,int seed)
+{
+ return nk_tree_element_base(ctx, type, &img, title, initial_state, selected, hash, len, seed);
+}
+NK_API void
+nk_tree_element_pop(struct nk_context *ctx)
+{
+ nk_tree_state_pop(ctx);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * GROUP
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_group_scrolled_offset_begin(struct nk_context *ctx,
+ nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags)
+{
+ struct nk_rect bounds;
+ struct nk_window panel;
+ struct nk_window *win;
+
+ win = ctx->current;
+ nk_panel_alloc_space(&bounds, ctx);
+ {const struct nk_rect *c = &win->layout->clip;
+ if (!NK_INTERSECT(c->x, c->y, c->w, c->h, bounds.x, bounds.y, bounds.w, bounds.h) &&
+ !(flags & NK_WINDOW_MOVABLE)) {
+ return 0;
+ }}
+ if (win->flags & NK_WINDOW_ROM)
+ flags |= NK_WINDOW_ROM;
+
+ /* initialize a fake window to create the panel from */
+ nk_zero(&panel, sizeof(panel));
+ panel.bounds = bounds;
+ panel.flags = flags;
+ panel.scrollbar.x = *x_offset;
+ panel.scrollbar.y = *y_offset;
+ panel.buffer = win->buffer;
+ panel.layout = (struct nk_panel*)nk_create_panel(ctx);
+ ctx->current = &panel;
+ nk_panel_begin(ctx, (flags & NK_WINDOW_TITLE) ? title: 0, NK_PANEL_GROUP);
+
+ win->buffer = panel.buffer;
+ win->buffer.clip = panel.layout->clip;
+ panel.layout->offset_x = x_offset;
+ panel.layout->offset_y = y_offset;
+ panel.layout->parent = win->layout;
+ win->layout = panel.layout;
+
+ ctx->current = win;
+ if ((panel.layout->flags & NK_WINDOW_CLOSED) ||
+ (panel.layout->flags & NK_WINDOW_MINIMIZED))
+ {
+ nk_flags f = panel.layout->flags;
+ nk_group_scrolled_end(ctx);
+ if (f & NK_WINDOW_CLOSED)
+ return NK_WINDOW_CLOSED;
+ if (f & NK_WINDOW_MINIMIZED)
+ return NK_WINDOW_MINIMIZED;
+ }
+ return 1;
+}
+NK_API void
+nk_group_scrolled_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_panel *parent;
+ struct nk_panel *g;
+
+ struct nk_rect clip;
+ struct nk_window pan;
+ struct nk_vec2 panel_padding;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return;
+
+ /* make sure nk_group_begin was called correctly */
+ NK_ASSERT(ctx->current);
+ win = ctx->current;
+ NK_ASSERT(win->layout);
+ g = win->layout;
+ NK_ASSERT(g->parent);
+ parent = g->parent;
+
+ /* dummy window */
+ nk_zero_struct(pan);
+ panel_padding = nk_panel_get_padding(&ctx->style, NK_PANEL_GROUP);
+ pan.bounds.y = g->bounds.y - (g->header_height + g->menu.h);
+ pan.bounds.x = g->bounds.x - panel_padding.x;
+ pan.bounds.w = g->bounds.w + 2 * panel_padding.x;
+ pan.bounds.h = g->bounds.h + g->header_height + g->menu.h;
+ if (g->flags & NK_WINDOW_BORDER) {
+ pan.bounds.x -= g->border;
+ pan.bounds.y -= g->border;
+ pan.bounds.w += 2*g->border;
+ pan.bounds.h += 2*g->border;
+ }
+ if (!(g->flags & NK_WINDOW_NO_SCROLLBAR)) {
+ pan.bounds.w += ctx->style.window.scrollbar_size.x;
+ pan.bounds.h += ctx->style.window.scrollbar_size.y;
+ }
+ pan.scrollbar.x = *g->offset_x;
+ pan.scrollbar.y = *g->offset_y;
+ pan.flags = g->flags;
+ pan.buffer = win->buffer;
+ pan.layout = g;
+ pan.parent = win;
+ ctx->current = &pan;
+
+ /* make sure group has correct clipping rectangle */
+ nk_unify(&clip, &parent->clip, pan.bounds.x, pan.bounds.y,
+ pan.bounds.x + pan.bounds.w, pan.bounds.y + pan.bounds.h + panel_padding.x);
+ nk_push_scissor(&pan.buffer, clip);
+ nk_end(ctx);
+
+ win->buffer = pan.buffer;
+ nk_push_scissor(&win->buffer, parent->clip);
+ ctx->current = win;
+ win->layout = parent;
+ g->bounds = pan.bounds;
+ return;
+}
+NK_API nk_bool
+nk_group_scrolled_begin(struct nk_context *ctx,
+ struct nk_scroll *scroll, const char *title, nk_flags flags)
+{
+ return nk_group_scrolled_offset_begin(ctx, &scroll->x, &scroll->y, title, flags);
+}
+NK_API nk_bool
+nk_group_begin_titled(struct nk_context *ctx, const char *id,
+ const char *title, nk_flags flags)
+{
+ int id_len;
+ nk_hash id_hash;
+ struct nk_window *win;
+ nk_uint *x_offset;
+ nk_uint *y_offset;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(id);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !id)
+ return 0;
+
+ /* find persistent group scrollbar value */
+ win = ctx->current;
+ id_len = (int)nk_strlen(id);
+ id_hash = nk_murmur_hash(id, (int)id_len, NK_PANEL_GROUP);
+ x_offset = nk_find_value(win, id_hash);
+ if (!x_offset) {
+ x_offset = nk_add_value(ctx, win, id_hash, 0);
+ y_offset = nk_add_value(ctx, win, id_hash+1, 0);
+
+ NK_ASSERT(x_offset);
+ NK_ASSERT(y_offset);
+ if (!x_offset || !y_offset) return 0;
+ *x_offset = *y_offset = 0;
+ } else y_offset = nk_find_value(win, id_hash+1);
+ return nk_group_scrolled_offset_begin(ctx, x_offset, y_offset, title, flags);
+}
+NK_API nk_bool
+nk_group_begin(struct nk_context *ctx, const char *title, nk_flags flags)
+{
+ return nk_group_begin_titled(ctx, title, title, flags);
+}
+NK_API void
+nk_group_end(struct nk_context *ctx)
+{
+ nk_group_scrolled_end(ctx);
+}
+NK_API void
+nk_group_get_scroll(struct nk_context *ctx, const char *id, nk_uint *x_offset, nk_uint *y_offset)
+{
+ int id_len;
+ nk_hash id_hash;
+ struct nk_window *win;
+ nk_uint *x_offset_ptr;
+ nk_uint *y_offset_ptr;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(id);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !id)
+ return;
+
+ /* find persistent group scrollbar value */
+ win = ctx->current;
+ id_len = (int)nk_strlen(id);
+ id_hash = nk_murmur_hash(id, (int)id_len, NK_PANEL_GROUP);
+ x_offset_ptr = nk_find_value(win, id_hash);
+ if (!x_offset_ptr) {
+ x_offset_ptr = nk_add_value(ctx, win, id_hash, 0);
+ y_offset_ptr = nk_add_value(ctx, win, id_hash+1, 0);
+
+ NK_ASSERT(x_offset_ptr);
+ NK_ASSERT(y_offset_ptr);
+ if (!x_offset_ptr || !y_offset_ptr) return;
+ *x_offset_ptr = *y_offset_ptr = 0;
+ } else y_offset_ptr = nk_find_value(win, id_hash+1);
+ if (x_offset)
+ *x_offset = *x_offset_ptr;
+ if (y_offset)
+ *y_offset = *y_offset_ptr;
+}
+NK_API void
+nk_group_set_scroll(struct nk_context *ctx, const char *id, nk_uint x_offset, nk_uint y_offset)
+{
+ int id_len;
+ nk_hash id_hash;
+ struct nk_window *win;
+ nk_uint *x_offset_ptr;
+ nk_uint *y_offset_ptr;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(id);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !id)
+ return;
+
+ /* find persistent group scrollbar value */
+ win = ctx->current;
+ id_len = (int)nk_strlen(id);
+ id_hash = nk_murmur_hash(id, (int)id_len, NK_PANEL_GROUP);
+ x_offset_ptr = nk_find_value(win, id_hash);
+ if (!x_offset_ptr) {
+ x_offset_ptr = nk_add_value(ctx, win, id_hash, 0);
+ y_offset_ptr = nk_add_value(ctx, win, id_hash+1, 0);
+
+ NK_ASSERT(x_offset_ptr);
+ NK_ASSERT(y_offset_ptr);
+ if (!x_offset_ptr || !y_offset_ptr) return;
+ *x_offset_ptr = *y_offset_ptr = 0;
+ } else y_offset_ptr = nk_find_value(win, id_hash+1);
+ *x_offset_ptr = x_offset;
+ *y_offset_ptr = y_offset;
+}
+
+
+
+
+/* ===============================================================
+ *
+ * LIST VIEW
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_list_view_begin(struct nk_context *ctx, struct nk_list_view *view,
+ const char *title, nk_flags flags, int row_height, int row_count)
+{
+ int title_len;
+ nk_hash title_hash;
+ nk_uint *x_offset;
+ nk_uint *y_offset;
+
+ int result;
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_style *style;
+ struct nk_vec2 item_spacing;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(view);
+ NK_ASSERT(title);
+ if (!ctx || !view || !title) return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ item_spacing = style->window.spacing;
+ row_height += NK_MAX(0, (int)item_spacing.y);
+
+ /* find persistent list view scrollbar offset */
+ title_len = (int)nk_strlen(title);
+ title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_GROUP);
+ x_offset = nk_find_value(win, title_hash);
+ if (!x_offset) {
+ x_offset = nk_add_value(ctx, win, title_hash, 0);
+ y_offset = nk_add_value(ctx, win, title_hash+1, 0);
+
+ NK_ASSERT(x_offset);
+ NK_ASSERT(y_offset);
+ if (!x_offset || !y_offset) return 0;
+ *x_offset = *y_offset = 0;
+ } else y_offset = nk_find_value(win, title_hash+1);
+ view->scroll_value = *y_offset;
+ view->scroll_pointer = y_offset;
+
+ *y_offset = 0;
+ result = nk_group_scrolled_offset_begin(ctx, x_offset, y_offset, title, flags);
+ win = ctx->current;
+ layout = win->layout;
+
+ view->total_height = row_height * NK_MAX(row_count,1);
+ view->begin = (int)NK_MAX(((float)view->scroll_value / (float)row_height), 0.0f);
+ view->count = (int)NK_MAX(nk_iceilf((layout->clip.h)/(float)row_height),0);
+ view->count = NK_MIN(view->count, row_count - view->begin);
+ view->end = view->begin + view->count;
+ view->ctx = ctx;
+ return result;
+}
+NK_API void
+nk_list_view_end(struct nk_list_view *view)
+{
+ struct nk_context *ctx;
+ struct nk_window *win;
+ struct nk_panel *layout;
+
+ NK_ASSERT(view);
+ NK_ASSERT(view->ctx);
+ NK_ASSERT(view->scroll_pointer);
+ if (!view || !view->ctx) return;
+
+ ctx = view->ctx;
+ win = ctx->current;
+ layout = win->layout;
+ layout->at_y = layout->bounds.y + (float)view->total_height;
+ *view->scroll_pointer = *view->scroll_pointer + view->scroll_value;
+ nk_group_end(view->ctx);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * WIDGET
+ *
+ * ===============================================================*/
+NK_API struct nk_rect
+nk_widget_bounds(struct nk_context *ctx)
+{
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return nk_rect(0,0,0,0);
+ nk_layout_peek(&bounds, ctx);
+ return bounds;
+}
+NK_API struct nk_vec2
+nk_widget_position(struct nk_context *ctx)
+{
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return nk_vec2(0,0);
+
+ nk_layout_peek(&bounds, ctx);
+ return nk_vec2(bounds.x, bounds.y);
+}
+NK_API struct nk_vec2
+nk_widget_size(struct nk_context *ctx)
+{
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return nk_vec2(0,0);
+
+ nk_layout_peek(&bounds, ctx);
+ return nk_vec2(bounds.w, bounds.h);
+}
+NK_API float
+nk_widget_width(struct nk_context *ctx)
+{
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return 0;
+
+ nk_layout_peek(&bounds, ctx);
+ return bounds.w;
+}
+NK_API float
+nk_widget_height(struct nk_context *ctx)
+{
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return 0;
+
+ nk_layout_peek(&bounds, ctx);
+ return bounds.h;
+}
+NK_API nk_bool
+nk_widget_is_hovered(struct nk_context *ctx)
+{
+ struct nk_rect c, v;
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current || ctx->active != ctx->current)
+ return 0;
+
+ c = ctx->current->layout->clip;
+ c.x = (float)((int)c.x);
+ c.y = (float)((int)c.y);
+ c.w = (float)((int)c.w);
+ c.h = (float)((int)c.h);
+
+ nk_layout_peek(&bounds, ctx);
+ nk_unify(&v, &c, bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h);
+ if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds.x, bounds.y, bounds.w, bounds.h))
+ return 0;
+ return nk_input_is_mouse_hovering_rect(&ctx->input, bounds);
+}
+NK_API nk_bool
+nk_widget_is_mouse_clicked(struct nk_context *ctx, enum nk_buttons btn)
+{
+ struct nk_rect c, v;
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current || ctx->active != ctx->current)
+ return 0;
+
+ c = ctx->current->layout->clip;
+ c.x = (float)((int)c.x);
+ c.y = (float)((int)c.y);
+ c.w = (float)((int)c.w);
+ c.h = (float)((int)c.h);
+
+ nk_layout_peek(&bounds, ctx);
+ nk_unify(&v, &c, bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h);
+ if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds.x, bounds.y, bounds.w, bounds.h))
+ return 0;
+ return nk_input_mouse_clicked(&ctx->input, btn, bounds);
+}
+NK_API nk_bool
+nk_widget_has_mouse_click_down(struct nk_context *ctx, enum nk_buttons btn, nk_bool down)
+{
+ struct nk_rect c, v;
+ struct nk_rect bounds;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current || ctx->active != ctx->current)
+ return 0;
+
+ c = ctx->current->layout->clip;
+ c.x = (float)((int)c.x);
+ c.y = (float)((int)c.y);
+ c.w = (float)((int)c.w);
+ c.h = (float)((int)c.h);
+
+ nk_layout_peek(&bounds, ctx);
+ nk_unify(&v, &c, bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h);
+ if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds.x, bounds.y, bounds.w, bounds.h))
+ return 0;
+ return nk_input_has_mouse_click_down_in_rect(&ctx->input, btn, bounds, down);
+}
+NK_API enum nk_widget_layout_states
+nk_widget(struct nk_rect *bounds, const struct nk_context *ctx)
+{
+ struct nk_rect c, v;
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return NK_WIDGET_INVALID;
+
+ /* allocate space and check if the widget needs to be updated and drawn */
+ nk_panel_alloc_space(bounds, ctx);
+ win = ctx->current;
+ layout = win->layout;
+ in = &ctx->input;
+ c = layout->clip;
+
+ /* if one of these triggers you forgot to add an `if` condition around either
+ a window, group, popup, combobox or contextual menu `begin` and `end` block.
+ Example:
+ if (nk_begin(...) {...} nk_end(...); or
+ if (nk_group_begin(...) { nk_group_end(...);} */
+ NK_ASSERT(!(layout->flags & NK_WINDOW_MINIMIZED));
+ NK_ASSERT(!(layout->flags & NK_WINDOW_HIDDEN));
+ NK_ASSERT(!(layout->flags & NK_WINDOW_CLOSED));
+
+ /* need to convert to int here to remove floating point errors */
+ bounds->x = (float)((int)bounds->x);
+ bounds->y = (float)((int)bounds->y);
+ bounds->w = (float)((int)bounds->w);
+ bounds->h = (float)((int)bounds->h);
+
+ c.x = (float)((int)c.x);
+ c.y = (float)((int)c.y);
+ c.w = (float)((int)c.w);
+ c.h = (float)((int)c.h);
+
+ nk_unify(&v, &c, bounds->x, bounds->y, bounds->x + bounds->w, bounds->y + bounds->h);
+ if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds->x, bounds->y, bounds->w, bounds->h))
+ return NK_WIDGET_INVALID;
+ if (win->widgets_disabled)
+ return NK_WIDGET_DISABLED;
+ if (!NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, v.x, v.y, v.w, v.h))
+ return NK_WIDGET_ROM;
+ return NK_WIDGET_VALID;
+}
+NK_API enum nk_widget_layout_states
+nk_widget_fitting(struct nk_rect *bounds, struct nk_context *ctx,
+ struct nk_vec2 item_padding)
+{
+ /* update the bounds to stand without padding */
+ enum nk_widget_layout_states state;
+ NK_UNUSED(item_padding);
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return NK_WIDGET_INVALID;
+
+ state = nk_widget(bounds, ctx);
+ return state;
+}
+NK_API void
+nk_spacing(struct nk_context *ctx, int cols)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ struct nk_rect none;
+ int i, index, rows;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ /* spacing over row boundaries */
+ win = ctx->current;
+ layout = win->layout;
+ index = (layout->row.index + cols) % layout->row.columns;
+ rows = (layout->row.index + cols) / layout->row.columns;
+ if (rows) {
+ for (i = 0; i < rows; ++i)
+ nk_panel_alloc_row(ctx, win);
+ cols = index;
+ }
+ /* non table layout need to allocate space */
+ if (layout->row.type != NK_LAYOUT_DYNAMIC_FIXED &&
+ layout->row.type != NK_LAYOUT_STATIC_FIXED) {
+ for (i = 0; i < cols; ++i)
+ nk_panel_alloc_space(&none, ctx);
+ } layout->row.index = index;
+}
+NK_API void
+nk_widget_disable_begin(struct nk_context* ctx)
+{
+ struct nk_window* win;
+ struct nk_style* style;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+
+ if (!ctx || !ctx->current)
+ return;
+
+ win = ctx->current;
+ style = &ctx->style;
+
+ win->widgets_disabled = nk_true;
+
+ style->button.color_factor_text = style->button.disabled_factor;
+ style->button.color_factor_background = style->button.disabled_factor;
+ style->chart.color_factor = style->chart.disabled_factor;
+ style->checkbox.color_factor = style->checkbox.disabled_factor;
+ style->combo.color_factor = style->combo.disabled_factor;
+ style->combo.button.color_factor_text = style->combo.button.disabled_factor;
+ style->combo.button.color_factor_background = style->combo.button.disabled_factor;
+ style->contextual_button.color_factor_text = style->contextual_button.disabled_factor;
+ style->contextual_button.color_factor_background = style->contextual_button.disabled_factor;
+ style->edit.color_factor = style->edit.disabled_factor;
+ style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor;
+ style->menu_button.color_factor_text = style->menu_button.disabled_factor;
+ style->menu_button.color_factor_background = style->menu_button.disabled_factor;
+ style->option.color_factor = style->option.disabled_factor;
+ style->progress.color_factor = style->progress.disabled_factor;
+ style->property.color_factor = style->property.disabled_factor;
+ style->property.inc_button.color_factor_text = style->property.inc_button.disabled_factor;
+ style->property.inc_button.color_factor_background = style->property.inc_button.disabled_factor;
+ style->property.dec_button.color_factor_text = style->property.dec_button.disabled_factor;
+ style->property.dec_button.color_factor_background = style->property.dec_button.disabled_factor;
+ style->property.edit.color_factor = style->property.edit.disabled_factor;
+ style->scrollh.color_factor = style->scrollh.disabled_factor;
+ style->scrollh.inc_button.color_factor_text = style->scrollh.inc_button.disabled_factor;
+ style->scrollh.inc_button.color_factor_background = style->scrollh.inc_button.disabled_factor;
+ style->scrollh.dec_button.color_factor_text = style->scrollh.dec_button.disabled_factor;
+ style->scrollh.dec_button.color_factor_background = style->scrollh.dec_button.disabled_factor;
+ style->scrollv.color_factor = style->scrollv.disabled_factor;
+ style->scrollv.inc_button.color_factor_text = style->scrollv.inc_button.disabled_factor;
+ style->scrollv.inc_button.color_factor_background = style->scrollv.inc_button.disabled_factor;
+ style->scrollv.dec_button.color_factor_text = style->scrollv.dec_button.disabled_factor;
+ style->scrollv.dec_button.color_factor_background = style->scrollv.dec_button.disabled_factor;
+ style->selectable.color_factor = style->selectable.disabled_factor;
+ style->slider.color_factor = style->slider.disabled_factor;
+ style->slider.inc_button.color_factor_text = style->slider.inc_button.disabled_factor;
+ style->slider.inc_button.color_factor_background = style->slider.inc_button.disabled_factor;
+ style->slider.dec_button.color_factor_text = style->slider.dec_button.disabled_factor;
+ style->slider.dec_button.color_factor_background = style->slider.dec_button.disabled_factor;
+ style->tab.color_factor = style->tab.disabled_factor;
+ style->tab.node_maximize_button.color_factor_text = style->tab.node_maximize_button.disabled_factor;
+ style->tab.node_minimize_button.color_factor_text = style->tab.node_minimize_button.disabled_factor;
+ style->tab.tab_maximize_button.color_factor_text = style->tab.tab_maximize_button.disabled_factor;
+ style->tab.tab_maximize_button.color_factor_background = style->tab.tab_maximize_button.disabled_factor;
+ style->tab.tab_minimize_button.color_factor_text = style->tab.tab_minimize_button.disabled_factor;
+ style->tab.tab_minimize_button.color_factor_background = style->tab.tab_minimize_button.disabled_factor;
+ style->text.color_factor = style->text.disabled_factor;
+}
+NK_API void
+nk_widget_disable_end(struct nk_context* ctx)
+{
+ struct nk_window* win;
+ struct nk_style* style;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+
+ if (!ctx || !ctx->current)
+ return;
+
+ win = ctx->current;
+ style = &ctx->style;
+
+ win->widgets_disabled = nk_false;
+
+ style->button.color_factor_text = 1.0f;
+ style->button.color_factor_background = 1.0f;
+ style->chart.color_factor = 1.0f;
+ style->checkbox.color_factor = 1.0f;
+ style->combo.color_factor = 1.0f;
+ style->combo.button.color_factor_text = 1.0f;
+ style->combo.button.color_factor_background = 1.0f;
+ style->contextual_button.color_factor_text = 1.0f;
+ style->contextual_button.color_factor_background = 1.0f;
+ style->edit.color_factor = 1.0f;
+ style->edit.scrollbar.color_factor = 1.0f;
+ style->menu_button.color_factor_text = 1.0f;
+ style->menu_button.color_factor_background = 1.0f;
+ style->option.color_factor = 1.0f;
+ style->progress.color_factor = 1.0f;
+ style->property.color_factor = 1.0f;
+ style->property.inc_button.color_factor_text = 1.0f;
+ style->property.inc_button.color_factor_background = 1.0f;
+ style->property.dec_button.color_factor_text = 1.0f;
+ style->property.dec_button.color_factor_background = 1.0f;
+ style->property.edit.color_factor = 1.0f;
+ style->scrollh.color_factor = 1.0f;
+ style->scrollh.inc_button.color_factor_text = 1.0f;
+ style->scrollh.inc_button.color_factor_background = 1.0f;
+ style->scrollh.dec_button.color_factor_text = 1.0f;
+ style->scrollh.dec_button.color_factor_background = 1.0f;
+ style->scrollv.color_factor = 1.0f;
+ style->scrollv.inc_button.color_factor_text = 1.0f;
+ style->scrollv.inc_button.color_factor_background = 1.0f;
+ style->scrollv.dec_button.color_factor_text = 1.0f;
+ style->scrollv.dec_button.color_factor_background = 1.0f;
+ style->selectable.color_factor = 1.0f;
+ style->slider.color_factor = 1.0f;
+ style->slider.inc_button.color_factor_text = 1.0f;
+ style->slider.inc_button.color_factor_background = 1.0f;
+ style->slider.dec_button.color_factor_text = 1.0f;
+ style->slider.dec_button.color_factor_background = 1.0f;
+ style->tab.color_factor = 1.0f;
+ style->tab.node_maximize_button.color_factor_text = 1.0f;
+ style->tab.node_minimize_button.color_factor_text = 1.0f;
+ style->tab.tab_maximize_button.color_factor_text = 1.0f;
+ style->tab.tab_maximize_button.color_factor_background = 1.0f;
+ style->tab.tab_minimize_button.color_factor_text = 1.0f;
+ style->tab.tab_minimize_button.color_factor_background = 1.0f;
+ style->text.color_factor = 1.0f;
+}
+
+
+
+
+/* ===============================================================
+ *
+ * TEXT
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_widget_text(struct nk_command_buffer *o, struct nk_rect b,
+ const char *string, int len, const struct nk_text *t,
+ nk_flags a, const struct nk_user_font *f)
+{
+ struct nk_rect label;
+ float text_width;
+
+ NK_ASSERT(o);
+ NK_ASSERT(t);
+ if (!o || !t) return;
+
+ b.h = NK_MAX(b.h, 2 * t->padding.y);
+ label.x = 0; label.w = 0;
+ label.y = b.y + t->padding.y;
+ label.h = NK_MIN(f->height, b.h - 2 * t->padding.y);
+
+ text_width = f->width(f->userdata, f->height, (const char*)string, len);
+ text_width += (2.0f * t->padding.x);
+
+ /* align in x-axis */
+ if (a & NK_TEXT_ALIGN_LEFT) {
+ label.x = b.x + t->padding.x;
+ label.w = NK_MAX(0, b.w - 2 * t->padding.x);
+ } else if (a & NK_TEXT_ALIGN_CENTERED) {
+ label.w = NK_MAX(1, 2 * t->padding.x + (float)text_width);
+ label.x = (b.x + t->padding.x + ((b.w - 2 * t->padding.x) - label.w) / 2);
+ label.x = NK_MAX(b.x + t->padding.x, label.x);
+ label.w = NK_MIN(b.x + b.w, label.x + label.w);
+ if (label.w >= label.x) label.w -= label.x;
+ } else if (a & NK_TEXT_ALIGN_RIGHT) {
+ label.x = NK_MAX(b.x + t->padding.x, (b.x + b.w) - (2 * t->padding.x + (float)text_width));
+ label.w = (float)text_width + 2 * t->padding.x;
+ } else return;
+
+ /* align in y-axis */
+ if (a & NK_TEXT_ALIGN_MIDDLE) {
+ label.y = b.y + b.h/2.0f - (float)f->height/2.0f;
+ label.h = NK_MAX(b.h/2.0f, b.h - (b.h/2.0f + f->height/2.0f));
+ } else if (a & NK_TEXT_ALIGN_BOTTOM) {
+ label.y = b.y + b.h - f->height;
+ label.h = f->height;
+ }
+ nk_draw_text(o, label, (const char*)string, len, f, t->background, t->text);
+}
+NK_LIB void
+nk_widget_text_wrap(struct nk_command_buffer *o, struct nk_rect b,
+ const char *string, int len, const struct nk_text *t,
+ const struct nk_user_font *f)
+{
+ float width;
+ int glyphs = 0;
+ int fitting = 0;
+ int done = 0;
+ struct nk_rect line;
+ struct nk_text text;
+ NK_INTERN nk_rune seperator[] = {' '};
+
+ NK_ASSERT(o);
+ NK_ASSERT(t);
+ if (!o || !t) return;
+
+ text.padding = nk_vec2(0,0);
+ text.background = t->background;
+ text.text = t->text;
+
+ b.w = NK_MAX(b.w, 2 * t->padding.x);
+ b.h = NK_MAX(b.h, 2 * t->padding.y);
+ b.h = b.h - 2 * t->padding.y;
+
+ line.x = b.x + t->padding.x;
+ line.y = b.y + t->padding.y;
+ line.w = b.w - 2 * t->padding.x;
+ line.h = 2 * t->padding.y + f->height;
+
+ fitting = nk_text_clamp(f, string, len, line.w, &glyphs, &width, seperator,NK_LEN(seperator));
+ while (done < len) {
+ if (!fitting || line.y + line.h >= (b.y + b.h)) break;
+ nk_widget_text(o, line, &string[done], fitting, &text, NK_TEXT_LEFT, f);
+ done += fitting;
+ line.y += f->height + 2 * t->padding.y;
+ fitting = nk_text_clamp(f, &string[done], len - done, line.w, &glyphs, &width, seperator,NK_LEN(seperator));
+ }
+}
+NK_API void
+nk_text_colored(struct nk_context *ctx, const char *str, int len,
+ nk_flags alignment, struct nk_color color)
+{
+ struct nk_window *win;
+ const struct nk_style *style;
+
+ struct nk_vec2 item_padding;
+ struct nk_rect bounds;
+ struct nk_text text;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) return;
+
+ win = ctx->current;
+ style = &ctx->style;
+ nk_panel_alloc_space(&bounds, ctx);
+ item_padding = style->text.padding;
+
+ text.padding.x = item_padding.x;
+ text.padding.y = item_padding.y;
+ text.background = style->window.background;
+ text.text = nk_rgb_factor(color, style->text.color_factor);
+ nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font);
+}
+NK_API void
+nk_text_wrap_colored(struct nk_context *ctx, const char *str,
+ int len, struct nk_color color)
+{
+ struct nk_window *win;
+ const struct nk_style *style;
+
+ struct nk_vec2 item_padding;
+ struct nk_rect bounds;
+ struct nk_text text;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) return;
+
+ win = ctx->current;
+ style = &ctx->style;
+ nk_panel_alloc_space(&bounds, ctx);
+ item_padding = style->text.padding;
+
+ text.padding.x = item_padding.x;
+ text.padding.y = item_padding.y;
+ text.background = style->window.background;
+ text.text = nk_rgb_factor(color, style->text.color_factor);
+ nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font);
+}
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+NK_API void
+nk_labelf_colored(struct nk_context *ctx, nk_flags flags,
+ struct nk_color color, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ nk_labelfv_colored(ctx, flags, color, fmt, args);
+ va_end(args);
+}
+NK_API void
+nk_labelf_colored_wrap(struct nk_context *ctx, struct nk_color color,
+ const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ nk_labelfv_colored_wrap(ctx, color, fmt, args);
+ va_end(args);
+}
+NK_API void
+nk_labelf(struct nk_context *ctx, nk_flags flags, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ nk_labelfv(ctx, flags, fmt, args);
+ va_end(args);
+}
+NK_API void
+nk_labelf_wrap(struct nk_context *ctx, const char *fmt,...)
+{
+ va_list args;
+ va_start(args, fmt);
+ nk_labelfv_wrap(ctx, fmt, args);
+ va_end(args);
+}
+NK_API void
+nk_labelfv_colored(struct nk_context *ctx, nk_flags flags,
+ struct nk_color color, const char *fmt, va_list args)
+{
+ char buf[256];
+ nk_strfmt(buf, NK_LEN(buf), fmt, args);
+ nk_label_colored(ctx, buf, flags, color);
+}
+
+NK_API void
+nk_labelfv_colored_wrap(struct nk_context *ctx, struct nk_color color,
+ const char *fmt, va_list args)
+{
+ char buf[256];
+ nk_strfmt(buf, NK_LEN(buf), fmt, args);
+ nk_label_colored_wrap(ctx, buf, color);
+}
+
+NK_API void
+nk_labelfv(struct nk_context *ctx, nk_flags flags, const char *fmt, va_list args)
+{
+ char buf[256];
+ nk_strfmt(buf, NK_LEN(buf), fmt, args);
+ nk_label(ctx, buf, flags);
+}
+
+NK_API void
+nk_labelfv_wrap(struct nk_context *ctx, const char *fmt, va_list args)
+{
+ char buf[256];
+ nk_strfmt(buf, NK_LEN(buf), fmt, args);
+ nk_label_wrap(ctx, buf);
+}
+
+NK_API void
+nk_value_bool(struct nk_context *ctx, const char *prefix, int value)
+{
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: %s", prefix, ((value) ? "true": "false"));
+}
+NK_API void
+nk_value_int(struct nk_context *ctx, const char *prefix, int value)
+{
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: %d", prefix, value);
+}
+NK_API void
+nk_value_uint(struct nk_context *ctx, const char *prefix, unsigned int value)
+{
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: %u", prefix, value);
+}
+NK_API void
+nk_value_float(struct nk_context *ctx, const char *prefix, float value)
+{
+ double double_value = (double)value;
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: %.3f", prefix, double_value);
+}
+NK_API void
+nk_value_color_byte(struct nk_context *ctx, const char *p, struct nk_color c)
+{
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: (%d, %d, %d, %d)", p, c.r, c.g, c.b, c.a);
+}
+NK_API void
+nk_value_color_float(struct nk_context *ctx, const char *p, struct nk_color color)
+{
+ double c[4]; nk_color_dv(c, color);
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: (%.2f, %.2f, %.2f, %.2f)",
+ p, c[0], c[1], c[2], c[3]);
+}
+NK_API void
+nk_value_color_hex(struct nk_context *ctx, const char *prefix, struct nk_color color)
+{
+ char hex[16];
+ nk_color_hex_rgba(hex, color);
+ nk_labelf(ctx, NK_TEXT_LEFT, "%s: %s", prefix, hex);
+}
+#endif
+NK_API void
+nk_text(struct nk_context *ctx, const char *str, int len, nk_flags alignment)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ nk_text_colored(ctx, str, len, alignment, ctx->style.text.color);
+}
+NK_API void
+nk_text_wrap(struct nk_context *ctx, const char *str, int len)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ nk_text_wrap_colored(ctx, str, len, ctx->style.text.color);
+}
+NK_API void
+nk_label(struct nk_context *ctx, const char *str, nk_flags alignment)
+{
+ nk_text(ctx, str, nk_strlen(str), alignment);
+}
+NK_API void
+nk_label_colored(struct nk_context *ctx, const char *str, nk_flags align,
+ struct nk_color color)
+{
+ nk_text_colored(ctx, str, nk_strlen(str), align, color);
+}
+NK_API void
+nk_label_wrap(struct nk_context *ctx, const char *str)
+{
+ nk_text_wrap(ctx, str, nk_strlen(str));
+}
+NK_API void
+nk_label_colored_wrap(struct nk_context *ctx, const char *str, struct nk_color color)
+{
+ nk_text_wrap_colored(ctx, str, nk_strlen(str), color);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * IMAGE
+ *
+ * ===============================================================*/
+NK_API nk_handle
+nk_handle_ptr(void *ptr)
+{
+ nk_handle handle = {0};
+ handle.ptr = ptr;
+ return handle;
+}
+NK_API nk_handle
+nk_handle_id(int id)
+{
+ nk_handle handle;
+ nk_zero_struct(handle);
+ handle.id = id;
+ return handle;
+}
+NK_API struct nk_image
+nk_subimage_ptr(void *ptr, nk_ushort w, nk_ushort h, struct nk_rect r)
+{
+ struct nk_image s;
+ nk_zero(&s, sizeof(s));
+ s.handle.ptr = ptr;
+ s.w = w; s.h = h;
+ s.region[0] = (nk_ushort)r.x;
+ s.region[1] = (nk_ushort)r.y;
+ s.region[2] = (nk_ushort)r.w;
+ s.region[3] = (nk_ushort)r.h;
+ return s;
+}
+NK_API struct nk_image
+nk_subimage_id(int id, nk_ushort w, nk_ushort h, struct nk_rect r)
+{
+ struct nk_image s;
+ nk_zero(&s, sizeof(s));
+ s.handle.id = id;
+ s.w = w; s.h = h;
+ s.region[0] = (nk_ushort)r.x;
+ s.region[1] = (nk_ushort)r.y;
+ s.region[2] = (nk_ushort)r.w;
+ s.region[3] = (nk_ushort)r.h;
+ return s;
+}
+NK_API struct nk_image
+nk_subimage_handle(nk_handle handle, nk_ushort w, nk_ushort h, struct nk_rect r)
+{
+ struct nk_image s;
+ nk_zero(&s, sizeof(s));
+ s.handle = handle;
+ s.w = w; s.h = h;
+ s.region[0] = (nk_ushort)r.x;
+ s.region[1] = (nk_ushort)r.y;
+ s.region[2] = (nk_ushort)r.w;
+ s.region[3] = (nk_ushort)r.h;
+ return s;
+}
+NK_API struct nk_image
+nk_image_handle(nk_handle handle)
+{
+ struct nk_image s;
+ nk_zero(&s, sizeof(s));
+ s.handle = handle;
+ s.w = 0; s.h = 0;
+ s.region[0] = 0;
+ s.region[1] = 0;
+ s.region[2] = 0;
+ s.region[3] = 0;
+ return s;
+}
+NK_API struct nk_image
+nk_image_ptr(void *ptr)
+{
+ struct nk_image s;
+ nk_zero(&s, sizeof(s));
+ NK_ASSERT(ptr);
+ s.handle.ptr = ptr;
+ s.w = 0; s.h = 0;
+ s.region[0] = 0;
+ s.region[1] = 0;
+ s.region[2] = 0;
+ s.region[3] = 0;
+ return s;
+}
+NK_API struct nk_image
+nk_image_id(int id)
+{
+ struct nk_image s;
+ nk_zero(&s, sizeof(s));
+ s.handle.id = id;
+ s.w = 0; s.h = 0;
+ s.region[0] = 0;
+ s.region[1] = 0;
+ s.region[2] = 0;
+ s.region[3] = 0;
+ return s;
+}
+NK_API nk_bool
+nk_image_is_subimage(const struct nk_image* img)
+{
+ NK_ASSERT(img);
+ return !(img->w == 0 && img->h == 0);
+}
+NK_API void
+nk_image(struct nk_context *ctx, struct nk_image img)
+{
+ struct nk_window *win;
+ struct nk_rect bounds;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) return;
+
+ win = ctx->current;
+ if (!nk_widget(&bounds, ctx)) return;
+ nk_draw_image(&win->buffer, bounds, &img, nk_white);
+}
+NK_API void
+nk_image_color(struct nk_context *ctx, struct nk_image img, struct nk_color col)
+{
+ struct nk_window *win;
+ struct nk_rect bounds;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout) return;
+
+ win = ctx->current;
+ if (!nk_widget(&bounds, ctx)) return;
+ nk_draw_image(&win->buffer, bounds, &img, col);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * 9-SLICE
+ *
+ * ===============================================================*/
+NK_API struct nk_nine_slice
+nk_sub9slice_ptr(void *ptr, nk_ushort w, nk_ushort h, struct nk_rect rgn, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b)
+{
+ struct nk_nine_slice s;
+ struct nk_image *i = &s.img;
+ nk_zero(&s, sizeof(s));
+ i->handle.ptr = ptr;
+ i->w = w; i->h = h;
+ i->region[0] = (nk_ushort)rgn.x;
+ i->region[1] = (nk_ushort)rgn.y;
+ i->region[2] = (nk_ushort)rgn.w;
+ i->region[3] = (nk_ushort)rgn.h;
+ s.l = l; s.t = t; s.r = r; s.b = b;
+ return s;
+}
+NK_API struct nk_nine_slice
+nk_sub9slice_id(int id, nk_ushort w, nk_ushort h, struct nk_rect rgn, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b)
+{
+ struct nk_nine_slice s;
+ struct nk_image *i = &s.img;
+ nk_zero(&s, sizeof(s));
+ i->handle.id = id;
+ i->w = w; i->h = h;
+ i->region[0] = (nk_ushort)rgn.x;
+ i->region[1] = (nk_ushort)rgn.y;
+ i->region[2] = (nk_ushort)rgn.w;
+ i->region[3] = (nk_ushort)rgn.h;
+ s.l = l; s.t = t; s.r = r; s.b = b;
+ return s;
+}
+NK_API struct nk_nine_slice
+nk_sub9slice_handle(nk_handle handle, nk_ushort w, nk_ushort h, struct nk_rect rgn, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b)
+{
+ struct nk_nine_slice s;
+ struct nk_image *i = &s.img;
+ nk_zero(&s, sizeof(s));
+ i->handle = handle;
+ i->w = w; i->h = h;
+ i->region[0] = (nk_ushort)rgn.x;
+ i->region[1] = (nk_ushort)rgn.y;
+ i->region[2] = (nk_ushort)rgn.w;
+ i->region[3] = (nk_ushort)rgn.h;
+ s.l = l; s.t = t; s.r = r; s.b = b;
+ return s;
+}
+NK_API struct nk_nine_slice
+nk_nine_slice_handle(nk_handle handle, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b)
+{
+ struct nk_nine_slice s;
+ struct nk_image *i = &s.img;
+ nk_zero(&s, sizeof(s));
+ i->handle = handle;
+ i->w = 0; i->h = 0;
+ i->region[0] = 0;
+ i->region[1] = 0;
+ i->region[2] = 0;
+ i->region[3] = 0;
+ s.l = l; s.t = t; s.r = r; s.b = b;
+ return s;
+}
+NK_API struct nk_nine_slice
+nk_nine_slice_ptr(void *ptr, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b)
+{
+ struct nk_nine_slice s;
+ struct nk_image *i = &s.img;
+ nk_zero(&s, sizeof(s));
+ NK_ASSERT(ptr);
+ i->handle.ptr = ptr;
+ i->w = 0; i->h = 0;
+ i->region[0] = 0;
+ i->region[1] = 0;
+ i->region[2] = 0;
+ i->region[3] = 0;
+ s.l = l; s.t = t; s.r = r; s.b = b;
+ return s;
+}
+NK_API struct nk_nine_slice
+nk_nine_slice_id(int id, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b)
+{
+ struct nk_nine_slice s;
+ struct nk_image *i = &s.img;
+ nk_zero(&s, sizeof(s));
+ i->handle.id = id;
+ i->w = 0; i->h = 0;
+ i->region[0] = 0;
+ i->region[1] = 0;
+ i->region[2] = 0;
+ i->region[3] = 0;
+ s.l = l; s.t = t; s.r = r; s.b = b;
+ return s;
+}
+NK_API int
+nk_nine_slice_is_sub9slice(const struct nk_nine_slice* slice)
+{
+ NK_ASSERT(slice);
+ return !(slice->img.w == 0 && slice->img.h == 0);
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * BUTTON
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_draw_symbol(struct nk_command_buffer *out, enum nk_symbol_type type,
+ struct nk_rect content, struct nk_color background, struct nk_color foreground,
+ float border_width, const struct nk_user_font *font)
+{
+ switch (type) {
+ case NK_SYMBOL_X:
+ case NK_SYMBOL_UNDERSCORE:
+ case NK_SYMBOL_PLUS:
+ case NK_SYMBOL_MINUS: {
+ /* single character text symbol */
+ const char *X = (type == NK_SYMBOL_X) ? "x":
+ (type == NK_SYMBOL_UNDERSCORE) ? "_":
+ (type == NK_SYMBOL_PLUS) ? "+": "-";
+ struct nk_text text;
+ text.padding = nk_vec2(0,0);
+ text.background = background;
+ text.text = foreground;
+ nk_widget_text(out, content, X, 1, &text, NK_TEXT_CENTERED, font);
+ } break;
+ case NK_SYMBOL_CIRCLE_SOLID:
+ case NK_SYMBOL_CIRCLE_OUTLINE:
+ case NK_SYMBOL_RECT_SOLID:
+ case NK_SYMBOL_RECT_OUTLINE: {
+ /* simple empty/filled shapes */
+ if (type == NK_SYMBOL_RECT_SOLID || type == NK_SYMBOL_RECT_OUTLINE) {
+ nk_fill_rect(out, content, 0, foreground);
+ if (type == NK_SYMBOL_RECT_OUTLINE)
+ nk_fill_rect(out, nk_shrink_rect(content, border_width), 0, background);
+ } else {
+ nk_fill_circle(out, content, foreground);
+ if (type == NK_SYMBOL_CIRCLE_OUTLINE)
+ nk_fill_circle(out, nk_shrink_rect(content, 1), background);
+ }
+ } break;
+ case NK_SYMBOL_TRIANGLE_UP:
+ case NK_SYMBOL_TRIANGLE_DOWN:
+ case NK_SYMBOL_TRIANGLE_LEFT:
+ case NK_SYMBOL_TRIANGLE_RIGHT: {
+ enum nk_heading heading;
+ struct nk_vec2 points[3];
+ heading = (type == NK_SYMBOL_TRIANGLE_RIGHT) ? NK_RIGHT :
+ (type == NK_SYMBOL_TRIANGLE_LEFT) ? NK_LEFT:
+ (type == NK_SYMBOL_TRIANGLE_UP) ? NK_UP: NK_DOWN;
+ nk_triangle_from_direction(points, content, 0, 0, heading);
+ nk_fill_triangle(out, points[0].x, points[0].y, points[1].x, points[1].y,
+ points[2].x, points[2].y, foreground);
+ } break;
+ default:
+ case NK_SYMBOL_NONE:
+ case NK_SYMBOL_MAX: break;
+ }
+}
+NK_LIB nk_bool
+nk_button_behavior(nk_flags *state, struct nk_rect r,
+ const struct nk_input *i, enum nk_button_behavior behavior)
+{
+ int ret = 0;
+ nk_widget_state_reset(state);
+ if (!i) return 0;
+ if (nk_input_is_mouse_hovering_rect(i, r)) {
+ *state = NK_WIDGET_STATE_HOVERED;
+ if (nk_input_is_mouse_down(i, NK_BUTTON_LEFT))
+ *state = NK_WIDGET_STATE_ACTIVE;
+ if (nk_input_has_mouse_click_in_button_rect(i, NK_BUTTON_LEFT, r)) {
+ ret = (behavior != NK_BUTTON_DEFAULT) ?
+ nk_input_is_mouse_down(i, NK_BUTTON_LEFT):
+#ifdef NK_BUTTON_TRIGGER_ON_RELEASE
+ nk_input_is_mouse_released(i, NK_BUTTON_LEFT);
+#else
+ nk_input_is_mouse_pressed(i, NK_BUTTON_LEFT);
+#endif
+ }
+ }
+ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(i, r))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(i, r))
+ *state |= NK_WIDGET_STATE_LEFT;
+ return ret;
+}
+NK_LIB const struct nk_style_item*
+nk_draw_button(struct nk_command_buffer *out,
+ const struct nk_rect *bounds, nk_flags state,
+ const struct nk_style_button *style)
+{
+ const struct nk_style_item *background;
+ if (state & NK_WIDGET_STATE_HOVER)
+ background = &style->hover;
+ else if (state & NK_WIDGET_STATE_ACTIVED)
+ background = &style->active;
+ else background = &style->normal;
+
+ switch (background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor_background));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor_background));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor_background));
+ nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor_background));
+ break;
+ }
+ return background;
+}
+NK_LIB nk_bool
+nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r,
+ const struct nk_style_button *style, const struct nk_input *in,
+ enum nk_button_behavior behavior, struct nk_rect *content)
+{
+ struct nk_rect bounds;
+ NK_ASSERT(style);
+ NK_ASSERT(state);
+ NK_ASSERT(out);
+ if (!out || !style)
+ return nk_false;
+
+ /* calculate button content space */
+ content->x = r.x + style->padding.x + style->border + style->rounding;
+ content->y = r.y + style->padding.y + style->border + style->rounding;
+ content->w = r.w - (2 * (style->padding.x + style->border + style->rounding));
+ content->h = r.h - (2 * (style->padding.y + style->border + style->rounding));
+
+ /* execute button behavior */
+ bounds.x = r.x - style->touch_padding.x;
+ bounds.y = r.y - style->touch_padding.y;
+ bounds.w = r.w + 2 * style->touch_padding.x;
+ bounds.h = r.h + 2 * style->touch_padding.y;
+ return nk_button_behavior(state, bounds, in, behavior);
+}
+NK_LIB void
+nk_draw_button_text(struct nk_command_buffer *out,
+ const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state,
+ const struct nk_style_button *style, const char *txt, int len,
+ nk_flags text_alignment, const struct nk_user_font *font)
+{
+ struct nk_text text;
+ const struct nk_style_item *background;
+ background = nk_draw_button(out, bounds, state, style);
+
+ /* select correct colors/images */
+ if (background->type == NK_STYLE_ITEM_COLOR)
+ text.background = background->data.color;
+ else text.background = style->text_background;
+ if (state & NK_WIDGET_STATE_HOVER)
+ text.text = style->text_hover;
+ else if (state & NK_WIDGET_STATE_ACTIVED)
+ text.text = style->text_active;
+ else text.text = style->text_normal;
+
+ text.text = nk_rgb_factor(text.text, style->color_factor_text);
+
+ text.padding = nk_vec2(0,0);
+ nk_widget_text(out, *content, txt, len, &text, text_alignment, font);
+}
+NK_LIB nk_bool
+nk_do_button_text(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ const char *string, int len, nk_flags align, enum nk_button_behavior behavior,
+ const struct nk_style_button *style, const struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ struct nk_rect content;
+ int ret = nk_false;
+
+ NK_ASSERT(state);
+ NK_ASSERT(style);
+ NK_ASSERT(out);
+ NK_ASSERT(string);
+ NK_ASSERT(font);
+ if (!out || !style || !font || !string)
+ return nk_false;
+
+ ret = nk_do_button(state, out, bounds, style, in, behavior, &content);
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_button_text(out, &bounds, &content, *state, style, string, len, align, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return ret;
+}
+NK_LIB void
+nk_draw_button_symbol(struct nk_command_buffer *out,
+ const struct nk_rect *bounds, const struct nk_rect *content,
+ nk_flags state, const struct nk_style_button *style,
+ enum nk_symbol_type type, const struct nk_user_font *font)
+{
+ struct nk_color sym, bg;
+ const struct nk_style_item *background;
+
+ /* select correct colors/images */
+ background = nk_draw_button(out, bounds, state, style);
+ if (background->type == NK_STYLE_ITEM_COLOR)
+ bg = background->data.color;
+ else bg = style->text_background;
+
+ if (state & NK_WIDGET_STATE_HOVER)
+ sym = style->text_hover;
+ else if (state & NK_WIDGET_STATE_ACTIVED)
+ sym = style->text_active;
+ else sym = style->text_normal;
+
+ sym = nk_rgb_factor(sym, style->color_factor_text);
+ nk_draw_symbol(out, type, *content, bg, sym, 1, font);
+}
+NK_LIB nk_bool
+nk_do_button_symbol(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ enum nk_symbol_type symbol, enum nk_button_behavior behavior,
+ const struct nk_style_button *style, const struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ int ret;
+ struct nk_rect content;
+
+ NK_ASSERT(state);
+ NK_ASSERT(style);
+ NK_ASSERT(font);
+ NK_ASSERT(out);
+ if (!out || !style || !font || !state)
+ return nk_false;
+
+ ret = nk_do_button(state, out, bounds, style, in, behavior, &content);
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_button_symbol(out, &bounds, &content, *state, style, symbol, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return ret;
+}
+NK_LIB void
+nk_draw_button_image(struct nk_command_buffer *out,
+ const struct nk_rect *bounds, const struct nk_rect *content,
+ nk_flags state, const struct nk_style_button *style, const struct nk_image *img)
+{
+ nk_draw_button(out, bounds, state, style);
+ nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor_background));
+}
+NK_LIB nk_bool
+nk_do_button_image(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ struct nk_image img, enum nk_button_behavior b,
+ const struct nk_style_button *style, const struct nk_input *in)
+{
+ int ret;
+ struct nk_rect content;
+
+ NK_ASSERT(state);
+ NK_ASSERT(style);
+ NK_ASSERT(out);
+ if (!out || !style || !state)
+ return nk_false;
+
+ ret = nk_do_button(state, out, bounds, style, in, b, &content);
+ content.x += style->image_padding.x;
+ content.y += style->image_padding.y;
+ content.w -= 2 * style->image_padding.x;
+ content.h -= 2 * style->image_padding.y;
+
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_button_image(out, &bounds, &content, *state, style, &img);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return ret;
+}
+NK_LIB void
+nk_draw_button_text_symbol(struct nk_command_buffer *out,
+ const struct nk_rect *bounds, const struct nk_rect *label,
+ const struct nk_rect *symbol, nk_flags state, const struct nk_style_button *style,
+ const char *str, int len, enum nk_symbol_type type,
+ const struct nk_user_font *font)
+{
+ struct nk_color sym;
+ struct nk_text text;
+ const struct nk_style_item *background;
+
+ /* select correct background colors/images */
+ background = nk_draw_button(out, bounds, state, style);
+ if (background->type == NK_STYLE_ITEM_COLOR)
+ text.background = background->data.color;
+ else text.background = style->text_background;
+
+ /* select correct text colors */
+ if (state & NK_WIDGET_STATE_HOVER) {
+ sym = style->text_hover;
+ text.text = style->text_hover;
+ } else if (state & NK_WIDGET_STATE_ACTIVED) {
+ sym = style->text_active;
+ text.text = style->text_active;
+ } else {
+ sym = style->text_normal;
+ text.text = style->text_normal;
+ }
+
+ sym = nk_rgb_factor(sym, style->color_factor_text);
+ text.text = nk_rgb_factor(text.text, style->color_factor_text);
+ text.padding = nk_vec2(0,0);
+ nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font);
+ nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font);
+}
+NK_LIB nk_bool
+nk_do_button_text_symbol(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ enum nk_symbol_type symbol, const char *str, int len, nk_flags align,
+ enum nk_button_behavior behavior, const struct nk_style_button *style,
+ const struct nk_user_font *font, const struct nk_input *in)
+{
+ int ret;
+ struct nk_rect tri = {0,0,0,0};
+ struct nk_rect content;
+
+ NK_ASSERT(style);
+ NK_ASSERT(out);
+ NK_ASSERT(font);
+ if (!out || !style || !font)
+ return nk_false;
+
+ ret = nk_do_button(state, out, bounds, style, in, behavior, &content);
+ tri.y = content.y + (content.h/2) - font->height/2;
+ tri.w = font->height; tri.h = font->height;
+ if (align & NK_TEXT_ALIGN_LEFT) {
+ tri.x = (content.x + content.w) - (2 * style->padding.x + tri.w);
+ tri.x = NK_MAX(tri.x, 0);
+ } else tri.x = content.x + 2 * style->padding.x;
+
+ /* draw button */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_button_text_symbol(out, &bounds, &content, &tri,
+ *state, style, str, len, symbol, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return ret;
+}
+NK_LIB void
+nk_draw_button_text_image(struct nk_command_buffer *out,
+ const struct nk_rect *bounds, const struct nk_rect *label,
+ const struct nk_rect *image, nk_flags state, const struct nk_style_button *style,
+ const char *str, int len, const struct nk_user_font *font,
+ const struct nk_image *img)
+{
+ struct nk_text text;
+ const struct nk_style_item *background;
+ background = nk_draw_button(out, bounds, state, style);
+
+ /* select correct colors */
+ if (background->type == NK_STYLE_ITEM_COLOR)
+ text.background = background->data.color;
+ else text.background = style->text_background;
+ if (state & NK_WIDGET_STATE_HOVER)
+ text.text = style->text_hover;
+ else if (state & NK_WIDGET_STATE_ACTIVED)
+ text.text = style->text_active;
+ else text.text = style->text_normal;
+
+ text.text = nk_rgb_factor(text.text, style->color_factor_text);
+ text.padding = nk_vec2(0, 0);
+ nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font);
+ nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor_background));
+}
+NK_LIB nk_bool
+nk_do_button_text_image(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ struct nk_image img, const char* str, int len, nk_flags align,
+ enum nk_button_behavior behavior, const struct nk_style_button *style,
+ const struct nk_user_font *font, const struct nk_input *in)
+{
+ int ret;
+ struct nk_rect icon;
+ struct nk_rect content;
+
+ NK_ASSERT(style);
+ NK_ASSERT(state);
+ NK_ASSERT(font);
+ NK_ASSERT(out);
+ if (!out || !font || !style || !str)
+ return nk_false;
+
+ ret = nk_do_button(state, out, bounds, style, in, behavior, &content);
+ icon.y = bounds.y + style->padding.y;
+ icon.w = icon.h = bounds.h - 2 * style->padding.y;
+ if (align & NK_TEXT_ALIGN_LEFT) {
+ icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w);
+ icon.x = NK_MAX(icon.x, 0);
+ } else icon.x = bounds.x + 2 * style->padding.x;
+
+ icon.x += style->image_padding.x;
+ icon.y += style->image_padding.y;
+ icon.w -= 2 * style->image_padding.x;
+ icon.h -= 2 * style->image_padding.y;
+
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_button_text_image(out, &bounds, &content, &icon, *state, style, str, len, font, &img);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return ret;
+}
+NK_API void
+nk_button_set_behavior(struct nk_context *ctx, enum nk_button_behavior behavior)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return;
+ ctx->button_behavior = behavior;
+}
+NK_API nk_bool
+nk_button_push_behavior(struct nk_context *ctx, enum nk_button_behavior behavior)
+{
+ struct nk_config_stack_button_behavior *button_stack;
+ struct nk_config_stack_button_behavior_element *element;
+
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+
+ button_stack = &ctx->stacks.button_behaviors;
+ NK_ASSERT(button_stack->head < (int)NK_LEN(button_stack->elements));
+ if (button_stack->head >= (int)NK_LEN(button_stack->elements))
+ return 0;
+
+ element = &button_stack->elements[button_stack->head++];
+ element->address = &ctx->button_behavior;
+ element->old_value = ctx->button_behavior;
+ ctx->button_behavior = behavior;
+ return 1;
+}
+NK_API nk_bool
+nk_button_pop_behavior(struct nk_context *ctx)
+{
+ struct nk_config_stack_button_behavior *button_stack;
+ struct nk_config_stack_button_behavior_element *element;
+
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+
+ button_stack = &ctx->stacks.button_behaviors;
+ NK_ASSERT(button_stack->head > 0);
+ if (button_stack->head < 1)
+ return 0;
+
+ element = &button_stack->elements[--button_stack->head];
+ *element->address = element->old_value;
+ return 1;
+}
+NK_API nk_bool
+nk_button_text_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, const char *title, int len)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(style);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!style || !ctx || !ctx->current || !ctx->current->layout) return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+ state = nk_widget(&bounds, ctx);
+
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds,
+ title, len, style->text_alignment, ctx->button_behavior,
+ style, in, ctx->style.font);
+}
+NK_API nk_bool
+nk_button_text(struct nk_context *ctx, const char *title, int len)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ return nk_button_text_styled(ctx, &ctx->style.button, title, len);
+}
+NK_API nk_bool nk_button_label_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, const char *title)
+{
+ return nk_button_text_styled(ctx, style, title, nk_strlen(title));
+}
+NK_API nk_bool nk_button_label(struct nk_context *ctx, const char *title)
+{
+ return nk_button_text(ctx, title, nk_strlen(title));
+}
+NK_API nk_bool
+nk_button_color(struct nk_context *ctx, struct nk_color color)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ struct nk_style_button button;
+
+ int ret = 0;
+ struct nk_rect bounds;
+ struct nk_rect content;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+
+ button = ctx->style.button;
+ button.normal = nk_style_item_color(color);
+ button.hover = nk_style_item_color(color);
+ button.active = nk_style_item_color(color);
+ ret = nk_do_button(&ctx->last_widget_state, &win->buffer, bounds,
+ &button, in, ctx->button_behavior, &content);
+ nk_draw_button(&win->buffer, &bounds, ctx->last_widget_state, &button);
+ return ret;
+}
+NK_API nk_bool
+nk_button_symbol_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, enum nk_symbol_type symbol)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds,
+ symbol, ctx->button_behavior, style, in, ctx->style.font);
+}
+NK_API nk_bool
+nk_button_symbol(struct nk_context *ctx, enum nk_symbol_type symbol)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ return nk_button_symbol_styled(ctx, &ctx->style.button, symbol);
+}
+NK_API nk_bool
+nk_button_image_styled(struct nk_context *ctx, const struct nk_style_button *style,
+ struct nk_image img)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds,
+ img, ctx->button_behavior, style, in);
+}
+NK_API nk_bool
+nk_button_image(struct nk_context *ctx, struct nk_image img)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ return nk_button_image_styled(ctx, &ctx->style.button, img);
+}
+NK_API nk_bool
+nk_button_symbol_text_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, enum nk_symbol_type symbol,
+ const char *text, int len, nk_flags align)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds,
+ symbol, text, len, align, ctx->button_behavior,
+ style, ctx->style.font, in);
+}
+NK_API nk_bool
+nk_button_symbol_text(struct nk_context *ctx, enum nk_symbol_type symbol,
+ const char* text, int len, nk_flags align)
+{
+ NK_ASSERT(ctx);
+ if (!ctx) return 0;
+ return nk_button_symbol_text_styled(ctx, &ctx->style.button, symbol, text, len, align);
+}
+NK_API nk_bool nk_button_symbol_label(struct nk_context *ctx, enum nk_symbol_type symbol,
+ const char *label, nk_flags align)
+{
+ return nk_button_symbol_text(ctx, symbol, label, nk_strlen(label), align);
+}
+NK_API nk_bool nk_button_symbol_label_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, enum nk_symbol_type symbol,
+ const char *title, nk_flags align)
+{
+ return nk_button_symbol_text_styled(ctx, style, symbol, title, nk_strlen(title), align);
+}
+NK_API nk_bool
+nk_button_image_text_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, struct nk_image img, const char *text,
+ int len, nk_flags align)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer,
+ bounds, img, text, len, align, ctx->button_behavior,
+ style, ctx->style.font, in);
+}
+NK_API nk_bool
+nk_button_image_text(struct nk_context *ctx, struct nk_image img,
+ const char *text, int len, nk_flags align)
+{
+ return nk_button_image_text_styled(ctx, &ctx->style.button,img, text, len, align);
+}
+NK_API nk_bool nk_button_image_label(struct nk_context *ctx, struct nk_image img,
+ const char *label, nk_flags align)
+{
+ return nk_button_image_text(ctx, img, label, nk_strlen(label), align);
+}
+NK_API nk_bool nk_button_image_label_styled(struct nk_context *ctx,
+ const struct nk_style_button *style, struct nk_image img,
+ const char *label, nk_flags text_alignment)
+{
+ return nk_button_image_text_styled(ctx, style, img, label, nk_strlen(label), text_alignment);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * TOGGLE
+ *
+ * ===============================================================*/
+NK_LIB nk_bool
+nk_toggle_behavior(const struct nk_input *in, struct nk_rect select,
+ nk_flags *state, nk_bool active)
+{
+ nk_widget_state_reset(state);
+ if (nk_button_behavior(state, select, in, NK_BUTTON_DEFAULT)) {
+ *state = NK_WIDGET_STATE_ACTIVE;
+ active = !active;
+ }
+ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, select))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(in, select))
+ *state |= NK_WIDGET_STATE_LEFT;
+ return active;
+}
+NK_LIB void
+nk_draw_checkbox(struct nk_command_buffer *out,
+ nk_flags state, const struct nk_style_toggle *style, nk_bool active,
+ const struct nk_rect *label, const struct nk_rect *selector,
+ const struct nk_rect *cursors, const char *string, int len,
+ const struct nk_user_font *font, nk_flags text_alignment)
+{
+ const struct nk_style_item *background;
+ const struct nk_style_item *cursor;
+ struct nk_text text;
+
+ /* select correct colors/images */
+ if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ cursor = &style->cursor_hover;
+ text.text = style->text_hover;
+ } else if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->hover;
+ cursor = &style->cursor_hover;
+ text.text = style->text_active;
+ } else {
+ background = &style->normal;
+ cursor = &style->cursor_normal;
+ text.text = style->text_normal;
+ }
+
+ text.text = nk_rgb_factor(text.text, style->color_factor);
+ text.padding.x = 0;
+ text.padding.y = 0;
+ text.background = style->text_background;
+ nk_widget_text(out, *label, string, len, &text, text_alignment, font);
+
+ /* draw background and cursor */
+ if (background->type == NK_STYLE_ITEM_COLOR) {
+ nk_fill_rect(out, *selector, 0, nk_rgb_factor(style->border_color, style->color_factor));
+ nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, nk_rgb_factor(background->data.color, style->color_factor));
+ } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ if (active) {
+ if (cursor->type == NK_STYLE_ITEM_IMAGE)
+ nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ else nk_fill_rect(out, *cursors, 0, cursor->data.color);
+ }
+}
+NK_LIB void
+nk_draw_option(struct nk_command_buffer *out,
+ nk_flags state, const struct nk_style_toggle *style, nk_bool active,
+ const struct nk_rect *label, const struct nk_rect *selector,
+ const struct nk_rect *cursors, const char *string, int len,
+ const struct nk_user_font *font, nk_flags text_alignment)
+{
+ const struct nk_style_item *background;
+ const struct nk_style_item *cursor;
+ struct nk_text text;
+
+ /* select correct colors/images */
+ if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ cursor = &style->cursor_hover;
+ text.text = style->text_hover;
+ } else if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->hover;
+ cursor = &style->cursor_hover;
+ text.text = style->text_active;
+ } else {
+ background = &style->normal;
+ cursor = &style->cursor_normal;
+ text.text = style->text_normal;
+ }
+
+ text.text = nk_rgb_factor(text.text, style->color_factor);
+ text.padding.x = 0;
+ text.padding.y = 0;
+ text.background = style->text_background;
+ nk_widget_text(out, *label, string, len, &text, text_alignment, font);
+
+ /* draw background and cursor */
+ if (background->type == NK_STYLE_ITEM_COLOR) {
+ nk_fill_circle(out, *selector, nk_rgb_factor(style->border_color, style->color_factor));
+ nk_fill_circle(out, nk_shrink_rect(*selector, style->border), nk_rgb_factor(background->data.color, style->color_factor));
+ } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ if (active) {
+ if (cursor->type == NK_STYLE_ITEM_IMAGE)
+ nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ else nk_fill_circle(out, *cursors, cursor->data.color);
+ }
+}
+NK_LIB nk_bool
+nk_do_toggle(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect r,
+ nk_bool *active, const char *str, int len, enum nk_toggle_type type,
+ const struct nk_style_toggle *style, const struct nk_input *in,
+ const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ int was_active;
+ struct nk_rect bounds;
+ struct nk_rect select;
+ struct nk_rect cursor;
+ struct nk_rect label;
+
+ NK_ASSERT(style);
+ NK_ASSERT(out);
+ NK_ASSERT(font);
+ if (!out || !style || !font || !active)
+ return 0;
+
+ r.w = NK_MAX(r.w, font->height + 2 * style->padding.x);
+ r.h = NK_MAX(r.h, font->height + 2 * style->padding.y);
+
+ /* add additional touch padding for touch screen devices */
+ bounds.x = r.x - style->touch_padding.x;
+ bounds.y = r.y - style->touch_padding.y;
+ bounds.w = r.w + 2 * style->touch_padding.x;
+ bounds.h = r.h + 2 * style->touch_padding.y;
+
+ /* calculate the selector space */
+ select.w = font->height;
+ select.h = select.w;
+
+ if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) {
+ select.x = r.x + r.w - font->height;
+
+ /* label in front of the selector */
+ label.x = r.x;
+ label.w = r.w - select.w - style->spacing * 2;
+ } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) {
+ select.x = r.x + (r.w - select.w) / 2;
+
+ /* label in front of selector */
+ label.x = r.x;
+ label.w = (r.w - select.w - style->spacing * 2) / 2;
+ } else { /* Default: NK_WIDGET_ALIGN_LEFT */
+ select.x = r.x;
+
+ /* label behind the selector */
+ label.x = select.x + select.w + style->spacing;
+ label.w = NK_MAX(r.x + r.w, label.x) - label.x;
+ }
+
+ if (widget_alignment & NK_WIDGET_ALIGN_TOP) {
+ select.y = r.y;
+ } else if (widget_alignment & NK_WIDGET_ALIGN_BOTTOM) {
+ select.y = r.y + r.h - select.h - 2 * style->padding.y;
+ } else { /* Default: NK_WIDGET_ALIGN_MIDDLE */
+ select.y = r.y + r.h/2.0f - select.h/2.0f;
+ }
+
+ label.y = select.y;
+ label.h = select.w;
+
+ /* calculate the bounds of the cursor inside the selector */
+ cursor.x = select.x + style->padding.x + style->border;
+ cursor.y = select.y + style->padding.y + style->border;
+ cursor.w = select.w - (2 * style->padding.x + 2 * style->border);
+ cursor.h = select.h - (2 * style->padding.y + 2 * style->border);
+
+ /* update selector */
+ was_active = *active;
+ *active = nk_toggle_behavior(in, bounds, state, *active);
+
+ /* draw selector */
+ if (style->draw_begin)
+ style->draw_begin(out, style->userdata);
+ if (type == NK_TOGGLE_CHECK) {
+ nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment);
+ } else {
+ nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment);
+ }
+ if (style->draw_end)
+ style->draw_end(out, style->userdata);
+ return (was_active != *active);
+}
+/*----------------------------------------------------------------
+ *
+ * CHECKBOX
+ *
+ * --------------------------------------------------------------*/
+NK_API nk_bool
+nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return active;
+
+ win = ctx->current;
+ style = &ctx->style;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return active;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active,
+ text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT);
+ return active;
+}
+NK_API nk_bool
+nk_check_text_align(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return active;
+
+ win = ctx->current;
+ style = &ctx->style;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return active;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active,
+ text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, widget_alignment, text_alignment);
+ return active;
+}
+NK_API unsigned int
+nk_check_flags_text(struct nk_context *ctx, const char *text, int len,
+ unsigned int flags, unsigned int value)
+{
+ int old_active;
+ NK_ASSERT(ctx);
+ NK_ASSERT(text);
+ if (!ctx || !text) return flags;
+ old_active = (int)((flags & value) & value);
+ if (nk_check_text(ctx, text, len, old_active))
+ flags |= value;
+ else flags &= ~value;
+ return flags;
+}
+NK_API nk_bool
+nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *active)
+{
+ int old_val;
+ NK_ASSERT(ctx);
+ NK_ASSERT(text);
+ NK_ASSERT(active);
+ if (!ctx || !text || !active) return 0;
+ old_val = *active;
+ *active = nk_check_text(ctx, text, len, *active);
+ return old_val != *active;
+}
+NK_API nk_bool
+nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ int old_val;
+ NK_ASSERT(ctx);
+ NK_ASSERT(text);
+ NK_ASSERT(active);
+ if (!ctx || !text || !active) return 0;
+ old_val = *active;
+ *active = nk_check_text_align(ctx, text, len, *active, widget_alignment, text_alignment);
+ return old_val != *active;
+}
+NK_API nk_bool
+nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len,
+ unsigned int *flags, unsigned int value)
+{
+ nk_bool active;
+ NK_ASSERT(ctx);
+ NK_ASSERT(text);
+ NK_ASSERT(flags);
+ if (!ctx || !text || !flags) return 0;
+
+ active = (int)((*flags & value) & value);
+ if (nk_checkbox_text(ctx, text, len, &active)) {
+ if (active) *flags |= value;
+ else *flags &= ~value;
+ return 1;
+ }
+ return 0;
+}
+NK_API nk_bool nk_check_label(struct nk_context *ctx, const char *label, nk_bool active)
+{
+ return nk_check_text(ctx, label, nk_strlen(label), active);
+}
+NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label,
+ unsigned int flags, unsigned int value)
+{
+ return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value);
+}
+NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_bool *active)
+{
+ return nk_checkbox_text(ctx, label, nk_strlen(label), active);
+}
+NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ return nk_checkbox_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment);
+}
+NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label,
+ unsigned int *flags, unsigned int value)
+{
+ return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value);
+}
+/*----------------------------------------------------------------
+ *
+ * OPTION
+ *
+ * --------------------------------------------------------------*/
+NK_API nk_bool
+nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_active)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return is_active;
+
+ win = ctx->current;
+ style = &ctx->style;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return (int)state;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active,
+ text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT);
+ return is_active;
+}
+NK_API nk_bool
+nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return is_active;
+
+ win = ctx->current;
+ style = &ctx->style;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return (int)state;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active,
+ text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, widget_alignment, text_alignment);
+ return is_active;
+}
+NK_API nk_bool
+nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active)
+{
+ int old_value;
+ NK_ASSERT(ctx);
+ NK_ASSERT(text);
+ NK_ASSERT(active);
+ if (!ctx || !text || !active) return 0;
+ old_value = *active;
+ *active = nk_option_text(ctx, text, len, old_value);
+ return old_value != *active;
+}
+NK_API nk_bool
+nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ int old_value;
+ NK_ASSERT(ctx);
+ NK_ASSERT(text);
+ NK_ASSERT(active);
+ if (!ctx || !text || !active) return 0;
+ old_value = *active;
+ *active = nk_option_text_align(ctx, text, len, old_value, widget_alignment, text_alignment);
+ return old_value != *active;
+}
+NK_API nk_bool
+nk_option_label(struct nk_context *ctx, const char *label, nk_bool active)
+{
+ return nk_option_text(ctx, label, nk_strlen(label), active);
+}
+NK_API nk_bool
+nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ return nk_option_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment);
+}
+NK_API nk_bool
+nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active)
+{
+ return nk_radio_text(ctx, label, nk_strlen(label), active);
+}
+NK_API nk_bool
+nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment)
+{
+ return nk_radio_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * SELECTABLE
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_draw_selectable(struct nk_command_buffer *out,
+ nk_flags state, const struct nk_style_selectable *style, nk_bool active,
+ const struct nk_rect *bounds,
+ const struct nk_rect *icon, const struct nk_image *img, enum nk_symbol_type sym,
+ const char *string, int len, nk_flags align, const struct nk_user_font *font)
+{
+ const struct nk_style_item *background;
+ struct nk_text text;
+ text.padding = style->padding;
+
+ /* select correct colors/images */
+ if (!active) {
+ if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->pressed;
+ text.text = style->text_pressed;
+ } else if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ text.text = style->text_hover;
+ } else {
+ background = &style->normal;
+ text.text = style->text_normal;
+ }
+ } else {
+ if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->pressed_active;
+ text.text = style->text_pressed_active;
+ } else if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover_active;
+ text.text = style->text_hover_active;
+ } else {
+ background = &style->normal_active;
+ text.text = style->text_normal_active;
+ }
+ }
+
+ text.text = nk_rgb_factor(text.text, style->color_factor);
+
+ /* draw selectable background and text */
+ switch (background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ text.background = background->data.color;
+ nk_fill_rect(out, *bounds, style->rounding, background->data.color);
+ break;
+ }
+ if (icon) {
+ if (img) nk_draw_image(out, *icon, img, nk_rgb_factor(nk_white, style->color_factor));
+ else nk_draw_symbol(out, sym, *icon, text.background, text.text, 1, font);
+ }
+ nk_widget_text(out, *bounds, string, len, &text, align, font);
+}
+NK_LIB nk_bool
+nk_do_selectable(nk_flags *state, struct nk_command_buffer *out,
+ struct nk_rect bounds, const char *str, int len, nk_flags align, nk_bool *value,
+ const struct nk_style_selectable *style, const struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ int old_value;
+ struct nk_rect touch;
+
+ NK_ASSERT(state);
+ NK_ASSERT(out);
+ NK_ASSERT(str);
+ NK_ASSERT(len);
+ NK_ASSERT(value);
+ NK_ASSERT(style);
+ NK_ASSERT(font);
+
+ if (!state || !out || !str || !len || !value || !style || !font) return 0;
+ old_value = *value;
+
+ /* remove padding */
+ touch.x = bounds.x - style->touch_padding.x;
+ touch.y = bounds.y - style->touch_padding.y;
+ touch.w = bounds.w + style->touch_padding.x * 2;
+ touch.h = bounds.h + style->touch_padding.y * 2;
+
+ /* update button */
+ if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT))
+ *value = !(*value);
+
+ /* draw selectable */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_selectable(out, *state, style, *value, &bounds, 0,0,NK_SYMBOL_NONE, str, len, align, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return old_value != *value;
+}
+NK_LIB nk_bool
+nk_do_selectable_image(nk_flags *state, struct nk_command_buffer *out,
+ struct nk_rect bounds, const char *str, int len, nk_flags align, nk_bool *value,
+ const struct nk_image *img, const struct nk_style_selectable *style,
+ const struct nk_input *in, const struct nk_user_font *font)
+{
+ nk_bool old_value;
+ struct nk_rect touch;
+ struct nk_rect icon;
+
+ NK_ASSERT(state);
+ NK_ASSERT(out);
+ NK_ASSERT(str);
+ NK_ASSERT(len);
+ NK_ASSERT(value);
+ NK_ASSERT(style);
+ NK_ASSERT(font);
+
+ if (!state || !out || !str || !len || !value || !style || !font) return 0;
+ old_value = *value;
+
+ /* toggle behavior */
+ touch.x = bounds.x - style->touch_padding.x;
+ touch.y = bounds.y - style->touch_padding.y;
+ touch.w = bounds.w + style->touch_padding.x * 2;
+ touch.h = bounds.h + style->touch_padding.y * 2;
+ if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT))
+ *value = !(*value);
+
+ icon.y = bounds.y + style->padding.y;
+ icon.w = icon.h = bounds.h - 2 * style->padding.y;
+ if (align & NK_TEXT_ALIGN_LEFT) {
+ icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w);
+ icon.x = NK_MAX(icon.x, 0);
+ } else icon.x = bounds.x + 2 * style->padding.x;
+
+ icon.x += style->image_padding.x;
+ icon.y += style->image_padding.y;
+ icon.w -= 2 * style->image_padding.x;
+ icon.h -= 2 * style->image_padding.y;
+
+ /* draw selectable */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_selectable(out, *state, style, *value, &bounds, &icon, img, NK_SYMBOL_NONE, str, len, align, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return old_value != *value;
+}
+NK_LIB nk_bool
+nk_do_selectable_symbol(nk_flags *state, struct nk_command_buffer *out,
+ struct nk_rect bounds, const char *str, int len, nk_flags align, nk_bool *value,
+ enum nk_symbol_type sym, const struct nk_style_selectable *style,
+ const struct nk_input *in, const struct nk_user_font *font)
+{
+ int old_value;
+ struct nk_rect touch;
+ struct nk_rect icon;
+
+ NK_ASSERT(state);
+ NK_ASSERT(out);
+ NK_ASSERT(str);
+ NK_ASSERT(len);
+ NK_ASSERT(value);
+ NK_ASSERT(style);
+ NK_ASSERT(font);
+
+ if (!state || !out || !str || !len || !value || !style || !font) return 0;
+ old_value = *value;
+
+ /* toggle behavior */
+ touch.x = bounds.x - style->touch_padding.x;
+ touch.y = bounds.y - style->touch_padding.y;
+ touch.w = bounds.w + style->touch_padding.x * 2;
+ touch.h = bounds.h + style->touch_padding.y * 2;
+ if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT))
+ *value = !(*value);
+
+ icon.y = bounds.y + style->padding.y;
+ icon.w = icon.h = bounds.h - 2 * style->padding.y;
+ if (align & NK_TEXT_ALIGN_LEFT) {
+ icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w);
+ icon.x = NK_MAX(icon.x, 0);
+ } else icon.x = bounds.x + 2 * style->padding.x;
+
+ icon.x += style->image_padding.x;
+ icon.y += style->image_padding.y;
+ icon.w -= 2 * style->image_padding.x;
+ icon.h -= 2 * style->image_padding.y;
+
+ /* draw selectable */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_selectable(out, *state, style, *value, &bounds, &icon, 0, sym, str, len, align, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return old_value != *value;
+}
+
+NK_API nk_bool
+nk_selectable_text(struct nk_context *ctx, const char *str, int len,
+ nk_flags align, nk_bool *value)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ enum nk_widget_layout_states state;
+ struct nk_rect bounds;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(value);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !value)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+ style = &ctx->style;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds,
+ str, len, align, value, &style->selectable, in, style->font);
+}
+NK_API nk_bool
+nk_selectable_image_text(struct nk_context *ctx, struct nk_image img,
+ const char *str, int len, nk_flags align, nk_bool *value)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ enum nk_widget_layout_states state;
+ struct nk_rect bounds;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(value);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !value)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+ style = &ctx->style;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds,
+ str, len, align, value, &img, &style->selectable, in, style->font);
+}
+NK_API nk_bool
+nk_selectable_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *str, int len, nk_flags align, nk_bool *value)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_input *in;
+ const struct nk_style *style;
+
+ enum nk_widget_layout_states state;
+ struct nk_rect bounds;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(value);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !value)
+ return 0;
+
+ win = ctx->current;
+ layout = win->layout;
+ style = &ctx->style;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_selectable_symbol(&ctx->last_widget_state, &win->buffer, bounds,
+ str, len, align, value, sym, &style->selectable, in, style->font);
+}
+NK_API nk_bool
+nk_selectable_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *title, nk_flags align, nk_bool *value)
+{
+ return nk_selectable_symbol_text(ctx, sym, title, nk_strlen(title), align, value);
+}
+NK_API nk_bool nk_select_text(struct nk_context *ctx, const char *str, int len,
+ nk_flags align, nk_bool value)
+{
+ nk_selectable_text(ctx, str, len, align, &value);return value;
+}
+NK_API nk_bool nk_selectable_label(struct nk_context *ctx, const char *str, nk_flags align, nk_bool *value)
+{
+ return nk_selectable_text(ctx, str, nk_strlen(str), align, value);
+}
+NK_API nk_bool nk_selectable_image_label(struct nk_context *ctx,struct nk_image img,
+ const char *str, nk_flags align, nk_bool *value)
+{
+ return nk_selectable_image_text(ctx, img, str, nk_strlen(str), align, value);
+}
+NK_API nk_bool nk_select_label(struct nk_context *ctx, const char *str, nk_flags align, nk_bool value)
+{
+ nk_selectable_text(ctx, str, nk_strlen(str), align, &value);return value;
+}
+NK_API nk_bool nk_select_image_label(struct nk_context *ctx, struct nk_image img,
+ const char *str, nk_flags align, nk_bool value)
+{
+ nk_selectable_image_text(ctx, img, str, nk_strlen(str), align, &value);return value;
+}
+NK_API nk_bool nk_select_image_text(struct nk_context *ctx, struct nk_image img,
+ const char *str, int len, nk_flags align, nk_bool value)
+{
+ nk_selectable_image_text(ctx, img, str, len, align, &value);return value;
+}
+NK_API nk_bool
+nk_select_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *title, int title_len, nk_flags align, nk_bool value)
+{
+ nk_selectable_symbol_text(ctx, sym, title, title_len, align, &value);return value;
+}
+NK_API nk_bool
+nk_select_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *title, nk_flags align, nk_bool value)
+{
+ return nk_select_symbol_text(ctx, sym, title, nk_strlen(title), align, value);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * SLIDER
+ *
+ * ===============================================================*/
+NK_LIB float
+nk_slider_behavior(nk_flags *state, struct nk_rect *logical_cursor,
+ struct nk_rect *visual_cursor, struct nk_input *in,
+ struct nk_rect bounds, float slider_min, float slider_max, float slider_value,
+ float slider_step, float slider_steps)
+{
+ int left_mouse_down;
+ int left_mouse_click_in_cursor;
+
+ /* check if visual cursor is being dragged */
+ nk_widget_state_reset(state);
+ left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down;
+ left_mouse_click_in_cursor = in && nk_input_has_mouse_click_down_in_rect(in,
+ NK_BUTTON_LEFT, *visual_cursor, nk_true);
+
+ if (left_mouse_down && left_mouse_click_in_cursor) {
+ float ratio = 0;
+ const float d = in->mouse.pos.x - (visual_cursor->x+visual_cursor->w*0.5f);
+ const float pxstep = bounds.w / slider_steps;
+
+ /* only update value if the next slider step is reached */
+ *state = NK_WIDGET_STATE_ACTIVE;
+ if (NK_ABS(d) >= pxstep) {
+ const float steps = (float)((int)(NK_ABS(d) / pxstep));
+ slider_value += (d > 0) ? (slider_step*steps) : -(slider_step*steps);
+ slider_value = NK_CLAMP(slider_min, slider_value, slider_max);
+ ratio = (slider_value - slider_min)/slider_step;
+ logical_cursor->x = bounds.x + (logical_cursor->w * ratio);
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = logical_cursor->x;
+ }
+ }
+
+ /* slider widget state */
+ if (nk_input_is_mouse_hovering_rect(in, bounds))
+ *state = NK_WIDGET_STATE_HOVERED;
+ if (*state & NK_WIDGET_STATE_HOVER &&
+ !nk_input_is_mouse_prev_hovering_rect(in, bounds))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(in, bounds))
+ *state |= NK_WIDGET_STATE_LEFT;
+ return slider_value;
+}
+NK_LIB void
+nk_draw_slider(struct nk_command_buffer *out, nk_flags state,
+ const struct nk_style_slider *style, const struct nk_rect *bounds,
+ const struct nk_rect *visual_cursor, float min, float value, float max)
+{
+ struct nk_rect fill;
+ struct nk_rect bar;
+ const struct nk_style_item *background;
+
+ /* select correct slider images/colors */
+ struct nk_color bar_color;
+ const struct nk_style_item *cursor;
+
+ NK_UNUSED(min);
+ NK_UNUSED(max);
+ NK_UNUSED(value);
+
+ if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->active;
+ bar_color = style->bar_active;
+ cursor = &style->cursor_active;
+ } else if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ bar_color = style->bar_hover;
+ cursor = &style->cursor_hover;
+ } else {
+ background = &style->normal;
+ bar_color = style->bar_normal;
+ cursor = &style->cursor_normal;
+ }
+
+ /* calculate slider background bar */
+ bar.x = bounds->x;
+ bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12;
+ bar.w = bounds->w;
+ bar.h = bounds->h/6;
+
+ /* filled background bar style */
+ fill.w = (visual_cursor->x + (visual_cursor->w/2.0f)) - bar.x;
+ fill.x = bar.x;
+ fill.y = bar.y;
+ fill.h = bar.h;
+
+ /* draw background */
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor));
+ nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor));
+ break;
+ }
+
+ /* draw slider bar */
+ nk_fill_rect(out, bar, style->rounding, nk_rgb_factor(bar_color, style->color_factor));
+ nk_fill_rect(out, fill, style->rounding, nk_rgb_factor(style->bar_filled, style->color_factor));
+
+ /* draw cursor */
+ if (cursor->type == NK_STYLE_ITEM_IMAGE)
+ nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ else
+ nk_fill_circle(out, *visual_cursor, nk_rgb_factor(cursor->data.color, style->color_factor));
+}
+NK_LIB float
+nk_do_slider(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ float min, float val, float max, float step,
+ const struct nk_style_slider *style, struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ float slider_range;
+ float slider_min;
+ float slider_max;
+ float slider_value;
+ float slider_steps;
+ float cursor_offset;
+
+ struct nk_rect visual_cursor;
+ struct nk_rect logical_cursor;
+
+ NK_ASSERT(style);
+ NK_ASSERT(out);
+ if (!out || !style)
+ return 0;
+
+ /* remove padding from slider bounds */
+ bounds.x = bounds.x + style->padding.x;
+ bounds.y = bounds.y + style->padding.y;
+ bounds.h = NK_MAX(bounds.h, 2*style->padding.y);
+ bounds.w = NK_MAX(bounds.w, 2*style->padding.x + style->cursor_size.x);
+ bounds.w -= 2 * style->padding.x;
+ bounds.h -= 2 * style->padding.y;
+
+ /* optional buttons */
+ if (style->show_buttons) {
+ nk_flags ws;
+ struct nk_rect button;
+ button.y = bounds.y;
+ button.w = bounds.h;
+ button.h = bounds.h;
+
+ /* decrement button */
+ button.x = bounds.x;
+ if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, NK_BUTTON_DEFAULT,
+ &style->dec_button, in, font))
+ val -= step;
+
+ /* increment button */
+ button.x = (bounds.x + bounds.w) - button.w;
+ if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, NK_BUTTON_DEFAULT,
+ &style->inc_button, in, font))
+ val += step;
+
+ bounds.x = bounds.x + button.w + style->spacing.x;
+ bounds.w = bounds.w - (2*button.w + 2*style->spacing.x);
+ }
+
+ /* remove one cursor size to support visual cursor */
+ bounds.x += style->cursor_size.x*0.5f;
+ bounds.w -= style->cursor_size.x;
+
+ /* make sure the provided values are correct */
+ slider_max = NK_MAX(min, max);
+ slider_min = NK_MIN(min, max);
+ slider_value = NK_CLAMP(slider_min, val, slider_max);
+ slider_range = slider_max - slider_min;
+ slider_steps = slider_range / step;
+ cursor_offset = (slider_value - slider_min) / step;
+
+ /* calculate cursor
+ Basically you have two cursors. One for visual representation and interaction
+ and one for updating the actual cursor value. */
+ logical_cursor.h = bounds.h;
+ logical_cursor.w = bounds.w / slider_steps;
+ logical_cursor.x = bounds.x + (logical_cursor.w * cursor_offset);
+ logical_cursor.y = bounds.y;
+
+ visual_cursor.h = style->cursor_size.y;
+ visual_cursor.w = style->cursor_size.x;
+ visual_cursor.y = (bounds.y + bounds.h*0.5f) - visual_cursor.h*0.5f;
+ visual_cursor.x = logical_cursor.x - visual_cursor.w*0.5f;
+
+ slider_value = nk_slider_behavior(state, &logical_cursor, &visual_cursor,
+ in, bounds, slider_min, slider_max, slider_value, step, slider_steps);
+ visual_cursor.x = logical_cursor.x - visual_cursor.w*0.5f;
+
+ /* draw slider */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_slider(out, *state, style, &bounds, &visual_cursor, slider_min, slider_value, slider_max);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return slider_value;
+}
+NK_API nk_bool
+nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max_value,
+ float value_step)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ struct nk_input *in;
+ const struct nk_style *style;
+
+ int ret = 0;
+ float old_value;
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ NK_ASSERT(value);
+ if (!ctx || !ctx->current || !ctx->current->layout || !value)
+ return ret;
+
+ win = ctx->current;
+ style = &ctx->style;
+ layout = win->layout;
+
+ state = nk_widget(&bounds, ctx);
+ if (!state) return ret;
+ in = (/*state == NK_WIDGET_ROM || */ state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+
+ old_value = *value;
+ *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value,
+ old_value, max_value, value_step, &style->slider, in, style->font);
+ return (old_value > *value || old_value < *value);
+}
+NK_API float
+nk_slide_float(struct nk_context *ctx, float min, float val, float max, float step)
+{
+ nk_slider_float(ctx, min, &val, max, step); return val;
+}
+NK_API int
+nk_slide_int(struct nk_context *ctx, int min, int val, int max, int step)
+{
+ float value = (float)val;
+ nk_slider_float(ctx, (float)min, &value, (float)max, (float)step);
+ return (int)value;
+}
+NK_API nk_bool
+nk_slider_int(struct nk_context *ctx, int min, int *val, int max, int step)
+{
+ int ret;
+ float value = (float)*val;
+ ret = nk_slider_float(ctx, (float)min, &value, (float)max, (float)step);
+ *val = (int)value;
+ return ret;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * PROGRESS
+ *
+ * ===============================================================*/
+NK_LIB nk_size
+nk_progress_behavior(nk_flags *state, struct nk_input *in,
+ struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable)
+{
+ int left_mouse_down = 0;
+ int left_mouse_click_in_cursor = 0;
+
+ nk_widget_state_reset(state);
+ if (!in || !modifiable) return value;
+ left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down;
+ left_mouse_click_in_cursor = in && nk_input_has_mouse_click_down_in_rect(in,
+ NK_BUTTON_LEFT, cursor, nk_true);
+ if (nk_input_is_mouse_hovering_rect(in, r))
+ *state = NK_WIDGET_STATE_HOVERED;
+
+ if (in && left_mouse_down && left_mouse_click_in_cursor) {
+ if (left_mouse_down && left_mouse_click_in_cursor) {
+ float ratio = NK_MAX(0, (float)(in->mouse.pos.x - cursor.x)) / (float)cursor.w;
+ value = (nk_size)NK_CLAMP(0, (float)max * ratio, (float)max);
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = cursor.x + cursor.w/2.0f;
+ *state |= NK_WIDGET_STATE_ACTIVE;
+ }
+ }
+ /* set progressbar widget state */
+ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, r))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(in, r))
+ *state |= NK_WIDGET_STATE_LEFT;
+ return value;
+}
+NK_LIB void
+nk_draw_progress(struct nk_command_buffer *out, nk_flags state,
+ const struct nk_style_progress *style, const struct nk_rect *bounds,
+ const struct nk_rect *scursor, nk_size value, nk_size max)
+{
+ const struct nk_style_item *background;
+ const struct nk_style_item *cursor;
+
+ NK_UNUSED(max);
+ NK_UNUSED(value);
+
+ /* select correct colors/images to draw */
+ if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->active;
+ cursor = &style->cursor_active;
+ } else if (state & NK_WIDGET_STATE_HOVER){
+ background = &style->hover;
+ cursor = &style->cursor_hover;
+ } else {
+ background = &style->normal;
+ cursor = &style->cursor_normal;
+ }
+
+ /* draw background */
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor));
+ nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor));
+ break;
+ }
+
+ /* draw cursor */
+ switch(cursor->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, *scursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, *scursor, style->rounding, nk_rgb_factor(cursor->data.color, style->color_factor));
+ nk_stroke_rect(out, *scursor, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor));
+ break;
+ }
+}
+NK_LIB nk_size
+nk_do_progress(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect bounds,
+ nk_size value, nk_size max, nk_bool modifiable,
+ const struct nk_style_progress *style, struct nk_input *in)
+{
+ float prog_scale;
+ nk_size prog_value;
+ struct nk_rect cursor;
+
+ NK_ASSERT(style);
+ NK_ASSERT(out);
+ if (!out || !style) return 0;
+
+ /* calculate progressbar cursor */
+ cursor.w = NK_MAX(bounds.w, 2 * style->padding.x + 2 * style->border);
+ cursor.h = NK_MAX(bounds.h, 2 * style->padding.y + 2 * style->border);
+ cursor = nk_pad_rect(bounds, nk_vec2(style->padding.x + style->border, style->padding.y + style->border));
+ prog_scale = (float)value / (float)max;
+
+ /* update progressbar */
+ prog_value = NK_MIN(value, max);
+ prog_value = nk_progress_behavior(state, in, bounds, cursor,max, prog_value, modifiable);
+ cursor.w = cursor.w * prog_scale;
+
+ /* draw progressbar */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_progress(out, *state, style, &bounds, &cursor, value, max);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return prog_value;
+}
+NK_API nk_bool
+nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, nk_bool is_modifyable)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_style *style;
+ struct nk_input *in;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states state;
+ nk_size old_value;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(cur);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !cur)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ layout = win->layout;
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ old_value = *cur;
+ *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds,
+ *cur, max, is_modifyable, &style->progress, in);
+ return (*cur != old_value);
+}
+NK_API nk_size
+nk_prog(struct nk_context *ctx, nk_size cur, nk_size max, nk_bool modifyable)
+{
+ nk_progress(ctx, &cur, max, modifyable);
+ return cur;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * SCROLLBAR
+ *
+ * ===============================================================*/
+NK_LIB float
+nk_scrollbar_behavior(nk_flags *state, struct nk_input *in,
+ int has_scrolling, const struct nk_rect *scroll,
+ const struct nk_rect *cursor, const struct nk_rect *empty0,
+ const struct nk_rect *empty1, float scroll_offset,
+ float target, float scroll_step, enum nk_orientation o)
+{
+ nk_flags ws = 0;
+ int left_mouse_down;
+ unsigned int left_mouse_clicked;
+ int left_mouse_click_in_cursor;
+ float scroll_delta;
+
+ nk_widget_state_reset(state);
+ if (!in) return scroll_offset;
+
+ left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down;
+ left_mouse_clicked = in->mouse.buttons[NK_BUTTON_LEFT].clicked;
+ left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in,
+ NK_BUTTON_LEFT, *cursor, nk_true);
+ if (nk_input_is_mouse_hovering_rect(in, *scroll))
+ *state = NK_WIDGET_STATE_HOVERED;
+
+ scroll_delta = (o == NK_VERTICAL) ? in->mouse.scroll_delta.y: in->mouse.scroll_delta.x;
+ if (left_mouse_down && left_mouse_click_in_cursor && !left_mouse_clicked) {
+ /* update cursor by mouse dragging */
+ float pixel, delta;
+ *state = NK_WIDGET_STATE_ACTIVE;
+ if (o == NK_VERTICAL) {
+ float cursor_y;
+ pixel = in->mouse.delta.y;
+ delta = (pixel / scroll->h) * target;
+ scroll_offset = NK_CLAMP(0, scroll_offset + delta, target - scroll->h);
+ cursor_y = scroll->y + ((scroll_offset/target) * scroll->h);
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y = cursor_y + cursor->h/2.0f;
+ } else {
+ float cursor_x;
+ pixel = in->mouse.delta.x;
+ delta = (pixel / scroll->w) * target;
+ scroll_offset = NK_CLAMP(0, scroll_offset + delta, target - scroll->w);
+ cursor_x = scroll->x + ((scroll_offset/target) * scroll->w);
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = cursor_x + cursor->w/2.0f;
+ }
+ } else if ((nk_input_is_key_pressed(in, NK_KEY_SCROLL_UP) && o == NK_VERTICAL && has_scrolling)||
+ nk_button_behavior(&ws, *empty0, in, NK_BUTTON_DEFAULT)) {
+ /* scroll page up by click on empty space or shortcut */
+ if (o == NK_VERTICAL)
+ scroll_offset = NK_MAX(0, scroll_offset - scroll->h);
+ else scroll_offset = NK_MAX(0, scroll_offset - scroll->w);
+ } else if ((nk_input_is_key_pressed(in, NK_KEY_SCROLL_DOWN) && o == NK_VERTICAL && has_scrolling) ||
+ nk_button_behavior(&ws, *empty1, in, NK_BUTTON_DEFAULT)) {
+ /* scroll page down by click on empty space or shortcut */
+ if (o == NK_VERTICAL)
+ scroll_offset = NK_MIN(scroll_offset + scroll->h, target - scroll->h);
+ else scroll_offset = NK_MIN(scroll_offset + scroll->w, target - scroll->w);
+ } else if (has_scrolling) {
+ if ((scroll_delta < 0 || (scroll_delta > 0))) {
+ /* update cursor by mouse scrolling */
+ scroll_offset = scroll_offset + scroll_step * (-scroll_delta);
+ if (o == NK_VERTICAL)
+ scroll_offset = NK_CLAMP(0, scroll_offset, target - scroll->h);
+ else scroll_offset = NK_CLAMP(0, scroll_offset, target - scroll->w);
+ } else if (nk_input_is_key_pressed(in, NK_KEY_SCROLL_START)) {
+ /* update cursor to the beginning */
+ if (o == NK_VERTICAL) scroll_offset = 0;
+ } else if (nk_input_is_key_pressed(in, NK_KEY_SCROLL_END)) {
+ /* update cursor to the end */
+ if (o == NK_VERTICAL) scroll_offset = target - scroll->h;
+ }
+ }
+ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, *scroll))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(in, *scroll))
+ *state |= NK_WIDGET_STATE_LEFT;
+ return scroll_offset;
+}
+NK_LIB void
+nk_draw_scrollbar(struct nk_command_buffer *out, nk_flags state,
+ const struct nk_style_scrollbar *style, const struct nk_rect *bounds,
+ const struct nk_rect *scroll)
+{
+ const struct nk_style_item *background;
+ const struct nk_style_item *cursor;
+
+ /* select correct colors/images to draw */
+ if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->active;
+ cursor = &style->cursor_active;
+ } else if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ cursor = &style->cursor_hover;
+ } else {
+ background = &style->normal;
+ cursor = &style->cursor_normal;
+ }
+
+ /* draw background */
+ switch (background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, *bounds, &background->data.image, nk_white);
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white);
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, *bounds, style->rounding, background->data.color);
+ nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color);
+ break;
+ }
+
+ /* draw cursor */
+ switch (cursor->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, *scroll, &cursor->data.image, nk_white);
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, *scroll, &cursor->data.slice, nk_white);
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, *scroll, style->rounding_cursor, cursor->data.color);
+ nk_stroke_rect(out, *scroll, style->rounding_cursor, style->border_cursor, style->cursor_border_color);
+ break;
+ }
+}
+NK_LIB float
+nk_do_scrollbarv(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling,
+ float offset, float target, float step, float button_pixel_inc,
+ const struct nk_style_scrollbar *style, struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ struct nk_rect empty_north;
+ struct nk_rect empty_south;
+ struct nk_rect cursor;
+
+ float scroll_step;
+ float scroll_offset;
+ float scroll_off;
+ float scroll_ratio;
+
+ NK_ASSERT(out);
+ NK_ASSERT(style);
+ NK_ASSERT(state);
+ if (!out || !style) return 0;
+
+ scroll.w = NK_MAX(scroll.w, 1);
+ scroll.h = NK_MAX(scroll.h, 0);
+ if (target <= scroll.h) return 0;
+
+ /* optional scrollbar buttons */
+ if (style->show_buttons) {
+ nk_flags ws;
+ float scroll_h;
+ struct nk_rect button;
+
+ button.x = scroll.x;
+ button.w = scroll.w;
+ button.h = scroll.w;
+
+ scroll_h = NK_MAX(scroll.h - 2 * button.h,0);
+ scroll_step = NK_MIN(step, button_pixel_inc);
+
+ /* decrement button */
+ button.y = scroll.y;
+ if (nk_do_button_symbol(&ws, out, button, style->dec_symbol,
+ NK_BUTTON_REPEATER, &style->dec_button, in, font))
+ offset = offset - scroll_step;
+
+ /* increment button */
+ button.y = scroll.y + scroll.h - button.h;
+ if (nk_do_button_symbol(&ws, out, button, style->inc_symbol,
+ NK_BUTTON_REPEATER, &style->inc_button, in, font))
+ offset = offset + scroll_step;
+
+ scroll.y = scroll.y + button.h;
+ scroll.h = scroll_h;
+ }
+
+ /* calculate scrollbar constants */
+ scroll_step = NK_MIN(step, scroll.h);
+ scroll_offset = NK_CLAMP(0, offset, target - scroll.h);
+ scroll_ratio = scroll.h / target;
+ scroll_off = scroll_offset / target;
+
+ /* calculate scrollbar cursor bounds */
+ cursor.h = NK_MAX((scroll_ratio * scroll.h) - (2*style->border + 2*style->padding.y), 0);
+ cursor.y = scroll.y + (scroll_off * scroll.h) + style->border + style->padding.y;
+ cursor.w = scroll.w - (2 * style->border + 2 * style->padding.x);
+ cursor.x = scroll.x + style->border + style->padding.x;
+
+ /* calculate empty space around cursor */
+ empty_north.x = scroll.x;
+ empty_north.y = scroll.y;
+ empty_north.w = scroll.w;
+ empty_north.h = NK_MAX(cursor.y - scroll.y, 0);
+
+ empty_south.x = scroll.x;
+ empty_south.y = cursor.y + cursor.h;
+ empty_south.w = scroll.w;
+ empty_south.h = NK_MAX((scroll.y + scroll.h) - (cursor.y + cursor.h), 0);
+
+ /* update scrollbar */
+ scroll_offset = nk_scrollbar_behavior(state, in, has_scrolling, &scroll, &cursor,
+ &empty_north, &empty_south, scroll_offset, target, scroll_step, NK_VERTICAL);
+ scroll_off = scroll_offset / target;
+ cursor.y = scroll.y + (scroll_off * scroll.h) + style->border_cursor + style->padding.y;
+
+ /* draw scrollbar */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_scrollbar(out, *state, style, &scroll, &cursor);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return scroll_offset;
+}
+NK_LIB float
+nk_do_scrollbarh(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling,
+ float offset, float target, float step, float button_pixel_inc,
+ const struct nk_style_scrollbar *style, struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ struct nk_rect cursor;
+ struct nk_rect empty_west;
+ struct nk_rect empty_east;
+
+ float scroll_step;
+ float scroll_offset;
+ float scroll_off;
+ float scroll_ratio;
+
+ NK_ASSERT(out);
+ NK_ASSERT(style);
+ if (!out || !style) return 0;
+
+ /* scrollbar background */
+ scroll.h = NK_MAX(scroll.h, 1);
+ scroll.w = NK_MAX(scroll.w, 2 * scroll.h);
+ if (target <= scroll.w) return 0;
+
+ /* optional scrollbar buttons */
+ if (style->show_buttons) {
+ nk_flags ws;
+ float scroll_w;
+ struct nk_rect button;
+ button.y = scroll.y;
+ button.w = scroll.h;
+ button.h = scroll.h;
+
+ scroll_w = scroll.w - 2 * button.w;
+ scroll_step = NK_MIN(step, button_pixel_inc);
+
+ /* decrement button */
+ button.x = scroll.x;
+ if (nk_do_button_symbol(&ws, out, button, style->dec_symbol,
+ NK_BUTTON_REPEATER, &style->dec_button, in, font))
+ offset = offset - scroll_step;
+
+ /* increment button */
+ button.x = scroll.x + scroll.w - button.w;
+ if (nk_do_button_symbol(&ws, out, button, style->inc_symbol,
+ NK_BUTTON_REPEATER, &style->inc_button, in, font))
+ offset = offset + scroll_step;
+
+ scroll.x = scroll.x + button.w;
+ scroll.w = scroll_w;
+ }
+
+ /* calculate scrollbar constants */
+ scroll_step = NK_MIN(step, scroll.w);
+ scroll_offset = NK_CLAMP(0, offset, target - scroll.w);
+ scroll_ratio = scroll.w / target;
+ scroll_off = scroll_offset / target;
+
+ /* calculate cursor bounds */
+ cursor.w = (scroll_ratio * scroll.w) - (2*style->border + 2*style->padding.x);
+ cursor.x = scroll.x + (scroll_off * scroll.w) + style->border + style->padding.x;
+ cursor.h = scroll.h - (2 * style->border + 2 * style->padding.y);
+ cursor.y = scroll.y + style->border + style->padding.y;
+
+ /* calculate empty space around cursor */
+ empty_west.x = scroll.x;
+ empty_west.y = scroll.y;
+ empty_west.w = cursor.x - scroll.x;
+ empty_west.h = scroll.h;
+
+ empty_east.x = cursor.x + cursor.w;
+ empty_east.y = scroll.y;
+ empty_east.w = (scroll.x + scroll.w) - (cursor.x + cursor.w);
+ empty_east.h = scroll.h;
+
+ /* update scrollbar */
+ scroll_offset = nk_scrollbar_behavior(state, in, has_scrolling, &scroll, &cursor,
+ &empty_west, &empty_east, scroll_offset, target, scroll_step, NK_HORIZONTAL);
+ scroll_off = scroll_offset / target;
+ cursor.x = scroll.x + (scroll_off * scroll.w);
+
+ /* draw scrollbar */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_scrollbar(out, *state, style, &scroll, &cursor);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+ return scroll_offset;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * TEXT EDITOR
+ *
+ * ===============================================================*/
+/* stb_textedit.h - v1.8 - public domain - Sean Barrett */
+struct nk_text_find {
+ float x,y; /* position of n'th character */
+ float height; /* height of line */
+ int first_char, length; /* first char of row, and length */
+ int prev_first; /*_ first char of previous row */
+};
+
+struct nk_text_edit_row {
+ float x0,x1;
+ /* starting x location, end x location (allows for align=right, etc) */
+ float baseline_y_delta;
+ /* position of baseline relative to previous row's baseline*/
+ float ymin,ymax;
+ /* height of row above and below baseline */
+ int num_chars;
+};
+
+/* forward declarations */
+NK_INTERN void nk_textedit_makeundo_delete(struct nk_text_edit*, int, int);
+NK_INTERN void nk_textedit_makeundo_insert(struct nk_text_edit*, int, int);
+NK_INTERN void nk_textedit_makeundo_replace(struct nk_text_edit*, int, int, int);
+#define NK_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end)
+
+NK_INTERN float
+nk_textedit_get_width(const struct nk_text_edit *edit, int line_start, int char_id,
+ const struct nk_user_font *font)
+{
+ int len = 0;
+ nk_rune unicode = 0;
+ const char *str = nk_str_at_const(&edit->string, line_start + char_id, &unicode, &len);
+ return font->width(font->userdata, font->height, str, len);
+}
+NK_INTERN void
+nk_textedit_layout_row(struct nk_text_edit_row *r, struct nk_text_edit *edit,
+ int line_start_id, float row_height, const struct nk_user_font *font)
+{
+ int l;
+ int glyphs = 0;
+ nk_rune unicode;
+ const char *remaining;
+ int len = nk_str_len_char(&edit->string);
+ const char *end = nk_str_get_const(&edit->string) + len;
+ const char *text = nk_str_at_const(&edit->string, line_start_id, &unicode, &l);
+ const struct nk_vec2 size = nk_text_calculate_text_bounds(font,
+ text, (int)(end - text), row_height, &remaining, 0, &glyphs, NK_STOP_ON_NEW_LINE);
+
+ r->x0 = 0.0f;
+ r->x1 = size.x;
+ r->baseline_y_delta = size.y;
+ r->ymin = 0.0f;
+ r->ymax = size.y;
+ r->num_chars = glyphs;
+}
+NK_INTERN int
+nk_textedit_locate_coord(struct nk_text_edit *edit, float x, float y,
+ const struct nk_user_font *font, float row_height)
+{
+ struct nk_text_edit_row r;
+ int n = edit->string.len;
+ float base_y = 0, prev_x;
+ int i=0, k;
+
+ r.x0 = r.x1 = 0;
+ r.ymin = r.ymax = 0;
+ r.num_chars = 0;
+
+ /* search rows to find one that straddles 'y' */
+ while (i < n) {
+ nk_textedit_layout_row(&r, edit, i, row_height, font);
+ if (r.num_chars <= 0)
+ return n;
+
+ if (i==0 && y < base_y + r.ymin)
+ return 0;
+
+ if (y < base_y + r.ymax)
+ break;
+
+ i += r.num_chars;
+ base_y += r.baseline_y_delta;
+ }
+
+ /* below all text, return 'after' last character */
+ if (i >= n)
+ return n;
+
+ /* check if it's before the beginning of the line */
+ if (x < r.x0)
+ return i;
+
+ /* check if it's before the end of the line */
+ if (x < r.x1) {
+ /* search characters in row for one that straddles 'x' */
+ k = i;
+ prev_x = r.x0;
+ for (i=0; i < r.num_chars; ++i) {
+ float w = nk_textedit_get_width(edit, k, i, font);
+ if (x < prev_x+w) {
+ if (x < prev_x+w/2)
+ return k+i;
+ else return k+i+1;
+ }
+ prev_x += w;
+ }
+ /* shouldn't happen, but if it does, fall through to end-of-line case */
+ }
+
+ /* if the last character is a newline, return that.
+ * otherwise return 'after' the last character */
+ if (nk_str_rune_at(&edit->string, i+r.num_chars-1) == '\n')
+ return i+r.num_chars-1;
+ else return i+r.num_chars;
+}
+NK_LIB void
+nk_textedit_click(struct nk_text_edit *state, float x, float y,
+ const struct nk_user_font *font, float row_height)
+{
+ /* API click: on mouse down, move the cursor to the clicked location,
+ * and reset the selection */
+ state->cursor = nk_textedit_locate_coord(state, x, y, font, row_height);
+ state->select_start = state->cursor;
+ state->select_end = state->cursor;
+ state->has_preferred_x = 0;
+}
+NK_LIB void
+nk_textedit_drag(struct nk_text_edit *state, float x, float y,
+ const struct nk_user_font *font, float row_height)
+{
+ /* API drag: on mouse drag, move the cursor and selection endpoint
+ * to the clicked location */
+ int p = nk_textedit_locate_coord(state, x, y, font, row_height);
+ if (state->select_start == state->select_end)
+ state->select_start = state->cursor;
+ state->cursor = state->select_end = p;
+}
+NK_INTERN void
+nk_textedit_find_charpos(struct nk_text_find *find, struct nk_text_edit *state,
+ int n, int single_line, const struct nk_user_font *font, float row_height)
+{
+ /* find the x/y location of a character, and remember info about the previous
+ * row in case we get a move-up event (for page up, we'll have to rescan) */
+ struct nk_text_edit_row r;
+ int prev_start = 0;
+ int z = state->string.len;
+ int i=0, first;
+
+ nk_zero_struct(r);
+ if (n == z) {
+ /* if it's at the end, then find the last line -- simpler than trying to
+ explicitly handle this case in the regular code */
+ nk_textedit_layout_row(&r, state, 0, row_height, font);
+ if (single_line) {
+ find->first_char = 0;
+ find->length = z;
+ } else {
+ while (i < z) {
+ prev_start = i;
+ i += r.num_chars;
+ nk_textedit_layout_row(&r, state, i, row_height, font);
+ }
+
+ find->first_char = i;
+ find->length = r.num_chars;
+ }
+ find->x = r.x1;
+ find->y = r.ymin;
+ find->height = r.ymax - r.ymin;
+ find->prev_first = prev_start;
+ return;
+ }
+
+ /* search rows to find the one that straddles character n */
+ find->y = 0;
+
+ for(;;) {
+ nk_textedit_layout_row(&r, state, i, row_height, font);
+ if (n < i + r.num_chars) break;
+ prev_start = i;
+ i += r.num_chars;
+ find->y += r.baseline_y_delta;
+ }
+
+ find->first_char = first = i;
+ find->length = r.num_chars;
+ find->height = r.ymax - r.ymin;
+ find->prev_first = prev_start;
+
+ /* now scan to find xpos */
+ find->x = r.x0;
+ for (i=0; first+i < n; ++i)
+ find->x += nk_textedit_get_width(state, first, i, font);
+}
+NK_INTERN void
+nk_textedit_clamp(struct nk_text_edit *state)
+{
+ /* make the selection/cursor state valid if client altered the string */
+ int n = state->string.len;
+ if (NK_TEXT_HAS_SELECTION(state)) {
+ if (state->select_start > n) state->select_start = n;
+ if (state->select_end > n) state->select_end = n;
+ /* if clamping forced them to be equal, move the cursor to match */
+ if (state->select_start == state->select_end)
+ state->cursor = state->select_start;
+ }
+ if (state->cursor > n) state->cursor = n;
+}
+NK_API void
+nk_textedit_delete(struct nk_text_edit *state, int where, int len)
+{
+ /* delete characters while updating undo */
+ nk_textedit_makeundo_delete(state, where, len);
+ nk_str_delete_runes(&state->string, where, len);
+ state->has_preferred_x = 0;
+}
+NK_API void
+nk_textedit_delete_selection(struct nk_text_edit *state)
+{
+ /* delete the section */
+ nk_textedit_clamp(state);
+ if (NK_TEXT_HAS_SELECTION(state)) {
+ if (state->select_start < state->select_end) {
+ nk_textedit_delete(state, state->select_start,
+ state->select_end - state->select_start);
+ state->select_end = state->cursor = state->select_start;
+ } else {
+ nk_textedit_delete(state, state->select_end,
+ state->select_start - state->select_end);
+ state->select_start = state->cursor = state->select_end;
+ }
+ state->has_preferred_x = 0;
+ }
+}
+NK_INTERN void
+nk_textedit_sortselection(struct nk_text_edit *state)
+{
+ /* canonicalize the selection so start <= end */
+ if (state->select_end < state->select_start) {
+ int temp = state->select_end;
+ state->select_end = state->select_start;
+ state->select_start = temp;
+ }
+}
+NK_INTERN void
+nk_textedit_move_to_first(struct nk_text_edit *state)
+{
+ /* move cursor to first character of selection */
+ if (NK_TEXT_HAS_SELECTION(state)) {
+ nk_textedit_sortselection(state);
+ state->cursor = state->select_start;
+ state->select_end = state->select_start;
+ state->has_preferred_x = 0;
+ }
+}
+NK_INTERN void
+nk_textedit_move_to_last(struct nk_text_edit *state)
+{
+ /* move cursor to last character of selection */
+ if (NK_TEXT_HAS_SELECTION(state)) {
+ nk_textedit_sortselection(state);
+ nk_textedit_clamp(state);
+ state->cursor = state->select_end;
+ state->select_start = state->select_end;
+ state->has_preferred_x = 0;
+ }
+}
+NK_INTERN int
+nk_is_word_boundary( struct nk_text_edit *state, int idx)
+{
+ int len;
+ nk_rune c;
+ if (idx <= 0) return 1;
+ if (!nk_str_at_rune(&state->string, idx, &c, &len)) return 1;
+ return (c == ' ' || c == '\t' ||c == 0x3000 || c == ',' || c == ';' ||
+ c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' ||
+ c == '|');
+}
+NK_INTERN int
+nk_textedit_move_to_word_previous(struct nk_text_edit *state)
+{
+ int c = state->cursor - 1;
+ while( c >= 0 && !nk_is_word_boundary(state, c))
+ --c;
+
+ if( c < 0 )
+ c = 0;
+
+ return c;
+}
+NK_INTERN int
+nk_textedit_move_to_word_next(struct nk_text_edit *state)
+{
+ const int len = state->string.len;
+ int c = state->cursor+1;
+ while( c < len && !nk_is_word_boundary(state, c))
+ ++c;
+
+ if( c > len )
+ c = len;
+
+ return c;
+}
+NK_INTERN void
+nk_textedit_prep_selection_at_cursor(struct nk_text_edit *state)
+{
+ /* update selection and cursor to match each other */
+ if (!NK_TEXT_HAS_SELECTION(state))
+ state->select_start = state->select_end = state->cursor;
+ else state->cursor = state->select_end;
+}
+NK_API nk_bool
+nk_textedit_cut(struct nk_text_edit *state)
+{
+ /* API cut: delete selection */
+ if (state->mode == NK_TEXT_EDIT_MODE_VIEW)
+ return 0;
+ if (NK_TEXT_HAS_SELECTION(state)) {
+ nk_textedit_delete_selection(state); /* implicitly clamps */
+ state->has_preferred_x = 0;
+ return 1;
+ }
+ return 0;
+}
+NK_API nk_bool
+nk_textedit_paste(struct nk_text_edit *state, char const *ctext, int len)
+{
+ /* API paste: replace existing selection with passed-in text */
+ int glyphs;
+ const char *text = (const char *) ctext;
+ if (state->mode == NK_TEXT_EDIT_MODE_VIEW) return 0;
+
+ /* if there's a selection, the paste should delete it */
+ nk_textedit_clamp(state);
+ nk_textedit_delete_selection(state);
+
+ /* try to insert the characters */
+ glyphs = nk_utf_len(ctext, len);
+ if (nk_str_insert_text_char(&state->string, state->cursor, text, len)) {
+ nk_textedit_makeundo_insert(state, state->cursor, glyphs);
+ state->cursor += len;
+ state->has_preferred_x = 0;
+ return 1;
+ }
+ /* remove the undo since we didn't actually insert the characters */
+ if (state->undo.undo_point)
+ --state->undo.undo_point;
+ return 0;
+}
+NK_API void
+nk_textedit_text(struct nk_text_edit *state, const char *text, int total_len)
+{
+ nk_rune unicode;
+ int glyph_len;
+ int text_len = 0;
+
+ NK_ASSERT(state);
+ NK_ASSERT(text);
+ if (!text || !total_len || state->mode == NK_TEXT_EDIT_MODE_VIEW) return;
+
+ glyph_len = nk_utf_decode(text, &unicode, total_len);
+ while ((text_len < total_len) && glyph_len)
+ {
+ /* don't insert a backward delete, just process the event */
+ if (unicode == 127) goto next;
+ /* can't add newline in single-line mode */
+ if (unicode == '\n' && state->single_line) goto next;
+ /* filter incoming text */
+ if (state->filter && !state->filter(state, unicode)) goto next;
+
+ if (!NK_TEXT_HAS_SELECTION(state) &&
+ state->cursor < state->string.len)
+ {
+ if (state->mode == NK_TEXT_EDIT_MODE_REPLACE) {
+ nk_textedit_makeundo_replace(state, state->cursor, 1, 1);
+ nk_str_delete_runes(&state->string, state->cursor, 1);
+ }
+ if (nk_str_insert_text_utf8(&state->string, state->cursor,
+ text+text_len, 1))
+ {
+ ++state->cursor;
+ state->has_preferred_x = 0;
+ }
+ } else {
+ nk_textedit_delete_selection(state); /* implicitly clamps */
+ if (nk_str_insert_text_utf8(&state->string, state->cursor,
+ text+text_len, 1))
+ {
+ nk_textedit_makeundo_insert(state, state->cursor, 1);
+ state->cursor = NK_MIN(state->cursor + 1, state->string.len);
+ state->has_preferred_x = 0;
+ }
+ }
+ next:
+ text_len += glyph_len;
+ glyph_len = nk_utf_decode(text + text_len, &unicode, total_len-text_len);
+ }
+}
+NK_LIB void
+nk_textedit_key(struct nk_text_edit *state, enum nk_keys key, int shift_mod,
+ const struct nk_user_font *font, float row_height)
+{
+retry:
+ switch (key)
+ {
+ case NK_KEY_NONE:
+ case NK_KEY_CTRL:
+ case NK_KEY_ENTER:
+ case NK_KEY_SHIFT:
+ case NK_KEY_TAB:
+ case NK_KEY_COPY:
+ case NK_KEY_CUT:
+ case NK_KEY_PASTE:
+ case NK_KEY_MAX:
+ default: break;
+ case NK_KEY_TEXT_UNDO:
+ nk_textedit_undo(state);
+ state->has_preferred_x = 0;
+ break;
+
+ case NK_KEY_TEXT_REDO:
+ nk_textedit_redo(state);
+ state->has_preferred_x = 0;
+ break;
+
+ case NK_KEY_TEXT_SELECT_ALL:
+ nk_textedit_select_all(state);
+ state->has_preferred_x = 0;
+ break;
+
+ case NK_KEY_TEXT_INSERT_MODE:
+ if (state->mode == NK_TEXT_EDIT_MODE_VIEW)
+ state->mode = NK_TEXT_EDIT_MODE_INSERT;
+ break;
+ case NK_KEY_TEXT_REPLACE_MODE:
+ if (state->mode == NK_TEXT_EDIT_MODE_VIEW)
+ state->mode = NK_TEXT_EDIT_MODE_REPLACE;
+ break;
+ case NK_KEY_TEXT_RESET_MODE:
+ if (state->mode == NK_TEXT_EDIT_MODE_INSERT ||
+ state->mode == NK_TEXT_EDIT_MODE_REPLACE)
+ state->mode = NK_TEXT_EDIT_MODE_VIEW;
+ break;
+
+ case NK_KEY_LEFT:
+ if (shift_mod) {
+ nk_textedit_clamp(state);
+ nk_textedit_prep_selection_at_cursor(state);
+ /* move selection left */
+ if (state->select_end > 0)
+ --state->select_end;
+ state->cursor = state->select_end;
+ state->has_preferred_x = 0;
+ } else {
+ /* if currently there's a selection,
+ * move cursor to start of selection */
+ if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_move_to_first(state);
+ else if (state->cursor > 0)
+ --state->cursor;
+ state->has_preferred_x = 0;
+ } break;
+
+ case NK_KEY_RIGHT:
+ if (shift_mod) {
+ nk_textedit_prep_selection_at_cursor(state);
+ /* move selection right */
+ ++state->select_end;
+ nk_textedit_clamp(state);
+ state->cursor = state->select_end;
+ state->has_preferred_x = 0;
+ } else {
+ /* if currently there's a selection,
+ * move cursor to end of selection */
+ if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_move_to_last(state);
+ else ++state->cursor;
+ nk_textedit_clamp(state);
+ state->has_preferred_x = 0;
+ } break;
+
+ case NK_KEY_TEXT_WORD_LEFT:
+ if (shift_mod) {
+ if( !NK_TEXT_HAS_SELECTION( state ) )
+ nk_textedit_prep_selection_at_cursor(state);
+ state->cursor = nk_textedit_move_to_word_previous(state);
+ state->select_end = state->cursor;
+ nk_textedit_clamp(state );
+ } else {
+ if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_move_to_first(state);
+ else {
+ state->cursor = nk_textedit_move_to_word_previous(state);
+ nk_textedit_clamp(state );
+ }
+ } break;
+
+ case NK_KEY_TEXT_WORD_RIGHT:
+ if (shift_mod) {
+ if( !NK_TEXT_HAS_SELECTION( state ) )
+ nk_textedit_prep_selection_at_cursor(state);
+ state->cursor = nk_textedit_move_to_word_next(state);
+ state->select_end = state->cursor;
+ nk_textedit_clamp(state);
+ } else {
+ if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_move_to_last(state);
+ else {
+ state->cursor = nk_textedit_move_to_word_next(state);
+ nk_textedit_clamp(state );
+ }
+ } break;
+
+ case NK_KEY_DOWN: {
+ struct nk_text_find find;
+ struct nk_text_edit_row row;
+ int i, sel = shift_mod;
+
+ if (state->single_line) {
+ /* on windows, up&down in single-line behave like left&right */
+ key = NK_KEY_RIGHT;
+ goto retry;
+ }
+
+ if (sel)
+ nk_textedit_prep_selection_at_cursor(state);
+ else if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_move_to_last(state);
+
+ /* compute current position of cursor point */
+ nk_textedit_clamp(state);
+ nk_textedit_find_charpos(&find, state, state->cursor, state->single_line,
+ font, row_height);
+
+ /* now find character position down a row */
+ if (find.length)
+ {
+ float x;
+ float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
+ int start = find.first_char + find.length;
+
+ state->cursor = start;
+ nk_textedit_layout_row(&row, state, state->cursor, row_height, font);
+ x = row.x0;
+
+ for (i=0; i < row.num_chars && x < row.x1; ++i) {
+ float dx = nk_textedit_get_width(state, start, i, font);
+ x += dx;
+ if (x > goal_x)
+ break;
+ ++state->cursor;
+ }
+ nk_textedit_clamp(state);
+
+ state->has_preferred_x = 1;
+ state->preferred_x = goal_x;
+ if (sel)
+ state->select_end = state->cursor;
+ }
+ } break;
+
+ case NK_KEY_UP: {
+ struct nk_text_find find;
+ struct nk_text_edit_row row;
+ int i, sel = shift_mod;
+
+ if (state->single_line) {
+ /* on windows, up&down become left&right */
+ key = NK_KEY_LEFT;
+ goto retry;
+ }
+
+ if (sel)
+ nk_textedit_prep_selection_at_cursor(state);
+ else if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_move_to_first(state);
+
+ /* compute current position of cursor point */
+ nk_textedit_clamp(state);
+ nk_textedit_find_charpos(&find, state, state->cursor, state->single_line,
+ font, row_height);
+
+ /* can only go up if there's a previous row */
+ if (find.prev_first != find.first_char) {
+ /* now find character position up a row */
+ float x;
+ float goal_x = state->has_preferred_x ? state->preferred_x : find.x;
+
+ state->cursor = find.prev_first;
+ nk_textedit_layout_row(&row, state, state->cursor, row_height, font);
+ x = row.x0;
+
+ for (i=0; i < row.num_chars && x < row.x1; ++i) {
+ float dx = nk_textedit_get_width(state, find.prev_first, i, font);
+ x += dx;
+ if (x > goal_x)
+ break;
+ ++state->cursor;
+ }
+ nk_textedit_clamp(state);
+
+ state->has_preferred_x = 1;
+ state->preferred_x = goal_x;
+ if (sel) state->select_end = state->cursor;
+ }
+ } break;
+
+ case NK_KEY_DEL:
+ if (state->mode == NK_TEXT_EDIT_MODE_VIEW)
+ break;
+ if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_delete_selection(state);
+ else {
+ int n = state->string.len;
+ if (state->cursor < n)
+ nk_textedit_delete(state, state->cursor, 1);
+ }
+ state->has_preferred_x = 0;
+ break;
+
+ case NK_KEY_BACKSPACE:
+ if (state->mode == NK_TEXT_EDIT_MODE_VIEW)
+ break;
+ if (NK_TEXT_HAS_SELECTION(state))
+ nk_textedit_delete_selection(state);
+ else {
+ nk_textedit_clamp(state);
+ if (state->cursor > 0) {
+ nk_textedit_delete(state, state->cursor-1, 1);
+ --state->cursor;
+ }
+ }
+ state->has_preferred_x = 0;
+ break;
+
+ case NK_KEY_TEXT_START:
+ if (shift_mod) {
+ nk_textedit_prep_selection_at_cursor(state);
+ state->cursor = state->select_end = 0;
+ state->has_preferred_x = 0;
+ } else {
+ state->cursor = state->select_start = state->select_end = 0;
+ state->has_preferred_x = 0;
+ }
+ break;
+
+ case NK_KEY_TEXT_END:
+ if (shift_mod) {
+ nk_textedit_prep_selection_at_cursor(state);
+ state->cursor = state->select_end = state->string.len;
+ state->has_preferred_x = 0;
+ } else {
+ state->cursor = state->string.len;
+ state->select_start = state->select_end = 0;
+ state->has_preferred_x = 0;
+ }
+ break;
+
+ case NK_KEY_TEXT_LINE_START: {
+ if (shift_mod) {
+ struct nk_text_find find;
+ nk_textedit_clamp(state);
+ nk_textedit_prep_selection_at_cursor(state);
+ if (state->string.len && state->cursor == state->string.len)
+ --state->cursor;
+ nk_textedit_find_charpos(&find, state,state->cursor, state->single_line,
+ font, row_height);
+ state->cursor = state->select_end = find.first_char;
+ state->has_preferred_x = 0;
+ } else {
+ struct nk_text_find find;
+ if (state->string.len && state->cursor == state->string.len)
+ --state->cursor;
+ nk_textedit_clamp(state);
+ nk_textedit_move_to_first(state);
+ nk_textedit_find_charpos(&find, state, state->cursor, state->single_line,
+ font, row_height);
+ state->cursor = find.first_char;
+ state->has_preferred_x = 0;
+ }
+ } break;
+
+ case NK_KEY_TEXT_LINE_END: {
+ if (shift_mod) {
+ struct nk_text_find find;
+ nk_textedit_clamp(state);
+ nk_textedit_prep_selection_at_cursor(state);
+ nk_textedit_find_charpos(&find, state, state->cursor, state->single_line,
+ font, row_height);
+ state->has_preferred_x = 0;
+ state->cursor = find.first_char + find.length;
+ if (find.length > 0 && nk_str_rune_at(&state->string, state->cursor-1) == '\n')
+ --state->cursor;
+ state->select_end = state->cursor;
+ } else {
+ struct nk_text_find find;
+ nk_textedit_clamp(state);
+ nk_textedit_move_to_first(state);
+ nk_textedit_find_charpos(&find, state, state->cursor, state->single_line,
+ font, row_height);
+
+ state->has_preferred_x = 0;
+ state->cursor = find.first_char + find.length;
+ if (find.length > 0 && nk_str_rune_at(&state->string, state->cursor-1) == '\n')
+ --state->cursor;
+ }} break;
+ }
+}
+NK_INTERN void
+nk_textedit_flush_redo(struct nk_text_undo_state *state)
+{
+ state->redo_point = NK_TEXTEDIT_UNDOSTATECOUNT;
+ state->redo_char_point = NK_TEXTEDIT_UNDOCHARCOUNT;
+}
+NK_INTERN void
+nk_textedit_discard_undo(struct nk_text_undo_state *state)
+{
+ /* discard the oldest entry in the undo list */
+ if (state->undo_point > 0) {
+ /* if the 0th undo state has characters, clean those up */
+ if (state->undo_rec[0].char_storage >= 0) {
+ int n = state->undo_rec[0].insert_length, i;
+ /* delete n characters from all other records */
+ state->undo_char_point = (short)(state->undo_char_point - n);
+ NK_MEMCPY(state->undo_char, state->undo_char + n,
+ (nk_size)state->undo_char_point*sizeof(nk_rune));
+ for (i=0; i < state->undo_point; ++i) {
+ if (state->undo_rec[i].char_storage >= 0)
+ state->undo_rec[i].char_storage = (short)
+ (state->undo_rec[i].char_storage - n);
+ }
+ }
+ --state->undo_point;
+ NK_MEMCPY(state->undo_rec, state->undo_rec+1,
+ (nk_size)((nk_size)state->undo_point * sizeof(state->undo_rec[0])));
+ }
+}
+NK_INTERN void
+nk_textedit_discard_redo(struct nk_text_undo_state *state)
+{
+/* discard the oldest entry in the redo list--it's bad if this
+ ever happens, but because undo & redo have to store the actual
+ characters in different cases, the redo character buffer can
+ fill up even though the undo buffer didn't */
+ nk_size num;
+ int k = NK_TEXTEDIT_UNDOSTATECOUNT-1;
+ if (state->redo_point <= k) {
+ /* if the k'th undo state has characters, clean those up */
+ if (state->undo_rec[k].char_storage >= 0) {
+ int n = state->undo_rec[k].insert_length, i;
+ /* delete n characters from all other records */
+ state->redo_char_point = (short)(state->redo_char_point + n);
+ num = (nk_size)(NK_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point);
+ NK_MEMCPY(state->undo_char + state->redo_char_point,
+ state->undo_char + state->redo_char_point-n, num * sizeof(char));
+ for (i = state->redo_point; i < k; ++i) {
+ if (state->undo_rec[i].char_storage >= 0) {
+ state->undo_rec[i].char_storage = (short)
+ (state->undo_rec[i].char_storage + n);
+ }
+ }
+ }
+ ++state->redo_point;
+ num = (nk_size)(NK_TEXTEDIT_UNDOSTATECOUNT - state->redo_point);
+ if (num) NK_MEMCPY(state->undo_rec + state->redo_point-1,
+ state->undo_rec + state->redo_point, num * sizeof(state->undo_rec[0]));
+ }
+}
+NK_INTERN struct nk_text_undo_record*
+nk_textedit_create_undo_record(struct nk_text_undo_state *state, int numchars)
+{
+ /* any time we create a new undo record, we discard redo*/
+ nk_textedit_flush_redo(state);
+
+ /* if we have no free records, we have to make room,
+ * by sliding the existing records down */
+ if (state->undo_point == NK_TEXTEDIT_UNDOSTATECOUNT)
+ nk_textedit_discard_undo(state);
+
+ /* if the characters to store won't possibly fit in the buffer,
+ * we can't undo */
+ if (numchars > NK_TEXTEDIT_UNDOCHARCOUNT) {
+ state->undo_point = 0;
+ state->undo_char_point = 0;
+ return 0;
+ }
+
+ /* if we don't have enough free characters in the buffer,
+ * we have to make room */
+ while (state->undo_char_point + numchars > NK_TEXTEDIT_UNDOCHARCOUNT)
+ nk_textedit_discard_undo(state);
+ return &state->undo_rec[state->undo_point++];
+}
+NK_INTERN nk_rune*
+nk_textedit_createundo(struct nk_text_undo_state *state, int pos,
+ int insert_len, int delete_len)
+{
+ struct nk_text_undo_record *r = nk_textedit_create_undo_record(state, insert_len);
+ if (r == 0)
+ return 0;
+
+ r->where = pos;
+ r->insert_length = (short) insert_len;
+ r->delete_length = (short) delete_len;
+
+ if (insert_len == 0) {
+ r->char_storage = -1;
+ return 0;
+ } else {
+ r->char_storage = state->undo_char_point;
+ state->undo_char_point = (short)(state->undo_char_point + insert_len);
+ return &state->undo_char[r->char_storage];
+ }
+}
+NK_API void
+nk_textedit_undo(struct nk_text_edit *state)
+{
+ struct nk_text_undo_state *s = &state->undo;
+ struct nk_text_undo_record u, *r;
+ if (s->undo_point == 0)
+ return;
+
+ /* we need to do two things: apply the undo record, and create a redo record */
+ u = s->undo_rec[s->undo_point-1];
+ r = &s->undo_rec[s->redo_point-1];
+ r->char_storage = -1;
+
+ r->insert_length = u.delete_length;
+ r->delete_length = u.insert_length;
+ r->where = u.where;
+
+ if (u.delete_length)
+ {
+ /* if the undo record says to delete characters, then the redo record will
+ need to re-insert the characters that get deleted, so we need to store
+ them.
+ there are three cases:
+ - there's enough room to store the characters
+ - characters stored for *redoing* don't leave room for redo
+ - characters stored for *undoing* don't leave room for redo
+ if the last is true, we have to bail */
+ if (s->undo_char_point + u.delete_length >= NK_TEXTEDIT_UNDOCHARCOUNT) {
+ /* the undo records take up too much character space; there's no space
+ * to store the redo characters */
+ r->insert_length = 0;
+ } else {
+ int i;
+ /* there's definitely room to store the characters eventually */
+ while (s->undo_char_point + u.delete_length > s->redo_char_point) {
+ /* there's currently not enough room, so discard a redo record */
+ nk_textedit_discard_redo(s);
+ /* should never happen: */
+ if (s->redo_point == NK_TEXTEDIT_UNDOSTATECOUNT)
+ return;
+ }
+
+ r = &s->undo_rec[s->redo_point-1];
+ r->char_storage = (short)(s->redo_char_point - u.delete_length);
+ s->redo_char_point = (short)(s->redo_char_point - u.delete_length);
+
+ /* now save the characters */
+ for (i=0; i < u.delete_length; ++i)
+ s->undo_char[r->char_storage + i] =
+ nk_str_rune_at(&state->string, u.where + i);
+ }
+ /* now we can carry out the deletion */
+ nk_str_delete_runes(&state->string, u.where, u.delete_length);
+ }
+
+ /* check type of recorded action: */
+ if (u.insert_length) {
+ /* easy case: was a deletion, so we need to insert n characters */
+ nk_str_insert_text_runes(&state->string, u.where,
+ &s->undo_char[u.char_storage], u.insert_length);
+ s->undo_char_point = (short)(s->undo_char_point - u.insert_length);
+ }
+ state->cursor = (short)(u.where + u.insert_length);
+
+ s->undo_point--;
+ s->redo_point--;
+}
+NK_API void
+nk_textedit_redo(struct nk_text_edit *state)
+{
+ struct nk_text_undo_state *s = &state->undo;
+ struct nk_text_undo_record *u, r;
+ if (s->redo_point == NK_TEXTEDIT_UNDOSTATECOUNT)
+ return;
+
+ /* we need to do two things: apply the redo record, and create an undo record */
+ u = &s->undo_rec[s->undo_point];
+ r = s->undo_rec[s->redo_point];
+
+ /* we KNOW there must be room for the undo record, because the redo record
+ was derived from an undo record */
+ u->delete_length = r.insert_length;
+ u->insert_length = r.delete_length;
+ u->where = r.where;
+ u->char_storage = -1;
+
+ if (r.delete_length) {
+ /* the redo record requires us to delete characters, so the undo record
+ needs to store the characters */
+ if (s->undo_char_point + u->insert_length > s->redo_char_point) {
+ u->insert_length = 0;
+ u->delete_length = 0;
+ } else {
+ int i;
+ u->char_storage = s->undo_char_point;
+ s->undo_char_point = (short)(s->undo_char_point + u->insert_length);
+
+ /* now save the characters */
+ for (i=0; i < u->insert_length; ++i) {
+ s->undo_char[u->char_storage + i] =
+ nk_str_rune_at(&state->string, u->where + i);
+ }
+ }
+ nk_str_delete_runes(&state->string, r.where, r.delete_length);
+ }
+
+ if (r.insert_length) {
+ /* easy case: need to insert n characters */
+ nk_str_insert_text_runes(&state->string, r.where,
+ &s->undo_char[r.char_storage], r.insert_length);
+ }
+ state->cursor = r.where + r.insert_length;
+
+ s->undo_point++;
+ s->redo_point++;
+}
+NK_INTERN void
+nk_textedit_makeundo_insert(struct nk_text_edit *state, int where, int length)
+{
+ nk_textedit_createundo(&state->undo, where, 0, length);
+}
+NK_INTERN void
+nk_textedit_makeundo_delete(struct nk_text_edit *state, int where, int length)
+{
+ int i;
+ nk_rune *p = nk_textedit_createundo(&state->undo, where, length, 0);
+ if (p) {
+ for (i=0; i < length; ++i)
+ p[i] = nk_str_rune_at(&state->string, where+i);
+ }
+}
+NK_INTERN void
+nk_textedit_makeundo_replace(struct nk_text_edit *state, int where,
+ int old_length, int new_length)
+{
+ int i;
+ nk_rune *p = nk_textedit_createundo(&state->undo, where, old_length, new_length);
+ if (p) {
+ for (i=0; i < old_length; ++i)
+ p[i] = nk_str_rune_at(&state->string, where+i);
+ }
+}
+NK_LIB void
+nk_textedit_clear_state(struct nk_text_edit *state, enum nk_text_edit_type type,
+ nk_plugin_filter filter)
+{
+ /* reset the state to default */
+ state->undo.undo_point = 0;
+ state->undo.undo_char_point = 0;
+ state->undo.redo_point = NK_TEXTEDIT_UNDOSTATECOUNT;
+ state->undo.redo_char_point = NK_TEXTEDIT_UNDOCHARCOUNT;
+ state->select_end = state->select_start = 0;
+ state->cursor = 0;
+ state->has_preferred_x = 0;
+ state->preferred_x = 0;
+ state->cursor_at_end_of_line = 0;
+ state->initialized = 1;
+ state->single_line = (unsigned char)(type == NK_TEXT_EDIT_SINGLE_LINE);
+ state->mode = NK_TEXT_EDIT_MODE_VIEW;
+ state->filter = filter;
+ state->scrollbar = nk_vec2(0,0);
+}
+NK_API void
+nk_textedit_init_fixed(struct nk_text_edit *state, void *memory, nk_size size)
+{
+ NK_ASSERT(state);
+ NK_ASSERT(memory);
+ if (!state || !memory || !size) return;
+ NK_MEMSET(state, 0, sizeof(struct nk_text_edit));
+ nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0);
+ nk_str_init_fixed(&state->string, memory, size);
+}
+NK_API void
+nk_textedit_init(struct nk_text_edit *state, struct nk_allocator *alloc, nk_size size)
+{
+ NK_ASSERT(state);
+ NK_ASSERT(alloc);
+ if (!state || !alloc) return;
+ NK_MEMSET(state, 0, sizeof(struct nk_text_edit));
+ nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0);
+ nk_str_init(&state->string, alloc, size);
+}
+#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
+NK_API void
+nk_textedit_init_default(struct nk_text_edit *state)
+{
+ NK_ASSERT(state);
+ if (!state) return;
+ NK_MEMSET(state, 0, sizeof(struct nk_text_edit));
+ nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0);
+ nk_str_init_default(&state->string);
+}
+#endif
+NK_API void
+nk_textedit_select_all(struct nk_text_edit *state)
+{
+ NK_ASSERT(state);
+ state->select_start = 0;
+ state->select_end = state->string.len;
+}
+NK_API void
+nk_textedit_free(struct nk_text_edit *state)
+{
+ NK_ASSERT(state);
+ if (!state) return;
+ nk_str_free(&state->string);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * FILTER
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_filter_default(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(unicode);
+ NK_UNUSED(box);
+ return nk_true;
+}
+NK_API nk_bool
+nk_filter_ascii(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(box);
+ if (unicode > 128) return nk_false;
+ else return nk_true;
+}
+NK_API nk_bool
+nk_filter_float(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(box);
+ if ((unicode < '0' || unicode > '9') && unicode != '.' && unicode != '-')
+ return nk_false;
+ else return nk_true;
+}
+NK_API nk_bool
+nk_filter_decimal(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(box);
+ if ((unicode < '0' || unicode > '9') && unicode != '-')
+ return nk_false;
+ else return nk_true;
+}
+NK_API nk_bool
+nk_filter_hex(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(box);
+ if ((unicode < '0' || unicode > '9') &&
+ (unicode < 'a' || unicode > 'f') &&
+ (unicode < 'A' || unicode > 'F'))
+ return nk_false;
+ else return nk_true;
+}
+NK_API nk_bool
+nk_filter_oct(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(box);
+ if (unicode < '0' || unicode > '7')
+ return nk_false;
+ else return nk_true;
+}
+NK_API nk_bool
+nk_filter_binary(const struct nk_text_edit *box, nk_rune unicode)
+{
+ NK_UNUSED(box);
+ if (unicode != '0' && unicode != '1')
+ return nk_false;
+ else return nk_true;
+}
+
+/* ===============================================================
+ *
+ * EDIT
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_edit_draw_text(struct nk_command_buffer *out,
+ const struct nk_style_edit *style, float pos_x, float pos_y,
+ float x_offset, const char *text, int byte_len, float row_height,
+ const struct nk_user_font *font, struct nk_color background,
+ struct nk_color foreground, nk_bool is_selected)
+{
+ NK_ASSERT(out);
+ NK_ASSERT(font);
+ NK_ASSERT(style);
+ if (!text || !byte_len || !out || !style) return;
+
+ {int glyph_len = 0;
+ nk_rune unicode = 0;
+ int text_len = 0;
+ float line_width = 0;
+ float glyph_width;
+ const char *line = text;
+ float line_offset = 0;
+ int line_count = 0;
+
+ struct nk_text txt;
+ txt.padding = nk_vec2(0,0);
+ txt.background = background;
+ txt.text = foreground;
+
+ foreground = nk_rgb_factor(foreground, style->color_factor);
+ background = nk_rgb_factor(background, style->color_factor);
+
+ glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len);
+ if (!glyph_len) return;
+ while ((text_len < byte_len) && glyph_len)
+ {
+ if (unicode == '\n') {
+ /* new line separator so draw previous line */
+ struct nk_rect label;
+ label.y = pos_y + line_offset;
+ label.h = row_height;
+ label.w = line_width;
+ label.x = pos_x;
+ if (!line_count)
+ label.x += x_offset;
+
+ if (is_selected) /* selection needs to draw different background color */
+ nk_fill_rect(out, label, 0, background);
+ nk_widget_text(out, label, line, (int)((text + text_len) - line),
+ &txt, NK_TEXT_CENTERED, font);
+
+ text_len++;
+ line_count++;
+ line_width = 0;
+ line = text + text_len;
+ line_offset += row_height;
+ glyph_len = nk_utf_decode(text + text_len, &unicode, (int)(byte_len-text_len));
+ continue;
+ }
+ if (unicode == '\r') {
+ text_len++;
+ glyph_len = nk_utf_decode(text + text_len, &unicode, byte_len-text_len);
+ continue;
+ }
+ glyph_width = font->width(font->userdata, font->height, text+text_len, glyph_len);
+ line_width += (float)glyph_width;
+ text_len += glyph_len;
+ glyph_len = nk_utf_decode(text + text_len, &unicode, byte_len-text_len);
+ continue;
+ }
+ if (line_width > 0) {
+ /* draw last line */
+ struct nk_rect label;
+ label.y = pos_y + line_offset;
+ label.h = row_height;
+ label.w = line_width;
+ label.x = pos_x;
+ if (!line_count)
+ label.x += x_offset;
+
+ if (is_selected)
+ nk_fill_rect(out, label, 0, background);
+ nk_widget_text(out, label, line, (int)((text + text_len) - line),
+ &txt, NK_TEXT_LEFT, font);
+ }}
+}
+NK_LIB nk_flags
+nk_do_edit(nk_flags *state, struct nk_command_buffer *out,
+ struct nk_rect bounds, nk_flags flags, nk_plugin_filter filter,
+ struct nk_text_edit *edit, const struct nk_style_edit *style,
+ struct nk_input *in, const struct nk_user_font *font)
+{
+ struct nk_rect area;
+ nk_flags ret = 0;
+ float row_height;
+ char prev_state = 0;
+ char is_hovered = 0;
+ char select_all = 0;
+ char cursor_follow = 0;
+ struct nk_rect old_clip;
+ struct nk_rect clip;
+
+ NK_ASSERT(state);
+ NK_ASSERT(out);
+ NK_ASSERT(style);
+ if (!state || !out || !style)
+ return ret;
+
+ /* visible text area calculation */
+ area.x = bounds.x + style->padding.x + style->border;
+ area.y = bounds.y + style->padding.y + style->border;
+ area.w = bounds.w - (2.0f * style->padding.x + 2 * style->border);
+ area.h = bounds.h - (2.0f * style->padding.y + 2 * style->border);
+ if (flags & NK_EDIT_MULTILINE)
+ area.w = NK_MAX(0, area.w - style->scrollbar_size.x);
+ row_height = (flags & NK_EDIT_MULTILINE)? font->height + style->row_padding: area.h;
+
+ /* calculate clipping rectangle */
+ old_clip = out->clip;
+ nk_unify(&clip, &old_clip, area.x, area.y, area.x + area.w, area.y + area.h);
+
+ /* update edit state */
+ prev_state = (char)edit->active;
+ is_hovered = (char)nk_input_is_mouse_hovering_rect(in, bounds);
+ if (in && in->mouse.buttons[NK_BUTTON_LEFT].clicked && in->mouse.buttons[NK_BUTTON_LEFT].down) {
+ edit->active = NK_INBOX(in->mouse.pos.x, in->mouse.pos.y,
+ bounds.x, bounds.y, bounds.w, bounds.h);
+ }
+
+ /* (de)activate text editor */
+ if (!prev_state && edit->active) {
+ const enum nk_text_edit_type type = (flags & NK_EDIT_MULTILINE) ?
+ NK_TEXT_EDIT_MULTI_LINE: NK_TEXT_EDIT_SINGLE_LINE;
+ /* keep scroll position when re-activating edit widget */
+ struct nk_vec2 oldscrollbar = edit->scrollbar;
+ nk_textedit_clear_state(edit, type, filter);
+ edit->scrollbar = oldscrollbar;
+ if (flags & NK_EDIT_AUTO_SELECT)
+ select_all = nk_true;
+ if (flags & NK_EDIT_GOTO_END_ON_ACTIVATE) {
+ edit->cursor = edit->string.len;
+ in = 0;
+ }
+ } else if (!edit->active) edit->mode = NK_TEXT_EDIT_MODE_VIEW;
+ if (flags & NK_EDIT_READ_ONLY)
+ edit->mode = NK_TEXT_EDIT_MODE_VIEW;
+ else if (flags & NK_EDIT_ALWAYS_INSERT_MODE)
+ edit->mode = NK_TEXT_EDIT_MODE_INSERT;
+
+ ret = (edit->active) ? NK_EDIT_ACTIVE: NK_EDIT_INACTIVE;
+ if (prev_state != edit->active)
+ ret |= (edit->active) ? NK_EDIT_ACTIVATED: NK_EDIT_DEACTIVATED;
+
+ /* handle user input */
+ if (edit->active && in)
+ {
+ int shift_mod = in->keyboard.keys[NK_KEY_SHIFT].down;
+ const float mouse_x = (in->mouse.pos.x - area.x) + edit->scrollbar.x;
+ const float mouse_y = (in->mouse.pos.y - area.y) + edit->scrollbar.y;
+
+ /* mouse click handler */
+ is_hovered = (char)nk_input_is_mouse_hovering_rect(in, area);
+ if (select_all) {
+ nk_textedit_select_all(edit);
+ } else if (is_hovered && in->mouse.buttons[NK_BUTTON_LEFT].down &&
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked) {
+ nk_textedit_click(edit, mouse_x, mouse_y, font, row_height);
+ } else if (is_hovered && in->mouse.buttons[NK_BUTTON_LEFT].down &&
+ (in->mouse.delta.x != 0.0f || in->mouse.delta.y != 0.0f)) {
+ nk_textedit_drag(edit, mouse_x, mouse_y, font, row_height);
+ cursor_follow = nk_true;
+ } else if (is_hovered && in->mouse.buttons[NK_BUTTON_RIGHT].clicked &&
+ in->mouse.buttons[NK_BUTTON_RIGHT].down) {
+ nk_textedit_key(edit, NK_KEY_TEXT_WORD_LEFT, nk_false, font, row_height);
+ nk_textedit_key(edit, NK_KEY_TEXT_WORD_RIGHT, nk_true, font, row_height);
+ cursor_follow = nk_true;
+ }
+
+ {int i; /* keyboard input */
+ int old_mode = edit->mode;
+ for (i = 0; i < NK_KEY_MAX; ++i) {
+ if (i == NK_KEY_ENTER || i == NK_KEY_TAB) continue; /* special case */
+ if (nk_input_is_key_pressed(in, (enum nk_keys)i)) {
+ nk_textedit_key(edit, (enum nk_keys)i, shift_mod, font, row_height);
+ cursor_follow = nk_true;
+ }
+ }
+ if (old_mode != edit->mode) {
+ in->keyboard.text_len = 0;
+ }}
+
+ /* text input */
+ edit->filter = filter;
+ if (in->keyboard.text_len) {
+ nk_textedit_text(edit, in->keyboard.text, in->keyboard.text_len);
+ cursor_follow = nk_true;
+ in->keyboard.text_len = 0;
+ }
+
+ /* enter key handler */
+ if (nk_input_is_key_pressed(in, NK_KEY_ENTER)) {
+ cursor_follow = nk_true;
+ if (flags & NK_EDIT_CTRL_ENTER_NEWLINE && shift_mod)
+ nk_textedit_text(edit, "\n", 1);
+ else if (flags & NK_EDIT_SIG_ENTER)
+ ret |= NK_EDIT_COMMITED;
+ else nk_textedit_text(edit, "\n", 1);
+ }
+
+ /* cut & copy handler */
+ {int copy= nk_input_is_key_pressed(in, NK_KEY_COPY);
+ int cut = nk_input_is_key_pressed(in, NK_KEY_CUT);
+ if ((copy || cut) && (flags & NK_EDIT_CLIPBOARD))
+ {
+ int glyph_len;
+ nk_rune unicode;
+ const char *text;
+ int b = edit->select_start;
+ int e = edit->select_end;
+
+ int begin = NK_MIN(b, e);
+ int end = NK_MAX(b, e);
+ text = nk_str_at_const(&edit->string, begin, &unicode, &glyph_len);
+ if (edit->clip.copy)
+ edit->clip.copy(edit->clip.userdata, text, end - begin);
+ if (cut && !(flags & NK_EDIT_READ_ONLY)){
+ nk_textedit_cut(edit);
+ cursor_follow = nk_true;
+ }
+ }}
+
+ /* paste handler */
+ {int paste = nk_input_is_key_pressed(in, NK_KEY_PASTE);
+ if (paste && (flags & NK_EDIT_CLIPBOARD) && edit->clip.paste) {
+ edit->clip.paste(edit->clip.userdata, edit);
+ cursor_follow = nk_true;
+ }}
+
+ /* tab handler */
+ {int tab = nk_input_is_key_pressed(in, NK_KEY_TAB);
+ if (tab && (flags & NK_EDIT_ALLOW_TAB)) {
+ nk_textedit_text(edit, " ", 4);
+ cursor_follow = nk_true;
+ }}
+ }
+
+ /* set widget state */
+ if (edit->active)
+ *state = NK_WIDGET_STATE_ACTIVE;
+ else nk_widget_state_reset(state);
+
+ if (is_hovered)
+ *state |= NK_WIDGET_STATE_HOVERED;
+
+ /* DRAW EDIT */
+ {const char *text = nk_str_get_const(&edit->string);
+ int len = nk_str_len_char(&edit->string);
+
+ {/* select background colors/images */
+ const struct nk_style_item *background;
+ if (*state & NK_WIDGET_STATE_ACTIVED)
+ background = &style->active;
+ else if (*state & NK_WIDGET_STATE_HOVER)
+ background = &style->hover;
+ else background = &style->normal;
+
+ /* draw background frame */
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(out, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(out, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(out, bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor));
+ nk_stroke_rect(out, bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor));
+ break;
+ }}
+
+
+ area.w = NK_MAX(0, area.w - style->cursor_size);
+ if (edit->active)
+ {
+ int total_lines = 1;
+ struct nk_vec2 text_size = nk_vec2(0,0);
+
+ /* text pointer positions */
+ const char *cursor_ptr = 0;
+ const char *select_begin_ptr = 0;
+ const char *select_end_ptr = 0;
+
+ /* 2D pixel positions */
+ struct nk_vec2 cursor_pos = nk_vec2(0,0);
+ struct nk_vec2 selection_offset_start = nk_vec2(0,0);
+ struct nk_vec2 selection_offset_end = nk_vec2(0,0);
+
+ int selection_begin = NK_MIN(edit->select_start, edit->select_end);
+ int selection_end = NK_MAX(edit->select_start, edit->select_end);
+
+ /* calculate total line count + total space + cursor/selection position */
+ float line_width = 0.0f;
+ if (text && len)
+ {
+ /* utf8 encoding */
+ float glyph_width;
+ int glyph_len = 0;
+ nk_rune unicode = 0;
+ int text_len = 0;
+ int glyphs = 0;
+ int row_begin = 0;
+
+ glyph_len = nk_utf_decode(text, &unicode, len);
+ glyph_width = font->width(font->userdata, font->height, text, glyph_len);
+ line_width = 0;
+
+ /* iterate all lines */
+ while ((text_len < len) && glyph_len)
+ {
+ /* set cursor 2D position and line */
+ if (!cursor_ptr && glyphs == edit->cursor)
+ {
+ int glyph_offset;
+ struct nk_vec2 out_offset;
+ struct nk_vec2 row_size;
+ const char *remaining;
+
+ /* calculate 2d position */
+ cursor_pos.y = (float)(total_lines-1) * row_height;
+ row_size = nk_text_calculate_text_bounds(font, text+row_begin,
+ text_len-row_begin, row_height, &remaining,
+ &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE);
+ cursor_pos.x = row_size.x;
+ cursor_ptr = text + text_len;
+ }
+
+ /* set start selection 2D position and line */
+ if (!select_begin_ptr && edit->select_start != edit->select_end &&
+ glyphs == selection_begin)
+ {
+ int glyph_offset;
+ struct nk_vec2 out_offset;
+ struct nk_vec2 row_size;
+ const char *remaining;
+
+ /* calculate 2d position */
+ selection_offset_start.y = (float)(NK_MAX(total_lines-1,0)) * row_height;
+ row_size = nk_text_calculate_text_bounds(font, text+row_begin,
+ text_len-row_begin, row_height, &remaining,
+ &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE);
+ selection_offset_start.x = row_size.x;
+ select_begin_ptr = text + text_len;
+ }
+
+ /* set end selection 2D position and line */
+ if (!select_end_ptr && edit->select_start != edit->select_end &&
+ glyphs == selection_end)
+ {
+ int glyph_offset;
+ struct nk_vec2 out_offset;
+ struct nk_vec2 row_size;
+ const char *remaining;
+
+ /* calculate 2d position */
+ selection_offset_end.y = (float)(total_lines-1) * row_height;
+ row_size = nk_text_calculate_text_bounds(font, text+row_begin,
+ text_len-row_begin, row_height, &remaining,
+ &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE);
+ selection_offset_end.x = row_size.x;
+ select_end_ptr = text + text_len;
+ }
+ if (unicode == '\n') {
+ text_size.x = NK_MAX(text_size.x, line_width);
+ total_lines++;
+ line_width = 0;
+ text_len++;
+ glyphs++;
+ row_begin = text_len;
+ glyph_len = nk_utf_decode(text + text_len, &unicode, len-text_len);
+ glyph_width = font->width(font->userdata, font->height, text+text_len, glyph_len);
+ continue;
+ }
+
+ glyphs++;
+ text_len += glyph_len;
+ line_width += (float)glyph_width;
+
+ glyph_len = nk_utf_decode(text + text_len, &unicode, len-text_len);
+ glyph_width = font->width(font->userdata, font->height,
+ text+text_len, glyph_len);
+ continue;
+ }
+ text_size.y = (float)total_lines * row_height;
+
+ /* handle case when cursor is at end of text buffer */
+ if (!cursor_ptr && edit->cursor == edit->string.len) {
+ cursor_pos.x = line_width;
+ cursor_pos.y = text_size.y - row_height;
+ }
+ }
+ {
+ /* scrollbar */
+ if (cursor_follow)
+ {
+ /* update scrollbar to follow cursor */
+ if (!(flags & NK_EDIT_NO_HORIZONTAL_SCROLL)) {
+ /* horizontal scroll */
+ const float scroll_increment = area.w * 0.25f;
+ if (cursor_pos.x < edit->scrollbar.x)
+ edit->scrollbar.x = (float)(int)NK_MAX(0.0f, cursor_pos.x - scroll_increment);
+ if (cursor_pos.x >= edit->scrollbar.x + area.w)
+ edit->scrollbar.x = (float)(int)NK_MAX(0.0f, cursor_pos.x - area.w + scroll_increment);
+ } else edit->scrollbar.x = 0;
+
+ if (flags & NK_EDIT_MULTILINE) {
+ /* vertical scroll */
+ if (cursor_pos.y < edit->scrollbar.y)
+ edit->scrollbar.y = NK_MAX(0.0f, cursor_pos.y - row_height);
+ if (cursor_pos.y >= edit->scrollbar.y + row_height)
+ edit->scrollbar.y = edit->scrollbar.y + row_height;
+ } else edit->scrollbar.y = 0;
+ }
+
+ /* scrollbar widget */
+ if (flags & NK_EDIT_MULTILINE)
+ {
+ nk_flags ws;
+ struct nk_rect scroll;
+ float scroll_target;
+ float scroll_offset;
+ float scroll_step;
+ float scroll_inc;
+
+ scroll = area;
+ scroll.x = (bounds.x + bounds.w - style->border) - style->scrollbar_size.x;
+ scroll.w = style->scrollbar_size.x;
+
+ scroll_offset = edit->scrollbar.y;
+ scroll_step = scroll.h * 0.10f;
+ scroll_inc = scroll.h * 0.01f;
+ scroll_target = text_size.y;
+ edit->scrollbar.y = nk_do_scrollbarv(&ws, out, scroll, 0,
+ scroll_offset, scroll_target, scroll_step, scroll_inc,
+ &style->scrollbar, in, font);
+ }
+ }
+
+ /* draw text */
+ {struct nk_color background_color;
+ struct nk_color text_color;
+ struct nk_color sel_background_color;
+ struct nk_color sel_text_color;
+ struct nk_color cursor_color;
+ struct nk_color cursor_text_color;
+ const struct nk_style_item *background;
+ nk_push_scissor(out, clip);
+
+ /* select correct colors to draw */
+ if (*state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->active;
+ text_color = style->text_active;
+ sel_text_color = style->selected_text_hover;
+ sel_background_color = style->selected_hover;
+ cursor_color = style->cursor_hover;
+ cursor_text_color = style->cursor_text_hover;
+ } else if (*state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ text_color = style->text_hover;
+ sel_text_color = style->selected_text_hover;
+ sel_background_color = style->selected_hover;
+ cursor_text_color = style->cursor_text_hover;
+ cursor_color = style->cursor_hover;
+ } else {
+ background = &style->normal;
+ text_color = style->text_normal;
+ sel_text_color = style->selected_text_normal;
+ sel_background_color = style->selected_normal;
+ cursor_color = style->cursor_normal;
+ cursor_text_color = style->cursor_text_normal;
+ }
+ if (background->type == NK_STYLE_ITEM_IMAGE)
+ background_color = nk_rgba(0,0,0,0);
+ else
+ background_color = background->data.color;
+
+ cursor_color = nk_rgb_factor(cursor_color, style->color_factor);
+ cursor_text_color = nk_rgb_factor(cursor_text_color, style->color_factor);
+
+ if (edit->select_start == edit->select_end) {
+ /* no selection so just draw the complete text */
+ const char *begin = nk_str_get_const(&edit->string);
+ int l = nk_str_len_char(&edit->string);
+ nk_edit_draw_text(out, style, area.x - edit->scrollbar.x,
+ area.y - edit->scrollbar.y, 0, begin, l, row_height, font,
+ background_color, text_color, nk_false);
+ } else {
+ /* edit has selection so draw 1-3 text chunks */
+ if (edit->select_start != edit->select_end && selection_begin > 0){
+ /* draw unselected text before selection */
+ const char *begin = nk_str_get_const(&edit->string);
+ NK_ASSERT(select_begin_ptr);
+ nk_edit_draw_text(out, style, area.x - edit->scrollbar.x,
+ area.y - edit->scrollbar.y, 0, begin, (int)(select_begin_ptr - begin),
+ row_height, font, background_color, text_color, nk_false);
+ }
+ if (edit->select_start != edit->select_end) {
+ /* draw selected text */
+ NK_ASSERT(select_begin_ptr);
+ if (!select_end_ptr) {
+ const char *begin = nk_str_get_const(&edit->string);
+ select_end_ptr = begin + nk_str_len_char(&edit->string);
+ }
+ nk_edit_draw_text(out, style,
+ area.x - edit->scrollbar.x,
+ area.y + selection_offset_start.y - edit->scrollbar.y,
+ selection_offset_start.x,
+ select_begin_ptr, (int)(select_end_ptr - select_begin_ptr),
+ row_height, font, sel_background_color, sel_text_color, nk_true);
+ }
+ if ((edit->select_start != edit->select_end &&
+ selection_end < edit->string.len))
+ {
+ /* draw unselected text after selected text */
+ const char *begin = select_end_ptr;
+ const char *end = nk_str_get_const(&edit->string) +
+ nk_str_len_char(&edit->string);
+ NK_ASSERT(select_end_ptr);
+ nk_edit_draw_text(out, style,
+ area.x - edit->scrollbar.x,
+ area.y + selection_offset_end.y - edit->scrollbar.y,
+ selection_offset_end.x,
+ begin, (int)(end - begin), row_height, font,
+ background_color, text_color, nk_true);
+ }
+ }
+
+ /* cursor */
+ if (edit->select_start == edit->select_end)
+ {
+ if (edit->cursor >= nk_str_len(&edit->string) ||
+ (cursor_ptr && *cursor_ptr == '\n')) {
+ /* draw cursor at end of line */
+ struct nk_rect cursor;
+ cursor.w = style->cursor_size;
+ cursor.h = font->height;
+ cursor.x = area.x + cursor_pos.x - edit->scrollbar.x;
+ cursor.y = area.y + cursor_pos.y + row_height/2.0f - cursor.h/2.0f;
+ cursor.y -= edit->scrollbar.y;
+ nk_fill_rect(out, cursor, 0, cursor_color);
+ } else {
+ /* draw cursor inside text */
+ int glyph_len;
+ struct nk_rect label;
+ struct nk_text txt;
+
+ nk_rune unicode;
+ NK_ASSERT(cursor_ptr);
+ glyph_len = nk_utf_decode(cursor_ptr, &unicode, 4);
+
+ label.x = area.x + cursor_pos.x - edit->scrollbar.x;
+ label.y = area.y + cursor_pos.y - edit->scrollbar.y;
+ label.w = font->width(font->userdata, font->height, cursor_ptr, glyph_len);
+ label.h = row_height;
+
+ txt.padding = nk_vec2(0,0);
+ txt.background = cursor_color;;
+ txt.text = cursor_text_color;
+ nk_fill_rect(out, label, 0, cursor_color);
+ nk_widget_text(out, label, cursor_ptr, glyph_len, &txt, NK_TEXT_LEFT, font);
+ }
+ }}
+ } else {
+ /* not active so just draw text */
+ int l = nk_str_len_char(&edit->string);
+ const char *begin = nk_str_get_const(&edit->string);
+
+ const struct nk_style_item *background;
+ struct nk_color background_color;
+ struct nk_color text_color;
+ nk_push_scissor(out, clip);
+ if (*state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->active;
+ text_color = style->text_active;
+ } else if (*state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ text_color = style->text_hover;
+ } else {
+ background = &style->normal;
+ text_color = style->text_normal;
+ }
+ if (background->type == NK_STYLE_ITEM_IMAGE)
+ background_color = nk_rgba(0,0,0,0);
+ else
+ background_color = background->data.color;
+
+ background_color = nk_rgb_factor(background_color, style->color_factor);
+ text_color = nk_rgb_factor(text_color, style->color_factor);
+
+ nk_edit_draw_text(out, style, area.x - edit->scrollbar.x,
+ area.y - edit->scrollbar.y, 0, begin, l, row_height, font,
+ background_color, text_color, nk_false);
+ }
+ nk_push_scissor(out, old_clip);}
+ return ret;
+}
+NK_API void
+nk_edit_focus(struct nk_context *ctx, nk_flags flags)
+{
+ nk_hash hash;
+ struct nk_window *win;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return;
+
+ win = ctx->current;
+ hash = win->edit.seq;
+ win->edit.active = nk_true;
+ win->edit.name = hash;
+ if (flags & NK_EDIT_ALWAYS_INSERT_MODE)
+ win->edit.mode = NK_TEXT_EDIT_MODE_INSERT;
+}
+NK_API void
+nk_edit_unfocus(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return;
+
+ win = ctx->current;
+ win->edit.active = nk_false;
+ win->edit.name = 0;
+}
+NK_API nk_flags
+nk_edit_string(struct nk_context *ctx, nk_flags flags,
+ char *memory, int *len, int max, nk_plugin_filter filter)
+{
+ nk_hash hash;
+ nk_flags state;
+ struct nk_text_edit *edit;
+ struct nk_window *win;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(memory);
+ NK_ASSERT(len);
+ if (!ctx || !memory || !len)
+ return 0;
+
+ filter = (!filter) ? nk_filter_default: filter;
+ win = ctx->current;
+ hash = win->edit.seq;
+ edit = &ctx->text_edit;
+ nk_textedit_clear_state(&ctx->text_edit, (flags & NK_EDIT_MULTILINE)?
+ NK_TEXT_EDIT_MULTI_LINE: NK_TEXT_EDIT_SINGLE_LINE, filter);
+
+ if (win->edit.active && hash == win->edit.name) {
+ if (flags & NK_EDIT_NO_CURSOR)
+ edit->cursor = nk_utf_len(memory, *len);
+ else edit->cursor = win->edit.cursor;
+ if (!(flags & NK_EDIT_SELECTABLE)) {
+ edit->select_start = win->edit.cursor;
+ edit->select_end = win->edit.cursor;
+ } else {
+ edit->select_start = win->edit.sel_start;
+ edit->select_end = win->edit.sel_end;
+ }
+ edit->mode = win->edit.mode;
+ edit->scrollbar.x = (float)win->edit.scrollbar.x;
+ edit->scrollbar.y = (float)win->edit.scrollbar.y;
+ edit->active = nk_true;
+ } else edit->active = nk_false;
+
+ max = NK_MAX(1, max);
+ *len = NK_MIN(*len, max-1);
+ nk_str_init_fixed(&edit->string, memory, (nk_size)max);
+ edit->string.buffer.allocated = (nk_size)*len;
+ edit->string.len = nk_utf_len(memory, *len);
+ state = nk_edit_buffer(ctx, flags, edit, filter);
+ *len = (int)edit->string.buffer.allocated;
+
+ if (edit->active) {
+ win->edit.cursor = edit->cursor;
+ win->edit.sel_start = edit->select_start;
+ win->edit.sel_end = edit->select_end;
+ win->edit.mode = edit->mode;
+ win->edit.scrollbar.x = (nk_uint)edit->scrollbar.x;
+ win->edit.scrollbar.y = (nk_uint)edit->scrollbar.y;
+ } return state;
+}
+NK_API nk_flags
+nk_edit_buffer(struct nk_context *ctx, nk_flags flags,
+ struct nk_text_edit *edit, nk_plugin_filter filter)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ struct nk_input *in;
+
+ enum nk_widget_layout_states state;
+ struct nk_rect bounds;
+
+ nk_flags ret_flags = 0;
+ unsigned char prev_state;
+ nk_hash hash;
+
+ /* make sure correct values */
+ NK_ASSERT(ctx);
+ NK_ASSERT(edit);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ state = nk_widget(&bounds, ctx);
+ if (!state) return state;
+ else if (state == NK_WIDGET_DISABLED)
+ flags |= NK_EDIT_READ_ONLY;
+ in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+
+ /* check if edit is currently hot item */
+ hash = win->edit.seq++;
+ if (win->edit.active && hash == win->edit.name) {
+ if (flags & NK_EDIT_NO_CURSOR)
+ edit->cursor = edit->string.len;
+ if (!(flags & NK_EDIT_SELECTABLE)) {
+ edit->select_start = edit->cursor;
+ edit->select_end = edit->cursor;
+ }
+ if (flags & NK_EDIT_CLIPBOARD)
+ edit->clip = ctx->clip;
+ edit->active = (unsigned char)win->edit.active;
+ } else edit->active = nk_false;
+ edit->mode = win->edit.mode;
+
+ filter = (!filter) ? nk_filter_default: filter;
+ prev_state = (unsigned char)edit->active;
+ in = (flags & NK_EDIT_READ_ONLY) ? 0: in;
+ ret_flags = nk_do_edit(&ctx->last_widget_state, &win->buffer, bounds, flags,
+ filter, edit, &style->edit, in, style->font);
+
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_TEXT];
+ if (edit->active && prev_state != edit->active) {
+ /* current edit is now hot */
+ win->edit.active = nk_true;
+ win->edit.name = hash;
+ } else if (prev_state && !edit->active) {
+ /* current edit is now cold */
+ win->edit.active = nk_false;
+ } return ret_flags;
+}
+NK_API nk_flags
+nk_edit_string_zero_terminated(struct nk_context *ctx, nk_flags flags,
+ char *buffer, int max, nk_plugin_filter filter)
+{
+ nk_flags result;
+ int len = nk_strlen(buffer);
+ result = nk_edit_string(ctx, flags, buffer, &len, max, filter);
+ buffer[NK_MIN(NK_MAX(max-1,0), len)] = '\0';
+ return result;
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * PROPERTY
+ *
+ * ===============================================================*/
+NK_LIB void
+nk_drag_behavior(nk_flags *state, const struct nk_input *in,
+ struct nk_rect drag, struct nk_property_variant *variant,
+ float inc_per_pixel)
+{
+ int left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down;
+ int left_mouse_click_in_cursor = in &&
+ nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, drag, nk_true);
+
+ nk_widget_state_reset(state);
+ if (nk_input_is_mouse_hovering_rect(in, drag))
+ *state = NK_WIDGET_STATE_HOVERED;
+
+ if (left_mouse_down && left_mouse_click_in_cursor) {
+ float delta, pixels;
+ pixels = in->mouse.delta.x;
+ delta = pixels * inc_per_pixel;
+ switch (variant->kind) {
+ default: break;
+ case NK_PROPERTY_INT:
+ variant->value.i = variant->value.i + (int)delta;
+ variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i, variant->max_value.i);
+ break;
+ case NK_PROPERTY_FLOAT:
+ variant->value.f = variant->value.f + (float)delta;
+ variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f, variant->max_value.f);
+ break;
+ case NK_PROPERTY_DOUBLE:
+ variant->value.d = variant->value.d + (double)delta;
+ variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d, variant->max_value.d);
+ break;
+ }
+ *state = NK_WIDGET_STATE_ACTIVE;
+ }
+ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, drag))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(in, drag))
+ *state |= NK_WIDGET_STATE_LEFT;
+}
+NK_LIB void
+nk_property_behavior(nk_flags *ws, const struct nk_input *in,
+ struct nk_rect property, struct nk_rect label, struct nk_rect edit,
+ struct nk_rect empty, int *state, struct nk_property_variant *variant,
+ float inc_per_pixel)
+{
+ nk_widget_state_reset(ws);
+ if (in && *state == NK_PROPERTY_DEFAULT) {
+ if (nk_button_behavior(ws, edit, in, NK_BUTTON_DEFAULT))
+ *state = NK_PROPERTY_EDIT;
+ else if (nk_input_is_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, label, nk_true))
+ *state = NK_PROPERTY_DRAG;
+ else if (nk_input_is_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, empty, nk_true))
+ *state = NK_PROPERTY_DRAG;
+ }
+ if (*state == NK_PROPERTY_DRAG) {
+ nk_drag_behavior(ws, in, property, variant, inc_per_pixel);
+ if (!(*ws & NK_WIDGET_STATE_ACTIVED)) *state = NK_PROPERTY_DEFAULT;
+ }
+}
+NK_LIB void
+nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property *style,
+ const struct nk_rect *bounds, const struct nk_rect *label, nk_flags state,
+ const char *name, int len, const struct nk_user_font *font)
+{
+ struct nk_text text;
+ const struct nk_style_item *background;
+
+ /* select correct background and text color */
+ if (state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->active;
+ text.text = style->label_active;
+ } else if (state & NK_WIDGET_STATE_HOVER) {
+ background = &style->hover;
+ text.text = style->label_hover;
+ } else {
+ background = &style->normal;
+ text.text = style->label_normal;
+ }
+
+ text.text = nk_rgb_factor(text.text, style->color_factor);
+
+ /* draw background */
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ text.background = background->data.color;
+ nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor));
+ nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(background->data.color, style->color_factor));
+ break;
+ }
+
+ /* draw label */
+ text.padding = nk_vec2(0,0);
+ if (name && name[0] != '#') {
+ nk_widget_text(out, *label, name, len, &text, NK_TEXT_CENTERED, font);
+ }
+}
+NK_LIB void
+nk_do_property(nk_flags *ws,
+ struct nk_command_buffer *out, struct nk_rect property,
+ const char *name, struct nk_property_variant *variant,
+ float inc_per_pixel, char *buffer, int *len,
+ int *state, int *cursor, int *select_begin, int *select_end,
+ const struct nk_style_property *style,
+ enum nk_property_filter filter, struct nk_input *in,
+ const struct nk_user_font *font, struct nk_text_edit *text_edit,
+ enum nk_button_behavior behavior)
+{
+ const nk_plugin_filter filters[] = {
+ nk_filter_decimal,
+ nk_filter_float
+ };
+ nk_bool active, old;
+ int num_len = 0, name_len = 0;
+ char string[NK_MAX_NUMBER_BUFFER];
+ float size;
+
+ char *dst = 0;
+ int *length;
+
+ struct nk_rect left;
+ struct nk_rect right;
+ struct nk_rect label;
+ struct nk_rect edit;
+ struct nk_rect empty;
+
+ /* left decrement button */
+ left.h = font->height/2;
+ left.w = left.h;
+ left.x = property.x + style->border + style->padding.x;
+ left.y = property.y + style->border + property.h/2.0f - left.h/2;
+
+ /* text label */
+ if (name && name[0] != '#') {
+ name_len = nk_strlen(name);
+ }
+ size = font->width(font->userdata, font->height, name, name_len);
+ label.x = left.x + left.w + style->padding.x;
+ label.w = (float)size + 2 * style->padding.x;
+ label.y = property.y + style->border + style->padding.y;
+ label.h = property.h - (2 * style->border + 2 * style->padding.y);
+
+ /* right increment button */
+ right.y = left.y;
+ right.w = left.w;
+ right.h = left.h;
+ right.x = property.x + property.w - (right.w + style->padding.x);
+
+ /* edit */
+ if (*state == NK_PROPERTY_EDIT) {
+ size = font->width(font->userdata, font->height, buffer, *len);
+ size += style->edit.cursor_size;
+ length = len;
+ dst = buffer;
+ } else {
+ switch (variant->kind) {
+ default: break;
+ case NK_PROPERTY_INT:
+ nk_itoa(string, variant->value.i);
+ num_len = nk_strlen(string);
+ break;
+ case NK_PROPERTY_FLOAT:
+ NK_DTOA(string, (double)variant->value.f);
+ num_len = nk_string_float_limit(string, NK_MAX_FLOAT_PRECISION);
+ break;
+ case NK_PROPERTY_DOUBLE:
+ NK_DTOA(string, variant->value.d);
+ num_len = nk_string_float_limit(string, NK_MAX_FLOAT_PRECISION);
+ break;
+ }
+ size = font->width(font->userdata, font->height, string, num_len);
+ dst = string;
+ length = &num_len;
+ }
+
+ edit.w = (float)size + 2 * style->padding.x;
+ edit.w = NK_MIN(edit.w, right.x - (label.x + label.w));
+ edit.x = right.x - (edit.w + style->padding.x);
+ edit.y = property.y + style->border;
+ edit.h = property.h - (2 * style->border);
+
+ /* empty left space activator */
+ empty.w = edit.x - (label.x + label.w);
+ empty.x = label.x + label.w;
+ empty.y = property.y;
+ empty.h = property.h;
+
+ /* update property */
+ old = (*state == NK_PROPERTY_EDIT);
+ nk_property_behavior(ws, in, property, label, edit, empty, state, variant, inc_per_pixel);
+
+ /* draw property */
+ if (style->draw_begin) style->draw_begin(out, style->userdata);
+ nk_draw_property(out, style, &property, &label, *ws, name, name_len, font);
+ if (style->draw_end) style->draw_end(out, style->userdata);
+
+ /* execute right button */
+ if (nk_do_button_symbol(ws, out, left, style->sym_left, behavior, &style->dec_button, in, font)) {
+ switch (variant->kind) {
+ default: break;
+ case NK_PROPERTY_INT:
+ variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i - variant->step.i, variant->max_value.i); break;
+ case NK_PROPERTY_FLOAT:
+ variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f - variant->step.f, variant->max_value.f); break;
+ case NK_PROPERTY_DOUBLE:
+ variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d - variant->step.d, variant->max_value.d); break;
+ }
+ }
+ /* execute left button */
+ if (nk_do_button_symbol(ws, out, right, style->sym_right, behavior, &style->inc_button, in, font)) {
+ switch (variant->kind) {
+ default: break;
+ case NK_PROPERTY_INT:
+ variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i + variant->step.i, variant->max_value.i); break;
+ case NK_PROPERTY_FLOAT:
+ variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f + variant->step.f, variant->max_value.f); break;
+ case NK_PROPERTY_DOUBLE:
+ variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d + variant->step.d, variant->max_value.d); break;
+ }
+ }
+ if (old != NK_PROPERTY_EDIT && (*state == NK_PROPERTY_EDIT)) {
+ /* property has been activated so setup buffer */
+ NK_MEMCPY(buffer, dst, (nk_size)*length);
+ *cursor = nk_utf_len(buffer, *length);
+ *len = *length;
+ length = len;
+ dst = buffer;
+ active = 0;
+ } else active = (*state == NK_PROPERTY_EDIT);
+
+ /* execute and run text edit field */
+ nk_textedit_clear_state(text_edit, NK_TEXT_EDIT_SINGLE_LINE, filters[filter]);
+ text_edit->active = (unsigned char)active;
+ text_edit->string.len = *length;
+ text_edit->cursor = NK_CLAMP(0, *cursor, *length);
+ text_edit->select_start = NK_CLAMP(0,*select_begin, *length);
+ text_edit->select_end = NK_CLAMP(0,*select_end, *length);
+ text_edit->string.buffer.allocated = (nk_size)*length;
+ text_edit->string.buffer.memory.size = NK_MAX_NUMBER_BUFFER;
+ text_edit->string.buffer.memory.ptr = dst;
+ text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER;
+ text_edit->mode = NK_TEXT_EDIT_MODE_INSERT;
+ nk_do_edit(ws, out, edit, (int)NK_EDIT_FIELD|(int)NK_EDIT_AUTO_SELECT,
+ filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font);
+
+ *length = text_edit->string.len;
+ *cursor = text_edit->cursor;
+ *select_begin = text_edit->select_start;
+ *select_end = text_edit->select_end;
+ if (text_edit->active && nk_input_is_key_pressed(in, NK_KEY_ENTER))
+ text_edit->active = nk_false;
+
+ if (active && !text_edit->active) {
+ /* property is now not active so convert edit text to value*/
+ *state = NK_PROPERTY_DEFAULT;
+ buffer[*len] = '\0';
+ switch (variant->kind) {
+ default: break;
+ case NK_PROPERTY_INT:
+ variant->value.i = nk_strtoi(buffer, 0);
+ variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i, variant->max_value.i);
+ break;
+ case NK_PROPERTY_FLOAT:
+ nk_string_float_limit(buffer, NK_MAX_FLOAT_PRECISION);
+ variant->value.f = nk_strtof(buffer, 0);
+ variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f, variant->max_value.f);
+ break;
+ case NK_PROPERTY_DOUBLE:
+ nk_string_float_limit(buffer, NK_MAX_FLOAT_PRECISION);
+ variant->value.d = nk_strtod(buffer, 0);
+ variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d, variant->max_value.d);
+ break;
+ }
+ }
+}
+NK_LIB struct nk_property_variant
+nk_property_variant_int(int value, int min_value, int max_value, int step)
+{
+ struct nk_property_variant result;
+ result.kind = NK_PROPERTY_INT;
+ result.value.i = value;
+ result.min_value.i = min_value;
+ result.max_value.i = max_value;
+ result.step.i = step;
+ return result;
+}
+NK_LIB struct nk_property_variant
+nk_property_variant_float(float value, float min_value, float max_value, float step)
+{
+ struct nk_property_variant result;
+ result.kind = NK_PROPERTY_FLOAT;
+ result.value.f = value;
+ result.min_value.f = min_value;
+ result.max_value.f = max_value;
+ result.step.f = step;
+ return result;
+}
+NK_LIB struct nk_property_variant
+nk_property_variant_double(double value, double min_value, double max_value,
+ double step)
+{
+ struct nk_property_variant result;
+ result.kind = NK_PROPERTY_DOUBLE;
+ result.value.d = value;
+ result.min_value.d = min_value;
+ result.max_value.d = max_value;
+ result.step.d = step;
+ return result;
+}
+NK_LIB void
+nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant *variant,
+ float inc_per_pixel, const enum nk_property_filter filter)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ struct nk_input *in;
+ const struct nk_style *style;
+
+ struct nk_rect bounds;
+ enum nk_widget_layout_states s;
+
+ int *state = 0;
+ nk_hash hash = 0;
+ char *buffer = 0;
+ int *len = 0;
+ int *cursor = 0;
+ int *select_begin = 0;
+ int *select_end = 0;
+ int old_state;
+
+ char dummy_buffer[NK_MAX_NUMBER_BUFFER];
+ int dummy_state = NK_PROPERTY_DEFAULT;
+ int dummy_length = 0;
+ int dummy_cursor = 0;
+ int dummy_select_begin = 0;
+ int dummy_select_end = 0;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return;
+
+ win = ctx->current;
+ layout = win->layout;
+ style = &ctx->style;
+ s = nk_widget(&bounds, ctx);
+ if (!s) return;
+
+ /* calculate hash from name */
+ if (name[0] == '#') {
+ hash = nk_murmur_hash(name, (int)nk_strlen(name), win->property.seq++);
+ name++; /* special number hash */
+ } else hash = nk_murmur_hash(name, (int)nk_strlen(name), 42);
+
+ /* check if property is currently hot item */
+ if (win->property.active && hash == win->property.name) {
+ buffer = win->property.buffer;
+ len = &win->property.length;
+ cursor = &win->property.cursor;
+ state = &win->property.state;
+ select_begin = &win->property.select_start;
+ select_end = &win->property.select_end;
+ } else {
+ buffer = dummy_buffer;
+ len = &dummy_length;
+ cursor = &dummy_cursor;
+ state = &dummy_state;
+ select_begin = &dummy_select_begin;
+ select_end = &dummy_select_end;
+ }
+
+ /* execute property widget */
+ old_state = *state;
+ ctx->text_edit.clip = ctx->clip;
+ in = ((s == NK_WIDGET_ROM && !win->property.active) ||
+ layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED) ? 0 : &ctx->input;
+ nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name,
+ variant, inc_per_pixel, buffer, len, state, cursor, select_begin,
+ select_end, &style->property, filter, in, style->font, &ctx->text_edit,
+ ctx->button_behavior);
+
+ if (in && *state != NK_PROPERTY_DEFAULT && !win->property.active) {
+ /* current property is now hot */
+ win->property.active = 1;
+ NK_MEMCPY(win->property.buffer, buffer, (nk_size)*len);
+ win->property.length = *len;
+ win->property.cursor = *cursor;
+ win->property.state = *state;
+ win->property.name = hash;
+ win->property.select_start = *select_begin;
+ win->property.select_end = *select_end;
+ if (*state == NK_PROPERTY_DRAG) {
+ ctx->input.mouse.grab = nk_true;
+ ctx->input.mouse.grabbed = nk_true;
+ }
+ }
+ /* check if previously active property is now inactive */
+ if (*state == NK_PROPERTY_DEFAULT && old_state != NK_PROPERTY_DEFAULT) {
+ if (old_state == NK_PROPERTY_DRAG) {
+ ctx->input.mouse.grab = nk_false;
+ ctx->input.mouse.grabbed = nk_false;
+ ctx->input.mouse.ungrab = nk_true;
+ }
+ win->property.select_start = 0;
+ win->property.select_end = 0;
+ win->property.active = 0;
+ }
+}
+NK_API void
+nk_property_int(struct nk_context *ctx, const char *name,
+ int min, int *val, int max, int step, float inc_per_pixel)
+{
+ struct nk_property_variant variant;
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+ NK_ASSERT(val);
+
+ if (!ctx || !ctx->current || !name || !val) return;
+ variant = nk_property_variant_int(*val, min, max, step);
+ nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_INT);
+ *val = variant.value.i;
+}
+NK_API void
+nk_property_float(struct nk_context *ctx, const char *name,
+ float min, float *val, float max, float step, float inc_per_pixel)
+{
+ struct nk_property_variant variant;
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+ NK_ASSERT(val);
+
+ if (!ctx || !ctx->current || !name || !val) return;
+ variant = nk_property_variant_float(*val, min, max, step);
+ nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT);
+ *val = variant.value.f;
+}
+NK_API void
+nk_property_double(struct nk_context *ctx, const char *name,
+ double min, double *val, double max, double step, float inc_per_pixel)
+{
+ struct nk_property_variant variant;
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+ NK_ASSERT(val);
+
+ if (!ctx || !ctx->current || !name || !val) return;
+ variant = nk_property_variant_double(*val, min, max, step);
+ nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT);
+ *val = variant.value.d;
+}
+NK_API int
+nk_propertyi(struct nk_context *ctx, const char *name, int min, int val,
+ int max, int step, float inc_per_pixel)
+{
+ struct nk_property_variant variant;
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+
+ if (!ctx || !ctx->current || !name) return val;
+ variant = nk_property_variant_int(val, min, max, step);
+ nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_INT);
+ val = variant.value.i;
+ return val;
+}
+NK_API float
+nk_propertyf(struct nk_context *ctx, const char *name, float min,
+ float val, float max, float step, float inc_per_pixel)
+{
+ struct nk_property_variant variant;
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+
+ if (!ctx || !ctx->current || !name) return val;
+ variant = nk_property_variant_float(val, min, max, step);
+ nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT);
+ val = variant.value.f;
+ return val;
+}
+NK_API double
+nk_propertyd(struct nk_context *ctx, const char *name, double min,
+ double val, double max, double step, float inc_per_pixel)
+{
+ struct nk_property_variant variant;
+ NK_ASSERT(ctx);
+ NK_ASSERT(name);
+
+ if (!ctx || !ctx->current || !name) return val;
+ variant = nk_property_variant_double(val, min, max, step);
+ nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT);
+ val = variant.value.d;
+ return val;
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * CHART
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type,
+ struct nk_color color, struct nk_color highlight,
+ int count, float min_value, float max_value)
+{
+ struct nk_window *win;
+ struct nk_chart *chart;
+ const struct nk_style *config;
+ const struct nk_style_chart *style;
+
+ const struct nk_style_item *background;
+ struct nk_rect bounds = {0, 0, 0, 0};
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+
+ if (!ctx || !ctx->current || !ctx->current->layout) return 0;
+ if (!nk_widget(&bounds, ctx)) {
+ chart = &ctx->current->layout->chart;
+ nk_zero(chart, sizeof(*chart));
+ return 0;
+ }
+
+ win = ctx->current;
+ config = &ctx->style;
+ chart = &win->layout->chart;
+ style = &config->chart;
+
+ /* setup basic generic chart */
+ nk_zero(chart, sizeof(*chart));
+ chart->x = bounds.x + style->padding.x;
+ chart->y = bounds.y + style->padding.y;
+ chart->w = bounds.w - 2 * style->padding.x;
+ chart->h = bounds.h - 2 * style->padding.y;
+ chart->w = NK_MAX(chart->w, 2 * style->padding.x);
+ chart->h = NK_MAX(chart->h, 2 * style->padding.y);
+
+ /* add first slot into chart */
+ {struct nk_chart_slot *slot = &chart->slots[chart->slot++];
+ slot->type = type;
+ slot->count = count;
+ slot->color = nk_rgb_factor(color, style->color_factor);
+ slot->highlight = highlight;
+ slot->min = NK_MIN(min_value, max_value);
+ slot->max = NK_MAX(min_value, max_value);
+ slot->range = slot->max - slot->min;
+ slot->show_markers = style->show_markers;}
+
+ /* draw chart background */
+ background = &style->background;
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor));
+ nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border),
+ style->rounding, nk_rgb_factor(style->background.data.color, style->color_factor));
+ break;
+ }
+ return 1;
+}
+NK_API nk_bool
+nk_chart_begin(struct nk_context *ctx, const enum nk_chart_type type,
+ int count, float min_value, float max_value)
+{
+ return nk_chart_begin_colored(ctx, type, ctx->style.chart.color,
+ ctx->style.chart.selected_color, count, min_value, max_value);
+}
+NK_API void
+nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type,
+ struct nk_color color, struct nk_color highlight,
+ int count, float min_value, float max_value)
+{
+ const struct nk_style_chart* style;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ NK_ASSERT(ctx->current->layout->chart.slot < NK_CHART_MAX_SLOT);
+ if (!ctx || !ctx->current || !ctx->current->layout) return;
+ if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return;
+
+ style = &ctx->style.chart;
+
+ /* add another slot into the graph */
+ {struct nk_chart *chart = &ctx->current->layout->chart;
+ struct nk_chart_slot *slot = &chart->slots[chart->slot++];
+ slot->type = type;
+ slot->count = count;
+ slot->color = nk_rgb_factor(color, style->color_factor);
+ slot->highlight = highlight;
+ slot->min = NK_MIN(min_value, max_value);
+ slot->max = NK_MAX(min_value, max_value);
+ slot->range = slot->max - slot->min;
+ slot->show_markers = style->show_markers;}
+}
+NK_API void
+nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type,
+ int count, float min_value, float max_value)
+{
+ nk_chart_add_slot_colored(ctx, type, ctx->style.chart.color,
+ ctx->style.chart.selected_color, count, min_value, max_value);
+}
+NK_INTERN nk_flags
+nk_chart_push_line(struct nk_context *ctx, struct nk_window *win,
+ struct nk_chart *g, float value, int slot)
+{
+ struct nk_panel *layout = win->layout;
+ const struct nk_input *i = ctx->current->widgets_disabled ? 0 : &ctx->input;
+ struct nk_command_buffer *out = &win->buffer;
+
+ nk_flags ret = 0;
+ struct nk_vec2 cur;
+ struct nk_rect bounds;
+ struct nk_color color;
+ float step;
+ float range;
+ float ratio;
+
+ NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT);
+ step = g->w / (float)g->slots[slot].count;
+ range = g->slots[slot].max - g->slots[slot].min;
+ ratio = (value - g->slots[slot].min) / range;
+
+ if (g->slots[slot].index == 0) {
+ /* first data point does not have a connection */
+ g->slots[slot].last.x = g->x;
+ g->slots[slot].last.y = (g->y + g->h) - ratio * (float)g->h;
+
+ bounds.x = g->slots[slot].last.x - 2;
+ bounds.y = g->slots[slot].last.y - 2;
+ bounds.w = bounds.h = 4;
+
+ color = g->slots[slot].color;
+ if (!(layout->flags & NK_WINDOW_ROM) && i &&
+ NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){
+ ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0;
+ ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down &&
+ i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0;
+ color = g->slots[slot].highlight;
+ }
+ if (g->slots[slot].show_markers) {
+ nk_fill_rect(out, bounds, 0, color);
+ }
+ g->slots[slot].index += 1;
+ return ret;
+ }
+
+ /* draw a line between the last data point and the new one */
+ color = g->slots[slot].color;
+ cur.x = g->x + (float)(step * (float)g->slots[slot].index);
+ cur.y = (g->y + g->h) - (ratio * (float)g->h);
+ nk_stroke_line(out, g->slots[slot].last.x, g->slots[slot].last.y, cur.x, cur.y, 1.0f, color);
+
+ bounds.x = cur.x - 3;
+ bounds.y = cur.y - 3;
+ bounds.w = bounds.h = 6;
+
+ /* user selection of current data point */
+ if (!(layout->flags & NK_WINDOW_ROM)) {
+ if (nk_input_is_mouse_hovering_rect(i, bounds)) {
+ ret = NK_CHART_HOVERING;
+ ret |= (!i->mouse.buttons[NK_BUTTON_LEFT].down &&
+ i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0;
+ color = g->slots[slot].highlight;
+ }
+ }
+ if (g->slots[slot].show_markers) {
+ nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color);
+ }
+
+ /* save current data point position */
+ g->slots[slot].last.x = cur.x;
+ g->slots[slot].last.y = cur.y;
+ g->slots[slot].index += 1;
+ return ret;
+}
+NK_INTERN nk_flags
+nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win,
+ struct nk_chart *chart, float value, int slot)
+{
+ struct nk_command_buffer *out = &win->buffer;
+ const struct nk_input *in = ctx->current->widgets_disabled ? 0 : &ctx->input;
+ struct nk_panel *layout = win->layout;
+
+ float ratio;
+ nk_flags ret = 0;
+ struct nk_color color;
+ struct nk_rect item = {0,0,0,0};
+
+ NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT);
+ if (chart->slots[slot].index >= chart->slots[slot].count)
+ return nk_false;
+ if (chart->slots[slot].count) {
+ float padding = (float)(chart->slots[slot].count-1);
+ item.w = (chart->w - padding) / (float)(chart->slots[slot].count);
+ }
+
+ /* calculate bounds of current bar chart entry */
+ color = chart->slots[slot].color;;
+ item.h = chart->h * NK_ABS((value/chart->slots[slot].range));
+ if (value >= 0) {
+ ratio = (value + NK_ABS(chart->slots[slot].min)) / NK_ABS(chart->slots[slot].range);
+ item.y = (chart->y + chart->h) - chart->h * ratio;
+ } else {
+ ratio = (value - chart->slots[slot].max) / chart->slots[slot].range;
+ item.y = chart->y + (chart->h * NK_ABS(ratio)) - item.h;
+ }
+ item.x = chart->x + ((float)chart->slots[slot].index * item.w);
+ item.x = item.x + ((float)chart->slots[slot].index);
+
+ /* user chart bar selection */
+ if (!(layout->flags & NK_WINDOW_ROM) && in &&
+ NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) {
+ ret = NK_CHART_HOVERING;
+ ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down &&
+ in->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0;
+ color = chart->slots[slot].highlight;
+ }
+ nk_fill_rect(out, item, 0, color);
+ chart->slots[slot].index += 1;
+ return ret;
+}
+NK_API nk_flags
+nk_chart_push_slot(struct nk_context *ctx, float value, int slot)
+{
+ nk_flags flags;
+ struct nk_window *win;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT);
+ NK_ASSERT(slot < ctx->current->layout->chart.slot);
+ if (!ctx || !ctx->current || slot >= NK_CHART_MAX_SLOT) return nk_false;
+ if (slot >= ctx->current->layout->chart.slot) return nk_false;
+
+ win = ctx->current;
+ if (win->layout->chart.slot < slot) return nk_false;
+ switch (win->layout->chart.slots[slot].type) {
+ case NK_CHART_LINES:
+ flags = nk_chart_push_line(ctx, win, &win->layout->chart, value, slot); break;
+ case NK_CHART_COLUMN:
+ flags = nk_chart_push_column(ctx, win, &win->layout->chart, value, slot); break;
+ default:
+ case NK_CHART_MAX:
+ flags = 0;
+ }
+ return flags;
+}
+NK_API nk_flags
+nk_chart_push(struct nk_context *ctx, float value)
+{
+ return nk_chart_push_slot(ctx, value, 0);
+}
+NK_API void
+nk_chart_end(struct nk_context *ctx)
+{
+ struct nk_window *win;
+ struct nk_chart *chart;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current)
+ return;
+
+ win = ctx->current;
+ chart = &win->layout->chart;
+ NK_MEMSET(chart, 0, sizeof(*chart));
+ return;
+}
+NK_API void
+nk_plot(struct nk_context *ctx, enum nk_chart_type type, const float *values,
+ int count, int offset)
+{
+ int i = 0;
+ float min_value;
+ float max_value;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(values);
+ if (!ctx || !values || !count) return;
+
+ min_value = values[offset];
+ max_value = values[offset];
+ for (i = 0; i < count; ++i) {
+ min_value = NK_MIN(values[i + offset], min_value);
+ max_value = NK_MAX(values[i + offset], max_value);
+ }
+
+ if (nk_chart_begin(ctx, type, count, min_value, max_value)) {
+ for (i = 0; i < count; ++i)
+ nk_chart_push(ctx, values[i + offset]);
+ nk_chart_end(ctx);
+ }
+}
+NK_API void
+nk_plot_function(struct nk_context *ctx, enum nk_chart_type type, void *userdata,
+ float(*value_getter)(void* user, int index), int count, int offset)
+{
+ int i = 0;
+ float min_value;
+ float max_value;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(value_getter);
+ if (!ctx || !value_getter || !count) return;
+
+ max_value = min_value = value_getter(userdata, offset);
+ for (i = 0; i < count; ++i) {
+ float value = value_getter(userdata, i + offset);
+ min_value = NK_MIN(value, min_value);
+ max_value = NK_MAX(value, max_value);
+ }
+
+ if (nk_chart_begin(ctx, type, count, min_value, max_value)) {
+ for (i = 0; i < count; ++i)
+ nk_chart_push(ctx, value_getter(userdata, i + offset));
+ nk_chart_end(ctx);
+ }
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * COLOR PICKER
+ *
+ * ===============================================================*/
+NK_LIB nk_bool
+nk_color_picker_behavior(nk_flags *state,
+ const struct nk_rect *bounds, const struct nk_rect *matrix,
+ const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar,
+ struct nk_colorf *color, const struct nk_input *in)
+{
+ float hsva[4];
+ nk_bool value_changed = 0;
+ nk_bool hsv_changed = 0;
+
+ NK_ASSERT(state);
+ NK_ASSERT(matrix);
+ NK_ASSERT(hue_bar);
+ NK_ASSERT(color);
+
+ /* color matrix */
+ nk_colorf_hsva_fv(hsva, *color);
+ if (nk_button_behavior(state, *matrix, in, NK_BUTTON_REPEATER)) {
+ hsva[1] = NK_SATURATE((in->mouse.pos.x - matrix->x) / (matrix->w-1));
+ hsva[2] = 1.0f - NK_SATURATE((in->mouse.pos.y - matrix->y) / (matrix->h-1));
+ value_changed = hsv_changed = 1;
+ }
+ /* hue bar */
+ if (nk_button_behavior(state, *hue_bar, in, NK_BUTTON_REPEATER)) {
+ hsva[0] = NK_SATURATE((in->mouse.pos.y - hue_bar->y) / (hue_bar->h-1));
+ value_changed = hsv_changed = 1;
+ }
+ /* alpha bar */
+ if (alpha_bar) {
+ if (nk_button_behavior(state, *alpha_bar, in, NK_BUTTON_REPEATER)) {
+ hsva[3] = 1.0f - NK_SATURATE((in->mouse.pos.y - alpha_bar->y) / (alpha_bar->h-1));
+ value_changed = 1;
+ }
+ }
+ nk_widget_state_reset(state);
+ if (hsv_changed) {
+ *color = nk_hsva_colorfv(hsva);
+ *state = NK_WIDGET_STATE_ACTIVE;
+ }
+ if (value_changed) {
+ color->a = hsva[3];
+ *state = NK_WIDGET_STATE_ACTIVE;
+ }
+ /* set color picker widget state */
+ if (nk_input_is_mouse_hovering_rect(in, *bounds))
+ *state = NK_WIDGET_STATE_HOVERED;
+ if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, *bounds))
+ *state |= NK_WIDGET_STATE_ENTERED;
+ else if (nk_input_is_mouse_prev_hovering_rect(in, *bounds))
+ *state |= NK_WIDGET_STATE_LEFT;
+ return value_changed;
+}
+NK_LIB void
+nk_draw_color_picker(struct nk_command_buffer *o, const struct nk_rect *matrix,
+ const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar,
+ struct nk_colorf col)
+{
+ NK_STORAGE const struct nk_color black = {0,0,0,255};
+ NK_STORAGE const struct nk_color white = {255, 255, 255, 255};
+ NK_STORAGE const struct nk_color black_trans = {0,0,0,0};
+
+ const float crosshair_size = 7.0f;
+ struct nk_color temp;
+ float hsva[4];
+ float line_y;
+ int i;
+
+ NK_ASSERT(o);
+ NK_ASSERT(matrix);
+ NK_ASSERT(hue_bar);
+
+ /* draw hue bar */
+ nk_colorf_hsva_fv(hsva, col);
+ for (i = 0; i < 6; ++i) {
+ NK_GLOBAL const struct nk_color hue_colors[] = {
+ {255, 0, 0, 255}, {255,255,0,255}, {0,255,0,255}, {0, 255,255,255},
+ {0,0,255,255}, {255, 0, 255, 255}, {255, 0, 0, 255}
+ };
+ nk_fill_rect_multi_color(o,
+ nk_rect(hue_bar->x, hue_bar->y + (float)i * (hue_bar->h/6.0f) + 0.5f,
+ hue_bar->w, (hue_bar->h/6.0f) + 0.5f), hue_colors[i], hue_colors[i],
+ hue_colors[i+1], hue_colors[i+1]);
+ }
+ line_y = (float)(int)(hue_bar->y + hsva[0] * matrix->h + 0.5f);
+ nk_stroke_line(o, hue_bar->x-1, line_y, hue_bar->x + hue_bar->w + 2,
+ line_y, 1, nk_rgb(255,255,255));
+
+ /* draw alpha bar */
+ if (alpha_bar) {
+ float alpha = NK_SATURATE(col.a);
+ line_y = (float)(int)(alpha_bar->y + (1.0f - alpha) * matrix->h + 0.5f);
+
+ nk_fill_rect_multi_color(o, *alpha_bar, white, white, black, black);
+ nk_stroke_line(o, alpha_bar->x-1, line_y, alpha_bar->x + alpha_bar->w + 2,
+ line_y, 1, nk_rgb(255,255,255));
+ }
+
+ /* draw color matrix */
+ temp = nk_hsv_f(hsva[0], 1.0f, 1.0f);
+ nk_fill_rect_multi_color(o, *matrix, white, temp, temp, white);
+ nk_fill_rect_multi_color(o, *matrix, black_trans, black_trans, black, black);
+
+ /* draw cross-hair */
+ {struct nk_vec2 p; float S = hsva[1]; float V = hsva[2];
+ p.x = (float)(int)(matrix->x + S * matrix->w);
+ p.y = (float)(int)(matrix->y + (1.0f - V) * matrix->h);
+ nk_stroke_line(o, p.x - crosshair_size, p.y, p.x-2, p.y, 1.0f, white);
+ nk_stroke_line(o, p.x + crosshair_size + 1, p.y, p.x+3, p.y, 1.0f, white);
+ nk_stroke_line(o, p.x, p.y + crosshair_size + 1, p.x, p.y+3, 1.0f, white);
+ nk_stroke_line(o, p.x, p.y - crosshair_size, p.x, p.y-2, 1.0f, white);}
+}
+NK_LIB nk_bool
+nk_do_color_picker(nk_flags *state,
+ struct nk_command_buffer *out, struct nk_colorf *col,
+ enum nk_color_format fmt, struct nk_rect bounds,
+ struct nk_vec2 padding, const struct nk_input *in,
+ const struct nk_user_font *font)
+{
+ int ret = 0;
+ struct nk_rect matrix;
+ struct nk_rect hue_bar;
+ struct nk_rect alpha_bar;
+ float bar_w;
+
+ NK_ASSERT(out);
+ NK_ASSERT(col);
+ NK_ASSERT(state);
+ NK_ASSERT(font);
+ if (!out || !col || !state || !font)
+ return ret;
+
+ bar_w = font->height;
+ bounds.x += padding.x;
+ bounds.y += padding.x;
+ bounds.w -= 2 * padding.x;
+ bounds.h -= 2 * padding.y;
+
+ matrix.x = bounds.x;
+ matrix.y = bounds.y;
+ matrix.h = bounds.h;
+ matrix.w = bounds.w - (3 * padding.x + 2 * bar_w);
+
+ hue_bar.w = bar_w;
+ hue_bar.y = bounds.y;
+ hue_bar.h = matrix.h;
+ hue_bar.x = matrix.x + matrix.w + padding.x;
+
+ alpha_bar.x = hue_bar.x + hue_bar.w + padding.x;
+ alpha_bar.y = bounds.y;
+ alpha_bar.w = bar_w;
+ alpha_bar.h = matrix.h;
+
+ ret = nk_color_picker_behavior(state, &bounds, &matrix, &hue_bar,
+ (fmt == NK_RGBA) ? &alpha_bar:0, col, in);
+ nk_draw_color_picker(out, &matrix, &hue_bar, (fmt == NK_RGBA) ? &alpha_bar:0, *col);
+ return ret;
+}
+NK_API nk_bool
+nk_color_pick(struct nk_context * ctx, struct nk_colorf *color,
+ enum nk_color_format fmt)
+{
+ struct nk_window *win;
+ struct nk_panel *layout;
+ const struct nk_style *config;
+ const struct nk_input *in;
+
+ enum nk_widget_layout_states state;
+ struct nk_rect bounds;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(color);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !color)
+ return 0;
+
+ win = ctx->current;
+ config = &ctx->style;
+ layout = win->layout;
+ state = nk_widget(&bounds, ctx);
+ if (!state) return 0;
+ in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input;
+ return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds,
+ nk_vec2(0,0), in, config->font);
+}
+NK_API struct nk_colorf
+nk_color_picker(struct nk_context *ctx, struct nk_colorf color,
+ enum nk_color_format fmt)
+{
+ nk_color_pick(ctx, &color, fmt);
+ return color;
+}
+
+
+
+
+
+/* ==============================================================
+ *
+ * COMBO
+ *
+ * ===============================================================*/
+NK_INTERN nk_bool
+nk_combo_begin(struct nk_context *ctx, struct nk_window *win,
+ struct nk_vec2 size, nk_bool is_clicked, struct nk_rect header)
+{
+ struct nk_window *popup;
+ int is_open = 0;
+ int is_active = 0;
+ struct nk_rect body;
+ nk_hash hash;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ popup = win->popup.win;
+ body.x = header.x;
+ body.w = size.x;
+ body.y = header.y + header.h-ctx->style.window.combo_border;
+ body.h = size.y;
+
+ hash = win->popup.combo_count++;
+ is_open = (popup) ? nk_true:nk_false;
+ is_active = (popup && (win->popup.name == hash) && win->popup.type == NK_PANEL_COMBO);
+ if ((is_clicked && is_open && !is_active) || (is_open && !is_active) ||
+ (!is_open && !is_active && !is_clicked)) return 0;
+ if (!nk_nonblock_begin(ctx, 0, body,
+ (is_clicked && is_open)?nk_rect(0,0,0,0):header, NK_PANEL_COMBO)) return 0;
+
+ win->popup.type = NK_PANEL_COMBO;
+ win->popup.name = hash;
+ return 1;
+}
+NK_API nk_bool
+nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len,
+ struct nk_vec2 size)
+{
+ const struct nk_input *in;
+ struct nk_window *win;
+ struct nk_style *style;
+
+ enum nk_widget_layout_states s;
+ int is_clicked = nk_false;
+ struct nk_rect header;
+ const struct nk_style_item *background;
+ struct nk_text text;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(selected);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout || !selected)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ s = nk_widget(&header, ctx);
+ if (s == NK_WIDGET_INVALID)
+ return 0;
+
+ in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input;
+ if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT))
+ is_clicked = nk_true;
+
+ /* draw combo box header background and border */
+ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->combo.active;
+ text.text = style->combo.label_active;
+ } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) {
+ background = &style->combo.hover;
+ text.text = style->combo.label_hover;
+ } else {
+ background = &style->combo.normal;
+ text.text = style->combo.label_normal;
+ }
+
+ text.text = nk_rgb_factor(text.text, style->combo.color_factor);
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ text.background = background->data.color;
+ nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor));
+ nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor));
+ break;
+ }
+ {
+ /* print currently selected text item */
+ struct nk_rect label;
+ struct nk_rect button;
+ struct nk_rect content;
+ int draw_button_symbol;
+
+ enum nk_symbol_type sym;
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ sym = style->combo.sym_hover;
+ else if (is_clicked)
+ sym = style->combo.sym_active;
+ else
+ sym = style->combo.sym_normal;
+
+ /* represents whether or not the combo's button symbol should be drawn */
+ draw_button_symbol = sym != NK_SYMBOL_NONE;
+
+ /* calculate button */
+ button.w = header.h - 2 * style->combo.button_padding.y;
+ button.x = (header.x + header.w - header.h) - style->combo.button_padding.x;
+ button.y = header.y + style->combo.button_padding.y;
+ button.h = button.w;
+
+ content.x = button.x + style->combo.button.padding.x;
+ content.y = button.y + style->combo.button.padding.y;
+ content.w = button.w - 2 * style->combo.button.padding.x;
+ content.h = button.h - 2 * style->combo.button.padding.y;
+
+ /* draw selected label */
+ text.padding = nk_vec2(0,0);
+ label.x = header.x + style->combo.content_padding.x;
+ label.y = header.y + style->combo.content_padding.y;
+ label.h = header.h - 2 * style->combo.content_padding.y;
+ if (draw_button_symbol)
+ label.w = button.x - (style->combo.content_padding.x + style->combo.spacing.x) - label.x;
+ else
+ label.w = header.w - 2 * style->combo.content_padding.x;
+ nk_widget_text(&win->buffer, label, selected, len, &text,
+ NK_TEXT_LEFT, ctx->style.font);
+
+ /* draw open/close button */
+ if (draw_button_symbol)
+ nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state,
+ &ctx->style.combo.button, sym, style->font);
+ }
+ return nk_combo_begin(ctx, win, size, is_clicked, header);
+}
+NK_API nk_bool
+nk_combo_begin_label(struct nk_context *ctx, const char *selected, struct nk_vec2 size)
+{
+ return nk_combo_begin_text(ctx, selected, nk_strlen(selected), size);
+}
+NK_API nk_bool
+nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ const struct nk_input *in;
+
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ enum nk_widget_layout_states s;
+ const struct nk_style_item *background;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ s = nk_widget(&header, ctx);
+ if (s == NK_WIDGET_INVALID)
+ return 0;
+
+ in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input;
+ if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT))
+ is_clicked = nk_true;
+
+ /* draw combo box header background and border */
+ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED)
+ background = &style->combo.active;
+ else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ background = &style->combo.hover;
+ else background = &style->combo.normal;
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor));
+ nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor));
+ break;
+ }
+ {
+ struct nk_rect content;
+ struct nk_rect button;
+ struct nk_rect bounds;
+ int draw_button_symbol;
+
+ enum nk_symbol_type sym;
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ sym = style->combo.sym_hover;
+ else if (is_clicked)
+ sym = style->combo.sym_active;
+ else sym = style->combo.sym_normal;
+
+ /* represents whether or not the combo's button symbol should be drawn */
+ draw_button_symbol = sym != NK_SYMBOL_NONE;
+
+ /* calculate button */
+ button.w = header.h - 2 * style->combo.button_padding.y;
+ button.x = (header.x + header.w - header.h) - style->combo.button_padding.x;
+ button.y = header.y + style->combo.button_padding.y;
+ button.h = button.w;
+
+ content.x = button.x + style->combo.button.padding.x;
+ content.y = button.y + style->combo.button.padding.y;
+ content.w = button.w - 2 * style->combo.button.padding.x;
+ content.h = button.h - 2 * style->combo.button.padding.y;
+
+ /* draw color */
+ bounds.h = header.h - 4 * style->combo.content_padding.y;
+ bounds.y = header.y + 2 * style->combo.content_padding.y;
+ bounds.x = header.x + 2 * style->combo.content_padding.x;
+ if (draw_button_symbol)
+ bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x;
+ else
+ bounds.w = header.w - 4 * style->combo.content_padding.x;
+ nk_fill_rect(&win->buffer, bounds, 0, nk_rgb_factor(color, style->combo.color_factor));
+
+ /* draw open/close button */
+ if (draw_button_symbol)
+ nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state,
+ &ctx->style.combo.button, sym, style->font);
+ }
+ return nk_combo_begin(ctx, win, size, is_clicked, header);
+}
+NK_API nk_bool
+nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ const struct nk_input *in;
+
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ enum nk_widget_layout_states s;
+ const struct nk_style_item *background;
+ struct nk_color sym_background;
+ struct nk_color symbol_color;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ s = nk_widget(&header, ctx);
+ if (s == NK_WIDGET_INVALID)
+ return 0;
+
+ in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input;
+ if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT))
+ is_clicked = nk_true;
+
+ /* draw combo box header background and border */
+ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->combo.active;
+ symbol_color = style->combo.symbol_active;
+ } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) {
+ background = &style->combo.hover;
+ symbol_color = style->combo.symbol_hover;
+ } else {
+ background = &style->combo.normal;
+ symbol_color = style->combo.symbol_hover;
+ }
+
+ symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor);
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ sym_background = nk_rgba(0, 0, 0, 0);
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ sym_background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ sym_background = background->data.color;
+ nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor));
+ nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor));
+ break;
+ }
+ {
+ struct nk_rect bounds = {0,0,0,0};
+ struct nk_rect content;
+ struct nk_rect button;
+
+ enum nk_symbol_type sym;
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ sym = style->combo.sym_hover;
+ else if (is_clicked)
+ sym = style->combo.sym_active;
+ else sym = style->combo.sym_normal;
+
+ /* calculate button */
+ button.w = header.h - 2 * style->combo.button_padding.y;
+ button.x = (header.x + header.w - header.h) - style->combo.button_padding.y;
+ button.y = header.y + style->combo.button_padding.y;
+ button.h = button.w;
+
+ content.x = button.x + style->combo.button.padding.x;
+ content.y = button.y + style->combo.button.padding.y;
+ content.w = button.w - 2 * style->combo.button.padding.x;
+ content.h = button.h - 2 * style->combo.button.padding.y;
+
+ /* draw symbol */
+ bounds.h = header.h - 2 * style->combo.content_padding.y;
+ bounds.y = header.y + style->combo.content_padding.y;
+ bounds.x = header.x + style->combo.content_padding.x;
+ bounds.w = (button.x - style->combo.content_padding.y) - bounds.x;
+ nk_draw_symbol(&win->buffer, symbol, bounds, sym_background, symbol_color,
+ 1.0f, style->font);
+
+ /* draw open/close button */
+ nk_draw_button_symbol(&win->buffer, &bounds, &content, ctx->last_widget_state,
+ &ctx->style.combo.button, sym, style->font);
+ }
+ return nk_combo_begin(ctx, win, size, is_clicked, header);
+}
+NK_API nk_bool
+nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len,
+ enum nk_symbol_type symbol, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ struct nk_input *in;
+
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ enum nk_widget_layout_states s;
+ const struct nk_style_item *background;
+ struct nk_color symbol_color;
+ struct nk_text text;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ s = nk_widget(&header, ctx);
+ if (!s) return 0;
+
+ in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input;
+ if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT))
+ is_clicked = nk_true;
+
+ /* draw combo box header background and border */
+ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->combo.active;
+ symbol_color = style->combo.symbol_active;
+ text.text = style->combo.label_active;
+ } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) {
+ background = &style->combo.hover;
+ symbol_color = style->combo.symbol_hover;
+ text.text = style->combo.label_hover;
+ } else {
+ background = &style->combo.normal;
+ symbol_color = style->combo.symbol_normal;
+ text.text = style->combo.label_normal;
+ }
+
+ text.text = nk_rgb_factor(text.text, style->combo.color_factor);
+ symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor);
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ text.background = background->data.color;
+ nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor));
+ nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor));
+ break;
+ }
+ {
+ struct nk_rect content;
+ struct nk_rect button;
+ struct nk_rect label;
+ struct nk_rect image;
+
+ enum nk_symbol_type sym;
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ sym = style->combo.sym_hover;
+ else if (is_clicked)
+ sym = style->combo.sym_active;
+ else sym = style->combo.sym_normal;
+
+ /* calculate button */
+ button.w = header.h - 2 * style->combo.button_padding.y;
+ button.x = (header.x + header.w - header.h) - style->combo.button_padding.x;
+ button.y = header.y + style->combo.button_padding.y;
+ button.h = button.w;
+
+ content.x = button.x + style->combo.button.padding.x;
+ content.y = button.y + style->combo.button.padding.y;
+ content.w = button.w - 2 * style->combo.button.padding.x;
+ content.h = button.h - 2 * style->combo.button.padding.y;
+ nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state,
+ &ctx->style.combo.button, sym, style->font);
+
+ /* draw symbol */
+ image.x = header.x + style->combo.content_padding.x;
+ image.y = header.y + style->combo.content_padding.y;
+ image.h = header.h - 2 * style->combo.content_padding.y;
+ image.w = image.h;
+ nk_draw_symbol(&win->buffer, symbol, image, text.background, symbol_color,
+ 1.0f, style->font);
+
+ /* draw label */
+ text.padding = nk_vec2(0,0);
+ label.x = image.x + image.w + style->combo.spacing.x + style->combo.content_padding.x;
+ label.y = header.y + style->combo.content_padding.y;
+ label.w = (button.x - style->combo.content_padding.x) - label.x;
+ label.h = header.h - 2 * style->combo.content_padding.y;
+ nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, style->font);
+ }
+ return nk_combo_begin(ctx, win, size, is_clicked, header);
+}
+NK_API nk_bool
+nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ const struct nk_input *in;
+
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ enum nk_widget_layout_states s;
+ const struct nk_style_item *background;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ s = nk_widget(&header, ctx);
+ if (s == NK_WIDGET_INVALID)
+ return 0;
+
+ in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input;
+ if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT))
+ is_clicked = nk_true;
+
+ /* draw combo box header background and border */
+ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED)
+ background = &style->combo.active;
+ else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ background = &style->combo.hover;
+ else background = &style->combo.normal;
+
+ switch (background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor));
+ nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor));
+ break;
+ }
+ {
+ struct nk_rect bounds = {0,0,0,0};
+ struct nk_rect content;
+ struct nk_rect button;
+ int draw_button_symbol;
+
+ enum nk_symbol_type sym;
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ sym = style->combo.sym_hover;
+ else if (is_clicked)
+ sym = style->combo.sym_active;
+ else sym = style->combo.sym_normal;
+
+ /* represents whether or not the combo's button symbol should be drawn */
+ draw_button_symbol = sym != NK_SYMBOL_NONE;
+
+ /* calculate button */
+ button.w = header.h - 2 * style->combo.button_padding.y;
+ button.x = (header.x + header.w - header.h) - style->combo.button_padding.y;
+ button.y = header.y + style->combo.button_padding.y;
+ button.h = button.w;
+
+ content.x = button.x + style->combo.button.padding.x;
+ content.y = button.y + style->combo.button.padding.y;
+ content.w = button.w - 2 * style->combo.button.padding.x;
+ content.h = button.h - 2 * style->combo.button.padding.y;
+
+ /* draw image */
+ bounds.h = header.h - 2 * style->combo.content_padding.y;
+ bounds.y = header.y + style->combo.content_padding.y;
+ bounds.x = header.x + style->combo.content_padding.x;
+ if (draw_button_symbol)
+ bounds.w = (button.x - style->combo.content_padding.y) - bounds.x;
+ else
+ bounds.w = header.w - 2 * style->combo.content_padding.x;
+ nk_draw_image(&win->buffer, bounds, &img, nk_rgb_factor(nk_white, style->combo.color_factor));
+
+ /* draw open/close button */
+ if (draw_button_symbol)
+ nk_draw_button_symbol(&win->buffer, &bounds, &content, ctx->last_widget_state,
+ &ctx->style.combo.button, sym, style->font);
+ }
+ return nk_combo_begin(ctx, win, size, is_clicked, header);
+}
+NK_API nk_bool
+nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len,
+ struct nk_image img, struct nk_vec2 size)
+{
+ struct nk_window *win;
+ struct nk_style *style;
+ struct nk_input *in;
+
+ struct nk_rect header;
+ int is_clicked = nk_false;
+ enum nk_widget_layout_states s;
+ const struct nk_style_item *background;
+ struct nk_text text;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ win = ctx->current;
+ style = &ctx->style;
+ s = nk_widget(&header, ctx);
+ if (!s) return 0;
+
+ in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input;
+ if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT))
+ is_clicked = nk_true;
+
+ /* draw combo box header background and border */
+ if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) {
+ background = &style->combo.active;
+ text.text = style->combo.label_active;
+ } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) {
+ background = &style->combo.hover;
+ text.text = style->combo.label_hover;
+ } else {
+ background = &style->combo.normal;
+ text.text = style->combo.label_normal;
+ }
+
+ text.text = nk_rgb_factor(text.text, style->combo.color_factor);
+
+ switch(background->type) {
+ case NK_STYLE_ITEM_IMAGE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_NINE_SLICE:
+ text.background = nk_rgba(0, 0, 0, 0);
+ nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor));
+ break;
+ case NK_STYLE_ITEM_COLOR:
+ text.background = background->data.color;
+ nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor));
+ nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor));
+ break;
+ }
+ {
+ struct nk_rect content;
+ struct nk_rect button;
+ struct nk_rect label;
+ struct nk_rect image;
+ int draw_button_symbol;
+
+ enum nk_symbol_type sym;
+ if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER)
+ sym = style->combo.sym_hover;
+ else if (is_clicked)
+ sym = style->combo.sym_active;
+ else sym = style->combo.sym_normal;
+
+ /* represents whether or not the combo's button symbol should be drawn */
+ draw_button_symbol = sym != NK_SYMBOL_NONE;
+
+ /* calculate button */
+ button.w = header.h - 2 * style->combo.button_padding.y;
+ button.x = (header.x + header.w - header.h) - style->combo.button_padding.x;
+ button.y = header.y + style->combo.button_padding.y;
+ button.h = button.w;
+
+ content.x = button.x + style->combo.button.padding.x;
+ content.y = button.y + style->combo.button.padding.y;
+ content.w = button.w - 2 * style->combo.button.padding.x;
+ content.h = button.h - 2 * style->combo.button.padding.y;
+ if (draw_button_symbol)
+ nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state,
+ &ctx->style.combo.button, sym, style->font);
+
+ /* draw image */
+ image.x = header.x + style->combo.content_padding.x;
+ image.y = header.y + style->combo.content_padding.y;
+ image.h = header.h - 2 * style->combo.content_padding.y;
+ image.w = image.h;
+ nk_draw_image(&win->buffer, image, &img, nk_rgb_factor(nk_white, style->combo.color_factor));
+
+ /* draw label */
+ text.padding = nk_vec2(0,0);
+ label.x = image.x + image.w + style->combo.spacing.x + style->combo.content_padding.x;
+ label.y = header.y + style->combo.content_padding.y;
+ label.h = header.h - 2 * style->combo.content_padding.y;
+ if (draw_button_symbol)
+ label.w = (button.x - style->combo.content_padding.x) - label.x;
+ else
+ label.w = (header.x + header.w - style->combo.content_padding.x) - label.x;
+ nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, style->font);
+ }
+ return nk_combo_begin(ctx, win, size, is_clicked, header);
+}
+NK_API nk_bool
+nk_combo_begin_symbol_label(struct nk_context *ctx,
+ const char *selected, enum nk_symbol_type type, struct nk_vec2 size)
+{
+ return nk_combo_begin_symbol_text(ctx, selected, nk_strlen(selected), type, size);
+}
+NK_API nk_bool
+nk_combo_begin_image_label(struct nk_context *ctx,
+ const char *selected, struct nk_image img, struct nk_vec2 size)
+{
+ return nk_combo_begin_image_text(ctx, selected, nk_strlen(selected), img, size);
+}
+NK_API nk_bool
+nk_combo_item_text(struct nk_context *ctx, const char *text, int len,nk_flags align)
+{
+ return nk_contextual_item_text(ctx, text, len, align);
+}
+NK_API nk_bool
+nk_combo_item_label(struct nk_context *ctx, const char *label, nk_flags align)
+{
+ return nk_contextual_item_label(ctx, label, align);
+}
+NK_API nk_bool
+nk_combo_item_image_text(struct nk_context *ctx, struct nk_image img, const char *text,
+ int len, nk_flags alignment)
+{
+ return nk_contextual_item_image_text(ctx, img, text, len, alignment);
+}
+NK_API nk_bool
+nk_combo_item_image_label(struct nk_context *ctx, struct nk_image img,
+ const char *text, nk_flags alignment)
+{
+ return nk_contextual_item_image_label(ctx, img, text, alignment);
+}
+NK_API nk_bool
+nk_combo_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *text, int len, nk_flags alignment)
+{
+ return nk_contextual_item_symbol_text(ctx, sym, text, len, alignment);
+}
+NK_API nk_bool
+nk_combo_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym,
+ const char *label, nk_flags alignment)
+{
+ return nk_contextual_item_symbol_label(ctx, sym, label, alignment);
+}
+NK_API void nk_combo_end(struct nk_context *ctx)
+{
+ nk_contextual_end(ctx);
+}
+NK_API void nk_combo_close(struct nk_context *ctx)
+{
+ nk_contextual_close(ctx);
+}
+NK_API int
+nk_combo(struct nk_context *ctx, const char **items, int count,
+ int selected, int item_height, struct nk_vec2 size)
+{
+ int i = 0;
+ int max_height;
+ struct nk_vec2 item_spacing;
+ struct nk_vec2 window_padding;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(items);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !items ||!count)
+ return selected;
+
+ item_spacing = ctx->style.window.spacing;
+ window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type);
+ max_height = count * item_height + count * (int)item_spacing.y;
+ max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2;
+ size.y = NK_MIN(size.y, (float)max_height);
+ if (nk_combo_begin_label(ctx, items[selected], size)) {
+ nk_layout_row_dynamic(ctx, (float)item_height, 1);
+ for (i = 0; i < count; ++i) {
+ if (nk_combo_item_label(ctx, items[i], NK_TEXT_LEFT))
+ selected = i;
+ }
+ nk_combo_end(ctx);
+ }
+ return selected;
+}
+NK_API int
+nk_combo_separator(struct nk_context *ctx, const char *items_separated_by_separator,
+ int separator, int selected, int count, int item_height, struct nk_vec2 size)
+{
+ int i;
+ int max_height;
+ struct nk_vec2 item_spacing;
+ struct nk_vec2 window_padding;
+ const char *current_item;
+ const char *iter;
+ int length = 0;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(items_separated_by_separator);
+ if (!ctx || !items_separated_by_separator)
+ return selected;
+
+ /* calculate popup window */
+ item_spacing = ctx->style.window.spacing;
+ window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type);
+ max_height = count * item_height + count * (int)item_spacing.y;
+ max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2;
+ size.y = NK_MIN(size.y, (float)max_height);
+
+ /* find selected item */
+ current_item = items_separated_by_separator;
+ for (i = 0; i < count; ++i) {
+ iter = current_item;
+ while (*iter && *iter != separator) iter++;
+ length = (int)(iter - current_item);
+ if (i == selected) break;
+ current_item = iter + 1;
+ }
+
+ if (nk_combo_begin_text(ctx, current_item, length, size)) {
+ current_item = items_separated_by_separator;
+ nk_layout_row_dynamic(ctx, (float)item_height, 1);
+ for (i = 0; i < count; ++i) {
+ iter = current_item;
+ while (*iter && *iter != separator) iter++;
+ length = (int)(iter - current_item);
+ if (nk_combo_item_text(ctx, current_item, length, NK_TEXT_LEFT))
+ selected = i;
+ current_item = current_item + length + 1;
+ }
+ nk_combo_end(ctx);
+ }
+ return selected;
+}
+NK_API int
+nk_combo_string(struct nk_context *ctx, const char *items_separated_by_zeros,
+ int selected, int count, int item_height, struct nk_vec2 size)
+{
+ return nk_combo_separator(ctx, items_separated_by_zeros, '\0', selected, count, item_height, size);
+}
+NK_API int
+nk_combo_callback(struct nk_context *ctx, void(*item_getter)(void*, int, const char**),
+ void *userdata, int selected, int count, int item_height, struct nk_vec2 size)
+{
+ int i;
+ int max_height;
+ struct nk_vec2 item_spacing;
+ struct nk_vec2 window_padding;
+ const char *item;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(item_getter);
+ if (!ctx || !item_getter)
+ return selected;
+
+ /* calculate popup window */
+ item_spacing = ctx->style.window.spacing;
+ window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type);
+ max_height = count * item_height + count * (int)item_spacing.y;
+ max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2;
+ size.y = NK_MIN(size.y, (float)max_height);
+
+ item_getter(userdata, selected, &item);
+ if (nk_combo_begin_label(ctx, item, size)) {
+ nk_layout_row_dynamic(ctx, (float)item_height, 1);
+ for (i = 0; i < count; ++i) {
+ item_getter(userdata, i, &item);
+ if (nk_combo_item_label(ctx, item, NK_TEXT_LEFT))
+ selected = i;
+ }
+ nk_combo_end(ctx);
+ } return selected;
+}
+NK_API void
+nk_combobox(struct nk_context *ctx, const char **items, int count,
+ int *selected, int item_height, struct nk_vec2 size)
+{
+ *selected = nk_combo(ctx, items, count, *selected, item_height, size);
+}
+NK_API void
+nk_combobox_string(struct nk_context *ctx, const char *items_separated_by_zeros,
+ int *selected, int count, int item_height, struct nk_vec2 size)
+{
+ *selected = nk_combo_string(ctx, items_separated_by_zeros, *selected, count, item_height, size);
+}
+NK_API void
+nk_combobox_separator(struct nk_context *ctx, const char *items_separated_by_separator,
+ int separator, int *selected, int count, int item_height, struct nk_vec2 size)
+{
+ *selected = nk_combo_separator(ctx, items_separated_by_separator, separator,
+ *selected, count, item_height, size);
+}
+NK_API void
+nk_combobox_callback(struct nk_context *ctx,
+ void(*item_getter)(void* data, int id, const char **out_text),
+ void *userdata, int *selected, int count, int item_height, struct nk_vec2 size)
+{
+ *selected = nk_combo_callback(ctx, item_getter, userdata, *selected, count, item_height, size);
+}
+
+
+
+
+
+/* ===============================================================
+ *
+ * TOOLTIP
+ *
+ * ===============================================================*/
+NK_API nk_bool
+nk_tooltip_begin(struct nk_context *ctx, float width)
+{
+ int x,y,w,h;
+ struct nk_window *win;
+ const struct nk_input *in;
+ struct nk_rect bounds;
+ int ret;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ if (!ctx || !ctx->current || !ctx->current->layout)
+ return 0;
+
+ /* make sure that no nonblocking popup is currently active */
+ win = ctx->current;
+ in = &ctx->input;
+ if (win->popup.win && ((int)win->popup.type & (int)NK_PANEL_SET_NONBLOCK))
+ return 0;
+
+ w = nk_iceilf(width);
+ h = nk_iceilf(nk_null_rect.h);
+ x = nk_ifloorf(in->mouse.pos.x + 1) - (int)win->layout->clip.x;
+ y = nk_ifloorf(in->mouse.pos.y + 1) - (int)win->layout->clip.y;
+
+ bounds.x = (float)x;
+ bounds.y = (float)y;
+ bounds.w = (float)w;
+ bounds.h = (float)h;
+
+ ret = nk_popup_begin(ctx, NK_POPUP_DYNAMIC,
+ "__##Tooltip##__", NK_WINDOW_NO_SCROLLBAR|NK_WINDOW_BORDER, bounds);
+ if (ret) win->layout->flags &= ~(nk_flags)NK_WINDOW_ROM;
+ win->popup.type = NK_PANEL_TOOLTIP;
+ ctx->current->layout->type = NK_PANEL_TOOLTIP;
+ return ret;
+}
+
+NK_API void
+nk_tooltip_end(struct nk_context *ctx)
+{
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ if (!ctx || !ctx->current) return;
+ ctx->current->seq--;
+ nk_popup_close(ctx);
+ nk_popup_end(ctx);
+}
+NK_API void
+nk_tooltip(struct nk_context *ctx, const char *text)
+{
+ const struct nk_style *style;
+ struct nk_vec2 padding;
+
+ int text_len;
+ float text_width;
+ float text_height;
+
+ NK_ASSERT(ctx);
+ NK_ASSERT(ctx->current);
+ NK_ASSERT(ctx->current->layout);
+ NK_ASSERT(text);
+ if (!ctx || !ctx->current || !ctx->current->layout || !text)
+ return;
+
+ /* fetch configuration data */
+ style = &ctx->style;
+ padding = style->window.padding;
+
+ /* calculate size of the text and tooltip */
+ text_len = nk_strlen(text);
+ text_width = style->font->width(style->font->userdata,
+ style->font->height, text, text_len);
+ text_width += (4 * padding.x);
+ text_height = (style->font->height + 2 * padding.y);
+
+ /* execute tooltip and fill with text */
+ if (nk_tooltip_begin(ctx, (float)text_width)) {
+ nk_layout_row_dynamic(ctx, (float)text_height, 1);
+ nk_text(ctx, text, text_len, NK_TEXT_LEFT);
+ nk_tooltip_end(ctx);
+ }
+}
+#ifdef NK_INCLUDE_STANDARD_VARARGS
+NK_API void
+nk_tooltipf(struct nk_context *ctx, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ nk_tooltipfv(ctx, fmt, args);
+ va_end(args);
+}
+NK_API void
+nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args)
+{
+ char buf[256];
+ nk_strfmt(buf, NK_LEN(buf), fmt, args);
+ nk_tooltip(ctx, buf);
+}
+#endif
+
+
+
+#endif /* NK_IMPLEMENTATION */
+
+/*
+/// ## License
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~none
+/// ------------------------------------------------------------------------------
+/// This software is available under 2 licenses -- choose whichever you prefer.
+/// ------------------------------------------------------------------------------
+/// ALTERNATIVE A - MIT License
+/// Copyright (c) 2016-2018 Micha Mettke
+/// Permission is hereby granted, free of charge, to any person obtaining a copy of
+/// this software and associated documentation files (the "Software"), to deal in
+/// the Software without restriction, including without limitation the rights to
+/// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+/// of the Software, and to permit persons to whom the Software is furnished to do
+/// so, subject to the following conditions:
+/// The above copyright notice and this permission notice shall be included in all
+/// copies or substantial portions of the Software.
+/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+/// SOFTWARE.
+/// ------------------------------------------------------------------------------
+/// ALTERNATIVE B - Public Domain (www.unlicense.org)
+/// This is free and unencumbered software released into the public domain.
+/// Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+/// software, either in source code form or as a compiled binary, for any purpose,
+/// commercial or non-commercial, and by any means.
+/// In jurisdictions that recognize copyright laws, the author or authors of this
+/// software dedicate any and all copyright interest in the software to the public
+/// domain. We make this dedication for the benefit of the public at large and to
+/// the detriment of our heirs and successors. We intend this dedication to be an
+/// overt act of relinquishment in perpetuity of all present and future rights to
+/// this software under copyright law.
+/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+/// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+/// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+/// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+/// ------------------------------------------------------------------------------
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+/// ## Changelog
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~none
+/// [date] ([x.y.z]) - [description]
+/// - [date]: date on which the change has been pushed
+/// - [x.y.z]: Version string, represented in Semantic Versioning format
+/// - [x]: Major version with API and library breaking changes
+/// - [y]: Minor version with non-breaking API and library changes
+/// - [z]: Patch version with no direct changes to the API
+///
+/// - 2024/03/07 (4.12.1) - Fix bitwise operations warnings in C++20
+/// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons.
+/// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end()
+/// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake()
+/// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly
+/// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0
+/// - 2022/09/03 (4.10.3) - Renamed the `null` texture variable to `tex_null`
+/// - 2022/08/01 (4.10.2) - Fix Apple Silicon with incorrect NK_SITE_TYPE and NK_POINTER_TYPE
+/// - 2022/08/01 (4.10.1) - Fix cursor jumping back to beginning of text when typing more than
+/// nk_edit_xxx limit
+/// - 2022/05/27 (4.10.0) - Add nk_input_has_mouse_click_in_button_rect() to fix window move bug
+/// - 2022/04/19 (4.9.8) - Added nk_rule_horizontal() widget
+/// - 2022/04/18 (4.9.7) - Change button behavior when NK_BUTTON_TRIGGER_ON_RELEASE is defined to
+/// only trigger when the mouse position was inside the same button on down
+/// - 2022/02/03 (4.9.6) - Allow overriding the NK_INV_SQRT function, similar to NK_SIN and NK_COS
+/// - 2021/12/22 (4.9.5) - Revert layout bounds not accounting for padding due to regressions
+/// - 2021/12/22 (4.9.4) - Fix checking hovering when window is minimized
+/// - 2021/12/22 (4.09.3) - Fix layout bounds not accounting for padding
+/// - 2021/12/19 (4.09.2) - Update to stb_rect_pack.h v1.01 and stb_truetype.h v1.26
+/// - 2021/12/16 (4.09.1) - Fix the majority of GCC warnings
+/// - 2021/10/16 (4.09.0) - Added nk_spacer() widget
+/// - 2021/09/22 (4.08.6) - Fix "may be used uninitialized" warnings in nk_widget
+/// - 2021/09/22 (4.08.5) - GCC __builtin_offsetof only exists in version 4 and later
+/// - 2021/09/15 (4.08.4) - Fix "'num_len' may be used uninitialized" in nk_do_property
+/// - 2021/09/15 (4.08.3) - Fix "Templates cannot be declared to have 'C' Linkage"
+/// - 2021/09/08 (4.08.2) - Fix warnings in C89 builds
+/// - 2021/09/08 (4.08.1) - Use compiler builtins for NK_OFFSETOF when possible
+/// - 2021/08/17 (4.08.0) - Implemented 9-slice scaling support for widget styles
+/// - 2021/08/16 (4.07.5) - Replace usage of memset in nk_font_atlas_bake with NK_MEMSET
+/// - 2021/08/15 (4.07.4) - Fix conversion and sign conversion warnings
+/// - 2021/08/08 (4.07.3) - Fix crash when baking merged fonts
+/// - 2021/08/08 (4.07.2) - Fix Multiline Edit wrong offset
+/// - 2021/03/17 (4.07.1) - Fix warning about unused parameter
+/// - 2021/03/17 (4.07.0) - Fix nk_property hover bug
+/// - 2021/03/15 (4.06.4) - Change nk_propertyi back to int
+/// - 2021/03/15 (4.06.3) - Update documentation for functions that now return nk_bool
+/// - 2020/12/19 (4.06.2) - Fix additional C++ style comments which are not allowed in ISO C90.
+/// - 2020/10/11 (4.06.1) - Fix C++ style comments which are not allowed in ISO C90.
+/// - 2020/10/07 (4.06.0) - Fix nk_combo return type wrongly changed to nk_bool
+/// - 2020/09/05 (4.05.0) - Use the nk_font_atlas allocator for stb_truetype memory management.
+/// - 2020/09/04 (4.04.1) - Replace every boolean int by nk_bool
+/// - 2020/09/04 (4.04.0) - Add nk_bool with NK_INCLUDE_STANDARD_BOOL
+/// - 2020/06/13 (4.03.1) - Fix nk_pool allocation sizes.
+/// - 2020/06/04 (4.03.0) - Made nk_combo header symbols optional.
+/// - 2020/05/27 (4.02.5) - Fix nk_do_edit: Keep scroll position when re-activating edit widget.
+/// - 2020/05/09 (4.02.4) - Fix nk_menubar height calculation bug
+/// - 2020/05/08 (4.02.3) - Fix missing stdarg.h with NK_INCLUDE_STANDARD_VARARGS
+/// - 2020/04/30 (4.02.2) - Fix nk_edit border drawing bug
+/// - 2020/04/09 (4.02.1) - Removed unused nk_sqrt function to fix compiler warnings
+/// - Fixed compiler warnings if you bring your own methods for
+/// nk_cos/nk_sin/nk_strtod/nk_memset/nk_memcopy/nk_dtoa
+/// - 2020/04/06 (4.01.10) - Fix bug: Do not use pool before checking for NULL
+/// - 2020/03/22 (4.01.9) - Fix bug where layout state wasn't restored correctly after
+/// popping a tree.
+/// - 2020/03/11 (4.01.8) - Fix bug where padding is subtracted from widget
+/// - 2020/03/06 (4.01.7) - Fix bug where width padding was applied twice
+/// - 2020/02/06 (4.01.6) - Update stb_truetype.h and stb_rect_pack.h and separate them
+/// - 2019/12/10 (4.01.5) - Fix off-by-one error in NK_INTERSECT
+/// - 2019/10/09 (4.01.4) - Fix bug for autoscrolling in nk_do_edit
+/// - 2019/09/20 (4.01.3) - Fixed a bug wherein combobox cannot be closed by clicking the header
+/// when NK_BUTTON_TRIGGER_ON_RELEASE is defined.
+/// - 2019/09/10 (4.01.2) - Fixed the nk_cos function, which deviated significantly.
+/// - 2019/09/08 (4.01.1) - Fixed a bug wherein re-baking of fonts caused a segmentation
+/// fault due to dst_font->glyph_count not being zeroed on subsequent
+/// bakes of the same set of fonts.
+/// - 2019/06/23 (4.01.0) - Added nk_***_get_scroll and nk_***_set_scroll for groups, windows, and popups.
+/// - 2019/06/12 (4.00.3) - Fix panel background drawing bug.
+/// - 2018/10/31 (4.00.2) - Added NK_KEYSTATE_BASED_INPUT to "fix" state based backends
+/// like GLFW without breaking key repeat behavior on event based.
+/// - 2018/04/01 (4.00.1) - Fixed calling `nk_convert` multiple time per single frame.
+/// - 2018/04/01 (4.00.0) - BREAKING CHANGE: nk_draw_list_clear no longer tries to
+/// clear provided buffers. So make sure to either free
+/// or clear each passed buffer after calling nk_convert.
+/// - 2018/02/23 (3.00.6) - Fixed slider dragging behavior.
+/// - 2018/01/31 (3.00.5) - Fixed overcalculation of cursor data in font baking process.
+/// - 2018/01/31 (3.00.4) - Removed name collision with stb_truetype.
+/// - 2018/01/28 (3.00.3) - Fixed panel window border drawing bug.
+/// - 2018/01/12 (3.00.2) - Added `nk_group_begin_titled` for separated group identifier and title.
+/// - 2018/01/07 (3.00.1) - Started to change documentation style.
+/// - 2018/01/05 (3.00.0) - BREAKING CHANGE: The previous color picker API was broken
+/// because of conversions between float and byte color representation.
+/// Color pickers now use floating point values to represent
+/// HSV values. To get back the old behavior I added some additional
+/// color conversion functions to cast between nk_color and
+/// nk_colorf.
+/// - 2017/12/23 (2.00.7) - Fixed small warning.
+/// - 2017/12/23 (2.00.7) - Fixed `nk_edit_buffer` behavior if activated to allow input.
+/// - 2017/12/23 (2.00.7) - Fixed modifyable progressbar dragging visuals and input behavior.
+/// - 2017/12/04 (2.00.6) - Added formatted string tooltip widget.
+/// - 2017/11/18 (2.00.5) - Fixed window becoming hidden with flag `NK_WINDOW_NO_INPUT`.
+/// - 2017/11/15 (2.00.4) - Fixed font merging.
+/// - 2017/11/07 (2.00.3) - Fixed window size and position modifier functions.
+/// - 2017/09/14 (2.00.2) - Fixed `nk_edit_buffer` and `nk_edit_focus` behavior.
+/// - 2017/09/14 (2.00.1) - Fixed window closing behavior.
+/// - 2017/09/14 (2.00.0) - BREAKING CHANGE: Modifying window position and size functions now
+/// require the name of the window and must happen outside the window
+/// building process (between function call nk_begin and nk_end).
+/// - 2017/09/11 (1.40.9) - Fixed window background flag if background window is declared last.
+/// - 2017/08/27 (1.40.8) - Fixed `nk_item_is_any_active` for hidden windows.
+/// - 2017/08/27 (1.40.7) - Fixed window background flag.
+/// - 2017/07/07 (1.40.6) - Fixed missing clipping rect check for hovering/clicked
+/// query for widgets.
+/// - 2017/07/07 (1.40.5) - Fixed drawing bug for vertex output for lines and stroked
+/// and filled rectangles.
+/// - 2017/07/07 (1.40.4) - Fixed bug in nk_convert trying to add windows that are in
+/// process of being destroyed.
+/// - 2017/07/07 (1.40.3) - Fixed table internal bug caused by storing table size in
+/// window instead of directly in table.
+/// - 2017/06/30 (1.40.2) - Removed unneeded semicolon in C++ NK_ALIGNOF macro.
+/// - 2017/06/30 (1.40.1) - Fixed drawing lines smaller or equal zero.
+/// - 2017/06/08 (1.40.0) - Removed the breaking part of last commit. Auto layout now only
+/// comes in effect if you pass in zero was row height argument.
+/// - 2017/06/08 (1.40.0) - BREAKING CHANGE: while not directly API breaking it will change
+/// how layouting works. From now there will be an internal minimum
+/// row height derived from font height. If you need a row smaller than
+/// that you can directly set it by `nk_layout_set_min_row_height` and
+/// reset the value back by calling `nk_layout_reset_min_row_height.
+/// - 2017/06/08 (1.39.1) - Fixed property text edit handling bug caused by past `nk_widget` fix.
+/// - 2017/06/08 (1.39.0) - Added function to retrieve window space without calling a `nk_layout_xxx` function.
+/// - 2017/06/06 (1.38.5) - Fixed `nk_convert` return flag for command buffer.
+/// - 2017/05/23 (1.38.4) - Fixed activation behavior for widgets partially clipped.
+/// - 2017/05/10 (1.38.3) - Fixed wrong min window size mouse scaling over boundaries.
+/// - 2017/05/09 (1.38.2) - Fixed vertical scrollbar drawing with not enough space.
+/// - 2017/05/09 (1.38.1) - Fixed scaler dragging behavior if window size hits minimum size.
+/// - 2017/05/06 (1.38.0) - Added platform double-click support.
+/// - 2017/04/20 (1.37.1) - Fixed key repeat found inside glfw demo backends.
+/// - 2017/04/20 (1.37.0) - Extended properties with selection and clipboard support.
+/// - 2017/04/20 (1.36.2) - Fixed #405 overlapping rows with zero padding and spacing.
+/// - 2017/04/09 (1.36.1) - Fixed #403 with another widget float error.
+/// - 2017/04/09 (1.36.0) - Added window `NK_WINDOW_NO_INPUT` and `NK_WINDOW_NOT_INTERACTIVE` flags.
+/// - 2017/04/09 (1.35.3) - Fixed buffer heap corruption.
+/// - 2017/03/25 (1.35.2) - Fixed popup overlapping for `NK_WINDOW_BACKGROUND` windows.
+/// - 2017/03/25 (1.35.1) - Fixed windows closing behavior.
+/// - 2017/03/18 (1.35.0) - Added horizontal scroll requested in #377.
+/// - 2017/03/18 (1.34.3) - Fixed long window header titles.
+/// - 2017/03/04 (1.34.2) - Fixed text edit filtering.
+/// - 2017/03/04 (1.34.1) - Fixed group closable flag.
+/// - 2017/02/25 (1.34.0) - Added custom draw command for better language binding support.
+/// - 2017/01/24 (1.33.0) - Added programmatic way to remove edit focus.
+/// - 2017/01/24 (1.32.3) - Fixed wrong define for basic type definitions for windows.
+/// - 2017/01/21 (1.32.2) - Fixed input capture from hidden or closed windows.
+/// - 2017/01/21 (1.32.1) - Fixed slider behavior and drawing.
+/// - 2017/01/13 (1.32.0) - Added flag to put scaler into the bottom left corner.
+/// - 2017/01/13 (1.31.0) - Added additional row layouting method to combine both
+/// dynamic and static widgets.
+/// - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit.
+/// - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows.
+/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error.
+/// - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters.
+/// - 2016/11/22 (1.28.6) - Fixed window minimized closing bug.
+/// - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior.
+/// - 2016/11/19 (1.28.4) - Fixed tooltip flickering.
+/// - 2016/11/19 (1.28.3) - Fixed memory leak caused by popup repeated closing.
+/// - 2016/11/18 (1.28.2) - Fixed memory leak caused by popup panel allocation.
+/// - 2016/11/10 (1.28.1) - Fixed some warnings and C++ error.
+/// - 2016/11/10 (1.28.0) - Added additional `nk_button` versions which allows to directly
+/// pass in a style struct to change buttons visual.
+/// - 2016/11/10 (1.27.0) - Added additional `nk_tree` versions to support external state
+/// storage. Just like last the `nk_group` commit the main
+/// advantage is that you optionally can minimize nuklears runtime
+/// memory consumption or handle hash collisions.
+/// - 2016/11/09 (1.26.0) - Added additional `nk_group` version to support external scrollbar
+/// offset storage. Main advantage is that you can externalize
+/// the memory management for the offset. It could also be helpful
+/// if you have a hash collision in `nk_group_begin` but really
+/// want the name. In addition I added `nk_list_view` which allows
+/// to draw big lists inside a group without actually having to
+/// commit the whole list to nuklear (issue #269).
+/// - 2016/10/30 (1.25.1) - Fixed clipping rectangle bug inside `nk_draw_list`.
+/// - 2016/10/29 (1.25.0) - Pulled `nk_panel` memory management into nuklear and out of
+/// the hands of the user. From now on users don't have to care
+/// about panels unless they care about some information. If you
+/// still need the panel just call `nk_window_get_panel`.
+/// - 2016/10/21 (1.24.0) - Changed widget border drawing to stroked rectangle from filled
+/// rectangle for less overdraw and widget background transparency.
+/// - 2016/10/18 (1.23.0) - Added `nk_edit_focus` for manually edit widget focus control.
+/// - 2016/09/29 (1.22.7) - Fixed deduction of basic type in non `` compilation.
+/// - 2016/09/29 (1.22.6) - Fixed edit widget UTF-8 text cursor drawing bug.
+/// - 2016/09/28 (1.22.5) - Fixed edit widget UTF-8 text appending/inserting/removing.
+/// - 2016/09/28 (1.22.4) - Fixed drawing bug inside edit widgets which offset all text
+/// text in every edit widget if one of them is scrolled.
+/// - 2016/09/28 (1.22.3) - Fixed small bug in edit widgets if not active. The wrong
+/// text length is passed. It should have been in bytes but
+/// was passed as glyphs.
+/// - 2016/09/20 (1.22.2) - Fixed color button size calculation.
+/// - 2016/09/20 (1.22.1) - Fixed some `nk_vsnprintf` behavior bugs and removed ``
+/// again from `NK_INCLUDE_STANDARD_VARARGS`.
+/// - 2016/09/18 (1.22.0) - C89 does not support vsnprintf only C99 and newer as well
+/// as C++11 and newer. In addition to use vsnprintf you have
+/// to include . So just defining `NK_INCLUDE_STD_VAR_ARGS`
+/// is not enough. That behavior is now fixed. By default if
+/// both varargs as well as stdio is selected I try to use
+/// vsnprintf if not possible I will revert to vsprintf. If
+/// varargs but not stdio was defined I will use my own function.
+/// - 2016/09/15 (1.21.2) - Fixed panel `close` behavior for deeper panel levels.
+/// - 2016/09/15 (1.21.1) - Fixed C++ errors and wrong argument to `nk_panel_get_xxxx`.
+/// - 2016/09/13 (1.21.0) - !BREAKING! Fixed nonblocking popup behavior in menu, combo,
+/// and contextual which prevented closing in y-direction if
+/// popup did not reach max height.
+/// In addition the height parameter was changed into vec2
+/// for width and height to have more control over the popup size.
+/// - 2016/09/13 (1.20.3) - Cleaned up and extended type selection.
+/// - 2016/09/13 (1.20.2) - Fixed slider behavior hopefully for the last time. This time
+/// all calculation are correct so no more hackery.
+/// - 2016/09/13 (1.20.1) - Internal change to divide window/panel flags into panel flags and types.
+/// Suprisinly spend years in C and still happened to confuse types
+/// with flags. Probably something to take note.
+/// - 2016/09/08 (1.20.0) - Added additional helper function to make it easier to just
+/// take the produced buffers from `nk_convert` and unplug the
+/// iteration process from `nk_context`. So now you can
+/// just use the vertex,element and command buffer + two pointer
+/// inside the command buffer retrieved by calls `nk__draw_begin`
+/// and `nk__draw_end` and macro `nk_draw_foreach_bounded`.
+/// - 2016/09/08 (1.19.0) - Added additional asserts to make sure every `nk_xxx_begin` call
+/// for windows, popups, combobox, menu and contextual is guarded by
+/// `if` condition and does not produce false drawing output.
+/// - 2016/09/08 (1.18.0) - Changed confusing name for `NK_SYMBOL_RECT_FILLED`, `NK_SYMBOL_RECT`
+/// to hopefully easier to understand `NK_SYMBOL_RECT_FILLED` and
+/// `NK_SYMBOL_RECT_OUTLINE`.
+/// - 2016/09/08 (1.17.0) - Changed confusing name for `NK_SYMBOL_CIRLCE_FILLED`, `NK_SYMBOL_CIRCLE`
+/// to hopefully easier to understand `NK_SYMBOL_CIRCLE_FILLED` and
+/// `NK_SYMBOL_CIRCLE_OUTLINE`.
+/// - 2016/09/08 (1.16.0) - Added additional checks to select correct types if `NK_INCLUDE_FIXED_TYPES`
+/// is not defined by supporting the biggest compiler GCC, clang and MSVC.
+/// - 2016/09/07 (1.15.3) - Fixed `NK_INCLUDE_COMMAND_USERDATA` define to not cause an error.
+/// - 2016/09/04 (1.15.2) - Fixed wrong combobox height calculation.
+/// - 2016/09/03 (1.15.1) - Fixed gaps inside combo boxes in OpenGL.
+/// - 2016/09/02 (1.15.0) - Changed nuklear to not have any default vertex layout and
+/// instead made it user provided. The range of types to convert
+/// to is quite limited at the moment, but I would be more than
+/// happy to accept PRs to add additional.
+/// - 2016/08/30 (1.14.2) - Removed unused variables.
+/// - 2016/08/30 (1.14.1) - Fixed C++ build errors.
+/// - 2016/08/30 (1.14.0) - Removed mouse dragging from SDL demo since it does not work correctly.
+/// - 2016/08/30 (1.13.4) - Tweaked some default styling variables.
+/// - 2016/08/30 (1.13.3) - Hopefully fixed drawing bug in slider, in general I would
+/// refrain from using slider with a big number of steps.
+/// - 2016/08/30 (1.13.2) - Fixed close and minimize button which would fire even if the
+/// window was in Read Only Mode.
+/// - 2016/08/30 (1.13.1) - Fixed popup panel padding handling which was previously just
+/// a hack for combo box and menu.
+/// - 2016/08/30 (1.13.0) - Removed `NK_WINDOW_DYNAMIC` flag from public API since
+/// it is bugged and causes issues in window selection.
+/// - 2016/08/30 (1.12.0) - Removed scaler size. The size of the scaler is now
+/// determined by the scrollbar size.
+/// - 2016/08/30 (1.11.2) - Fixed some drawing bugs caused by changes from 1.11.0.
+/// - 2016/08/30 (1.11.1) - Fixed overlapping minimized window selection.
+/// - 2016/08/30 (1.11.0) - Removed some internal complexity and overly complex code
+/// handling panel padding and panel border.
+/// - 2016/08/29 (1.10.0) - Added additional height parameter to `nk_combobox_xxx`.
+/// - 2016/08/29 (1.10.0) - Fixed drawing bug in dynamic popups.
+/// - 2016/08/29 (1.10.0) - Added experimental mouse scrolling to popups, menus and comboboxes.
+/// - 2016/08/26 (1.10.0) - Added window name string prepresentation to account for
+/// hash collisions. Currently limited to `NK_WINDOW_MAX_NAME`
+/// which in term can be redefined if not big enough.
+/// - 2016/08/26 (1.10.0) - Added stacks for temporary style/UI changes in code.
+/// - 2016/08/25 (1.10.0) - Changed `nk_input_is_key_pressed` and 'nk_input_is_key_released'
+/// to account for key press and release happening in one frame.
+/// - 2016/08/25 (1.10.0) - Added additional nk_edit flag to directly jump to the end on activate.
+/// - 2016/08/17 (1.09.6) - Removed invalid check for value zero in `nk_propertyx`.
+/// - 2016/08/16 (1.09.5) - Fixed ROM mode for deeper levels of popup windows parents.
+/// - 2016/08/15 (1.09.4) - Editbox are now still active if enter was pressed with flag
+/// `NK_EDIT_SIG_ENTER`. Main reasoning is to be able to keep
+/// typing after committing.
+/// - 2016/08/15 (1.09.4) - Removed redundant code.
+/// - 2016/08/15 (1.09.4) - Fixed negative numbers in `nk_strtoi` and remove unused variable.
+/// - 2016/08/15 (1.09.3) - Fixed `NK_WINDOW_BACKGROUND` flag behavior to select a background
+/// window only as selected by hovering and not by clicking.
+/// - 2016/08/14 (1.09.2) - Fixed a bug in font atlas which caused wrong loading
+/// of glyphs for font with multiple ranges.
+/// - 2016/08/12 (1.09.1) - Added additional function to check if window is currently
+/// hidden and therefore not visible.
+/// - 2016/08/12 (1.09.1) - nk_window_is_closed now queries the correct flag `NK_WINDOW_CLOSED`
+/// instead of the old flag `NK_WINDOW_HIDDEN`.
+/// - 2016/08/09 (1.09.0) - Added additional double version to nk_property and changed
+/// the underlying implementation to not cast to float and instead
+/// work directly on the given values.
+/// - 2016/08/09 (1.08.0) - Added additional define to overwrite library internal
+/// floating pointer number to string conversion for additional
+/// precision.
+/// - 2016/08/09 (1.08.0) - Added additional define to overwrite library internal
+/// string to floating point number conversion for additional
+/// precision.
+/// - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`.
+/// - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading
+/// to wrong widget width calculation which results in widgets falsely
+/// becoming tagged as not inside window and cannot be accessed.
+/// - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and
+/// closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown
+/// by using `nk_window_show` and closed by either clicking the close
+/// icon in a window or by calling `nk_window_close`. Only closed
+/// windows get removed at the end of the frame while hidden windows
+/// remain.
+/// - 2016/08/08 (1.06.0) - Added `nk_edit_string_zero_terminated` as a second option to
+/// `nk_edit_string` which takes, edits and outputs a '\0' terminated string.
+/// - 2016/08/08 (1.05.4) - Fixed scrollbar auto hiding behavior.
+/// - 2016/08/08 (1.05.3) - Fixed wrong panel padding selection in `nk_layout_widget_space`.
+/// - 2016/08/07 (1.05.2) - Fixed old bug in dynamic immediate mode layout API, calculating
+/// wrong item spacing and panel width.
+/// - 2016/08/07 (1.05.1) - Hopefully finally fixed combobox popup drawing bug.
+/// - 2016/08/07 (1.05.0) - Split varargs away from `NK_INCLUDE_STANDARD_IO` into own
+/// define `NK_INCLUDE_STANDARD_VARARGS` to allow more fine
+/// grained controlled over library includes.
+/// - 2016/08/06 (1.04.5) - Changed memset calls to `NK_MEMSET`.
+/// - 2016/08/04 (1.04.4) - Fixed fast window scaling behavior.
+/// - 2016/08/04 (1.04.3) - Fixed window scaling, movement bug which appears if you
+/// move/scale a window and another window is behind it.
+/// If you are fast enough then the window behind gets activated
+/// and the operation is blocked. I now require activating
+/// by hovering only if mouse is not pressed.
+/// - 2016/08/04 (1.04.2) - Fixed changing fonts.
+/// - 2016/08/03 (1.04.1) - Fixed `NK_WINDOW_BACKGROUND` behavior.
+/// - 2016/08/03 (1.04.0) - Added color parameter to `nk_draw_image`.
+/// - 2016/08/03 (1.04.0) - Added additional window padding style attributes for
+/// sub windows (combo, menu, ...).
+/// - 2016/08/03 (1.04.0) - Added functions to show/hide software cursor.
+/// - 2016/08/03 (1.04.0) - Added `NK_WINDOW_BACKGROUND` flag to force a window
+/// to be always in the background of the screen.
+/// - 2016/08/03 (1.03.2) - Removed invalid assert macro for NK_RGB color picker.
+/// - 2016/08/01 (1.03.1) - Added helper macros into header include guard.
+/// - 2016/07/29 (1.03.0) - Moved the window/table pool into the header part to
+/// simplify memory management by removing the need to
+/// allocate the pool.
+/// - 2016/07/29 (1.02.0) - Added auto scrollbar hiding window flag which if enabled
+/// will hide the window scrollbar after NK_SCROLLBAR_HIDING_TIMEOUT
+/// seconds without window interaction. To make it work
+/// you have to also set a delta time inside the `nk_context`.
+/// - 2016/07/25 (1.01.1) - Fixed small panel and panel border drawing bugs.
+/// - 2016/07/15 (1.01.0) - Added software cursor to `nk_style` and `nk_context`.
+/// - 2016/07/15 (1.01.0) - Added const correctness to `nk_buffer_push' data argument.
+/// - 2016/07/15 (1.01.0) - Removed internal font baking API and simplified
+/// font atlas memory management by converting pointer
+/// arrays for fonts and font configurations to lists.
+/// - 2016/07/15 (1.00.0) - Changed button API to use context dependent button
+/// behavior instead of passing it for every function call.
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+/// ## Gallery
+/// ![Figure [blue]: Feature overview with blue color styling](https://cloud.githubusercontent.com/assets/8057201/13538240/acd96876-e249-11e5-9547-5ac0b19667a0.png)
+/// ![Figure [red]: Feature overview with red color styling](https://cloud.githubusercontent.com/assets/8057201/13538243/b04acd4c-e249-11e5-8fd2-ad7744a5b446.png)
+/// ![Figure [widgets]: Widget overview](https://cloud.githubusercontent.com/assets/8057201/11282359/3325e3c6-8eff-11e5-86cb-cf02b0596087.png)
+/// ![Figure [blackwhite]: Black and white](https://cloud.githubusercontent.com/assets/8057201/11033668/59ab5d04-86e5-11e5-8091-c56f16411565.png)
+/// ![Figure [filexp]: File explorer](https://cloud.githubusercontent.com/assets/8057201/10718115/02a9ba08-7b6b-11e5-950f-adacdd637739.png)
+/// ![Figure [opengl]: OpenGL Editor](https://cloud.githubusercontent.com/assets/8057201/12779619/2a20d72c-ca69-11e5-95fe-4edecf820d5c.png)
+/// ![Figure [nodedit]: Node Editor](https://cloud.githubusercontent.com/assets/8057201/9976995/e81ac04a-5ef7-11e5-872b-acd54fbeee03.gif)
+/// ![Figure [skinning]: Using skinning in Nuklear](https://cloud.githubusercontent.com/assets/8057201/15991632/76494854-30b8-11e6-9555-a69840d0d50b.png)
+/// ![Figure [bf]: Heavy modified version](https://cloud.githubusercontent.com/assets/8057201/14902576/339926a8-0d9c-11e6-9fee-a8b73af04473.png)
+///
+/// ## Credits
+/// Developed by Micha Mettke and every direct or indirect github contributor.
+///
+/// Embeds [stb_texedit](https://github.com/nothings/stb/blob/master/stb_textedit.h), [stb_truetype](https://github.com/nothings/stb/blob/master/stb_truetype.h) and [stb_rectpack](https://github.com/nothings/stb/blob/master/stb_rect_pack.h) by Sean Barret (public domain)
+/// Uses [stddoc.c](https://github.com/r-lyeh/stddoc.c) from r-lyeh@github.com for documentation generation
+/// Embeds ProggyClean.ttf font by Tristan Grimmer (MIT license).
+///
+/// Big thank you to Omar Cornut (ocornut@github) for his [imgui library](https://github.com/ocornut/imgui) and
+/// giving me the inspiration for this library, Casey Muratori for handmade hero
+/// and his original immediate mode graphical user interface idea and Sean
+/// Barret for his amazing single header libraries which restored my faith
+/// in libraries and brought me to create some of my own. Finally Apoorva Joshi
+/// for his single header file packer.
+*/
+
diff --git a/external/nuklear/nuklear_sdl_gl3.h b/external/nuklear/nuklear_sdl_gl3.h
new file mode 100644
index 0000000..10a8f59
--- /dev/null
+++ b/external/nuklear/nuklear_sdl_gl3.h
@@ -0,0 +1,459 @@
+/*
+ * Nuklear - 1.32.0 - public domain
+ * no warrenty implied; use at your own risk.
+ * authored from 2015-2016 by Micha Mettke
+ */
+/*
+ * ==============================================================
+ *
+ * API
+ *
+ * ===============================================================
+ */
+#ifndef NK_SDL_GL3_H_
+#define NK_SDL_GL3_H_
+
+#include
+#include
+
+NK_API struct nk_context* nk_sdl_init(SDL_Window *win);
+NK_API void nk_sdl_font_stash_begin(struct nk_font_atlas **atlas);
+NK_API void nk_sdl_font_stash_end(void);
+NK_API int nk_sdl_handle_event(SDL_Event *evt);
+NK_API void nk_sdl_render(enum nk_anti_aliasing , int max_vertex_buffer, int max_element_buffer);
+NK_API void nk_sdl_shutdown(void);
+NK_API void nk_sdl_device_destroy(void);
+NK_API void nk_sdl_device_create(void);
+
+#endif
+
+/*
+ * ==============================================================
+ *
+ * IMPLEMENTATION
+ *
+ * ===============================================================
+ */
+#ifdef NK_SDL_GL3_IMPLEMENTATION
+
+#include
+#include
+#include
+
+struct nk_sdl_device {
+ struct nk_buffer cmds;
+ struct nk_draw_null_texture tex_null;
+ GLuint vbo, vao, ebo;
+ GLuint prog;
+ GLuint vert_shdr;
+ GLuint frag_shdr;
+ GLint attrib_pos;
+ GLint attrib_uv;
+ GLint attrib_col;
+ GLint uniform_tex;
+ GLint uniform_proj;
+ GLuint font_tex;
+};
+
+struct nk_sdl_vertex {
+ float position[2];
+ float uv[2];
+ nk_byte col[4];
+};
+
+static struct nk_sdl {
+ SDL_Window *win;
+ struct nk_sdl_device ogl;
+ struct nk_context ctx;
+ struct nk_font_atlas atlas;
+} sdl;
+
+#ifdef __APPLE__
+ #define NK_SHADER_VERSION "#version 150\n"
+#else
+ #define NK_SHADER_VERSION "#version 300 es\n"
+#endif
+NK_API void
+nk_sdl_device_create(void)
+{
+ GLint status;
+ static const GLchar *vertex_shader =
+ NK_SHADER_VERSION
+ "uniform mat4 ProjMtx;\n"
+ "in vec2 Position;\n"
+ "in vec2 TexCoord;\n"
+ "in vec4 Color;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main() {\n"
+ " Frag_UV = TexCoord;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n"
+ "}\n";
+ static const GLchar *fragment_shader =
+ NK_SHADER_VERSION
+ "precision mediump float;\n"
+ "uniform sampler2D Texture;\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "out vec4 Out_Color;\n"
+ "void main(){\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
+
+ struct nk_sdl_device *dev = &sdl.ogl;
+ nk_buffer_init_default(&dev->cmds);
+ dev->prog = glCreateProgram();
+ dev->vert_shdr = glCreateShader(GL_VERTEX_SHADER);
+ dev->frag_shdr = glCreateShader(GL_FRAGMENT_SHADER);
+ glShaderSource(dev->vert_shdr, 1, &vertex_shader, 0);
+ glShaderSource(dev->frag_shdr, 1, &fragment_shader, 0);
+ glCompileShader(dev->vert_shdr);
+ glCompileShader(dev->frag_shdr);
+ glGetShaderiv(dev->vert_shdr, GL_COMPILE_STATUS, &status);
+ assert(status == GL_TRUE);
+ glGetShaderiv(dev->frag_shdr, GL_COMPILE_STATUS, &status);
+ assert(status == GL_TRUE);
+ glAttachShader(dev->prog, dev->vert_shdr);
+ glAttachShader(dev->prog, dev->frag_shdr);
+ glLinkProgram(dev->prog);
+ glGetProgramiv(dev->prog, GL_LINK_STATUS, &status);
+ assert(status == GL_TRUE);
+
+ dev->uniform_tex = glGetUniformLocation(dev->prog, "Texture");
+ dev->uniform_proj = glGetUniformLocation(dev->prog, "ProjMtx");
+ dev->attrib_pos = glGetAttribLocation(dev->prog, "Position");
+ dev->attrib_uv = glGetAttribLocation(dev->prog, "TexCoord");
+ dev->attrib_col = glGetAttribLocation(dev->prog, "Color");
+
+ {
+ /* buffer setup */
+ GLsizei vs = sizeof(struct nk_sdl_vertex);
+ size_t vp = offsetof(struct nk_sdl_vertex, position);
+ size_t vt = offsetof(struct nk_sdl_vertex, uv);
+ size_t vc = offsetof(struct nk_sdl_vertex, col);
+
+ glGenBuffers(1, &dev->vbo);
+ glGenBuffers(1, &dev->ebo);
+ glGenVertexArrays(1, &dev->vao);
+
+ glBindVertexArray(dev->vao);
+ glBindBuffer(GL_ARRAY_BUFFER, dev->vbo);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dev->ebo);
+
+ glEnableVertexAttribArray((GLuint)dev->attrib_pos);
+ glEnableVertexAttribArray((GLuint)dev->attrib_uv);
+ glEnableVertexAttribArray((GLuint)dev->attrib_col);
+
+ glVertexAttribPointer((GLuint)dev->attrib_pos, 2, GL_FLOAT, GL_FALSE, vs, (void*)vp);
+ glVertexAttribPointer((GLuint)dev->attrib_uv, 2, GL_FLOAT, GL_FALSE, vs, (void*)vt);
+ glVertexAttribPointer((GLuint)dev->attrib_col, 4, GL_UNSIGNED_BYTE, GL_TRUE, vs, (void*)vc);
+ }
+
+ glBindTexture(GL_TEXTURE_2D, 0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glBindVertexArray(0);
+}
+
+NK_INTERN void
+nk_sdl_device_upload_atlas(const void *image, int width, int height)
+{
+ struct nk_sdl_device *dev = &sdl.ogl;
+ glGenTextures(1, &dev->font_tex);
+ glBindTexture(GL_TEXTURE_2D, dev->font_tex);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, 0,
+ GL_RGBA, GL_UNSIGNED_BYTE, image);
+}
+
+NK_API void
+nk_sdl_device_destroy(void)
+{
+ struct nk_sdl_device *dev = &sdl.ogl;
+ glDetachShader(dev->prog, dev->vert_shdr);
+ glDetachShader(dev->prog, dev->frag_shdr);
+ glDeleteShader(dev->vert_shdr);
+ glDeleteShader(dev->frag_shdr);
+ glDeleteProgram(dev->prog);
+ glDeleteTextures(1, &dev->font_tex);
+ glDeleteBuffers(1, &dev->vbo);
+ glDeleteBuffers(1, &dev->ebo);
+ nk_buffer_free(&dev->cmds);
+}
+
+NK_API void
+nk_sdl_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_buffer)
+{
+ struct nk_sdl_device *dev = &sdl.ogl;
+ int width, height;
+ int display_width, display_height;
+ struct nk_vec2 scale;
+ GLfloat ortho[4][4] = {
+ {2.0f, 0.0f, 0.0f, 0.0f},
+ {0.0f,-2.0f, 0.0f, 0.0f},
+ {0.0f, 0.0f,-1.0f, 0.0f},
+ {-1.0f,1.0f, 0.0f, 1.0f},
+ };
+ SDL_GetWindowSize(sdl.win, &width, &height);
+ SDL_GL_GetDrawableSize(sdl.win, &display_width, &display_height);
+ ortho[0][0] /= (GLfloat)width;
+ ortho[1][1] /= (GLfloat)height;
+
+ scale.x = (float)display_width/(float)width;
+ scale.y = (float)display_height/(float)height;
+
+ /* setup global state */
+ glViewport(0,0,display_width,display_height);
+ glEnable(GL_BLEND);
+ glBlendEquation(GL_FUNC_ADD);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glDisable(GL_CULL_FACE);
+ glDisable(GL_DEPTH_TEST);
+ glEnable(GL_SCISSOR_TEST);
+ glActiveTexture(GL_TEXTURE0);
+
+ /* setup program */
+ glUseProgram(dev->prog);
+ glUniform1i(dev->uniform_tex, 0);
+ glUniformMatrix4fv(dev->uniform_proj, 1, GL_FALSE, &ortho[0][0]);
+ {
+ /* convert from command queue into draw list and draw to screen */
+ const struct nk_draw_command *cmd;
+ void *vertices, *elements;
+ const nk_draw_index *offset = NULL;
+ struct nk_buffer vbuf, ebuf;
+
+ /* allocate vertex and element buffer */
+ glBindVertexArray(dev->vao);
+ glBindBuffer(GL_ARRAY_BUFFER, dev->vbo);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dev->ebo);
+
+ glBufferData(GL_ARRAY_BUFFER, max_vertex_buffer, NULL, GL_STREAM_DRAW);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, max_element_buffer, NULL, GL_STREAM_DRAW);
+
+ /* load vertices/elements directly into vertex/element buffer */
+ vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
+ elements = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY);
+ {
+ /* fill convert configuration */
+ struct nk_convert_config config;
+ static const struct nk_draw_vertex_layout_element vertex_layout[] = {
+ {NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_sdl_vertex, position)},
+ {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_sdl_vertex, uv)},
+ {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, NK_OFFSETOF(struct nk_sdl_vertex, col)},
+ {NK_VERTEX_LAYOUT_END}
+ };
+ memset(&config, 0, sizeof(config));
+ config.vertex_layout = vertex_layout;
+ config.vertex_size = sizeof(struct nk_sdl_vertex);
+ config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex);
+ config.tex_null = dev->tex_null;
+ config.circle_segment_count = 22;
+ config.curve_segment_count = 22;
+ config.arc_segment_count = 22;
+ config.global_alpha = 1.0f;
+ config.shape_AA = AA;
+ config.line_AA = AA;
+
+ /* setup buffers to load vertices and elements */
+ nk_buffer_init_fixed(&vbuf, vertices, (nk_size)max_vertex_buffer);
+ nk_buffer_init_fixed(&ebuf, elements, (nk_size)max_element_buffer);
+ nk_convert(&sdl.ctx, &dev->cmds, &vbuf, &ebuf, &config);
+ }
+ glUnmapBuffer(GL_ARRAY_BUFFER);
+ glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
+
+ /* iterate over and execute each draw command */
+ nk_draw_foreach(cmd, &sdl.ctx, &dev->cmds) {
+ if (!cmd->elem_count) continue;
+ glBindTexture(GL_TEXTURE_2D, (GLuint)cmd->texture.id);
+ glScissor((GLint)(cmd->clip_rect.x * scale.x),
+ (GLint)((height - (GLint)(cmd->clip_rect.y + cmd->clip_rect.h)) * scale.y),
+ (GLint)(cmd->clip_rect.w * scale.x),
+ (GLint)(cmd->clip_rect.h * scale.y));
+ glDrawElements(GL_TRIANGLES, (GLsizei)cmd->elem_count, GL_UNSIGNED_SHORT, offset);
+ offset += cmd->elem_count;
+ }
+ nk_clear(&sdl.ctx);
+ nk_buffer_clear(&dev->cmds);
+ }
+
+ glUseProgram(0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glBindVertexArray(0);
+ glDisable(GL_BLEND);
+ glDisable(GL_SCISSOR_TEST);
+}
+
+static void
+nk_sdl_clipboard_paste(nk_handle usr, struct nk_text_edit *edit)
+{
+ const char *text = SDL_GetClipboardText();
+ if (text) nk_textedit_paste(edit, text, nk_strlen(text));
+ (void)usr;
+}
+
+static void
+nk_sdl_clipboard_copy(nk_handle usr, const char *text, int len)
+{
+ char *str = 0;
+ (void)usr;
+ if (!len) return;
+ str = (char*)malloc((size_t)len+1);
+ if (!str) return;
+ memcpy(str, text, (size_t)len);
+ str[len] = '\0';
+ SDL_SetClipboardText(str);
+ free(str);
+}
+
+NK_API struct nk_context*
+nk_sdl_init(SDL_Window *win)
+{
+ sdl.win = win;
+ nk_init_default(&sdl.ctx, 0);
+ sdl.ctx.clip.copy = nk_sdl_clipboard_copy;
+ sdl.ctx.clip.paste = nk_sdl_clipboard_paste;
+ sdl.ctx.clip.userdata = nk_handle_ptr(0);
+ nk_sdl_device_create();
+ return &sdl.ctx;
+}
+
+NK_API void
+nk_sdl_font_stash_begin(struct nk_font_atlas **atlas)
+{
+ nk_font_atlas_init_default(&sdl.atlas);
+ nk_font_atlas_begin(&sdl.atlas);
+ *atlas = &sdl.atlas;
+}
+
+NK_API void
+nk_sdl_font_stash_end(void)
+{
+ const void *image; int w, h;
+ image = nk_font_atlas_bake(&sdl.atlas, &w, &h, NK_FONT_ATLAS_RGBA32);
+ nk_sdl_device_upload_atlas(image, w, h);
+ nk_font_atlas_end(&sdl.atlas, nk_handle_id((int)sdl.ogl.font_tex), &sdl.ogl.tex_null);
+ if (sdl.atlas.default_font)
+ nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle);
+
+}
+
+NK_API void
+nk_sdl_handle_grab(void)
+{
+ struct nk_context *ctx = &sdl.ctx;
+ if (ctx->input.mouse.grab) {
+ SDL_SetRelativeMouseMode(SDL_TRUE);
+ } else if (ctx->input.mouse.ungrab) {
+ /* better support for older SDL by setting mode first; causes an extra mouse motion event */
+ SDL_SetRelativeMouseMode(SDL_FALSE);
+ SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y);
+ } else if (ctx->input.mouse.grabbed) {
+ ctx->input.mouse.pos.x = ctx->input.mouse.prev.x;
+ ctx->input.mouse.pos.y = ctx->input.mouse.prev.y;
+ }
+}
+
+NK_API int
+nk_sdl_handle_event(SDL_Event *evt)
+{
+ struct nk_context *ctx = &sdl.ctx;
+
+ switch(evt->type)
+ {
+ case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */
+ case SDL_KEYDOWN:
+ {
+ int down = evt->type == SDL_KEYDOWN;
+ const Uint8* state = SDL_GetKeyboardState(0);
+ switch(evt->key.keysym.sym)
+ {
+ case SDLK_RSHIFT: /* RSHIFT & LSHIFT share same routine */
+ case SDLK_LSHIFT: nk_input_key(ctx, NK_KEY_SHIFT, down); break;
+ case SDLK_DELETE: nk_input_key(ctx, NK_KEY_DEL, down); break;
+ case SDLK_RETURN: nk_input_key(ctx, NK_KEY_ENTER, down); break;
+ case SDLK_TAB: nk_input_key(ctx, NK_KEY_TAB, down); break;
+ case SDLK_BACKSPACE: nk_input_key(ctx, NK_KEY_BACKSPACE, down); break;
+ case SDLK_HOME: nk_input_key(ctx, NK_KEY_TEXT_START, down);
+ nk_input_key(ctx, NK_KEY_SCROLL_START, down); break;
+ case SDLK_END: nk_input_key(ctx, NK_KEY_TEXT_END, down);
+ nk_input_key(ctx, NK_KEY_SCROLL_END, down); break;
+ case SDLK_PAGEDOWN: nk_input_key(ctx, NK_KEY_SCROLL_DOWN, down); break;
+ case SDLK_PAGEUP: nk_input_key(ctx, NK_KEY_SCROLL_UP, down); break;
+ case SDLK_z: nk_input_key(ctx, NK_KEY_TEXT_UNDO, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_r: nk_input_key(ctx, NK_KEY_TEXT_REDO, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_c: nk_input_key(ctx, NK_KEY_COPY, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_v: nk_input_key(ctx, NK_KEY_PASTE, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_x: nk_input_key(ctx, NK_KEY_CUT, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_b: nk_input_key(ctx, NK_KEY_TEXT_LINE_START, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_e: nk_input_key(ctx, NK_KEY_TEXT_LINE_END, down && state[SDL_SCANCODE_LCTRL]); break;
+ case SDLK_UP: nk_input_key(ctx, NK_KEY_UP, down); break;
+ case SDLK_DOWN: nk_input_key(ctx, NK_KEY_DOWN, down); break;
+ case SDLK_LEFT:
+ if (state[SDL_SCANCODE_LCTRL])
+ nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, down);
+ else nk_input_key(ctx, NK_KEY_LEFT, down);
+ break;
+ case SDLK_RIGHT:
+ if (state[SDL_SCANCODE_LCTRL])
+ nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, down);
+ else nk_input_key(ctx, NK_KEY_RIGHT, down);
+ break;
+ }
+ }
+ return 1;
+
+ case SDL_MOUSEBUTTONUP: /* MOUSEBUTTONUP & MOUSEBUTTONDOWN share same routine */
+ case SDL_MOUSEBUTTONDOWN:
+ {
+ int down = evt->type == SDL_MOUSEBUTTONDOWN;
+ const int x = evt->button.x, y = evt->button.y;
+ switch(evt->button.button)
+ {
+ case SDL_BUTTON_LEFT:
+ if (evt->button.clicks > 1)
+ nk_input_button(ctx, NK_BUTTON_DOUBLE, x, y, down);
+ nk_input_button(ctx, NK_BUTTON_LEFT, x, y, down); break;
+ case SDL_BUTTON_MIDDLE: nk_input_button(ctx, NK_BUTTON_MIDDLE, x, y, down); break;
+ case SDL_BUTTON_RIGHT: nk_input_button(ctx, NK_BUTTON_RIGHT, x, y, down); break;
+ }
+ }
+ return 1;
+
+ case SDL_MOUSEMOTION:
+ if (ctx->input.mouse.grabbed) {
+ int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y;
+ nk_input_motion(ctx, x + evt->motion.xrel, y + evt->motion.yrel);
+ }
+ else nk_input_motion(ctx, evt->motion.x, evt->motion.y);
+ return 1;
+
+ case SDL_TEXTINPUT:
+ {
+ nk_glyph glyph;
+ memcpy(glyph, evt->text.text, NK_UTF_SIZE);
+ nk_input_glyph(ctx, glyph);
+ }
+ return 1;
+
+ case SDL_MOUSEWHEEL:
+ nk_input_scroll(ctx,nk_vec2((float)evt->wheel.x,(float)evt->wheel.y));
+ return 1;
+ }
+ return 0;
+}
+
+NK_API
+void nk_sdl_shutdown(void)
+{
+ nk_font_atlas_clear(&sdl.atlas);
+ nk_free(&sdl.ctx);
+ nk_sdl_device_destroy();
+ memset(&sdl, 0, sizeof(sdl));
+}
+
+#endif
diff --git a/include/novaphysics/aabb.h b/include/novaphysics/aabb.h
index 1148c0d..f31fca1 100644
--- a/include/novaphysics/aabb.h
+++ b/include/novaphysics/aabb.h
@@ -31,5 +31,37 @@ typedef struct {
nv_float max_y; /**< Maximum Y */
} nvAABB;
+/**
+ * @brief Merge two AABBs.
+ *
+ * @param a First AABB
+ * @param b Second AABB
+ * @return nvAABB
+ */
+static inline nvAABB nvAABB_merge(nvAABB a, nvAABB b) {
+ return (nvAABB){
+ nv_fmin(a.min_x, b.min_x),
+ nv_fmin(a.min_y, b.min_y),
+ nv_fmax(a.max_x, b.max_x),
+ nv_fmax(a.max_y, b.max_y)
+ };
+}
+
+/**
+ * @brief Inflate an AABB in all directions.
+ *
+ * @param aabb AABB
+ * @param amount Amount to inflate
+ * @return nvAABB
+ */
+static inline nvAABB nvAABB_inflate(nvAABB aabb, nv_float amount) {
+ return (nvAABB){
+ aabb.min_x - amount,
+ aabb.min_y - amount,
+ aabb.max_x + amount,
+ aabb.max_y + amount
+ };
+}
+
#endif
\ No newline at end of file
diff --git a/include/novaphysics/body.h b/include/novaphysics/body.h
index 4862170..3d02dbf 100644
--- a/include/novaphysics/body.h
+++ b/include/novaphysics/body.h
@@ -11,189 +11,501 @@
#ifndef NOVAPHYSICS_BODY_H
#define NOVAPHYSICS_BODY_H
-#include
-#include
#include "novaphysics/internal.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
#include "novaphysics/vector.h"
#include "novaphysics/aabb.h"
#include "novaphysics/material.h"
#include "novaphysics/math.h"
-#include "novaphysics/matrix.h"
#include "novaphysics/shape.h"
/**
* @file body.h
*
- * @brief Body struct and methods.
- *
- * This module defines body enums, body struct and its methods.
+ * @brief Rigid body implementation.
*/
/**
- * @brief Body type enumerator.
+ * @brief Rigid body type enumerator.
*/
typedef enum {
- nvBodyType_STATIC, /**< Static bodies do not get affected or moved by any force in the simulation.
- They behave like they have infinite mass.
- Generally all terrain and ground objects are static bodies in games. */
+ nvRigidBodyType_STATIC, /**< Static bodies do not get affected or moved by any force in the simulation.
+ They behave like they have infinite mass.
+ Generally all terrain and ground objects are static bodies in games. */
- nvBodyType_DYNAMIC /**< Dynamic bodies interact with all the other objects in the space and
- are effected by all forces, gravity and collisions in the simulation.
- Their mass is calculated by their shape, and unless you know what you're doing,
- it's not recommended to change their mass manually.
- However, if you want a dynamic body that can't rotate,
- you can set it's inertia to 0. */
-} nvBodyType;
+ nvRigidBodyType_DYNAMIC /**< Dynamic bodies interact with all the other objects in the space and
+ are effected by all forces, gravity and collisions in the simulation.
+ Their mass is calculated by their shape, and unless you know what you're doing,
+ it's not recommended to change their mass manually.
+ However, if you want a dynamic body that can't rotate,
+ you can set it's inertia to 0. */
+} nvRigidBodyType;
/**
- * @brief Body struct.
+ * @brief Rigid body struct.
*
* A rigid body is a non deformable object with mass in space. It can be affected
* by various forces and constraints depending on its type.
*
- * Some things to keep in mind to keep the simulation accurate and stable:
- * - If you want to move bodies in space, applying forces is the best solution.
- * Changing velocities directly may result in poor accuracy.
- * Changing positions directly means teleporting them around.
- * - Avoid creating gigantic or really tiny dynamic bodies.
- * This of course depends on the application but keeping the sizes between
- * 0.1 and 10.0 is a good range.
- * - Make sure polygon shape's centroid is the same as the body's center position.
- * Or else the center of gravity will be off and the rotations will not be accurate.
+ * Few things to consider to keep the simulation accurate and stable:
+ * - If you want to move bodies in space, applying forces may be a better solution
+ * than changing velocities directly. Changing transforms (positions and angles)
+ * basically means teleporting them around so you should avoid it unless you
+ * know what you are doing.
+ * - In order to not lose floating point precision, it's best to not variate
+ * sizes of dynamic bodies too much. This of course depends on the application,
+ * but considering the penetration slop setting, keeping the size range around
+ * 0.5 and 10.0 would be sufficient in a game.
*/
typedef struct {
- struct nvSpace *space; /**< Space instance the body is in. */
+ /*
+ Private members
+ */
+ nv_bool cache_aabb;
+ nv_bool cache_transform;
+ nvAABB cached_aabb;
+
+ // For BVH splitting
+ nv_float bvh_median_x;
+ nv_float bvh_median_y;
+
+ // Accumulated forces
+ nvVector2 force;
+ nv_float torque;
+
+ // Inverse masses
+ nv_float invmass;
+ nv_float invinertia;
+
+ nvVector2 origin; /**< Body shape origin. */
+ nvVector2 com; /**< Local center of mass. */
+
+ /*
+ Public members (setters & getters)
+ */
+ void *user_data;
+
+ struct nvSpace *space;
- nv_uint16 id; /**< Unique identity number of the body. */
+ nv_uint32 id;
- nvBodyType type; /**< Type of the body. */
- nvShape *shape; /**< Shape of the body. */
+ nvRigidBodyType type;
- nvVector2 position; /**< Position of the body. */
- nv_float angle; /**< Rotation of the body in radians. */
+ nvArray *shapes;
- nvVector2 linear_velocity; /**< Linear velocity of the body. */
- nv_float angular_velocity; /**< Angular velocity of the bodyin radians/s. */
+ nvVector2 position;
+ nv_float angle;
- nv_float linear_damping; /**< Amount of damping applied to linear velocity of the body. */
- nv_float angular_damping; /**< Amount of damping applied to angular velocity of the body. */
+ nvVector2 linear_velocity;
+ nv_float angular_velocity;
- nvVector2 force; /**< Force applied on the body. This is reset every space step. */
- nv_float torque; /**< Torque applied on the body. This is reset every space step. */
+ nv_float linear_damping_scale;
+ nv_float angular_damping_scale;
- nv_float gravity_scale; /**< Scale multiplier to the gravity applied to this body. 1.0 by default. */
+ nv_float gravity_scale;
- nvMaterial material; /**< Material of the body. */
+ nvMaterial material;
- nv_float mass; /**< Mass of the body. */
- nv_float invmass; /**< Inverse mass of the body (1/M). Used in internal calculations. */
- nv_float inertia; /**< Moment of ineartia of the body. */
- nv_float invinertia; /**< Inverse moment of inertia of the body (1/I). Used in internal calculations. */
+ nv_float mass;
+ nv_float inertia;
- bool is_sleeping; /**< Flag reporting if the body is sleeping. */
- unsigned int sleep_timer; /**< Internal sleep counter of the body. */
+ nv_bool collision_enabled;
+ nv_uint32 collision_group;
+ nv_uint32 collision_category;
+ nv_uint32 collision_mask;
+} nvRigidBody;
- bool is_attractor; /**< Flag reporting if the body is an attractor. */
- bool enable_collision; /**< Whether to collide this body with other bodies or not. */
- nv_uint32 collision_group; /**< Collision group of the body.
- Bodies that share the same non-zero group do not collide. */
- nv_uint32 collision_category; /**< Bitmask defining this body's collision category. */
- nv_uint32 collision_mask; /**< Bitmask defining this body's collision mask. */
+/**
+ * @brief Rigid body initializer information.
+ *
+ * This struct holds basic information for initializing bodies and can be reused
+ * for multiple bodies.
+ */
+typedef struct {
+ nvRigidBodyType type;
+ nvVector2 position;
+ nv_float angle;
+ nvVector2 linear_velocity;
+ nv_float angular_velocity;
+ nvMaterial material;
+ void *user_data;
+} nvRigidBodyInitializer;
+
+static const nvRigidBodyInitializer nvRigidBodyInitializer_default = {
+ // It sucks that MSVC doesn't allow designated initializers here
+ nvRigidBodyType_STATIC,
+ {0.0, 0.0},
+ 0.0,
+ {0.0, 0.0},
+ 0.0,
+ {1.0, 0.1, 0.4},
+ NULL
+};
- bool _cache_aabb; /** Internal flag reporting whether to cache AABB or not. */
- bool _cache_transform; /** Internal flag reporting whether to cache vertices or not. */
- nvAABB _cached_aabb; /** Internal cached AABB. */
-} nvBody;
/**
* @brief Create a new body.
*
- * @param type Type of the body
- * @param shape Shape of the body
- * @param position Position of the body
- * @param angle Angle of the body in radians
- * @param material Material of the body
+ * When you add the rigid body to a space, space is responsible for the memory management.
+ * When you call @ref nvSpace_free it releases all resources it has.
+ * But if you removed the body or never added it in the first place, you have to
+ * manage the memory.
+ * Same thing applies to shapes, if you didn't attach a shape to a body you have to
+ * free it yourself.
*
- * @return nvBody *
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
+ * @param init Initializer info
+ * @return nvRigidBody *
*/
-nvBody *nvBody_new(
- nvBodyType type,
- nvShape *shape,
- nvVector2 position,
- nv_float angle,
- nvMaterial material
-);
+nvRigidBody *nvRigidBody_new(nvRigidBodyInitializer init);
/**
* @brief Free body.
*
+ * It's safe to pass `NULL` to this function.
+ *
* @param body Body to free
*/
-void nvBody_free(void *body);
+void nvRigidBody_free(nvRigidBody *body);
+
+/**
+ * @brief Set user data.
+ *
+ * @param body Body
+ * @param data Void pointer to user data
+ */
+void nvRigidBody_set_user_data(nvRigidBody *body, void *data);
+
+/**
+ * @brief Get user data.
+ *
+ * @param body Body
+ * @return void *
+ */
+void *nvRigidBody_get_user_data(const nvRigidBody *body);
+
+/**
+ * @brief Get the space instance body belongs to.
+ *
+ * @param body Body
+ * @return nvSpace *
+ */
+struct nvSpace *nvRigidBody_get_space(const nvRigidBody *body);
+
+/**
+ * @brief Get unique identity number of the body.
+ *
+ * @param body
+ * @return nv_uint32
+ */
+nv_uint32 nvRigidBody_get_id(const nvRigidBody *body);
+
+/**
+ * @brief Set motion type of the body.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @param body Body
+ * @param type Type
+ */
+int nvRigidBody_set_type(nvRigidBody *body, nvRigidBodyType type);
+
+/**
+ * @brief Get motion type of the body.
+ *
+ * @param body Body
+ * @return nvRigidBodyType
+ */
+nvRigidBodyType nvRigidBody_get_type(const nvRigidBody *body);
+
+/**
+ * @brief Set position (center of mass) of body in space.
+ *
+ * @param body Body
+ * @param new_position New position vector
+ */
+void nvRigidBody_set_position(nvRigidBody *body, nvVector2 new_position);
+
+/**
+ * @brief Get position (center of mass) of body in space.
+ *
+ * @param body Body
+ * @return nvVector2 Position vector
+ */
+nvVector2 nvRigidBody_get_position(const nvRigidBody *body);
+
+/**
+ * @brief Set angle (rotation) of body in radians.
+ *
+ * If you want to rotate dynamic bodies in a physically accurate manner, applying
+ * torques should be the preferred approach.
+ * See @ref nvRigidBody_apply_torque
+ *
+ * @param body
+ * @param new_angle
+ */
+void nvRigidBody_set_angle(nvRigidBody *body, nv_float new_angle);
+
+/**
+ * @brief Get angle (rotation) of body in radians.
+ *
+ * @param body
+ * @return nv_float
+ */
+nv_float nvRigidBody_get_angle(const nvRigidBody *body);
+
+/**
+ * @brief Set linear velocity of body.
+ *
+ * @param body Body
+ * @param new_position New velocity vector
+ */
+void nvRigidBody_set_linear_velocity(nvRigidBody *body, nvVector2 new_velocity);
+
+/**
+ * @brief Get linear velocity of body.
+ *
+ * @param body Body
+ * @return nvVector2 Velocity vector
+ */
+nvVector2 nvRigidBody_get_linear_velocity(const nvRigidBody *body);
+
+/**
+ * @brief Set angular velocity of body.
+ *
+ * If you want to rotate dynamic bodies in a physically accurate manner, applying
+ * torques should be the preferred approach.
+ * See @ref nvRigidBody_apply_torque
+ *
+ * @param body Body
+ * @param new_velocity New velocity
+ */
+void nvRigidBody_set_angular_velocity(nvRigidBody *body, nv_float new_velocity);
+
+/**
+ * @brief Get angular velocity of body.
+ *
+ * @param body Body
+ * @return nv_float
+ */
+nv_float nvRigidBody_get_angular_velocity(const nvRigidBody *body);
+
+/**
+ * @brief Set body's linear velocity damping factor.
+ *
+ * The default value 1.0 (100%) means the velocity damping applied to body is not affected.
+ *
+ * @param body Body
+ * @param scale Scaling factor
+ */
+void nvRigidBody_set_linear_damping_scale(nvRigidBody *body, nv_float scale);
+
+/**
+ * @brief Get body's linear velocity damping factor.
+ *
+ * The default value 1.0 (100%) means the velocity damping applied to body is not affected.
+ *
+ * @param body Body
+ * @return nv_float
+ */
+nv_float nvRigidBody_get_linear_damping_scale(const nvRigidBody *body);
+
+/**
+ * @brief Set body's angular velocity damping factor.
+ *
+ * The default value 1.0 (100%) means the velocity damping applied to body is not affected.
+ *
+ * @param body Body
+ * @param scale Scaling factor
+ */
+void nvRigidBody_set_angular_damping_scale(nvRigidBody *body, nv_float scale);
+
+/**
+ * @brief Get body's angular velocity damping factor.
+ *
+ * The default value 1.0 (100%) means the velocity damping applied to body is not affected.
+ *
+ * @param body Body
+ * @return nv_float
+ */
+nv_float nvRigidBody_get_angular_damping_scale(const nvRigidBody *body);
+
+/**
+ * @brief Set gravity scaling factor of body.
+ *
+ * The default value 1.0 (100%) means the global gravity applied to body is not affected.
+ *
+ * @param body Body
+ * @param scale Scaling factor
+ */
+void nvRigidBody_set_gravity_scale(nvRigidBody *body, nv_float scale);
/**
- * @brief Calculate and update mass and moment of inertia of the body.
+ * @brief get gravity scaling factor of body.
*
- * @param body Body to calculate masses of
+ * The default value 1.0 (100%) means the global gravity applied to body is not affected.
+ *
+ * @param body Body
+ * @return nv_float
*/
-void nvBody_calc_mass_and_inertia(nvBody *body);
+nv_float nvRigidBody_get_gravity_scale(const nvRigidBody *body);
/**
- * @brief Set mass (and moment of inertia) of the body.
+ * @brief Set material of body.
+ *
+ * @param body Body
+ * @param material Material
+ */
+void nvRigidBody_set_material(nvRigidBody *body, nvMaterial material);
+
+/**
+ * @brief Get material of body
+ *
+ * @param body Body
+ * @return nvMaterial
+ */
+nvMaterial nvRigidBody_get_material(const nvRigidBody *body);
+
+/**
+ * @brief Set mass of the body.
+ *
+ * Ideally you wouldn't need to set mass manually because it is calculated as
+ * you add shapes to the body.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @note Currently this doesn't change inertia with the new mass, so use at your own risk.
*
* @param body Body
* @param mass Mass
+ * @return int Status
+ */
+int nvRigidBody_set_mass(nvRigidBody *body, nv_float mass);
+
+/**
+ * @brief Get mass of the body.
+ *
+ * @param body Body
+ * @return nv_float
*/
-void nvBody_set_mass(nvBody *body, nv_float mass);
+nv_float nvRigidBody_get_mass(const nvRigidBody *body);
/**
- * @brief Set moment of inertia of the body.
+ * @brief Set inertia of the body.
+ *
+ * If you want to disable rotation you can set inertia to 0.
*
* @param body Body
* @param inertia Moment of inertia
*/
-void nvBody_set_inertia(nvBody *body, nv_float inertia);
+void nvRigidBody_set_inertia(nvRigidBody *body, nv_float inertia);
/**
- * @brief Set all velocities and forces of the body to 0.
+ * @brief Get inertia of the body.
*
* @param body Body
+ * @return nv_float
*/
-void nvBody_reset_velocities(nvBody *body);
+nv_float nvRigidBody_get_inertia(const nvRigidBody *body);
/**
- * @brief Integrate linear & angular accelerations.
+ * @brief Set collision group of body.
*
- * @param body Body to integrate accelerations of
- * @param dt Time step size (delta time)
+ * Bodies that share the same non-zero group do not collide.
+ *
+ * @param body
+ * @param group
*/
-void nvBody_integrate_accelerations(
- nvBody *body,
- nvVector2 gravity,
- nv_float dt
-);
+void nvRigidBody_set_collision_group(nvRigidBody *body, nv_uint32 group);
/**
- * @brief Integrate linear & angular velocities.
+ * @brief Get collision group of body.
*
- * @param body Body to integrate velocities of
- * @param dt Time step size (delta time)
+ * Bodies that share the same non-zero group do not collide.
+ *
+ * @param body Body
+ * @return nv_uint32
*/
-void nvBody_integrate_velocities(nvBody *body, nv_float dt);
+nv_uint32 nvRigidBody_get_collision_group(const nvRigidBody *body);
/**
- * @brief Apply attractive force to body towards attractor body.
+ * @brief Set collision category of body.
+ *
+ * This is a bitmask defining this body's collision category.
*
* @param body Body
- * @param attractor Attractor body
- * @param dt Time step size (delta time)
+ * @param category Category bitmask
*/
-void nvBody_apply_attraction(nvBody *body, nvBody *attractor, nv_float dt);
+void nvRigidBody_set_collision_category(nvRigidBody *body, nv_uint32 category);
+
+/**
+ * @brief Get collision category of body.
+ *
+ * This is a bitmask defining this body's collision category.
+ *
+ * @param body Body
+ * @return nv_uint32
+ */
+nv_uint32 nvRigidBody_get_collision_category(const nvRigidBody *body);
+
+/**
+ * @brief Set collision mask of body.
+ *
+ * This is a bitmask defining this body's collision mask.
+ *
+ * @param body Body
+ * @param category Mask
+ */
+void nvRigidBody_set_collision_mask(nvRigidBody *body, nv_uint32 mask);
+
+/**
+ * @brief Get collision mask of body.
+ *
+ * This is a bitmask defining this body's collision mask.
+ *
+ * @param body Body
+ * @return nv_uint32
+ */
+nv_uint32 nvRigidBody_get_collision_mask(const nvRigidBody *body);
+
+/**
+ * @brief Add a shape to the body.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @param body Body
+ * @param shape Shape
+ * @return int Status
+ */
+int nvRigidBody_add_shape(nvRigidBody *body, nvShape *shape);
+
+/**
+ * @brief Remove a shape from the body.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @param body Body
+ * @param shape Shape
+ * @return int Status
+ */
+int nvRigidBody_remove_shape(nvRigidBody *body, nvShape *shape);
+
+/**
+ * @brief Iterate over this rigid body's shapes.
+ *
+ * Make sure to reset the index if you alter the shapes in any way while iterating.
+ *
+ * @param body Body
+ * @param cons Pointer to shape
+ * @param index Pointer to iteration index
+ * @return nv_bool
+ */
+nv_bool nvRigidBody_iter_shapes(nvRigidBody *body, nvShape **shape, size_t *index);
/**
* @brief Apply force to body at its center of mass.
@@ -201,7 +513,7 @@ void nvBody_apply_attraction(nvBody *body, nvBody *attractor, nv_float dt);
* @param body Body to apply force on
* @param force Force
*/
-void nvBody_apply_force(nvBody *body, nvVector2 force);
+void nvRigidBody_apply_force(nvRigidBody *body, nvVector2 force);
/**
* @brief Apply force to body at some local point.
@@ -210,48 +522,68 @@ void nvBody_apply_force(nvBody *body, nvVector2 force);
* @param force Force
* @param position Local point to apply force at
*/
-void nvBody_apply_force_at(
- nvBody *body,
+void nvRigidBody_apply_force_at(
+ nvRigidBody *body,
nvVector2 force,
nvVector2 position
);
+/**
+ * @brief Apply torque to body.
+ *
+ * @param body Body to apply torque on
+ * @param torque Torque
+ */
+void nvRigidBody_apply_torque(nvRigidBody *body, nv_float torque);
+
/**
* @brief Apply impulse to body at some local point.
*
- * @note This method is mainly used internally by the engine.
+ * An impulse is a sudden change of velocity.
+ * Reason of this function existing is mainly for internal use.
*
* @param body Body to apply impulse on
* @param impulse Impulse
* @param position Local point to apply impulse at
*/
-void nvBody_apply_impulse(
- nvBody *body,
+void nvRigidBody_apply_impulse(
+ nvRigidBody *body,
nvVector2 impulse,
nvVector2 position
);
/**
- * @brief Sleep body.
+ * @brief Enable collisions for this body.
+ *
+ * If this is disabled, the body doesn't collide with anything at all.
+ *
+ * @param body Body
+ */
+void nvRigidBody_enable_collisions(nvRigidBody *body);
+
+/**
+ * @brief Disable collisions for this body.
+ *
+ * If this is disabled, the body doesn't collide with anything at all.
*
* @param body Body
*/
-void nvBody_sleep(nvBody *body);
+void nvRigidBody_disable_collisions(nvRigidBody *body);
/**
- * @brief Awake body.
+ * @brief Set all velocities and forces of the body to 0.
*
* @param body Body
*/
-void nvBody_awake(nvBody *body);
+void nvRigidBody_reset_velocities(nvRigidBody *body);
/**
* @brief Get AABB (Axis-Aligned Bounding Box) of the body.
*
- * @param body Body to get AABB of
+ * @param body Body
* @return nvAABB
*/
-nvAABB nvBody_get_aabb(nvBody *body);
+nvAABB nvRigidBody_get_aabb(nvRigidBody *body);
/**
* @brief Get kinetic energy of the body in joules.
@@ -259,7 +591,7 @@ nvAABB nvBody_get_aabb(nvBody *body);
* @param body Body
* @return nv_float
*/
-nv_float nvBody_get_kinetic_energy(nvBody *body);
+nv_float nvRigidBody_get_kinetic_energy(const nvRigidBody *body);
/**
* @brief Get rotational kinetic energy of the body in joules.
@@ -267,30 +599,27 @@ nv_float nvBody_get_kinetic_energy(nvBody *body);
* @param body Body
* @return nv_float
*/
-nv_float nvBody_get_rotational_energy(nvBody *body);
+nv_float nvRigidBody_get_rotational_energy(const nvRigidBody *body);
/**
- * @brief Set whether the body is attractor or not.
+ * @brief Integrate linear & angular accelerations.
*
* @param body Body
- * @param is_attractor Is attractor?
+ * @param dt Time step size (delta time)
*/
-void nvBody_set_is_attractor(nvBody *body, bool is_attractor);
+void nvRigidBody_integrate_accelerations(
+ nvRigidBody *body,
+ nvVector2 gravity,
+ nv_float dt
+);
/**
- * @brief Get whether the body is attractor or not.
+ * @brief Integrate linear & angular velocities.
*
* @param body Body
- * @return bool
- */
-bool nvBody_get_is_attractor(nvBody *body);
-
-/**
- * @brief Transform body's polygon shape's vertices from local space to world space.
- *
- * @param body Body with polygon shape
+ * @param dt Time step size (delta time)
*/
-void nvBody_local_to_world(nvBody *polygon);
+void nvRigidBody_integrate_velocities(nvRigidBody *body, nv_float dt);
#endif
\ No newline at end of file
diff --git a/include/novaphysics/broadphase.h b/include/novaphysics/broadphase.h
index a4cb87b..edefe76 100644
--- a/include/novaphysics/broadphase.h
+++ b/include/novaphysics/broadphase.h
@@ -13,7 +13,6 @@
#include "novaphysics/internal.h"
#include "novaphysics/body.h"
-#include "novaphysics/resolution.h"
/**
@@ -23,57 +22,47 @@
*/
+/**
+ * @brief Pair of two possibly colliding bodies,
+ * that is going to be used in narrowphase.
+ */
typedef struct {
- nvBody *a;
- nvBody *b;
- uint32_t id_pair;
+ nvRigidBody *a;
+ nvRigidBody *b;
} nvBroadPhasePair;
+static inline nv_uint64 nvBroadPhasePair_hash(void *item) {
+ nvBroadPhasePair *pair = (nvBroadPhasePair *)item;
+ return nv_u32pair(pair->a->id, pair->b->id);
+}
+
/**
* @brief Algorithm used in broad-phase collision detection.
*/
typedef enum {
- nvBroadPhaseAlg_BRUTE_FORCE, /**< Naive brute-force approach. */
- nvBroadPhaseAlg_SHG, /**< SHG (Spatial hash grid). */
- nvBroadPhaseAlg_BVH /**< BVH (Bounding Volume Hierarchy) tree.*/
-} nvBroadPhaseAlg;
+ nvBroadPhaseAlg_BRUTE_FORCE, /**< Naive brute-force approach.
+ Every rigid body is checked against each other. O(n^2)*/
+ nvBroadPhaseAlg_BVH /**< BVH (Bounding Volume Hierarchy) tree. */
+} nvBroadPhaseAlg;
-/**
- * @brief Brute-force algorithm.
- *
- * @param space Space
- */
-void nvBroadPhase_brute_force(struct nvSpace *space);
/**
- * @brief Spatial hash grid algorithm.
+ * @brief Do brute-force broadphase and update pairs.
*
* @param space Space
*/
-void nvBroadPhase_SHG(struct nvSpace *space);
+void nv_broadphase_brute_force(struct nvSpace *space);
/**
- * @brief Multi-threaded spatial hash grid algorithm.
+ * @brief Do BVH broadphase and update pairs.
*
- * @param space Space
+ * @param space
*/
-void nvBroadPhase_SHG_parallel(struct nvSpace *space);
+void nv_broadphase_BVH(struct nvSpace *space);
-/**
- * @brief BVH tree algorithm.
- *
- * @param space Space
- */
-void nvBroadPhase_BVH(struct nvSpace *space);
-
-/**
- * @brief Multi-hreaded BVH tree algorithm.
- *
- * @param space Space
- */
-void nvBroadPhase_BVH_parallel(struct nvSpace *space);
+void nv_broadphase_finalize(struct nvSpace *space);
#endif
\ No newline at end of file
diff --git a/include/novaphysics/bvh.h b/include/novaphysics/bvh.h
index 9482bdd..0a17fd1 100644
--- a/include/novaphysics/bvh.h
+++ b/include/novaphysics/bvh.h
@@ -8,12 +8,11 @@
*/
-#ifndef NOVAPHYSICS_BOUNDING_VOLUME_HIERARCHY_H
-#define NOVAPHYSICS_BOUNDING_VOLUME_HIERARCHY_H
+#ifndef NOVAPHYSICS_BOUNDING_VOLUME_HIERARCHY_TREE_H
+#define NOVAPHYSICS_BOUNDING_VOLUME_HIERARCHY_TREE_H
-#include
#include "novaphysics/internal.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
#include "novaphysics/aabb.h"
#include "novaphysics/body.h"
@@ -31,11 +30,12 @@ struct _nvBVHNode;
* @brief Bounding Volume Hierarchy tree node struct.
*/
struct _nvBVHNode {
- bool is_leaf; /**< Is this node a leaf node? */
+ nv_bool is_leaf; /**< Is this node a leaf node? */
struct _nvBVHNode *left; /**< Left branch of this node. */
struct _nvBVHNode *right; /**< Right branch of this node. */
nvAABB aabb; /**< Boundary of this node. */
nvArray *bodies; /**< Array of bodies residing on this node. */
+ size_t depth; // TODO: This is for debugging, remove!
};
typedef struct _nvBVHNode nvBVHNode;
@@ -47,7 +47,7 @@ typedef struct _nvBVHNode nvBVHNode;
* @param bodies Array of bodies
* @return nvBVHNode *
*/
-nvBVHNode *nvBVHNode_new(bool is_leaf, nvArray *bodies);
+nvBVHNode *nvBVHNode_new(nv_bool is_leaf, nvArray *bodies);
/**
* @brief Free BVH node.
@@ -73,7 +73,7 @@ void nvBVHNode_subdivide(nvBVHNode *node);
/**
* @brief Traverse trough the BVH tree and find collided bodies.
*/
-nvArray *nvBVHNode_collide(nvBVHNode *node, nvAABB aabb, bool *is_combined);
+nvArray *nvBVHNode_collide(nvBVHNode *node, nvAABB aabb, nv_bool *is_combined);
/**
* @brief Get the size of the BVH tree.
diff --git a/include/novaphysics/collision.h b/include/novaphysics/collision.h
index 237da42..5e566b0 100644
--- a/include/novaphysics/collision.h
+++ b/include/novaphysics/collision.h
@@ -11,81 +11,170 @@
#ifndef NOVAPHYSICS_COLLISION_H
#define NOVAPHYSICS_COLLISION_H
-#include
-#include "novaphysics/resolution.h"
+#include "novaphysics/contact.h"
/**
* @file collision.h
*
- * @brief Collision detection functions.
+ * @brief Collision detection and contact point generation functions.
*/
+// Vector used when the normal can't be calculated (usually when shapes overlap perfectly)
+#define NV_DEGENERATE_NORMAL NV_VECTOR2(0.0, 1.0)
+
+
/**
- * @brief Calculate the collision between two circles
+ * @brief Result of a single ray cast intersection.
+ */
+typedef struct {
+ nvVector2 position; /**< Point in world space where ray intersects object. */
+ nvVector2 normal; /**< Normal of the surface ray hit. */
+ nvRigidBody *body; /**< The rigid body that was hit. */
+ nvShape *shape; /**< First shape of the body which involved in the collision. */
+} nvRayCastResult;
+
+
+/**
+ * @brief Check circles collision and generate contact point information.
*
- * @param a First circle body
- * @param b Second circle body
- * @return nvResolution
+ * @param circle_a First circle shape
+ * @param xform_a First transform
+ * @param circle_b Second circle shape
+ * @param xform_b Second transform
+ * @return nvPersistentContactPair
*/
-nvResolution nv_collide_circle_x_circle(nvBody *a, nvBody *b);
+nvPersistentContactPair nv_collide_circle_x_circle(
+ nvShape *circle_a,
+ nvTransform xform_a,
+ nvShape *circle_b,
+ nvTransform xform_b
+);
/**
- * @brief Check if point is inside circle
+ * @brief Check if point is inside circle.
*
- * @param circle Circle body
+ * @param circle Circle shape
+ * @param xform Transform for the shape
* @param point Point
- * @return bool
+ * @return nv_bool
*/
-bool nv_collide_circle_x_point(nvBody *circle, nvVector2 point);
-
+nv_bool nv_collide_circle_x_point(
+ nvShape *circle,
+ nvTransform xform,
+ nvVector2 point
+);
/**
- * @brief Calculate the collision between polygon and circle
+ * @brief Check polygon x circle collision and generate contact point information.
*
- * @param polygon Polygon body
- * @param circle Circle body
- * @return nvResolution
+ * @param polygon Polygon shape
+ * @param xform_poly Transform for the polygon shape
+ * @param circle Circle shape
+ * @param xform_circle Transform for the circle shape
+ * @param flip_anchors Whether to flip anchors of contact or not
+ * @return nvPersistentContactPair
*/
-nvResolution nv_collide_polygon_x_circle(nvBody *polygon, nvBody *circle);
+nvPersistentContactPair nv_collide_polygon_x_circle(
+ nvShape *polygon,
+ nvTransform xform_poly,
+ nvShape *circle,
+ nvTransform xform_circle,
+ nv_bool flip_anchors
+);
/**
- * @brief Calculate the collision between two polygons
+ * @brief Check polygons collision and generate contact point information.
*
- * @param a First polygon body
- * @param b Second polygon body
- * @return nvResolution
+ * @param polygon_a First polygon shape
+ * @param xform_a First transform
+ * @param polygon_b Second polygon shape
+ * @param xform_b Second transform
+ * @return nvPersistentContactPair
*/
-nvResolution nv_collide_polygon_x_polygon(nvBody *a, nvBody *b);
+nvPersistentContactPair nv_collide_polygon_x_polygon(
+ nvShape *polygon_a,
+ nvTransform xform_a,
+ nvShape *polygon_b,
+ nvTransform xform_b
+);
/**
- * @brief Check if point is inside polygon
+ * @brief Check if point is inside polygon.
*
- * @param polygon Polygon body
+ * @param polygon Polygon shape
+ * @param xform Transform for the shape
* @param point Point
- * @return bool
+ * @return nv_bool
*/
-bool nv_collide_polygon_x_point(nvBody *polygon, nvVector2 point);
-
+nv_bool nv_collide_polygon_x_point(
+ nvShape *polygon,
+ nvTransform xform,
+ nvVector2 point
+);
/**
- * @brief Check if two AABBs collide
+ * @brief Check if two AABBs collide.
*
* @param a First AABB
* @param b Second AABB
- * @return bool
+ * @return nv_bool
*/
-bool nv_collide_aabb_x_aabb(nvAABB a, nvAABB b);
+nv_bool nv_collide_aabb_x_aabb(nvAABB a, nvAABB b);
/**
- * @brief Check if point is inside AABB
+ * @brief Check if point is inside AABB.
*
* @param aabb AABB
* @param point Point
- * @return bool
+ * @return nv_bool
+ */
+nv_bool nv_collide_aabb_x_point(nvAABB aabb, nvVector2 point);
+
+/**
+ * @brief Check if ray intersects circle.
+ *
+ * @note You should use @ref nvSpace_cast_ray unless you need this function standalone.
+ *
+ * @param result Ray cast result
+ * @param origin Ray starting point
+ * @param dir Ray direction
+ * @param maxsq Maximum ray range squared
+ * @param shape Circle shape
+ * @param xform Transform for the shape
+ * @return nv_bool
+ */
+nv_bool nv_collide_ray_x_circle(
+ nvRayCastResult *result,
+ nvVector2 origin,
+ nvVector2 dir,
+ nv_float maxsq,
+ nvShape *shape,
+ nvTransform xform
+);
+
+/**
+ * @brief Check if ray intersects polygon.
+ *
+ * @note You should use @ref nvSpace_cast_ray unless you need this function standalone.
+ *
+ * @param result Ray cast result
+ * @param origin Ray starting point
+ * @param dir Ray direction
+ * @param maxsq Maximum ray range squared
+ * @param shape Polygon shape
+ * @param xform Transform for the shape
+ * @return nv_bool
*/
-bool nv_collide_aabb_x_point(nvAABB aabb, nvVector2 point);
+nv_bool nv_collide_ray_x_polygon(
+ nvRayCastResult *result,
+ nvVector2 origin,
+ nvVector2 dir,
+ nv_float maxsq,
+ nvShape *shape,
+ nvTransform xform
+);
#endif
\ No newline at end of file
diff --git a/include/novaphysics/constants.h b/include/novaphysics/constants.h
index 27f18b2..b7bbee1 100644
--- a/include/novaphysics/constants.h
+++ b/include/novaphysics/constants.h
@@ -12,6 +12,7 @@
#define NOVAPHYSICS_CONSTANTS_H
#include
+#include
/**
@@ -23,6 +24,8 @@
#define NV_PI 3.141592653589793238462643383279502884
+// Inverse golden ratio, for golden-section search.
+#define NV_INV_PHI 0.6180339887498948482045868343656
#ifndef INFINITY
#define NV_INF (1.0 / 0.0)
@@ -30,25 +33,30 @@
#define NV_INF INFINITY
#endif
+#ifdef NV_USE_DOUBLE_PRECISION
+ #define NV_FLOAT_EPSILON DBL_EPSILON
+#else
+ #define NV_FLOAT_EPSILON FLT_EPSILON
+#endif
-/*
- Baumgarte stabilization factor is used to correct constraint erros
- in the iterative solver.
- You can learn about it in Erin Catto's publications about constraints:
- - https://box2d.org/files/ErinCatto_UnderstandingConstraints_GDC2014.pdf
- - https://box2d.org/files/ErinCatto_ModelingAndSolvingConstraints_GDC2009.pdf
-*/
-#define NV_BAUMGARTE 0.2
+// Maximum number of vertices one polygon shape can have.
+#define NV_POLYGON_MAX_VERTICES 16
-/*
- The default number of frames the collision resolutions stays cached.
- This can be changed from space's collision_persistence member.
-*/
-#define NV_COLLISION_PERSISTENCE 3
-// Amount of error allowed in position correction
-#define NV_POSITION_CORRECTION_SLOP 0.005//0.015
+// Maximum number of control points one spline constraint can have.
+#define NV_SPLINE_CONSTRAINT_MAX_CONTROL_POINTS 64
+
+// Number of samples used to get the closes spline segment.
+#define NV_SPLINE_CONSTRAINT_SAMPLES 500
+
+// Tolerance for golden-section search used in spline constraints.
+#define NV_SPLINE_CONSTRAINT_TOLERANCE 0.00001
+
+
+// How many bodies one leaf node can store before terminating
+#define NV_BVH_LEAF_THRESHOLD 1
+
// Gravitational constant. G = 6.6743 * 10^-11
#define NV_GRAV_CONST 6.6743e-11
@@ -64,14 +72,14 @@
#define NV_GRAV_SUN 275.0
#define NV_GRAV_VOID 0.0
+
// Default capacity of hash maps, must be a power of 2.
-#define NV_HASHMAP_CAPACITY 16
+#define NV_HASHMAP_CAPACITY 1024
-/*
- Specifies how many bodies one leaf node of the BVH tree can include
- before terminating the subdivision.
-*/
-#define NV_BVH_LEAF_THRESHOLD 1
+
+// Initial size for the broadphase memory pool.
+// 16B * 10000 =~ 160KB I think this is sufficient for an arbitrary default size.
+#define NV_BPH_POOL_INITIAL_SIZE 10000
#endif
\ No newline at end of file
diff --git a/include/novaphysics/constraint.h b/include/novaphysics/constraint.h
deleted file mode 100644
index 7dc5a3b..0000000
--- a/include/novaphysics/constraint.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_CONSTRAINT_H
-#define NOVAPHYSICS_CONSTRAINT_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-
-
-/**
- * @file constraint.h
- *
- * @brief Base constraint definition.
- */
-
-
-/**
- * @brief Constraint types.
- */
-typedef enum {
- nvConstraintType_SPRING, /**< Spring constraint type. See @ref nvSpring. */
- nvConstraintType_DISTANCEJOINT, /**< Distance joint constraint type. See @ref nvDistanceJoint. */
- nvConstraintType_HINGEJOINT /**< Hinge joint constraint type. See @ref nvHingeJoint. */
-} nvConstraintType;
-
-
-/**
- * @brief Constraint base struct.
- */
-typedef struct {
- nvConstraintType type; /**< Type of the constraint. */
- void *def; /**< Constraint definition class. (This needs to be casted) */
- nvBody *a; /**< First body. */
- nvBody *b; /**< Second body. */
-} nvConstraint;
-
-/**
- * @brief Free constraint.
- *
- * @param cons Constraint
- */
-void nvConstraint_free(void *cons);
-
-/**
- * @brief Prepare for solving.
- *
- * @param space Space
- * @param cons Constraintt
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nvConstraint_presolve(
- struct nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-);
-
-/**
- * @brief Solve constraint.
- *
- * @param cons Constraint
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nvConstraint_solve(nvConstraint *cons, nv_float inv_dt);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/constraints/constraint.h b/include/novaphysics/constraints/constraint.h
new file mode 100644
index 0000000..404707e
--- /dev/null
+++ b/include/novaphysics/constraints/constraint.h
@@ -0,0 +1,158 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_CONSTRAINT_H
+#define NOVAPHYSICS_CONSTRAINT_H
+
+#include "novaphysics/internal.h"
+#include "novaphysics/body.h"
+
+
+/**
+ * @file constraints/constraint.h
+ *
+ * @brief Base constraint definition.
+ */
+
+
+/**
+ * @brief Type of algorithm used to solve position error in collisions.
+ *
+ * @note Changing this setting should be usually avoided unless you have
+ * a specific need or familiar with the behavior.
+ *
+ * In baumgarte stabilization, the position error is fed back into the velocity
+ * constraint, this is an efficient solution however it adds energy to the system.
+ *
+ * NGS (Non-Linear Gauss-Seidel) uses pseudo-velocities to resolve the drift.
+ * It is computationally bit more expensive but more stable.
+ * It is what version 2 of Box2D uses.
+ *
+ * @warning Nova, as of 1.0.0, doesn't have NGS solver yet.
+ */
+typedef enum {
+ nvContactPositionCorrection_BAUMGARTE, /**< Baumgarte stabilization. */
+ nvContactPositionCorrection_NGS /**< Non-Linear Gauss-Seidel. */
+} nvContactPositionCorrection;
+
+
+/**
+ * @brief Coefficient mixing type is the method to mix various coefficients
+ * values like restitution and friction.
+ */
+typedef enum {
+ nvCoefficientMix_AVG, /**< (a + b) * 0.5 */
+ nvCoefficientMix_MUL, /**< a * b */
+ nvCoefficientMix_SQRT, /**< sqrt(a * b) */
+ nvCoefficientMix_MIN, /**< min(a, b) */
+ nvCoefficientMix_MAX /**< max(a, b) */
+} nvCoefficientMix;
+
+/**
+ * @brief Mix two coefficient values.
+ *
+ * @param a First value
+ * @param b Second value
+ * @param mix Mixing type
+ * @return nv_float
+ */
+static inline nv_float nv_mix_coefficients(
+ nv_float a,
+ nv_float b,
+ nvCoefficientMix mix
+) {
+ switch (mix) {
+ case nvCoefficientMix_AVG:
+ return (a + b) * (nv_float)0.5;
+
+ case nvCoefficientMix_MUL:
+ return a * b;
+
+ case nvCoefficientMix_SQRT:
+ return nv_sqrt(a * b);
+
+ case nvCoefficientMix_MIN:
+ return nv_fmin(a, b);
+
+ case nvCoefficientMix_MAX:
+ return nv_fmax(a, b);
+
+ default:
+ // worth setting error?
+ return 0.0;
+ }
+}
+
+
+/**
+ * @brief Constraint types.
+ *
+ * Contact constraint is not included because it's handled internally by the engine.
+ */
+typedef enum {
+ nvConstraintType_DISTANCE, /**< Distance constraint type. See @ref nvDistanceConstraint. */
+ nvConstraintType_HINGE, /**< Hinge constraint type. See @ref nvHingeConstraint. */
+ nvConstraintType_SPLINE /**< Spline constraint type. See @ref nvSplineConstraint. */
+} nvConstraintType;
+
+
+/**
+ * @brief Base two-body constraint.
+ */
+typedef struct {
+ nvConstraintType type; /**< Type of the constraint. */
+ void *def; /**< Constraint definition class. (This needs to be casted) */
+ nvRigidBody *a; /**< First body. */
+ nvRigidBody *b; /**< Second body. */
+ nv_bool ignore_collision; /**< Ignore collision of bodies connected with this constraint. */
+} nvConstraint;
+
+/**
+ * @brief Free constraint.
+ *
+ * It's safe to pass `NULL` to this function.
+ *
+ * @param cons Constraint
+ */
+void nvConstraint_free(nvConstraint *cons);
+
+/**
+ * @brief Prepare for solving.
+ *
+ * @param space Space
+ * @param cons Constraint
+ * @param dt Delta time
+ * @param inv_dt Inverse delta time
+ */
+void nvConstraint_presolve(
+ struct nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+);
+
+/**
+ * @brief Warmstart / Accumulate impulses from last frame.
+ *
+ * @param space Space
+ * @param cons Constraint
+ */
+void nvConstraint_warmstart(struct nvSpace *space, nvConstraint *cons);
+
+/**
+ * @brief Solve constraint.
+ *
+ * @param cons Constraint
+ * @param inv_dt Inverse delta time
+ */
+void nvConstraint_solve(nvConstraint *cons, nv_float inv_dt);
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/constraints/contact_constraint.h b/include/novaphysics/constraints/contact_constraint.h
new file mode 100644
index 0000000..21034fd
--- /dev/null
+++ b/include/novaphysics/constraints/contact_constraint.h
@@ -0,0 +1,64 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_CONTACT_CONSTRAINT_H
+#define NOVAPHYSICS_CONTACT_CONSTRAINT_H
+
+#include "novaphysics/internal.h"
+#include "novaphysics/body.h"
+#include "novaphysics/contact.h"
+#include "novaphysics/collision.h"
+#include "novaphysics/constraints/constraint.h"
+
+
+/**
+ * @file constraints/contact_constraint.h
+ *
+ * @brief Contact constraint solver functions.
+ */
+
+
+/**
+ * @brief Prepare for solving contact constraints.
+ *
+ * @param space Space
+ * @param pcp Contact pair
+ * @param inv_dt Inverse delta time
+ */
+void nv_contact_presolve(
+ struct nvSpace *space,
+ nvPersistentContactPair *pcp,
+ nv_float inv_dt
+);
+
+/**
+ * @brief Apply accumulated impulses from last frame.
+ *
+ * @param space Space
+ * @param pcp Contact pair
+ */
+void nv_contact_warmstart(struct nvSpace *space, nvPersistentContactPair *pcp);
+
+/**
+ * @brief Solve contact velocity constraints (PGS [+ Baumgarte]).
+ *
+ * @param pcp Contact pair
+ */
+void nv_contact_solve_velocity(nvPersistentContactPair *pcp);
+
+/**
+ * @brief Solve position error (NGS).
+ *
+ * @param pcp Contact pair
+ */
+void nv_contact_solve_position(nvPersistentContactPair *pcp);
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/constraints/distance_constraint.h b/include/novaphysics/constraints/distance_constraint.h
new file mode 100644
index 0000000..7d4cb78
--- /dev/null
+++ b/include/novaphysics/constraints/distance_constraint.h
@@ -0,0 +1,266 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_DISTANCE_CONSTRAINT_H
+#define NOVAPHYSICS_DISTANCE_CONSTRAINT_H
+
+#include "novaphysics/internal.h"
+#include "novaphysics/constraints/constraint.h"
+
+
+/**
+ * @file constraints/distance_constraint.h
+ *
+ * @brief Distance constraint solver.
+ */
+
+
+/**
+ * @brief Distance constraint definition.
+ *
+ * It constraints the distance of two points on the two bodies to be constant.
+ * This acts like as if the two bodies are linked with a solid bar.
+ * TODO: lower upper limit
+ * TODO: explain spring
+ */
+typedef struct {
+ /*
+ Private members
+ */
+ nvVector2 xanchor_a; /**< Anchor A transformed with body's rotation. */
+ nvVector2 xanchor_b; /**< Anchor B transformed with body's rotation. */
+ nvVector2 normal; /**< Normal axis of the constraint. */
+ nv_float bias; /**< Constraint position correction bias. */
+ nv_float mass; /**< Constraint effective mass. */
+ nv_float impulse; /**< Accumulated impulse. */
+ nv_float max_impulse; /**< Max force * dt. */
+
+ // Soft-constraint coefficients for the incremental lambda
+ nv_float bias_rate;
+ nv_float mass_coeff;
+ nv_float impulse_coeff;
+
+ /*
+ Public members (setters & getters)
+ */
+ nv_float length;
+ nvVector2 anchor_a;
+ nvVector2 anchor_b;
+ nv_float max_force;
+ nv_bool spring;
+ nv_float hertz;
+ nv_float damping;
+} nvDistanceConstraint;
+
+
+/**
+ * @brief Distance constraint initializer information.
+ *
+ * This struct holds basic information for initializing and can be reused
+ * for multiple constraints if the bodies are changed.
+ */
+typedef struct {
+ nvRigidBody *a; /**< Body A. */
+ nvRigidBody *b; /**< Body B. */
+ nv_float length; /**< Length of the distance constraint. */
+ nvVector2 anchor_a; /**< Local anchor point on body A. */
+ nvVector2 anchor_b; /**< Local anchor point on body B. */
+ nv_float max_force; /**< Maximum force allowed to solve the constraint. */
+ nv_bool spring; /**< Is this distance constraint spring (soft-constraint)? */
+ nv_float hertz; /**< Spring frequency. */
+ nv_float damping; /**< Spring damping ratio. */
+} nvDistanceConstraintInitializer;
+
+static const nvDistanceConstraintInitializer nvDistanceConstraintInitializer_default = {
+ NULL,
+ NULL,
+ 1.0,
+ {0.0, 0.0},
+ {0.0, 0.0},
+ NV_INF,
+ false,
+ 3.0,
+ 0.3
+};
+
+
+/**
+ * @brief Create a new distance constraint.
+ *
+ * Leave one of the body parameters as `NULL` to link the body to world.
+ * Don't forget to change the anchor point to be in world space as well.
+ *
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
+ * @param init Initializer info
+ * @return nvConstraint *
+ */
+nvConstraint *nvDistanceConstraint_new(nvDistanceConstraintInitializer init);
+
+/**
+ * @brief Get body A of the constraint.
+ *
+ * @param cons Constraint
+ * @return nvRigidBody *
+ */
+nvRigidBody *nvDistanceConstraint_get_body_a(const nvConstraint *cons);
+
+/**
+ * @brief Get body B of the constraint.
+ *
+ * @param cons Constraint
+ * @return nvRigidBody *
+ */
+nvRigidBody *nvDistanceConstraint_get_body_b(const nvConstraint *cons);
+
+/**
+ * @brief Set length of the distance constraint.
+ *
+ * @param cons Constraint
+ * @param length Length
+ */
+void nvDistanceConstraint_set_length(nvConstraint *cons, nv_float length);
+
+/**
+ * @brief Get length of the distance constraint.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvDistanceConstraint_get_length(const nvConstraint *cons);
+
+/**
+ * @brief Set local anchor point on body A.
+ *
+ * @param cons Constraint
+ * @param anchor_a Anchor
+ */
+void nvDistanceConstraint_set_anchor_a(nvConstraint *cons, nvVector2 anchor_a);
+
+/**
+ * @brief Get local anchor point on body A.
+ *
+ * @param cons Constraint
+ * @return nvVector2
+ */
+nvVector2 nvDistanceConstraint_get_anchor_a(const nvConstraint *cons);
+
+/**
+ * @brief Set local anchor point on body B.
+ *
+ * @param cons Constraint
+ * @param anchor_b Anchor
+ */
+void nvDistanceConstraint_set_anchor_b(nvConstraint *cons, nvVector2 anchor_b);
+
+/**
+ * @brief Get local anchor point on body B.
+ *
+ * @param cons Constraint
+ * @return nvVector2
+ */
+nvVector2 nvDistanceConstraint_get_anchor_b(const nvConstraint *cons);
+
+/**
+ * @brief Set max force used to solve the constraint.
+ *
+ * @param cons Constraint
+ * @param max_force Max force
+ */
+void nvDistanceConstraint_set_max_force(nvConstraint *cons, nv_float max_force);
+
+/**
+ * @brief Get max force used to solve the constraint.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvDistanceConstraint_get_max_force(const nvConstraint *cons);
+
+/**
+ * @brief Enable/disable spring behavior.
+ *
+ * @param cons Constraint
+ * @param spring Bool
+ */
+void nvDistanceConstraint_set_spring(nvConstraint *cons, nv_bool spring);
+
+/**
+ * @brief Get whether spring behavior is enabled or not.
+ *
+ * @param cons Constraint
+ * @return nv_bool
+ */
+nv_bool nvDistanceConstraint_get_spring(const nvConstraint *cons);
+
+/**
+ * @brief Set spring frequency.
+ *
+ * @param cons Constraint
+ * @param hertz Frequency
+ */
+void nvDistanceConstraint_set_hertz(nvConstraint *cons, nv_float hertz);
+
+/**
+ * @brief Get spring frequency.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvDistanceConstraint_get_hertz(const nvConstraint *cons);
+
+/**
+ * @brief Set spring damping ratio.
+ *
+ * @param cons Constraint
+ * @param damping Damping ratio
+ */
+void nvDistanceConstraint_set_damping(nvConstraint *cons, nv_float damping);
+
+/**
+ * @brief Get spring damping ratio.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvDistanceConstraint_get_damping(const nvConstraint *cons);
+
+/**
+ * @brief Prepare for solving.
+ *
+ * @param space Space
+ * @param cons Constraint
+ * @param dt Delta time
+ * @param inv_dt Inverse delta time
+ */
+void nvDistanceConstraint_presolve(
+ struct nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+);
+
+/**
+ * @brief Apply accumulated impulses from last frame.
+ *
+ * @param space Space
+ * @param cons Constraint
+ */
+void nvDistanceConstraint_warmstart(struct nvSpace *space, nvConstraint *cons);
+
+/**
+ * @brief Solve distance constraint.
+ *
+ * @param cons Constraint
+ */
+void nvDistanceConstraint_solve(nvConstraint *cons);
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/constraints/hinge_constraint.h b/include/novaphysics/constraints/hinge_constraint.h
new file mode 100644
index 0000000..9571240
--- /dev/null
+++ b/include/novaphysics/constraints/hinge_constraint.h
@@ -0,0 +1,232 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_HINGE_CONSTRAINT_H
+#define NOVAPHYSICS_HINGE_CONSTRAINT_H
+
+#include "novaphysics/internal.h"
+#include "novaphysics/constraints/constraint.h"
+
+
+/**
+ * @file constraints/hinge_constraint.h
+ *
+ * @brief Hinge constraint solver.
+ */
+
+
+/**
+ * @brief Hinge constraint definition.
+ *
+ * A hinge, also known as revolute or point, constraint allows the
+ * bodies to rotate around a common axis. Ensuring the relative orientation of
+ * the bodies remains fixed.
+ */
+typedef struct {
+ /*
+ Private members
+ */
+ nvVector2 anchor_a; /**< Anchor local to body A. */
+ nvVector2 anchor_b; /**< Anchor local to body B. */
+ nvVector2 xanchor_a; /**< Anchor A transformed with body's rotation. */
+ nvVector2 xanchor_b; /**< Anchor B transformed with body's rotation. */
+ nv_float upper_impulse; /**< Accumulated upper limit impulse. */
+ nv_float lower_impulse; /**< Accumulated lower limit impulse. */
+ nv_float upper_bias; /**< Upper angle limit constraint correction bias. */
+ nv_float lower_bias;/**< Lower angle limit constraint correction bias. */
+ nv_float reference_angle; /**< Reference angle for the constraint. */
+ nv_float axial_mass; /**< Axial effective mass. */
+ nvVector2 normal; /**< Normal axis of the constraint. */
+ nv_float bias; /**< Point constraint position correction bias. */
+ nv_float mass; /**< Point constraint effective mass. */
+ nv_float impulse; /**< Accumulated point constraint impulse. */
+ nv_float max_impulse; /**< Max force * dt. */
+
+ /*
+ Public members (setters & getters)
+ */
+ nvVector2 anchor;
+ nv_bool enable_limits;
+ nv_float upper_limit;
+ nv_float lower_limit;
+ nv_float angle;
+ nv_float max_force;
+} nvHingeConstraint;
+
+
+/**
+ * @brief Hinge constraint initializer information.
+ *
+ * This struct holds basic information for initializing and can be reused
+ * for multiple constraints if the bodies are changed.
+ */
+typedef struct {
+ nvRigidBody *a; /**< Body A. */
+ nvRigidBody *b; /**< Body B. */
+ nvVector2 anchor; /**< Anchor point in world space. */
+ nv_bool enable_limits; /**< Whether to enable angular limits or not. */
+ nv_float upper_limit; /**< Upper angle limit. */
+ nv_float lower_limit; /**< Lower angle limit. */
+ nv_float max_force; /**< Maximum force allowed to solve the constraint. */
+} nvHingeConstraintInitializer;
+
+static const nvHingeConstraintInitializer nvHingeConstraintInitializer_default = {
+ NULL,
+ NULL,
+ {0.0, 0.0},
+ false,
+ NV_PI * 0.5,
+ -NV_PI * 0.5,
+ NV_INF
+};
+
+
+/**
+ * @brief Create a new hinge constraint.
+ *
+ * Leave one of the body parameters as `NULL` to link the body to world.
+ * Don't forget to change the anchor point to be in world space as well.
+ *
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
+ * @param init Initializer info
+ * @return nvConstraint *
+ */
+nvConstraint *nvHingeConstraint_new(nvHingeConstraintInitializer init);
+
+/**
+ * @brief Get body A of the constraint.
+ *
+ * @param cons Constraint
+ * @return nvRigidBody *
+ */
+nvRigidBody *nvHingeConstraint_get_body_a(const nvConstraint *cons);
+
+/**
+ * @brief Get body B of the constraint.
+ *
+ * @param cons Constraint
+ * @return nvRigidBody *
+ */
+nvRigidBody *nvHingeConstraint_get_body_b(const nvConstraint *cons);
+
+/**
+ * @brief Set anchor of the hinge constraint in world space.
+ *
+ * @param cons Constraint
+ * @param anchor Anchor point in world space
+ */
+void nvHingeConstraint_set_anchor(nvConstraint *cons, nvVector2 anchor);
+
+/**
+ * @brief Get anchor of the hinge constraint in world space.
+ *
+ * @param cons Constraint
+ * @return nvVector2
+ */
+nvVector2 nvHingeConstraint_get_anchor(const nvConstraint *cons);
+
+/**
+ * @brief Enable/disable angular limits.
+ *
+ * @param cons Constraint
+ * @param limits Bool
+ */
+void nvHingeConstraint_set_limits(nvConstraint *cons, nv_bool limits);
+
+/**
+ * @brief Get whether angular limits is enabled or not.
+ *
+ * @param cons Constraint
+ * @return nv_bool
+ */
+nv_bool nvHingeConstraint_get_limits(const nvConstraint *cons);
+
+/**
+ * @brief Set upper angular limit.
+ *
+ * @param cons Constraint
+ * @param upper_limit Upper limit
+ */
+void nvHingeConstraint_set_upper_limit(nvConstraint *cons, nv_float upper_limit);
+
+/**
+ * @brief Get upper angular limit.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvHingeConstraint_get_upper_limit(const nvConstraint *cons);
+
+/**
+ * @brief Set lower angular limit.
+ *
+ * @param cons Constraint
+ * @param lower_limit Lower limit
+ */
+void nvHingeConstraint_set_lower_limit(nvConstraint *cons, nv_float lower_limit);
+
+/**
+ * @brief Get lower angular limit.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvHingeConstraint_get_lower_limit(const nvConstraint *cons);
+
+/**
+ * @brief Set max force used to solve the constraint.
+ *
+ * @param cons Constraint
+ * @param max_force Max force
+ */
+void nvHingeConstraint_set_max_force(nvConstraint *cons, nv_float max_force);
+
+/**
+ * @brief Get max force used to solve the constraint.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvHingeConstraint_get_max_force(const nvConstraint *cons);
+
+
+/**
+ * @brief Prepare for solving.
+ *
+ * @param space Space
+ * @param cons Constraint
+ * @param inv_dt Inverse delta time
+ */
+void nvHingeConstraint_presolve(
+ struct nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+);
+
+/**
+ * @brief Apply accumulated impulses from last frame.
+ *
+ * @param space Space
+ * @param cons Constraint
+ */
+void nvHingeConstraint_warmstart(struct nvSpace *space, nvConstraint *cons);
+
+/**
+ * @brief Solve hinge constraint.
+ *
+ * @param cons Constraint
+ * @param inv_dt Inverse delta time
+ */
+void nvHingeConstraint_solve(nvConstraint *cons, nv_float inv_dt);
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/constraints/spline_constraint.h b/include/novaphysics/constraints/spline_constraint.h
new file mode 100644
index 0000000..2eb273d
--- /dev/null
+++ b/include/novaphysics/constraints/spline_constraint.h
@@ -0,0 +1,188 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_SPLINE_CONSTRAINT_H
+#define NOVAPHYSICS_SPLINE_CONSTRAINT_H
+
+#include "novaphysics/internal.h"
+#include "novaphysics/constraints/constraint.h"
+
+
+/**
+ * @file constraints/spline_constraint.h
+ *
+ * @brief Spline constraint solver.
+ */
+
+
+/**
+ * @brief Spline constraint definition.
+ *
+ * This constrains the body to a catmull-rom spline path.
+ * https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline
+ */
+typedef struct {
+ /*
+ Private members
+ */
+ nvVector2 anchor_a; /**< Anchor local to body A. */
+ nvVector2 anchor_b; /**< Anchor local to body B. */
+ nvVector2 xanchor_a; /**< Anchor A transformed with body's rotation. */
+ nvVector2 xanchor_b; /**< Anchor B transformed with body's rotation. */
+ nvVector2 normal; /**< Normal axis of the constraint. */
+ nv_float bias; /**< Constraint position correction bias. */
+ nv_float mass; /**< Point constraint effective mass. */
+ nv_float impulse; /**< Accumulated point constraint impulse. */
+ nv_float max_impulse; /**< Max force * dt. */
+
+ /*
+ Public members (setters & getters)
+ */
+ nvVector2 anchor;
+ nv_float max_force;
+ nvVector2 controls[NV_SPLINE_CONSTRAINT_MAX_CONTROL_POINTS];
+ size_t num_controls;
+} nvSplineConstraint;
+
+
+/**
+ * @brief Spline constraint initializer information.
+ *
+ * This struct holds basic information for initializing and can be reused
+ * for multiple constraints if the bodies are changed.
+ */
+typedef struct {
+ nvRigidBody *body; /**< Body. */
+ nvVector2 anchor; /**< Anchor point in world space. */
+ nv_float max_force; /**< Maximum force allowed to solve the constraint. */
+} nvSplineConstraintInitializer;
+
+static const nvSplineConstraintInitializer nvSplineConstraintInitializer_default = {
+ NULL,
+ {0.0, 0.0},
+ NV_INF
+};
+
+
+/**
+ * @brief Create a new spline constraint.
+ *
+ * Leave one of the body parameters as `NULL` to link the body to world.
+ * Don't forget to change the anchor point to be in world space as well.
+ *
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
+ * @param init Initializer info
+ * @return nvConstraint *
+ */
+nvConstraint *nvSplineConstraint_new(nvSplineConstraintInitializer init);
+
+/**
+ * @brief Get body of the constraint.
+ *
+ * @param cons Constraint
+ * @return nvRigidBody *
+ */
+nvRigidBody *nvSplineConstraint_get_body(const nvConstraint *cons);
+
+/**
+ * @brief Set anchor point in world space.
+ *
+ * @param cons Constraint
+ * @param anchor Anchor
+ */
+void nvSplineConstraint_set_anchor(nvConstraint *cons, nvVector2 anchor);
+
+/**
+ * @brief Get anchor point in world space.
+ *
+ * @param cons Constraint
+ * @return nvVector2
+ */
+nvVector2 nvSplineConstraint_get_anchor(const nvConstraint *cons);
+
+/**
+ * @brief Set max force used to solve the constraint.
+ *
+ * @param cons Constraint
+ * @param max_force Max force
+ */
+void nvSplineConstraint_set_max_force(nvConstraint *cons, nv_float max_force);
+
+/**
+ * @brief Get max force used to solve the constraint.
+ *
+ * @param cons Constraint
+ * @return nv_float
+ */
+nv_float nvSplineConstraint_get_max_force(const nvConstraint *cons);
+
+/**
+ * @brief Set control points of the spline.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @param cons Constraint
+ * @param points Array of nvVector2
+ * @param num_points Number of points
+ */
+int nvSplineConstraint_set_control_points(
+ nvConstraint *cons,
+ nvVector2 *points,
+ size_t num_points
+);
+
+/**
+ * @brief Get control points of the spline.
+ *
+ * @param cons Constraint
+ * @return nvVector2 *
+ */
+nvVector2 *nvSplineConstraint_get_control_points(const nvConstraint *cons);
+
+/**
+ * @brief Get the number of control points of the spline.
+ *
+ * @param cons Constraints
+ * @return size_t
+ */
+size_t nvSplineConstraint_get_number_of_control_points(const nvConstraint *cons);
+
+/**
+ * @brief Prepare for solving.
+ *
+ * @param space Space
+ * @param cons Constraint
+ * @param inv_dt Inverse delta time
+ */
+void nvSplineConstraint_presolve(
+ struct nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+);
+
+/**
+ * @brief Apply accumulated impulses from last frame.
+ *
+ * @param space Space
+ * @param cons Constraint
+ */
+void nvSplineConstraint_warmstart(struct nvSpace *space, nvConstraint *cons);
+
+/**
+ * @brief Solve spline constraint.
+ *
+ * @param cons Constraint
+ */
+void nvSplineConstraint_solve(nvConstraint *cons);
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/contact.h b/include/novaphysics/contact.h
index a2066bb..89a4c30 100644
--- a/include/novaphysics/contact.h
+++ b/include/novaphysics/contact.h
@@ -11,44 +11,131 @@
#ifndef NOVAPHYSICS_CONTACT_H
#define NOVAPHYSICS_CONTACT_H
+#include "novaphysics/internal.h"
#include "novaphysics/vector.h"
-#include "novaphysics/array.h"
+#include "novaphysics/shape.h"
#include "novaphysics/body.h"
-#include "novaphysics/resolution.h"
/**
* @file contact.h
*
- * @brief Contact point calculation functions.
+ * @brief Collision and contact information.
*/
/**
- * @brief Calculate contact point between circle bodies
- *
- * @param res Collision resolution
- * @return nvVector2
+ * @brief Solver related information for collision.
*/
-void nv_contact_circle_x_circle(nvResolution *res);
+typedef struct {
+ nv_float normal_impulse; /**< Accumulated normal impulse. */
+ nv_float tangent_impulse; /**< Accumulated tangent impulse. */
+ nv_float mass_normal; /**< Normal effective mass. */
+ nv_float mass_tangent; /**< Tangent effective mass. */
+ nv_float velocity_bias; /**< Restitution bias. */
+ nv_float position_bias; /**< Baumgarte position correction bias. */
+ nv_float friction; /**< Friction coefficient. */
+} nvContactSolverInfo;
+
+static const nvContactSolverInfo nvContactSolverInfo_zero = {
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
+};
+
+
+/**
+ * @brief Contact point that persists across frames.
+ */
+typedef struct {
+ nvVector2 anchor_a; /**< Location of point relative to body A position. */
+ nvVector2 anchor_b; /**< Location of point relative to body B position. */
+ nv_float separation; /**< Depth of the contact point in reference body. */
+ nv_uint64 id; /**< Contact point feature ID. */
+ nv_bool is_persisted; /**< Did this contact point persist? */
+ nv_bool remove_invoked; /**< Did event listener invoke this point for removed? */
+ nvContactSolverInfo solver_info; /**< Solver related information. */
+} nvContact;
+
/**
- * @brief Calculate contact point between polygon and circle body
+ * @brief Collision information structure that persists across frames.
+ */
+typedef struct {
+ nvVector2 normal; /**< Normal axis of collision. */
+ nvContact contacts[2]; /**< Contact points. */
+ nv_uint32 contact_count; /**< Number of contact points. */
+ nvShape *shape_a; /**< First shape. */
+ nvShape *shape_b; /**< Second shape. */
+ nvRigidBody *body_a; /**< First body. */
+ nvRigidBody *body_b; /**< Second body. */
+} nvPersistentContactPair;
+
+/**
+ * @brief Is this current contact pair actually penetrating?
*
- * @param polygon Polygon body
- * @param circle Circle body
- * @return nvVector2
+ * @param pcp Persistent contact pair
+ * @return nv_bool
+ */
+nv_bool nvPersistentContactPair_penetrating(nvPersistentContactPair *pcp);
+
+/**
+ * @brief Make a unique key from two contact shapes.
*/
-void nv_contact_polygon_x_circle(nvResolution *res);
+static inline nv_uint64 nvPersistentContactPair_key(nvShape *a, nvShape *b) {
+ /*
+ Combining truncated parts of the pointers might better than using
+ just the truncated low bits.
+ */
+
+ // Using IDs directly instead of hashing creates lots of collisions
+ nv_uint32 fpa = nv_u32hash(a->id);
+ nv_uint32 fpb = nv_u32hash(b->id);
+
+ return nv_u32pair(fpa, fpb);
+}
/**
- * @brief Calculate contact points between polygon bodies
+ * @brief Persistent contact pair hashmap callback.
+ */
+nv_uint64 nvPersistentContactPair_hash(void *item);
+
+/**
+ * @brief Remove contact and invoke event.
*
- * @param a First polygon body
- * @param b Second polygon body
- * @return nvContacts
+ * @param space Space
+ */
+void nvPersistentContactPair_remove(
+ struct nvSpace *space,
+ nvPersistentContactPair *pcp
+);
+
+
+/**
+ * @brief Contact event information.
+ */
+typedef struct {
+ nvRigidBody *body_a; /**< Body A. */
+ nvRigidBody *body_b; /**< Body B. */
+ nvShape *shape_a; /**< Shape A. */
+ nvShape *shape_b; /**< Shape B. */
+ nvVector2 normal; /**< Collision normal. */
+ nv_float penetration; /**< Contact point penetration depth. */
+ nvVector2 position; /**< Contact point position in world space. */
+ nvVector2 normal_impulse; /**< Impulse applied for non-penetration. */
+ nvVector2 friction_impulse; /**< Impulse applied for friction. */
+ nv_uint64 id; /**< Contact feature ID. */
+} nvContactEvent;
+
+typedef void (*nvContactListenerCallback)(struct nvSpace *space, nvContactEvent event, void *user_arg);
+
+/**
+ * @brief Contact event listener.
*/
-void nv_contact_polygon_x_polygon(nvResolution *res);
+typedef struct {
+ nvContactListenerCallback on_contact_added; /**< This function is called the first frame where a contact point is detected.
+ Since it's not solved yet, impulse information is zeros. */
+ nvContactListenerCallback on_contact_persisted; /**< This function is called every frame when a contact point persist across frames. */
+ nvContactListenerCallback on_contact_removed; /**< This function is called the first frame when a contact point no longer exists. */
+} nvContactListener;
#endif
\ No newline at end of file
diff --git a/include/novaphysics/contact_solver.h b/include/novaphysics/contact_solver.h
deleted file mode 100644
index db61d0f..0000000
--- a/include/novaphysics/contact_solver.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_SOLVER_H
-#define NOVAPHYSICS_SOLVER_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-#include "novaphysics/collision.h"
-#include "novaphysics/resolution.h"
-#include "novaphysics/constraint.h"
-
-
-/**
- * @file contact_solver.h
- *
- * @brief Contact solver functions.
- */
-
-
-/**
- * @brief Type of algorithm used to solve position error in collisions.
- *
- * @note Changing this setting should be usually avoided unless you have
- * a specific need or familiar with the behavior.
- *
- * In baumgarte stabilization, the position error is fed back into the velocity
- * constraint, this is an efficient solution however it adds energy to the system.
- *
- * NGS (Non-Linear Gauss-Seidel) uses pseudo-velocities to resolve the drift.
- * It is computationally bit more expensive but more stable.
- */
-typedef enum {
- nvPositionCorrection_BAUMGARTE, /**< Baumgarte stabilization. */
- nvPositionCorrection_NGS /**< Non-Linear Gauss-Seidel. */
-} nvPositionCorrection;
-
-
-/**
- * @brief Prepare for solving contact constraints.
- *
- * @param space Space
- * @param res Collision resolution
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nv_presolve_contact(
- struct nvSpace *space,
- nvResolution *res,
- nv_float inv_dt
-);
-
-/**
- * @brief Apply accumulated impulses.
- *
- * @param space Space
- * @param res Collision resolution
- */
-void nv_warmstart(struct nvSpace *space, nvResolution *res);
-
-/**
- * @brief Solve contact velocity constraints.
- *
- * @param res Collision resolution
- */
-void nv_solve_velocity(nvResolution *res);
-
-/**
- * @brief Solve position error (pseudo-velocities / NGS).
- *
- * @param res Collision resolution
- */
-void nv_solve_position(nvResolution *res);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/array.h b/include/novaphysics/core/array.h
similarity index 78%
rename from include/novaphysics/array.h
rename to include/novaphysics/core/array.h
index 8687309..ee63d59 100644
--- a/include/novaphysics/array.h
+++ b/include/novaphysics/core/array.h
@@ -11,12 +11,11 @@
#ifndef NOVAPHYSICS_ARRAY_H
#define NOVAPHYSICS_ARRAY_H
-#include
#include "novaphysics/internal.h"
/**
- * @file array.h
+ * @file core/array.h
*
* @brief Type-generic dynamically growing array implementation.
*/
@@ -41,25 +40,32 @@ nvArray *nvArray_new();
/**
* @brief Free array.
*
+ * It's safe to pass `NULL` to this function.
+ *
* @param array Array to free
*/
void nvArray_free(nvArray *array);
+typedef void (*nvArray_free_each_callback)(void *);
+
/**
* @brief Free each element of array.
*
* @param array Array
* @param free_func Free function
*/
-void nvArray_free_each(nvArray *array, void (free_func)(void *));
+void nvArray_free_each(nvArray *array, nvArray_free_each_callback free_func);
/**
* @brief Add new element to array.
*
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
* @param array Array to append to
* @param elem Void pointer to element
+ * @return int Status
*/
-void nvArray_add(nvArray *array, void *elem);
+int nvArray_add(nvArray *array, void *elem);
/**
* @brief Remove element by index from array and return the element. Returns `NULL` if failed.
@@ -86,12 +92,15 @@ size_t nvArray_remove(nvArray *array, void *elem);
/**
* @brief Clear the array.
*
- * Elements are not freed if `NULL` is passed as freeing function.
+ * Elements are not freed if `NULL` is passed as freeing function. Use @ref nv_get_error to get more information.
+ *
+ * Returns non-zero on error.
*
* @param array Array
* @param free_func Free function
+ * @return int Status
*/
-void nvArray_clear(nvArray *array, void (free_func)(void *));
+int nvArray_clear(nvArray *array, void (free_func)(void *));
#endif
\ No newline at end of file
diff --git a/include/novaphysics/core/error.h b/include/novaphysics/core/error.h
new file mode 100644
index 0000000..bf1f2d0
--- /dev/null
+++ b/include/novaphysics/core/error.h
@@ -0,0 +1,48 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_ERROR_H
+#define NOVAPHYSICS_ERROR_H
+
+#include
+
+
+/**
+ * @file core/error.h
+ *
+ * @brief Error handling.
+ */
+
+
+#define NV_ERROR_BUFFER_SIZE 512
+extern char _nv_error_buffer[NV_ERROR_BUFFER_SIZE];
+
+/**
+ * @brief Fill the current error buffer in with related information.
+ *
+ * @param message Error message
+ */
+#define nv_set_error(message) { \
+ sprintf( \
+ _nv_error_buffer, \
+ "Nova Physics error in %s, line %d: %s\n", \
+ __FILE__, __LINE__, message \
+ ); \
+}
+
+/**
+ * @brief Get the last occured error.
+ *
+ * @return char *
+ */
+char *nv_get_error();
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/hashmap.h b/include/novaphysics/core/hashmap.h
similarity index 87%
rename from include/novaphysics/hashmap.h
rename to include/novaphysics/core/hashmap.h
index 54ff044..9a2bdc9 100644
--- a/include/novaphysics/hashmap.h
+++ b/include/novaphysics/core/hashmap.h
@@ -11,12 +11,11 @@
#ifndef NOVAPHYSICS_HASHMAP_H
#define NOVAPHYSICS_HASHMAP_H
-#include
-#include
+#include "novaphysics/internal.h"
/**
- * @file hashmap.h
+ * @file core/hashmap.h
*
* @brief Hash map implementation.
*/
@@ -27,7 +26,6 @@ typedef struct {
nv_uint64 dib: 16;
} nvHashMapBucket;
-
/**
* @brief Hash map.
*/
@@ -37,7 +35,7 @@ typedef struct {
nv_uint64 (*hash_func)(void *item); /**< Hashing callback function. */
size_t count; /**< Current number of entries in the hash map. */
- bool oom; /**< Flag reporting if the last set query overflowed memory. */
+ nv_bool oom; /**< Flag reporting if the last set query overflowed memory. */
size_t bucketsz;
size_t nbuckets;
@@ -54,6 +52,8 @@ typedef struct {
/**
* @brief Create new hash map.
*
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
* @param item_size Size of the entries stored in the hash map
* @param cap Starting capacity of the hash map
* @param hash_func Hash function callback
@@ -113,9 +113,9 @@ void *nvHashMap_remove(nvHashMap *hashmap, void *key);
* @param hashmap Hash map
* @param index Pointer to index counter
* @param item Pointer to entry pointer
- * @return bool
+ * @return nv_bool
*/
-bool nvHashMap_iter(nvHashMap *hashmap, size_t *index, void **item);
+nv_bool nvHashMap_iter(nvHashMap *hashmap, size_t *index, void **item);
#endif
\ No newline at end of file
diff --git a/include/novaphysics/core/pool.h b/include/novaphysics/core/pool.h
new file mode 100644
index 0000000..f2039b3
--- /dev/null
+++ b/include/novaphysics/core/pool.h
@@ -0,0 +1,73 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_MEMORYPOOL_H
+#define NOVAPHYSICS_MEMORYPOOL_H
+
+#include "novaphysics/internal.h"
+
+
+/**
+ * @file core/pool.h
+ *
+ * @brief Fixed-size memory pool implementation.
+ */
+
+
+/**
+ * @brief Fixed-size memory pool implementation.
+ */
+typedef struct {
+ size_t chunk_size; /**< Fixed chunk size. */
+ size_t pool_size; /**< Pool size. */
+ size_t current_size; /**< Current number of chunks. */
+ void *pool; /**< Pool block. */
+} nvMemoryPool;
+
+/**
+ * @brief Create new memory pool.
+ *
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
+ * @param chunk_size Fixed chunk size
+ * @param initial_num_chunks Initial number of chunks
+ * @return nvMemoryPool *
+ */
+nvMemoryPool *nvMemoryPool_new(size_t chunk_size, size_t initial_num_chunks);
+
+/**
+ * @brief Free memory pool.
+ *
+ * It's safe to pass `NULL` to this function.
+ *
+ * @param pool Memory pool
+ */
+void nvMemoryPool_free(nvMemoryPool *pool);
+
+/**
+ * @brief Add a new chunk to the pool.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @param pool Memory pool
+ * @param chunk Chunk data
+ * @return int Status
+ */
+int nvMemoryPool_add(nvMemoryPool *pool, void *chunk);
+
+/**
+ * @brief Clear pool.
+ *
+ * @param pool Memory pool
+ */
+void nvMemoryPool_clear(nvMemoryPool *pool);
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/debug.h b/include/novaphysics/debug.h
index 257983c..f94a996 100644
--- a/include/novaphysics/debug.h
+++ b/include/novaphysics/debug.h
@@ -11,8 +11,6 @@
#ifndef NOVAPHYSICS_DEBUG_H
#define NOVAPHYSICS_DEBUG_H
-#include
-#include
#include "novaphysics/internal.h"
#include "novaphysics/novaphysics.h"
@@ -57,70 +55,70 @@ static inline void nv_println_Vector2(nvVector2 vector) {
/*
- nvBody debug utilities
+ nvRigidBody debug utilities
*/
-static inline void nv_print_Body(nvBody *body) {
- char *p0 =
- "Body at 0x%X:\n"
- " ID: %u\n"
- " Type: %s\n"
- " Shape: %s\n"
- " Position: ";
-
- char *p1 =
- " Angle: %.4f rad (%.1f deg)\n"
- " Force: ";
-
- char *p2 =
- " Torque: %.1f Nm\n"
- " Mass: %.1f kg\n"
- " Inertia: %.1f kgm^2\n"
- " Vertices: %u\n"
- " Is sleeping? %s\n"
- " Is attractor? %s\n"
- " Material:\n"
- " Density: %.2f\n"
- " Restitution: %.2f\n"
- " Friction: %.2f\n";
-
- printf(
- p0,
- body,
- body->id,
- body->type ? "Dynamic" : "Static",
- body->shape->type ? "Polygon" : "Circle"
- );
-
- nv_print_Vector2(body->position);
- printf(" m\n");
-
- printf(
- p1,
- body->angle,
- body->angle * (180.0 / NV_PI)
- );
-
- nv_print_Vector2(body->force);
- printf(" N\n");
-
- size_t vertices;
- if (body->shape->type == nvShapeType_CIRCLE) vertices = 0;
- else if (body->shape->type == nvShapeType_POLYGON) vertices = body->shape->vertices->size;
-
- printf(
- p2,
- body->torque,
- body->mass,
- body->inertia,
- vertices,
- __B(body->is_sleeping),
- __B(body->is_attractor),
- body->material.density,
- body->material.restitution,
- body->material.friction
- );
-}
+// static inline void nv_print_Body(nvRigidBody *body) {
+// char *p0 =
+// "Body at 0x%X:\n"
+// " ID: %u\n"
+// " Type: %s\n"
+// " Shape: %s\n"
+// " Position: ";
+
+// char *p1 =
+// " Angle: %.4f rad (%.1f deg)\n"
+// " Force: ";
+
+// char *p2 =
+// " Torque: %.1f Nm\n"
+// " Mass: %.1f kg\n"
+// " Inertia: %.1f kgm^2\n"
+// " Vertices: %u\n"
+// " Is sleeping? %s\n"
+// " Is attractor? %s\n"
+// " Material:\n"
+// " Density: %.2f\n"
+// " Restitution: %.2f\n"
+// " Friction: %.2f\n";
+
+// printf(
+// p0,
+// body,
+// body->id,
+// body->type ? "Dynamic" : "Static",
+// body->shape->type ? "Polygon" : "Circle"
+// );
+
+// nv_print_Vector2(body->position);
+// printf(" m\n");
+
+// printf(
+// p1,
+// body->angle,
+// body->angle * (180.0 / NV_PI)
+// );
+
+// nv_print_Vector2(body->force);
+// printf(" N\n");
+
+// size_t vertices;
+// if (body->shape->type == nvShapeType_CIRCLE) vertices = 0;
+// else if (body->shape->type == nvShapeType_POLYGON) vertices = body->shape->vertices->size;
+
+// printf(
+// p2,
+// body->torque,
+// body->mass,
+// body->inertia,
+// vertices,
+// __B(body->is_sleeping),
+// __B(body->is_attractor),
+// body->material.density,
+// body->material.restitution,
+// body->material.friction
+// );
+// }
/*
@@ -142,7 +140,8 @@ static inline void nv_print_Resolution(nvResolution *res) {
" Velocity bias: %f, %f\n"
" Effective mass: %f, %f\n"
" Jn: %f, %f\n"
- " Jt: %f, %f\n";
+ " Jt: %f, %f\n"
+ " ID: %llu, %llu\n";
printf(
p0,
@@ -156,7 +155,8 @@ static inline void nv_print_Resolution(nvResolution *res) {
c0.velocity_bias, c1.velocity_bias,
c0.mass_normal, c1.mass_normal,
c0.jn, c1.jn,
- c0.jt, c1.jt
+ c0.jt, c1.jt,
+ c0.id, c1.id
);
}
@@ -168,7 +168,7 @@ static inline void nv_print_Resolution(nvResolution *res) {
static inline void nv_print_BVH(nvBVHNode *node, size_t indent) {
#ifdef NV_COMPILER_MSVC
- char *indent_str = malloc(sizeof(char) * (indent + 1));
+ char *indent_str = NV_MALLOC(sizeof(char) * (indent + 1));
#else
@@ -200,7 +200,7 @@ static inline void nv_print_BVH(nvBVHNode *node, size_t indent) {
#ifdef NV_COMPILER_MSVC
- free(indent_str);
+ NV_FREEindent_str);
#endif
}
diff --git a/include/novaphysics/distance_joint.h b/include/novaphysics/distance_joint.h
deleted file mode 100644
index f618e2e..0000000
--- a/include/novaphysics/distance_joint.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_DISTANCE_JOINT_CONSTRAINT_H
-#define NOVAPHYSICS_DISTANCE_JOINT_CONSTRAINT_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-#include "novaphysics/constraint.h"
-
-
-/**
- * @file distance_joint.h
- *
- * @brief Distance joint implementation.
- */
-
-
-/**
- * @brief Distance joint constraint definition.
- *
- * A distance joint constraints the distance of two points on the two bodies to be constant.
- * This acts like as if the two bodies are linked with a solid bar.
- * TODO: lower upper limit
- */
-typedef struct {
- nv_float length; /**< Length of the distance joint. */
- nvVector2 anchor_a; /**< Local anchor point on body A. */
- nvVector2 anchor_b; /**< Local anchor point on body B. */
-
- nvVector2 ra; /**< Anchor point on body A. */
- nvVector2 rb; /**< Anchor point on body B. */
- nvVector2 normal; /**< Normal of the constraint. */
- nv_float bias; /**< Constraint position correction bias. */
- nv_float mass; /**< Constraint effective mass. */
- nv_float jc; /**< Accumulated constraint impulse. */
-} nvDistanceJoint;
-
-/**
- * @brief Create a new distance joint constraint.
- *
- * Leave one of the body parameters as :code:`NULL` to link the body to world.
- * Don't forget to change the anchor point to be in world space as well.
- *
- * @param a First body
- * @param b Second body
- * @param anchor_a Local anchor point on body A
- * @param anchor_b Local anchor point on body B
- * @param length Length of the joint
- * @return nvConstraint *
- */
-nvConstraint *nvDistanceJoint_new(
- nvBody *a,
- nvBody *b,
- nvVector2 anchor_a,
- nvVector2 anchor_b,
- nv_float length
-);
-
-/**
- * @brief Prepare for solving.
- *
- * @param space Space
- * @param cons Constraint
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nvDistanceJoint_presolve(
- struct nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-);
-
-/**
- * @brief Solve distance constraint.
- *
- * @param cons Constraint
- */
-void nvDistanceJoint_solve(nvConstraint *cons);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/hinge_joint.h b/include/novaphysics/hinge_joint.h
deleted file mode 100644
index 970408d..0000000
--- a/include/novaphysics/hinge_joint.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_HINGE_JOINT_CONSTRAINT_H
-#define NOVAPHYSICS_HINGE_JOINT_CONSTRAINT_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-#include "novaphysics/constraint.h"
-
-
-/**
- * @file hinge_joint.h
- *
- * @brief Hinge joint implementation.
- */
-
-
-/**
- * @brief Hinge joint constraint definition.
- *
- * A hinge joint, also known as revolute join, allows the bodies to rotate around
- * a common axis. Ensuring the relative orientation of the bodies remains fixed.
- */
-typedef struct {
- nvVector2 anchor; /**< Anchor point in world space. */
- bool enable_limits; /**< Enable angular limits or not. */
- nv_float upper_limit; /**< Upper angle limit. */
- nv_float lower_limit; /**< Lower angle limit. */
- nv_float angle; /**< Angle of the constraint. */
-
- nvVector2 anchor_a; /**< Joint anchor translated to body A. */
- nvVector2 anchor_b; /**< Joint anchor translated to body B. */
- nv_float upper_impulse; /**< Accumulated upper limit impulse. */
- nv_float lower_impulse; /**< Accumulated lower limit impulse. */
- nv_float reference_angle; /**< Reference angle for the constrain. */
- nv_float axial_mass; /**< Axial effective mass. */
- nvVector2 ra; /**< Anchor point on body A. */
- nvVector2 rb; /**< Anchor point on body B. */
- nvVector2 normal; /**< Normal of the distance constraint. */
- nv_float bias; /**< Distance constraint position correction bias. */
- nv_float mass; /**< Distance constraint effective mass. */
- nv_float jc; /**< Accumulated distance constraint impulse. */
-} nvHingeJoint;
-
-/**
- * @brief Create a new hinge joint constraint.
- *
- * Leave one of the body parameters as :code:`NULL` to link the body to world.
- * Don't forget to change the anchor point to be in world space as well.
- *
- * @param a First body
- * @param b Second body
- * @param anchor_a Anchor point in world space.
- * @return nvConstraint *
- */
-nvConstraint *nvHingeJoint_new(
- nvBody *a,
- nvBody *b,
- nvVector2 anchor
-);
-
-/**
- * @brief Prepare for solving.
- *
- * @param space Space
- * @param cons Constraint
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nvHingeJoint_presolve(
- struct nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-);
-
-/**
- * @brief Solve hinge constraint.
- *
- * @param cons Constraint
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nvHingeJoint_solve(nvConstraint *cons, nv_float inv_dt);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/internal.h b/include/novaphysics/internal.h
index afd91f1..33ead7b 100644
--- a/include/novaphysics/internal.h
+++ b/include/novaphysics/internal.h
@@ -11,80 +11,17 @@
#ifndef NOVAPHYSICS_INTERNAL_H
#define NOVAPHYSICS_INTERNAL_H
-#include
#include
-#include
-#include
-#include
-#include
+#include
/**
* @file internal.h
*
- * @brief Nova Physics internal type definitions, utility functions
- * and forward declarations.
+ * @brief Nova Physics internal API header.
*/
-/*
- Nova Physics floating type.
-
- Double precision float is used as default for higher accuracy
- But the developer can define NV_USE_FLOAT at compile time to use
- single precision float as well.
- This can be simply done by passing -f or --float to build system.
-*/
-
-#ifdef NV_USE_FLOAT
-
- typedef float nv_float;
-
- #define nv_fabs fabsf
- #define nv_fmin fminf
- #define nv_fmax fmaxf
- #define nv_pow powf
- #define nv_exp expf
- #define nv_sqrt sqrtf
- #define nv_sin sinf
- #define nv_cos cosf
- #define nv_floor floorf
-
-#else
-
- typedef double nv_float;
-
- #define nv_fabs fabs
- #define nv_fmin fmin
- #define nv_fmax fmax
- #define nv_pow pow
- #define nv_exp exp
- #define nv_sqrt sqrt
- #define nv_sin sin
- #define nv_cos cos
- #define nv_floor floor
-
-#endif
-
-
-/*
- Nova Physics integer types.
-*/
-
-typedef int8_t nv_int8;
-typedef int16_t nv_int16;
-typedef int32_t nv_int32;
-typedef int64_t nv_int64;
-typedef uint8_t nv_uint8;
-typedef uint16_t nv_uint16;
-typedef uint32_t nv_uint32;
-typedef uint64_t nv_uint64;
-
-
-/*
- Platform and compiler detection.
-*/
-
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
#define NV_WINDOWS
@@ -108,27 +45,12 @@ typedef uint64_t nv_uint64;
#endif
-/*
- SIMD detection and utility functions.
-*/
-
-#ifdef __AVX__
-
- #define NV_AVX
-
- #define NV_AVX_VECTOR_FROM_FLOAT(x) _mm256_set_ps(x, x, x, x, x, x, x, x)
- #define NV_AVX_VECTOR_FROM_DOUBLE(x) _mm256_set_pd(x, x, x, x)
-
-#endif
-
-#ifdef __AVX2__
-
- #define NV_AVX2
-
-#endif
+#include "novaphysics/types.h"
+#include "novaphysics/constants.h"
+#include "novaphysics/core/error.h"
-// Align memory as given byte range. Used for SIMD storing functions.
+// Align memory as given byte range. Needed for some SIMD functions.
#if defined(NV_COMPILER_GCC)
@@ -148,7 +70,7 @@ typedef uint64_t nv_uint64;
/*
Profiling macros.
*/
-#ifdef NV_PROFILE
+#ifdef NV_ENABLE_PROFILER
#define NV_PROFILER_START(timer) (nvPrecisionTimer_start(&timer))
#define NV_PROFILER_STOP(timer, field) (field = nvPrecisionTimer_stop(&timer))
@@ -165,57 +87,19 @@ typedef uint64_t nv_uint64;
struct nvSpace;
-// Utility macro to allocate on HEAP
-#define NV_NEW(type) ((type *)malloc(sizeof(type)))
-
-
-/**
- * Internal error function.
- */
-#ifdef NV_COMPILER_GCC
- // Does Clang also use GCC warning pragmas?
- #pragma GCC diagnostic push
- #pragma GCC diagnostic ignored "-Wformat-security"
- #pragma GCC diagnostic ignored "-Wformat-overflow"
-#endif
-
-static inline void _nv_error(char *message, char *file, int line) {
- if (message == NULL) message = "\n";
-
- // 64 might not be sufficient, maybe use VLAs?
- char errmsg[64];
- sprintf(errmsg, "Nova Physics error in %s, line %d\n", file, line);
- fprintf(stderr, errmsg);
- fprintf(stderr, message);
- exit(1);
-}
-
-#ifdef NV_COMPILER_GCC
- #pragma GCC diagnostic pop
-#endif
-
-/**
- * Internal assert function.
-*/
-static inline void _nv_assert(bool condition, char *message, char *file, int line) {
- if (!condition)
- _nv_error(message, file, line);
-}
-
-/**
- * @brief Assert the condition and exit if needed.
- *
- * @param condition Condition bool
- * @param message Error message
- */
-#define NV_ASSERT(condition, message) (_nv_assert(condition, message, __FILE__, __LINE__))
+#define NV_MEM_CHECK(object) { \
+ if (!(object)) { \
+ nv_set_error("Failed to allocate memory."); \
+ return NULL; \
+ } \
+} \
-/**
- * @brief Raise error and exit.
- *
- * @param message Error message
- */
-#define NV_ERROR(message) (_nv_error(message, __FILE__, __LINE__))
+#define NV_MEM_CHECKI(object) { \
+ if (!(object)) { \
+ nv_set_error("Failed to allocate memory."); \
+ return 1; \
+ } \
+} \
/*
@@ -223,19 +107,48 @@ static inline void _nv_assert(bool condition, char *message, char *file, int lin
*/
#ifdef TRACY_ENABLE
- #include "../../src/tracy/TracyC.h"
+ #include "TracyC.h"
#define NV_TRACY_ZONE_START TracyCZone(_tracy_zone, true)
#define NV_TRACY_ZONE_END TracyCZoneEnd(_tracy_zone)
#define NV_TRACY_FRAMEMARK TracyCFrameMark
+ static inline void *NV_MALLOC(size_t size) {
+ void *ptr = malloc(size);
+ TracyCAlloc(ptr, size);
+ return ptr;
+ }
+
+ static inline void *NV_REALLOC(void *ptr, size_t new_size) {
+ if (ptr) {
+ TracyCFree(ptr);
+ }
+
+ void *new_ptr = realloc(ptr, new_size);
+ TracyCAlloc(new_ptr, new_size);
+
+ return new_ptr;
+ }
+
+ static inline void NV_FREE(void *ptr) {
+ TracyCFree(ptr);
+ free(ptr);
+ }
+
#else
#define NV_TRACY_ZONE_START
#define NV_TRACY_ZONE_END
#define NV_TRACY_FRAMEMARK
+ #define NV_MALLOC(size) malloc(size)
+ #define NV_REALLOC(ptr, new_size) realloc(ptr, new_size)
+ #define NV_FREE(ptr) free(ptr)
+
#endif
+#define NV_NEW(type) ((type *)NV_MALLOC(sizeof(type)))
+
+
#endif
\ No newline at end of file
diff --git a/include/novaphysics/material.h b/include/novaphysics/material.h
index dc3a97c..e1235e8 100644
--- a/include/novaphysics/material.h
+++ b/include/novaphysics/material.h
@@ -39,57 +39,57 @@ typedef struct {
*/
static const nvMaterial nvMaterial_BASIC = {
- .density = 1.0,
- .restitution = 0.1,
- .friction = 0.4
+ .density = (nv_float)1.0,
+ .restitution = (nv_float)0.1,
+ .friction = (nv_float)0.4
};
static const nvMaterial nvMaterial_STEEL = {
- .density = 7.8,
- .restitution = 0.43,
- .friction = 0.45
+ .density = (nv_float)7.8,
+ .restitution = (nv_float)0.43,
+ .friction = (nv_float)0.45
};
static const nvMaterial nvMaterial_WOOD = {
- .density = 1.5,
- .restitution = 0.37,
- .friction = 0.52
+ .density = (nv_float)1.5,
+ .restitution = (nv_float)0.37,
+ .friction = (nv_float)0.52
};
static const nvMaterial nvMaterial_GLASS = {
- .density = 2.5,
- .restitution = 0.55,
- .friction = 0.19
+ .density = (nv_float)2.5,
+ .restitution = (nv_float)0.55,
+ .friction = (nv_float)0.19
};
static const nvMaterial nvMaterial_ICE = {
- .density = 0.92,
- .restitution = 0.05,
- .friction = 0.02
+ .density = (nv_float)0.92,
+ .restitution = (nv_float)0.05,
+ .friction = (nv_float)0.02
};
static const nvMaterial nvMaterial_CONCRETE = {
- .density = 3.6,
- .restitution = 0.075,
- .friction = 0.73
+ .density = (nv_float)3.6,
+ .restitution = (nv_float)0.075,
+ .friction = (nv_float)0.73
};
static const nvMaterial nvMaterial_RUBBER = {
- .density = 1.4,
- .restitution = 0.89,
- .friction = 0.92
+ .density = (nv_float)1.4,
+ .restitution = (nv_float)0.89,
+ .friction = (nv_float)0.92
};
static const nvMaterial nvMaterial_GOLD = {
- .density = 19.3,
- .restitution = 0.4,
- .friction = 0.35
+ .density = (nv_float)19.3,
+ .restitution = (nv_float)0.4,
+ .friction = (nv_float)0.35
};
static const nvMaterial nvMaterial_CARDBOARD = {
- .density = 0.6,
- .restitution = 0.02,
- .friction = 0.2
+ .density = (nv_float)0.6,
+ .restitution = (nv_float)0.02,
+ .friction = (nv_float)0.2
};
diff --git a/include/novaphysics/math.h b/include/novaphysics/math.h
index fb3b171..4d814b8 100644
--- a/include/novaphysics/math.h
+++ b/include/novaphysics/math.h
@@ -11,10 +11,8 @@
#ifndef NOVAPHYSICS_MATH_H
#define NOVAPHYSICS_MATH_H
-#include
-#include
#include "novaphysics/internal.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
#include "novaphysics/vector.h"
#include "novaphysics/constants.h"
@@ -22,34 +20,27 @@
/**
* @file math.h
*
- * @brief Nova physics math utilities.
+ * @brief Nova Physics math utilities.
*/
/**
- * @brief Hash unsigned 32-bit integer.
- *
- * @param key Integer key to hash
- * @return nv_uint32
- */
-static inline nv_uint32 nv_hash(nv_uint32 key) {
- // https://stackoverflow.com/a/12996028
- key = ((key >> 16) ^ key) * 0x45d9f3b;
- key = ((key >> 16) ^ key) * 0x45d9f3b;
- key = (key >> 16) ^ key;
- return key;
-}
-
-/**
- * @brief Combine two 16-bit integers into unsigned 32-bit one.
+ * @brief Combine two 32-bit unsigned integers into unsigned 64-bit one.
*
* @param x First integer
* @param y Second ineger
- * @return nv_uint32
+ * @return nv_uint64
*/
-static inline nv_uint32 nv_pair(nv_int16 x, nv_int16 y) {
- // https://stackoverflow.com/a/919631
- return ((nv_uint32)x << 16) | (nv_uint32)y;
+static inline nv_uint64 nv_u32pair(nv_uint32 x, nv_uint32 y) {
+ // https://stackoverflow.com/a/2769598
+ return (nv_uint64)x << 32 | y;
+}
+
+static inline nv_uint32 nv_u32hash(nv_uint32 x) {
+ x = ((x >> 16) ^ x) * 0x45d9f3b;
+ x = ((x >> 16) ^ x) * 0x45d9f3b;
+ x = (x >> 16) ^ x;
+ return x;
}
@@ -66,14 +57,6 @@ static inline nv_float nv_fclamp(nv_float value, nv_float min_value, nv_float ma
}
-static inline bool nv_bias_greater_than(nv_float a, nv_float b) {
- // TODO: Look into Box2D's bias function
- nv_float k_biasRelative = 0.95;
- nv_float k_biasAbsolute = 0.01;
- return a >= b * k_biasRelative + a * k_biasAbsolute;
-}
-
-
/**
* @brief Calculate relative velocity.
*
@@ -132,7 +115,7 @@ static inline nv_float nv_calc_mass_k(
/*
Effective mass
- 1 1 (r⊥ᴬᴾ · n)² (r⊥ᴮᴾ · n)²
+ 1 1 (r⊥ᴬᴾ · n)^2 (r⊥ᴮᴾ · n)^2
─ + ─ + ─────────── + ───────────
Mᴬ Mᴮ Iᴬ Iᴮ
*/
@@ -150,46 +133,60 @@ static inline nv_float nv_calc_mass_k(
/**
- * @brief Calculate area of a circle (πr²).
+ * @brief Calculate area of a circle.
*
* @param radius Radius of the circle
* @return nv_float
*/
static inline nv_float nv_circle_area(nv_float radius) {
- return NV_PI * (radius * radius);
+ // πr^2
+ return (nv_float)NV_PI * (radius * radius);
}
/**
- * @brief Calculate moment of inertia of a circle (1/2 mr²).
+ * @brief Calculate moment of inertia of a circle.
*
* @param mass Mass of the circles
* @param radius Radius of the circle
+ * @param offset Center offset
* @return nv_float
*/
-static inline nv_float nv_circle_inertia(nv_float mass, nv_float radius) {
- return 0.5 * mass * (radius * radius);
+static inline nv_float nv_circle_inertia(
+ nv_float mass,
+ nv_float radius,
+ nvVector2 offset
+) {
+ // Circle inertia from center: 1/2 mr^2
+ // The Parallel Axis Theorem: I = Ic + mh^2
+ // 1/2 mr^2 + mh^2
+ return 0.5 * mass * (radius * radius) + mass * nvVector2_len2(offset);
}
/**
- * @brief Calculate area of a polygon (Shoelace formula).
+ * @brief Calculate area of a polygon.
*
* @param vertices Array of vertices of polygon
+ * @param num_vertices Number of vertices
* @return nv_float
*/
-static inline nv_float nv_polygon_area(nvArray *vertices) {
+static inline nv_float nv_polygon_area(
+ nvVector2 *vertices,
+ size_t num_vertices
+) {
+ // https://en.wikipedia.org/wiki/Shoelace_formula
+
nv_float area = 0.0;
- size_t n = vertices->size;
- size_t j = n - 1;
- for (size_t i = 0; i < n; i++) {
- nvVector2 va = NV_TO_VEC2(vertices->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices->data[j]);
+ size_t j = num_vertices - 1;
+ for (size_t i = 0; i < num_vertices; i++) {
+ nvVector2 va = vertices[i];
+ nvVector2 vb = vertices[j];
area += (vb.x + va.x) * (vb.y - va.y);
j = i;
}
- return fabs(area / 2.0);
+ return nv_fabs(area / 2.0);
}
/**
@@ -197,16 +194,20 @@ static inline nv_float nv_polygon_area(nvArray *vertices) {
*
* @param mass Mass of the polygon
* @param vertices Array of vertices of polygon
+ * @param num_vertices Number of vertices
* @return nv_float
*/
-static inline nv_float nv_polygon_inertia(nv_float mass, nvArray *vertices) {
+static inline nv_float nv_polygon_inertia(
+ nv_float mass,
+ nvVector2 *vertices,
+ size_t num_vertices
+) {
nv_float sum1 = 0.0;
nv_float sum2 = 0.0;
- size_t n = vertices->size;
- for (size_t i = 0; i < n; i++) {
- nvVector2 v1 = NV_TO_VEC2(vertices->data[i]);
- nvVector2 v2 = NV_TO_VEC2(vertices->data[(i + 1) % n]);
+ for (size_t i = 0; i < num_vertices; i++) {
+ nvVector2 v1 = vertices[i];
+ nvVector2 v2 = vertices[(i + 1) % num_vertices];
nv_float a = nvVector2_cross(v2, v1);
nv_float b = nvVector2_dot(v1, v1) +
@@ -224,197 +225,42 @@ static inline nv_float nv_polygon_inertia(nv_float mass, nvArray *vertices) {
* @brief Calculate centroid of a polygon.
*
* @param vertices Array of vertices of polygon
+ * @param num_vertices Number of vertices
* @return nvVector2
*/
-static inline nvVector2 nv_polygon_centroid(nvArray *vertices) {
- nvVector2 sum = nvVector2_zero;
- size_t n = vertices->size;
-
- for (size_t i = 0; i < n; i++) {
- sum = nvVector2_add(sum, NV_TO_VEC2(vertices->data[i]));
- }
-
- return nvVector2_div(sum, (nv_float)n);
-}
-
-
-/**
- * @brief Project circle onto axis and return extreme points.
- *
- * @param center Center of circle
- * @param radius Radius of circle
- * @param axis Axis vector to project on
- * @param min_out Pointer for out min value
- * @param max_out Pointer for out max value
- */
-static inline void nv_project_circle(
- nvVector2 center,
- nv_float radius,
- nvVector2 axis,
- nv_float *min_out,
- nv_float *max_out
-) {
- nvVector2 a = nvVector2_mul(nvVector2_normalize(axis), radius);
-
- nvVector2 p1 = nvVector2_add(center, a);
- nvVector2 p2 = nvVector2_sub(center, a);
-
- nv_float min = nvVector2_dot(p1, axis);
- nv_float max = nvVector2_dot(p2, axis);
-
- if (min > max) {
- nv_float temp = max;
- max = min;
- min = temp;
- }
-
- *min_out = min;
- *max_out = max;
-}
-
-/**
- * @brief Project polygon onto axis and return extreme points.
- *
- * @param vertices Vertices of the polygon
- * @param axis Axis vector to project on
- * @param min_out Pointer for out min value
- * @param max_out Pointer for out max value
- */
-static inline void nv_project_polyon(
- nvArray *vertices,
- nvVector2 axis,
- nv_float *min_out,
- nv_float *max_out
-) {
- nv_float min = NV_INF;
- nv_float max = -NV_INF;
-
- for (size_t i = 0; i < vertices->size; i++) {
- nv_float projection = nvVector2_dot(NV_TO_VEC2(vertices->data[i]), axis);
-
- if (projection < min) min = projection;
-
- if (projection > max) max = projection;
- }
-
- *min_out = min;
- *max_out = max;
-}
-
-
-/**
- * @brief Get support vertex of a polygon along the axis.
- *
- * @param vertices Vertices of the polygon
- * @param axis Axis
- * @return nvVector2
- */
-static inline nvVector2 nv_polygon_support(nvArray *vertices, nvVector2 axis) {
- nv_float best_proj = -NV_INF;
- nvVector2 best_vertex;
-
- for (size_t i = 0; i < vertices->size; i++) {
- nvVector2 v = NV_TO_VEC2(vertices->data[i]);
- nv_float proj = nvVector2_dot(v, axis);
-
- if (proj > best_proj) {
- best_proj = proj;
- best_vertex = v;
- }
- }
-
- return best_vertex;
-}
-
-
-/**
- * @brief Perpendicular distance between point and line segment.
- *
- * @param center Point
- * @param a Line segment start
- * @param b Line segment end
- * @param dist_out Distance
- * @param contact_out Contact point
- */
-static inline void nv_point_segment_dist(
- nvVector2 center,
- nvVector2 a,
- nvVector2 b,
- nv_float *dist_out,
- nvVector2 *contact_out
+static inline nvVector2 nv_polygon_centroid(
+ nvVector2 *vertices,
+ size_t num_vertices
) {
- nvVector2 ab = nvVector2_sub(b, a);
- nvVector2 ap = nvVector2_sub(center, a);
-
- nv_float projection = nvVector2_dot(ap, ab);
- nv_float ab_len = nvVector2_len2(ab);
- nv_float dist = projection / ab_len;
- nvVector2 contact;
-
- if (dist <= 0.0) contact = a;
-
- else if (dist >= 1.0) contact = b;
-
- else contact = nvVector2_add(a, nvVector2_mul(ab, dist));
-
- *dist_out = nvVector2_dist2(center, contact);
- *contact_out = contact;
-}
-
-
-/**
- * @brief Find closest vertex of the polygon to the circle.
-
- * @param center Center of the circle
- * @param vertices Vertices of the polygon
- * @return nvVector2
- */
-static inline nvVector2 nv_polygon_closest_vertex_to_circle(
- nvVector2 center,
- nvArray *vertices
-) {
- size_t closest = 0;
- nv_float min_dist = NV_INF;
- bool found = false;
-
- for (size_t i = 0; i < vertices->size; i++) {
- nv_float dist = nvVector2_dist2(NV_TO_VEC2(vertices->data[i]), center);
+ nvVector2 sum = nvVector2_zero;
- if (dist < min_dist) {
- min_dist = dist;
- closest = i;
- found = true;
- }
+ for (size_t i = 0; i < num_vertices; i++) {
+ sum = nvVector2_add(sum, vertices[i]);
}
- NV_ASSERT(found, "");
-
- return NV_TO_VEC2(vertices->data[closest]);
+ return nvVector2_div(sum, (nv_float)num_vertices);
}
/**
- * @brief Calculate convex polygon's winding order in the array.
+ * @brief Check winding order of a triangle.
*
- * Returns 0 if CW, 1 if CCW and -1 if collinear.
+ * Returns:
+ * -1 if CW
+ * 1 if CCW
+ * 0 if colliniear
*
- * @param vertices Array of polygon vertices
- * @return int
+ * @param vertices Triangle vertices
+ * @return int Winding order
*/
-static inline int nv_polygon_winding_order(nvArray *vertices) {
- size_t n = vertices->size;
- nv_float sum = 0.0;
-
- for (size_t i = 0; i < n; i++) {
- nvVector2 current = NV_TO_VEC2(vertices->data[i]);
- nvVector2 next = NV_TO_VEC2(vertices->data[(i + 1) % n]);
-
- sum += (next.x - current.x) * (next.y + current.y);
- }
-
- if (sum > 0.0) return 0;
- else if (sum < 0.0) return 1;
- else return -1;
+static inline int nv_triangle_winding(nvVector2 vertices[3]) {
+ nvVector2 ba = nvVector2_sub(vertices[1], vertices[0]);
+ nvVector2 ca = nvVector2_sub(vertices[2], vertices[0]);
+ nv_float z = nvVector2_cross(ba, ca);
+
+ if (z < 0.0) return -1;
+ else if (z > 0.0) return 1;
+ else return 0;
}
@@ -423,13 +269,13 @@ static nvVector2 _convex_hull_pivot;
static int _convex_hull_orientation(nvVector2 p, nvVector2 q, nvVector2 r) {
nv_float d = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
- if (d == 0.0) return 0.0; // Collinear
+ if (d == 0.0) return 0; // Collinear
return (d > 0.0) ? 1 : 2; // CW or CCW
}
static int _convex_hull_cmp(const void *el0, const void *el1) {
- nvVector2 v0 = NV_TO_VEC2(el0);
- nvVector2 v1 = NV_TO_VEC2(el1);
+ nvVector2 v0 = *(nvVector2 *)el0;
+ nvVector2 v1 = *(nvVector2 *)el1;
int o = _convex_hull_orientation(_convex_hull_pivot, v0, v1);
@@ -450,28 +296,33 @@ static int _convex_hull_cmp(const void *el0, const void *el1) {
/**
* @brief Generate a convex hull around the given points.
*
- * This function returns a new allocated array. Passed in array can be freed.
+ * @param points Points
+ * @param num_points Number of points
+ * @param vertices Output vertices array
*
- * @param points Array of vectors
- * @return nvArray *
+ * @return size_t Number of output vertices
*/
-static inline nvArray *nv_generate_convex_hull(nvArray *points) {
+static inline size_t nv_generate_convex_hull(
+ nvVector2 *points,
+ size_t num_points,
+ nvVector2 *vertices
+) {
// This function implements the Graham Scan algorithm
// https://en.wikipedia.org/wiki/Graham_scan
- size_t n = points->size;
+ size_t n = num_points;
size_t current_min_i = 0;
- nv_float min_y = NV_TO_VEC2(points->data[current_min_i]).x;
+ nv_float min_y = points[current_min_i].x;
nvVector2 pivot;
// Find the lowest y-coordinate and leftmost point
for (size_t i = 0; i < n; i++) {
- nvVector2 v = NV_TO_VEC2(points->data[i]);
+ nvVector2 v = points[i];
if (
v.y < min_y ||
- (v.y == min_y && v.x < NV_TO_VEC2(points->data[current_min_i]).x)
+ (v.y == min_y && v.x < points[current_min_i].x)
) {
current_min_i = i;
min_y = v.y;
@@ -479,72 +330,86 @@ static inline nvArray *nv_generate_convex_hull(nvArray *points) {
}
// Swap the pivot with the first point
- nvVector2 *temp = NV_TO_VEC2P(points->data[0]);
- points->data[0] = points->data[current_min_i];
- points->data[current_min_i] = temp;
+ nvVector2 temp = points[0];
+ points[0] = points[current_min_i];
+ points[current_min_i] = temp;
- pivot = NV_TO_VEC2(points->data[0]);
+ pivot = points[0];
_convex_hull_pivot = pivot;
#ifdef NV_COMPILER_MSVC
- nvVector2 *tmp_points = (nvVector2 *)malloc(sizeof(nvVector2) * points->size);
+ nvVector2 *tmp_points = NV_MALLOC(sizeof(nvVector2) * n);
#else
- nvVector2 tmp_points[points->size];
+ nvVector2 tmp_points[n];
#endif
- for (size_t i = 0; i < points->size; i++) {
- nvVector2 v = NV_TO_VEC2(points->data[i]);
+ for (size_t i = 0; i < n; i++) {
+ nvVector2 v = points[i];
tmp_points[i] = v;
}
- qsort(&tmp_points[1], points->size - 1, sizeof(nvVector2), _convex_hull_cmp);
+ qsort(&tmp_points[1], n - 1, sizeof(nvVector2), _convex_hull_cmp);
- for (size_t i = 0; i < points->size; i++) {
- nvVector2 *v = NV_TO_VEC2P(points->data[i]);
+ for (size_t i = 0; i < n; i++) {
+ nvVector2 *v = &points[i];
v->x = tmp_points[i].x;
v->y = tmp_points[i].y;
}
#ifdef NV_COMPILER_MSVC
- free(tmp_points);
+ NV_FREE(tmp_points);
#endif
- nvVector2 *hull = (nvVector2 *)malloc(sizeof(nvVector2) * n);
+ nvVector2 *hull = NV_MALLOC(sizeof(nvVector2) * n);
size_t hull_size = 3;
- hull[0] = NV_TO_VEC2(points->data[0]);
- hull[1] = NV_TO_VEC2(points->data[1]);
- hull[2] = NV_TO_VEC2(points->data[2]);
+ hull[0] = points[0];
+ hull[1] = points[1];
+ hull[2] = points[2];
- for (size_t i = 3; i < points->size; i++) {
+ for (size_t i = 3; i < n; i++) {
while (
hull_size > 1 &&
_convex_hull_orientation(
hull[hull_size - 2],
hull[hull_size - 1],
- NV_TO_VEC2(points->data[i])
+ points[i]
) != 2
) {
hull_size--;
}
- hull[hull_size++] = NV_TO_VEC2(points->data[i]);
+ hull[hull_size++] = points[i];
}
- nvArray *ret_hull = nvArray_new();
- for (size_t i = 0; i < hull_size; i++) {
- nvArray_add(ret_hull, NV_VEC2_NEW(hull[i].x, hull[i].y));
+ size_t final_size;
+ if (hull_size > NV_POLYGON_MAX_VERTICES)
+ final_size = NV_POLYGON_MAX_VERTICES;
+ else
+ final_size = hull_size;
+
+ for (size_t i = 0; i < final_size; i++) {
+ vertices[i] = hull[i];
}
- free(hull);
+ NV_FREE(hull);
- return ret_hull;
+ return final_size;
}
+/**
+ * @brief Transform info struct that is used to pass body transform to collision functions.
+ */
+typedef struct {
+ nvVector2 position;
+ nv_float angle;
+} nvTransform;
+
+
#endif
\ No newline at end of file
diff --git a/include/novaphysics/matrix.h b/include/novaphysics/matrix.h
deleted file mode 100644
index 724191d..0000000
--- a/include/novaphysics/matrix.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_MATRIX_H
-#define NOVAPHYSICS_MATRIX_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/vector.h"
-
-
-/**
- * @file matrix.h
- *
- * @brief Matrix types and math.
- */
-
-
-/**
- * @brief 2x2 column-major matrix type.
- */
-typedef struct {
- nvVector2 col1;
- nvVector2 col2;
-} nvMat2x2;
-
-
-/**
- * @brief Initialize new rotation matrix.
- *
- * @param angle Angle in radians
- * @return nvMat2x2
- */
-static inline nvMat2x2 nvMat2x2_from_angle(nv_float angle) {
- nv_float c = nv_cos(angle);
- nv_float s = nv_sin(angle);
-
- return (nvMat2x2){
- NV_VEC2(c, s),
- NV_VEC2(-s, c)
- };
-}
-
-/**
- * @brief Multiply matrix with a vector.
- *
- * @param mat Matrix
- * @param vector Vector
- * @return nvVector2
- */
-static inline nvVector2 nvMat2x2_mulv(nvMat2x2 mat, nvVector2 vector) {
- return NV_VEC2(
- mat.col1.x * vector.x + mat.col2.x * vector.y,
- mat.col1.y * vector.x + mat.col2.y * vector.y
- );
-}
-
-/**
- * @brief Multiply two matrices.
- *
- * @param a Left-hand matrix
- * @param b Right-hand matrix
- * @return nvMat2x2
- */
-static inline nvMat2x2 nvMat2x2_mul(nvMat2x2 a, nvMat2x2 b) {
- return (nvMat2x2){
- nvMat2x2_mulv(a, b.col1),
- nvMat2x2_mulv(a, b.col2)
- };
-}
-
-/**
- * @brief Transpose the matrix.
- *
- * @param mat Matrix
- * @return nvMat2x2
- */
-static inline nvMat2x2 nvMat2x2_transpose(nvMat2x2 mat) {
- return (nvMat2x2){
- NV_VEC2(mat.col1.x, mat.col2.x),
- NV_VEC2(mat.col1.y, mat.col2.y)
- };
-}
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/narrowphase.h b/include/novaphysics/narrowphase.h
index e90f47c..f083732 100644
--- a/include/novaphysics/narrowphase.h
+++ b/include/novaphysics/narrowphase.h
@@ -11,11 +11,7 @@
#ifndef NOVAPHYSICS_NARROWPHASE_H
#define NOVAPHYSICS_NARROWPHASE_H
-#include
#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-#include "novaphysics/resolution.h"
-#include "novaphysics/broadphase.h"
/**
@@ -27,27 +23,11 @@
/**
* @brief Check the final geometry between bodies after finding possible collision
- * pairs using broad-phase algorithms and update collision resolutions.
+ * pairs using broad-phase algorithms and update collision informations.
*
* @param space Space
*/
void nv_narrow_phase(struct nvSpace *space);
-/**
- * @brief Do narrow-phase check between bodies of single pair.
- *
- * @param space Space
- * @param pair Body pair
- * @param res_exists Does the resolution exist
- * @param found_res Resolution instance (if it exists)
- */
-void nv_narrow_phase_between_pair(
- struct nvSpace *space,
- nvBroadPhasePair *pair,
- bool res_exists,
- nvResolution *found_res
-);
-
-
#endif
\ No newline at end of file
diff --git a/include/novaphysics/novaphysics.h b/include/novaphysics/novaphysics.h
index 8d3d59f..53359ce 100644
--- a/include/novaphysics/novaphysics.h
+++ b/include/novaphysics/novaphysics.h
@@ -16,6 +16,14 @@
* @file novaphysics.h
*
* @brief Main Nova Physics API.
+ *
+ * Included STL headers:
+ * - stdlib.h
+ * - stdio.h (For sprintf in core/error)
+ * - stdint.h (For nv_uint and nv_int types)
+ * - math.h
+ * - float.h (For NV_FLOAT_EPSILON)
+ * - string.h (For memory functions)
*/
@@ -24,41 +32,32 @@
#define NV_STRINGIFY(x) _NV_STRINGIFY(x)
// Version in MAJOR.MINOR.PATCH format
-#define NV_VERSION_MAJOR 0
-#define NV_VERSION_MINOR 7
+#define NV_VERSION_MAJOR 1
+#define NV_VERSION_MINOR 0
#define NV_VERSION_PATCH 0
// Version string
-#define NV_VERSTR \
+#define NV_VERSION_STRING \
NV_STRINGIFY(NV_VERSION_MAJOR) "." \
NV_STRINGIFY(NV_VERSION_MINOR) "." \
NV_STRINGIFY(NV_VERSION_PATCH)
-// Include the Nova Physics API
-#include "novaphysics/internal.h"
+#include "novaphysics/core/error.h"
#include "novaphysics/vector.h"
#include "novaphysics/math.h"
-#include "novaphysics/matrix.h"
#include "novaphysics/aabb.h"
-#include "novaphysics/array.h"
#include "novaphysics/constants.h"
#include "novaphysics/material.h"
#include "novaphysics/broadphase.h"
#include "novaphysics/space.h"
#include "novaphysics/body.h"
-#include "novaphysics/constraint.h"
-#include "novaphysics/spring.h"
-#include "novaphysics/distance_joint.h"
-#include "novaphysics/hinge_joint.h"
#include "novaphysics/collision.h"
#include "novaphysics/contact.h"
-#include "novaphysics/contact_solver.h"
-#include "novaphysics/resolution.h"
-#include "novaphysics/hashmap.h"
-#include "novaphysics/shg.h"
-#include "novaphysics/bvh.h"
-#include "novaphysics/threading.h"
-#include "novaphysics/debug.h"
+#include "novaphysics/constraints/constraint.h"
+#include "novaphysics/constraints/contact_constraint.h"
+#include "novaphysics/constraints/distance_constraint.h"
+#include "novaphysics/constraints/hinge_constraint.h"
+#include "novaphysics/constraints/spline_constraint.h"
#endif
\ No newline at end of file
diff --git a/include/novaphysics/profiler.h b/include/novaphysics/profiler.h
index 41960d0..837f268 100644
--- a/include/novaphysics/profiler.h
+++ b/include/novaphysics/profiler.h
@@ -17,49 +17,58 @@
/**
* @file profiler.h
*
- * @brief Profiler.
+ * @brief Built-in performance profiler.
*/
+/**
+ * @brief Timings for parts of one space step in seconds.
+ */
typedef struct {
- double step;
- double integrate_accelerations;
- double broadphase;
- double update_resolutions;
- double narrowphase;
- double presolve_collisions;
- double solve_positions;
- double solve_velocities;
- double presolve_constraints;
- double solve_constraints;
- double integrate_velocities;
- double remove_bodies;
- double bvh_build;
- double bvh_traverse;
- double bvh_destroy;
+ double step; /**< Time spent in one simulation step. */
+ double broadphase; /**< Time spent for broadphase. */
+ double broadphase_finalize; /**< Time spent finalizing broadphase. */
+ double bvh_free; /**< Time spent destroying BVH-tree. */
+ double bvh_build; /**< Time spent building BVH-tree. */
+ double bvh_traverse; /**< Time spent traversing BVH-tree. */
+ double narrowphase; /**< Time spent for narrowphase. */
+ double integrate_accelerations; /**< Time spent integrating accelerations. */
+ double presolve; /**< Time spent preparing constraints for solving. */
+ double warmstart; /**< Time spent warmstarting constraints. */
+ double solve_velocities; /**< Time spent solving velocity constraints. */
+ double solve_positions; /**< Time spent for NGS. */
+ double integrate_velocities; /**< Time spent integrating velocities. */
} nvProfiler;
static inline void nvProfiler_reset(nvProfiler *profiler) {
profiler->step = 0.0;
- profiler->integrate_accelerations = 0.0;
profiler->broadphase = 0.0;
- profiler->update_resolutions = 0.0;
+ profiler->broadphase_finalize = 0.0;
+ profiler->bvh_free = 0.0;
+ profiler->bvh_build = 0.0;
+ profiler->bvh_traverse = 0.0;
profiler->narrowphase = 0.0;
- profiler->presolve_collisions = 0.0;
- profiler->solve_positions = 0.0;
+ profiler->integrate_accelerations = 0.0;
+ profiler->presolve = 0.0;
+ profiler->warmstart = 0.0;
profiler->solve_velocities = 0.0;
- profiler->presolve_constraints = 0.0;
- profiler->solve_constraints = 0.0;
+ profiler->solve_positions = 0.0;
profiler->integrate_velocities = 0.0;
- profiler->remove_bodies = 0.0;
- profiler->bvh_build = 0.0;
- profiler->bvh_traverse = 0.0;
- profiler->bvh_destroy = 0.0;
}
-#ifdef NV_WINDOWS
+#ifndef NV_ENABLE_PROFILER
+
+ typedef struct {
+ double elapsed;
+ } nvPrecisionTimer;
+
+ static inline void nvPrecisionTimer_start(nvPrecisionTimer *timer) {}
+
+ static inline double nvPrecisionTimer_stop(nvPrecisionTimer *timer ) {}
+
+#elif defined(NV_WINDOWS)
#include
diff --git a/include/novaphysics/resolution.h b/include/novaphysics/resolution.h
deleted file mode 100644
index 5e9d069..0000000
--- a/include/novaphysics/resolution.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_RESOLUTION_H
-#define NOVAPHYSICS_RESOLUTION_H
-
-#include
-#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-
-
-/**
- * @file resolution.h
- *
- * @brief Collision resolution data structure.
- */
-
-
-/**
- * @brief Collsion resolution states.
- */
-typedef enum {
- nvResolutionState_FIRST, /**< The collision just happened this frame. */
- nvResolutionState_NORMAL, /**< The collision has been existing. */
- nvResolutionState_CACHED /**< The collision has been separated and the resolution is cached. */
-} nvResolutionState;
-
-
-/**
- * @brief Data structure that holds information about contacts of collision.
- */
-typedef struct {
- nvVector2 position; /**< Position of the contact point. */
- nvVector2 ra; /**< Contact position relative to body A. */
- nvVector2 rb; /**< Contact position relative to body B. */
- nv_float adjusted_depth;
- nv_float a_angle0;
- nv_float b_angle0;
-
- nv_float velocity_bias; /**< Velocity bias for restitution. */
- nv_float position_bias; /**< Position bias for Baumgarte stabilization. */
-
- nv_float mass_normal; /**< Effective mass of normal impulse. */
- nv_float mass_tangent; /**< Effective mass of tangential impulse. */
-
- nv_float jn; /**< Accumulated normal impulse. */
- nv_float jt; /**< Accumulated tangential impulse. */
-} nvContact;
-
-
-/**
- * @brief Data structure that holds information about collision between two bodies.
- */
-typedef struct {
- bool collision; /**< Flag that reports if the collision has happened. */
-
- nvBody *a; /**< First body of the collision. */
- nvBody *b; /**< Second body of the collision. */
-
- nvVector2 normal; /**< Normal vector of the collision separation. */
- nv_float depth; /**< Penetration depth. */
-
- nv_float friction; /**< Mixed friction coefficient. */
-
- nvResolutionState state; /**< State of the resolution. */
- int lifetime; /**< Remaining lifetime of the resolution in ticks. */
-
- nvContact contacts[2]; /**< Contact points. */
- nv_uint8 contact_count; /**< Contact point count. */
-} nvResolution;
-
-
-/**
- * @brief Update state of the resolved collision resolution.
- *
- * @param space Space
- * @param res Resolution to update
- */
-void nvResolution_update(struct nvSpace *space, nvResolution *res);
-
-
-/**
- * @brief Coefficient mixing type is the method to mix various coefficients
- * values like restitution and friction.
- */
-typedef enum {
- nvCoefficientMix_AVG, /**< (a + b) / 2 */
- nvCoefficientMix_MUL, /**< a * b */
- nvCoefficientMix_SQRT, /**< sqrt(a * b) */
- nvCoefficientMix_MIN, /**< min(a, b) */
- nvCoefficientMix_MAX /**< max(a, b) */
-} nvCoefficientMix;
-
-/**
- * @brief Mix two coefficient values.
- *
- * @param a First value
- * @param b Second value
- * @param mix Mixing type
- * @return nv_float
- */
-static inline nv_float nv_mix_coefficients(nv_float a, nv_float b, nvCoefficientMix mix) {
- switch (mix) {
- case nvCoefficientMix_AVG:
- return (a + b) / 2.0;
-
- case nvCoefficientMix_MUL:
- return a * b;
-
- case nvCoefficientMix_SQRT:
- return nv_sqrt(a * b);
-
- case nvCoefficientMix_MIN:
- return nv_fmin(a, b);
-
- case nvCoefficientMix_MAX:
- return nv_fmax(a, b);
-
- default:
- NV_ERROR("Unknown coefficient mixing function.");
- return 0.0;
- }
-}
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/shape.h b/include/novaphysics/shape.h
index 7534757..c5604c6 100644
--- a/include/novaphysics/shape.h
+++ b/include/novaphysics/shape.h
@@ -12,15 +12,16 @@
#define NOVAPHYSICS_SHAPE_H
#include "novaphysics/internal.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
+#include "novaphysics/vector.h"
+#include "novaphysics/math.h"
+#include "novaphysics/aabb.h"
/**
* @file shape.h
*
- * @brief Shape struct and methods.
- *
- * This module defines ShapeType enum, Shape struct and its methods.
+ * @brief Collision shape implementations.
*/
@@ -28,88 +29,177 @@
* @brief Shape type enumerator.
*/
typedef enum {
- nvShapeType_CIRCLE, /**< Circle shape. It's the simplest collision shape. */
+ nvShapeType_CIRCLE, /**< Circle is the simplest collision shape. */
nvShapeType_POLYGON /**< Convex polygon shape. It's more complex than
circle shape and the calculations gets more expensive
as the vertex count goes higher. */
} nvShapeType;
+/**
+ * @brief Mass related information about shape.
+ */
+typedef struct {
+ nv_float mass;
+ nv_float inertia;
+ nvVector2 center;
+} nvShapeMassInfo;
+
+
+/**
+ * @brief Circle shape.
+ *
+ * Do not initialize manually. Use shape creation functions.
+ */
+typedef struct {
+ nvVector2 center; /**< Center position in local (body) space. */
+ nv_float radius; /**< Radius. */
+} nvCircle;
+
+
+/**
+ * @brief Convex polygon shape.
+ *
+ * Do not initialize manually. Use shape creation functions.
+ */
+typedef struct {
+ nvVector2 vertices[NV_POLYGON_MAX_VERTICES]; /**< Vertices in local (body) space. */
+ nvVector2 xvertices[NV_POLYGON_MAX_VERTICES]; /**< Vertices transformed into world space. */
+ nvVector2 normals[NV_POLYGON_MAX_VERTICES]; /**< Edge normals in local (body) space. */
+ size_t num_vertices; /**< Number of vertices. */
+} nvPolygon;
+
+
/**
* @brief Collision shape.
+ *
+ * Do not initialize manually. Use shape creation functions.
*/
typedef struct {
nvShapeType type; /**< Type of the shape */
+ nv_uint32 id;
union {
- nv_float radius; /**< Circle radius. */
-
- struct {
- nvArray *vertices; /**< Polygon local vertices. */
- nvArray *trans_vertices; /**< Polygon transformed vertices. */
- nvArray *normals; /**< Polygon edge normals. */
- };
-
+ nvCircle circle;
+ nvPolygon polygon;
};
} nvShape;
/**
* @brief Create a new circle shape.
*
- * @param radius Radius of the circle
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
+ * @param center Center position relative to body position
+ * @param radius Radius
* @return nvShape *
*/
-nvShape *nvCircleShape_new(nv_float radius);
+nvShape *nvCircleShape_new(nvVector2 center, nv_float radius);
/**
* @brief Create a new convex polygon shape.
*
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
* @param vertices Array of vertices
+ * @param offset Offset to centroid
* @return nvShape *
*/
-nvShape *nvPolygonShape_new(nvArray *vertices);
+nvShape *nvPolygonShape_new(
+ nvVector2 *vertices,
+ size_t num_vertices,
+ nvVector2 offset
+);
/**
* @brief Create a new polygon shape that is a rectangle.
*
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
* @param width Width
* @param height Height
+ * @param offset Offset to centroid
* @return nvShape *
*/
-nvShape *nvRectShape_new(nv_float width, nv_float height);
+nvShape *nvRectShape_new(nv_float width, nv_float height, nvVector2 offset);
/**
- * @brief Create a new polygon shape that is a rectangle. Alias for @ref nvRectShape_new
+ * @brief Create a new polygon shape that is a rectangle.
+ *
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
*
* @param width Width
* @param height Height
+ * @param offset Offset to centroid
* @return nvShape *
*/
-#define nvBoxShape_new(width, height) (nvRectShape_new(width, height))
+#define nvBoxShape_new(width, height, offset) (nvRectShape_new(width, height, offset))
/**
* @brief Create a new polygon shape that is a regular n-gon.
*
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
* @param n Number of vertices or edges
* @param radius Length of a vertex from the centroid
+ * @param offset Offset to centroid
* @return nvShape *
*/
-nvShape *nvNGonShape_new(size_t n, nv_float radius);
+nvShape *nvNGonShape_new(size_t n, nv_float radius, nvVector2 offset);
/**
* @brief Create a new polygon shape from a convex hull of an array of points.
*
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
* @param points Points to generate a convex hull from
+ * @param num_points Number of points
+ * @param offset Offset to centroid
+ * @param bool Transform hull so the centroid is at origin?
* @return nvShape *
*/
-nvShape *nvConvexHullShape_new(nvArray *points);
+nvShape *nvConvexHullShape_new(
+ nvVector2 *points,
+ size_t num_points,
+ nvVector2 offset,
+ nv_bool center
+);
/**
* @brief Free shape.
*
+ * It's safe to pass `NULL` to this function.
+ *
* @param shape Shape
*/
void nvShape_free(nvShape *shape);
+/**
+ * @brief Get AABB of shape.
+ *
+ * @param shape Shape
+ * @param xform Shape transform
+ * @return nvAABB
+ */
+nvAABB nvShape_get_aabb(nvShape *shape, nvTransform xform);
+
+/**
+ * @brief Calculate mass information of shape.
+ *
+ * Returns a struct filled with -1 on error. Use @ref nv_get_error to get more information.
+ *
+ * @param shape Shape
+ * @return nvShapeMassInfo
+ */
+nvShapeMassInfo nvShape_calculate_mass(nvShape *shape, nv_float density);
+
+/**
+ * @brief Transform the polygon shape vertices.
+ *
+ * @param shape Shape
+ * @param xform Transform
+ */
+void nvPolygon_transform(nvShape *shape, nvTransform xform);
+
#endif
\ No newline at end of file
diff --git a/include/novaphysics/shg.h b/include/novaphysics/shg.h
deleted file mode 100644
index ff4cbca..0000000
--- a/include/novaphysics/shg.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_SPATIAL_HASH_GRID_H
-#define NOVAPHYSICS_SPATIAL_HASH_GRID_H
-
-#include
-#include "novaphysics/internal.h"
-#include "novaphysics/aabb.h"
-#include "novaphysics/hashmap.h"
-#include "novaphysics/array.h"
-
-
-/**
- * @file shg.h
- *
- * @brief Spatial Hash Grid implementation.
- */
-
-
-typedef struct {
- nv_uint32 xy_pair;
- nvArray *cell;
-} nvSHGEntry;
-
-
-/**
- * @brief Spatial Hash Grid struct.
- */
-typedef struct {
- nvAABB bounds; /**< Boundaries of the grid. */
- nv_uint32 cols; /**< Columns of the grid (cells on X axis). */
- nv_uint32 rows; /**< Rows of the grid (cells on Y axis). */
- nv_float cell_width; /**< Width of one cell. */
- nv_float cell_height; /**< Height of one cell. */
- nvHashMap *map; /**< Hashmap used internally to store cells. */
-} nvSHG;
-
-/**
- * @brief Create a new Spatial Hash Grid.
- *
- * @param cell_width Width of one cell
- * @param cell_width Height of one cell
- * @return nvSHG *
- */
-nvSHG *nvSHG_new(
- nvAABB bounds,
- nv_float cell_width,
- nv_float cell_height
-) ;
-
-/**
- * @brief Free the Spatial Hash Grid.
- *
- * @param shg Spatial Hash Grid to free
- */
-void nvSHG_free(nvSHG *shg);
-
-/**
- * @brief Get content of one cell.
- *
- * @param shg Spatial Hash Grid
- * @param key Cell key
- * @return nvArray *
- */
-nvArray *nvSHG_get(nvSHG *shg, nv_uint32 key);
-
-/**
- * @brief Place bodies onto Spatial Hash Grid.
- *
- * @param shg Spatial Hash Grid
- * @param bodies Body array
- */
-void nvSHG_place(nvSHG *shg, nvArray *bodies);
-
-/**
- * @brief Get neighboring cell information.
- *
- * @param shg Spatial Hash Grid
- * @param x0 Cell X
- * @param y0 Cell y
- * @param neighbors 32-bit int array to insert pair keys at
- * @param neighbor_flags Neighbor flags
- */
-void nvSHG_get_neighbors(
- nvSHG *shg,
- nv_int16 x0,
- nv_int16 y0,
- nv_uint32 neighbors[],
- bool neighbor_flags[]
-);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/space.h b/include/novaphysics/space.h
index fa763d5..4e32a7b 100644
--- a/include/novaphysics/space.h
+++ b/include/novaphysics/space.h
@@ -12,17 +12,16 @@
#define NOVAPHYSICS_SPACE_H
#include "novaphysics/internal.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
+#include "novaphysics/core/hashmap.h"
+#include "novaphysics/core/pool.h"
#include "novaphysics/body.h"
#include "novaphysics/broadphase.h"
-#include "novaphysics/resolution.h"
#include "novaphysics/contact.h"
-#include "novaphysics/constraint.h"
-#include "novaphysics/contact_solver.h"
-#include "novaphysics/hashmap.h"
-#include "novaphysics/shg.h"
-#include "novaphysics/threading.h"
+#include "novaphysics/constraints/constraint.h"
+#include "novaphysics/constraints/contact_constraint.h"
#include "novaphysics/profiler.h"
+#include "novaphysics/space_settings.h"
/**
@@ -32,73 +31,42 @@
*/
-// Space callback type
-typedef void ( *nvSpace_callback)(struct nvSpace *space, void *user_data);
-
-
/**
* @brief Space struct.
*
- * Space is the core of the simulation.
+ * A space is the core of the physics simulation.
* It manages and simulates all bodies, constraints and collisions.
*/
struct nvSpace {
- nvArray *bodies; /**< Array of bodies in the space. */
- nvArray *awake_bodies;
- nvArray *attractors; /**< Array of attractive bodies in the space. */
- nvArray *constraints; /**< Array of constraints in the space. */
-
- nvArray *_removed_bodies; /**< Bodies that are waiting to be removed.
- You shouldn't access this directly, instead use @ref nvSpace_remove method. */
- nvArray *_killed_bodies; /**< Bodies that are waiting to be removed and freed.
- You shouldn't access this directly, instead use @ref nvSpace_kill method.*/
-
- nvHashMap *res; /**< Set of collision resolutions. */
-
- nvVector2 gravity; /**< Global and uniform gravity applied to all bodies in the space.
- For gravitational attraction between body pairs, see attractive bodies. */
-
- bool sleeping; /**< Flag that specifies if space allows sleeping of bodies. */
- nv_float sleep_energy_threshold; /**< Threshold value which bodies sleep if they exceed it. */
- nv_float wake_energy_threshold; /**< Threshold value which bodies wake up if they exceed it. */
- unsigned int sleep_timer_threshold; /**< How long space should count to before sleeping bodies. */
-
- bool warmstarting; /**< Flag that specifies if solvers use warm-starting for accumulated impulses. */
- int collision_persistence; /**< Number of frames the collision resolutions kept cached. */
- nvPositionCorrection position_correction; /**< Position correction algorithm used. */
-
- nvBroadPhaseAlg broadphase_algorithm; /**< Broad-phase algorithm used to detect possible collisions. */
- nvHashMap *broadphase_pairs;
- nvSHG *shg; /**< Spatial Hash Grid object.
- @warning Should be only accessed if the used broad-phase algorithm is SHG. */
-
- nvAABB kill_bounds; /**< Boundary where bodies get deleted if they go out of. */
- bool use_kill_bounds; /**< Whether to use the kill bounds or not. True by default. */
-
- nvCoefficientMix mix_restitution; /**< Method to mix restitution coefficients of collided bodies. */
- nvCoefficientMix mix_friction; /**< Method to mix friction coefficients of collided bodies. */
-
- void *callback_user_data; /**< User data passed to collision callbacks. */
- nvSpace_callback before_collision; /**< Callback function called before solving collisions. */
- nvSpace_callback after_collision; /**< Callback function called after solving collisions. */
-
- nvProfiler profiler; /**< Profiler. */
-
- bool multithreading; /**< Whether multi-threading is enabled or not. */
- size_t thread_count; /**< Number of threads Nova Physics utilizes.
- 0 if multithreading is disabled. */
- nvTaskExecutor *task_executor; /**< Task executor. */
- nvArray *mt_shg_pairs;
- nvArray *mt_shg_bins;
-
- nv_uint16 _id_counter; /**< Internal ID counter. */
+ /*
+ Private members
+ */
+ nvArray *bodies;
+ nvArray *constraints;
+ nvHashMap *contacts;
+ nvHashMap *removed_contacts;
+ nvMemoryPool *broadphase_pairs;
+ nv_uint32 id_counter;
+
+ /*
+ Public members (setters & getters)
+ */
+ nvVector2 gravity;
+ nvSpaceSettings settings;
+ nvBroadPhaseAlg broadphase_algorithm;
+
+ nvContactListener *listener;
+ void *listener_arg;
+
+ nvProfiler profiler;
};
-
typedef struct nvSpace nvSpace;
/**
* @brief Create new space instance.
*
+ * Returns `NULL` on error. Use @ref nv_get_error to get more information.
+ *
* @return nvSpace *
*/
nvSpace *nvSpace_new();
@@ -106,12 +74,33 @@ nvSpace *nvSpace_new();
/**
* @brief Free space.
*
+ * It's safe to pass `NULL` to this function.
+ *
* @param space Space to free
*/
void nvSpace_free(nvSpace *space);
/**
- * @brief Set the current broadphase algorithm used to check possible collision pairs.
+ * @brief Set global gravity vector.
+ *
+ * @param space Space
+ * @param gravity Gravity vector
+ */
+void nvSpace_set_gravity(nvSpace *space, nvVector2 gravity);
+
+/**
+ * @brief Get global gravity vector.
+ *
+ * @param space Space
+ * @return nvVector2 Gravity vector
+ */
+nvVector2 nvSpace_get_gravity(const nvSpace *space);
+
+/**
+ * @brief Set the current broadphase algorithm.
+ *
+ * Broadphase is where we check for possible collided pairs of bodies. Quickly
+ * determining those pairs is important for efficiency before narrowphase.
*
* @param space Space
* @param broadphase_type Broadphase algorithm
@@ -119,128 +108,169 @@ void nvSpace_free(nvSpace *space);
void nvSpace_set_broadphase(nvSpace *space, nvBroadPhaseAlg broadphase_alg_type);
/**
- * @brief Create & set a new SHG and release the old one.
+ * @brief Get the current broadphase algorithm.
*
* @param space Space
- * @param bounds Boundaries of the new SHG
- * @param cell_width Cell width of the new SHG
- * @param cell_height Cell height of the new SHG
+ * @return nvBroadPhaseAlg
*/
-void nvSpace_set_SHG(
+nvBroadPhaseAlg nvSpace_get_broadphase(const nvSpace *space);
+
+/**
+ * @brief Get the current simulation settings struct.
+ *
+ * This returns a pointer to the current settings. So you can directly modify it.
+ *
+ * @param space Space
+ * @return nvSpaceSettings *
+ */
+nvSpaceSettings *nvSpace_get_settings(nvSpace *space);
+
+/**
+ * @brief Get profiler of space.
+ *
+ * @param space Space
+ * @return nvProfiler
+ */
+nvProfiler nvSpace_get_profiler(const nvSpace *space);
+
+/**
+ * @brief Set the current contact event listener.
+ *
+ * Space allocates using the functions provided by listener param.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
+ * @param space Space
+ * @param listener Contact event listener
+ * @param user_arg User argument
+ */
+int nvSpace_set_contact_listener(
nvSpace *space,
- nvAABB bounds,
- nv_float cell_width,
- nv_float cell_height
+ nvContactListener listener,
+ void *user_arg
);
/**
- * @brief Clear and free everything in space.
+ * @brief Get the current contact event listener.
*
* @param space Space
+ * @return nvContactListener *
*/
-void nvSpace_clear(nvSpace *space);
+nvContactListener *nvSpace_get_contact_listener(const nvSpace *space);
/**
- * @brief Add body to space.
+ * @brief Clear bodies and constraints in space.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
*
* @param space Space
- * @param body Body to add
+ * @param free_all Whether to free objects after removing them from space
+ * @return int Status
*/
-void nvSpace_add(nvSpace *space, nvBody *body);
+int nvSpace_clear(nvSpace *space, nv_bool free_all);
/**
- * @brief Remove body from the space.
+ * @brief Add body to space.
*
- * The removal will not pe performed until the current simulation step ends.
- * After removing the body managing body's memory belongs to user. You should
- * use @ref nvBody_free if you are not going to add it to the space again.
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
*
* @param space Space
- * @param body Body to remove
+ * @param body Body to add
+ * @return int Status
*/
-void nvSpace_remove(nvSpace *space, nvBody *body);
+int nvSpace_add_rigidbody(nvSpace *space, nvRigidBody *body);
/**
- * @brief Remove body from the space and free it.
+ * @brief Remove body from the space.
+ *
+ * After removing the body, managing it's memory belongs to user. You should
+ * use @ref nvRigidBody_free if you are not going to add it to the space again.
*
- * The removal will not pe performed until the current simulation step ends.
- * Unlike @ref nvSpace_remove, this method also frees the body. It can be
- * useful in games where references to bullets aren't usually kept.
+ * This function also removes any constraints attached to the body.
+ *
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
*
* @param space Space
- * @param body Body to remove and free
+ * @param body Body to remove
+ * @return int Status
*/
-void nvSpace_kill(nvSpace *space, nvBody *body);
+int nvSpace_remove_rigidbody(nvSpace *space, nvRigidBody *body);
/**
* @brief Add constraint to space.
*
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
+ *
* @param space Space
* @param cons Constraint to add
+ * @return int Status
*/
-void nvSpace_add_constraint(nvSpace *space, nvConstraint *cons);
+int nvSpace_add_constraint(nvSpace *space, nvConstraint *cons);
/**
- * @brief Advance the simulation.
+ * @brief Remove constraint from the space.
*
- * Iteration counts defines how many iterations the solver uses to converge constraints.
- * Higher the iteration count, more accurate simulation but higher CPU usage, thus lower performance.
- * Velocity and position iteration counts are used for the contact constraint solver.
- * Constraint iteration count is used for other constraints like joints.
- * For a game, it is usually sufficient to keep them around 5-10.
+ * After removing the constraint managing it's memory belongs to user. You should
+ * use @ref nvConstraint_free if you are not going to add it to the space again.
*
- * Substep count defines how many substeps the current simulation step is going to get
- * divided into. This effectively increases the accuracy of the simulation but
- * also impacts the performance greatly because the whole simulation is processed
- * and collisions are recalculated by given amounts of times internally. In a game,
- * you wouldn't need this much detail. Best to leave it at 1.
+ * Returns non-zero on error. Use @ref nv_get_error to get more information.
*
- * @param space Space instance
- * @param dt Time step size (delta time)
- * @param velocity_iters Velocity solving iteration count
- * @param position_iters Position solving iteration count
- * @param constraint_iters Constraint solving iteration count
- * @param substeps Substep count
+ * @param space Space
+ * @param cons Constraint to remove
+ * @return int
*/
-void nvSpace_step(
- nvSpace *space,
- nv_float dt,
- size_t velocity_iters,
- size_t position_iters,
- size_t constraint_iters,
- size_t substeps
-);
+int nvSpace_remove_constraint(nvSpace *space, nvConstraint *cons);
/**
- * @brief Enable sleeping.
+ * @brief Iterate over the rigid bodies in this space.
+ *
+ * Make sure to reset the index if you alter the space in any way while iterating.
*
* @param space Space
+ * @param body Pointer to rigid body
+ * @param index Pointer to iteration index
+ * @return nv_bool
*/
-void nvSpace_enable_sleeping(nvSpace *space);
+nv_bool nvSpace_iter_bodies(nvSpace *space, nvRigidBody **body, size_t *index);
/**
- * @brief Disable sleeping.
+ * @brief Iterate over the constraints in this space.
+ *
+ * Make sure to reset the index if you alter the space in any way while iterating.
*
* @param space Space
+ * @param cons Pointer to constraint
+ * @param index Pointer to iteration index
+ * @return nv_bool
*/
-void nvSpace_disable_sleeping(nvSpace *space);
+nv_bool nvSpace_iter_constraints(nvSpace *space, nvConstraint **cons, size_t *index);
/**
- * @brief Enable multithreading.
- *
- * If the given number of threads is 0, system's CPU core count is used.
+ * @brief Advance the simulation.
*
- * @param space Space
- * @param threads Number of threads
+ * @param space Space instance
+ * @param dt Time step size (delta time)
*/
-void nvSpace_enable_multithreading(nvSpace *space, size_t threads);
+void nvSpace_step(nvSpace *space, nv_float dt);
/**
- * @brief Disable multithreading.
+ * @brief Cast a ray in space and collect intersections.
*
* @param space Space
+ * @param from Starting position of ray in world space
+ * @param to End position of ray in world space
+ * @param results_array Array of ray cast result structs to be filled
+ * @param num_hits Number of hits (size of results array)
+ * @param capacity Size allocated for the results array
*/
-void nvSpace_disable_multithreading(nvSpace *space);
+void nvSpace_cast_ray(
+ nvSpace *space,
+ nvVector2 from,
+ nvVector2 to,
+ nvRayCastResult *results_array,
+ size_t *num_hits,
+ size_t capacity
+);
#endif
\ No newline at end of file
diff --git a/include/novaphysics/space_settings.h b/include/novaphysics/space_settings.h
new file mode 100644
index 0000000..131d4cb
--- /dev/null
+++ b/include/novaphysics/space_settings.h
@@ -0,0 +1,80 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_SPACE_SETTINGS_H
+#define NOVAPHYSICS_SPACE_SETTINGS_H
+
+#include "novaphysics/internal.h"
+#include "novaphysics/constraints/constraint.h"
+
+
+/**
+ * @file space_settings.h
+ *
+ * @brief Physics space simulation settings.
+ */
+
+
+/**
+ * @brief Space settings struct.
+ */
+typedef struct {
+ nv_float baumgarte; /**< Baumgarte stabilization factor is used to correct constraint erros by feeding them back to the velocity constraints.
+ This can add some energy to the system. It's a value between [0, 1]. For a game, it's best to leave this at default. */
+
+ nv_float penetration_slop; /**< Amount of penetration error allowed in position correction.
+ The reason we allow some error is for stability and avoid jitter.
+ You can adjust it depending on the general size range of your game objects.
+ But it's best to keep it at default and respect the guidance on shape sizes explained in @ref nvRigidBody */
+
+ nvContactPositionCorrection contact_position_correction; /**< Position correction method to use for collisions. */
+
+ nv_uint32 velocity_iterations; /**< Nova uses Sequential Impulses (or Projected Gauss-Seidel), which is an iterative method.
+ This value defines the number of iterations done by the solver in order to solve velocity constraints.
+ If you have high number of iterations, constraints should converge to a better solution
+ with the cost of more load on CPU. Lower number of iterations can result in poor
+ accuracy and the simulation may look spongy. For a game 6-10 should be sufficient. */
+
+ nv_uint32 position_iterations; /**< Iteration count for Nonlinear Gauss-Seidel solver for collisions only.
+ For a game 3-6 should be sufficient.
+ @warning Currently unused. */
+
+ nv_uint32 substeps; /**< This defines how many substeps the current simulation step is going to get
+ divided into. This effectively increases the accuracy of the simulation but
+ also impacts the performance greatly because the whole simulation is processed
+ and collisions are recalculated by given amounts of times internally. In a game,
+ you wouldn't need this much detail. Best to leave it at 1. */
+
+ nv_float linear_damping; /**< Amount of damping applied to linear motion.
+ It is required to remove potential energy
+ added trough numerical instability.
+ The final damping value is calculated as
+ `0.99 ^ (r * d)` where `d` is this value and
+ `r` is damping ratio of a rigid body, usually 1.
+ You can change damping ratios of individual bodies
+ in order to have them lose energy more. */
+
+ nv_float angular_damping; /**< Same as `linear_damping` but for angular motion. */
+
+ nv_bool warmstarting; /**< Whether to allow warmstarting constraints or not.
+ This is a really neat feature of Gauss-Seidel based solvers that
+ allows to have greatly increased stability with little overhead.
+ Warmstarting is basically using the last simulation step's solutions
+ for constraints as the starting guess in the solver.
+ For a game, you don't really have any reason to turn this off. */
+
+ nvCoefficientMix restitution_mix; /**< Mixing function used for restitution. */
+
+ nvCoefficientMix friction_mix; /**< Mixing function used for friction. */
+
+} nvSpaceSettings;
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/space_step.h b/include/novaphysics/space_step.h
deleted file mode 100644
index cf3e698..0000000
--- a/include/novaphysics/space_step.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_SPACE_STEP_H
-#define NOVAPHYSICS_SPACE_STEP_H
-
-#include "novaphysics/internal.h"
-
-
-/**
- * @file space_step.h
- *
- * @brief Internal functions the space uses in a simulation step.
- */
-
-
-// Hashing functions for space & broadphase hashmaps
-
-nv_uint64 _nvSpace_resolution_hash(void *item);
-
-nv_uint64 _nvSpace_broadphase_pair_hash(void *item);
-
-
-/**
- * Apply forces, gravity, integrate accelerations (update velocities) and apply damping.
- */
-void _nvSpace_integrate_accelerations(
- struct nvSpace *space,
- nv_float dt,
- size_t i
-);
-
-/**
- * Integrate velocities (update positions) and check out-of-bound bodies.
- */
-void _nvSpace_integrate_velocities(
- struct nvSpace *space,
- nv_float dt,
- size_t i
-);
-
-#ifdef NV_AVX
-
- /**
- * Integrate accelerations using AVX float vectors.
- */
- void _nvSpace_integrate_accelerations_AVX(
- struct nvSpace *space,
- nv_float dt
- );
-
- /**
- * Integrate velocities using AVX float vectors.
- */
- void _nvSpace_integrate_velocities_AVX(
- struct nvSpace *space,
- nv_float dt
- );
-
-#endif
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/spring.h b/include/novaphysics/spring.h
deleted file mode 100644
index a9e1659..0000000
--- a/include/novaphysics/spring.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_SPRING_CONSTRAINT_H
-#define NOVAPHYSICS_SPRING_CONSTRAINT_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/body.h"
-#include "novaphysics/constraint.h"
-
-
-/**
- * @file spring.h
- *
- * @brief Damped spring implementation.
- */
-
-
-/**
- * @brief Spring constraint definition.
- *
- * A spring constraint is a damped spring with rest length, stiffness and damping value.
- */
-typedef struct {
- nv_float length; /**< Resting length of the spring. */
- nv_float stiffness; /**< Stiffness (strength) of the spring. */
- nv_float damping; /**< Damping of the spring. */
-
- nvVector2 anchor_a; /**< Local anchor point on body A. */
- nvVector2 anchor_b; /**< Local anchor point on body B. */
- nv_float target_vel; /**< Target relative velocity. */
- nv_float damping_bias; /**< Damping bias. */
- nvVector2 ra; /**< Anchor point on body A. */
- nvVector2 rb; /**< Anchor point on body B. */
- nvVector2 normal; /**< Normal of the constraint. */
- nv_float mass; /**< Constraint effective mass. */
- nv_float jc; /**< Accumulated constraint impulse. */
-} nvSpring;
-
-/**
- * @brief Create a new spring constraint.
- *
- * Leave one of the body parameters as :code:`NULL` to link the body to world.
- * Don't forget to change the anchor point to be in world space as well.
- *
- * @param a First body
- * @param b Second body
- * @param anchor_a Local anchor point on body A
- * @param anchor_b Local anchor point on body B
- * @param length Length of the spring
- * @param stiffness Stiffness (strength) of the spring
- * @param damping Damping of the spring
- *
- * @return nvConstraint *
- */
-nvConstraint *nvSpring_new(
- nvBody *a,
- nvBody *b,
- nvVector2 anchor_a,
- nvVector2 anchor_b,
- nv_float length,
- nv_float stiffness,
- nv_float damping
-);
-
-/**
- * @brief Prepare for solving.
- *
- * @param space Space
- * @param cons Constraint
- * @param inv_dt Inverse delta time (1/Δt)
- */
-void nvSpring_presolve(
- struct nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-);
-
-/**
- * @brief Solve spring constraint.
- *
- * @param cons Constraint
- */
-void nvSpring_solve(nvConstraint *cons);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/threading.h b/include/novaphysics/threading.h
deleted file mode 100644
index 9c3f521..0000000
--- a/include/novaphysics/threading.h
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#ifndef NOVAPHYSICS_THREADING_H
-#define NOVAPHYSICS_THREADING_H
-
-#include "novaphysics/internal.h"
-#include "novaphysics/array.h"
-
-
-/**
- * @file threading.h
- *
- * @brief Cross-platform multi-threading API.
- */
-
-
-/**
- * @brief Get the number of CPU cores on the system.
- *
- * @return nv_uint32
- */
-nv_uint32 nv_get_cpu_count();
-
-
-/**
- * @brief Cross-platform mutex implementation.
- */
-typedef struct {
- void *_handle; /**< Win32 API object handle. */
-} nvMutex;
-
-/**
- * @brief Create new mutex.
- *
- * @return nvMutex *
- */
-nvMutex *nvMutex_new();
-
-/**
- * @brief Free mutex.
- *
- * @param mutex Mutex
- */
-void nvMutex_free(nvMutex *mutex);
-
-/**
- * @brief Lock the mutex.
- *
- * @param mutex Mutex
- * @return bool
- */
-bool nvMutex_lock(nvMutex *mutex);
-
-/**
- * @brief Unlock the mutex.
- *
- * @param mutex Mutex
- * @return bool
- */
-bool nvMutex_unlock(nvMutex *mutex);
-
-
-/**
- * @brief Cross-platform event / condition variable implementation.
- */
-typedef struct {
- void *_handle;
-} nvCondition;
-
-/**
- * @brief Create new condition.
- *
- * @return nvCondition *
- */
-nvCondition *nvCondition_new();
-
-/**
- * @brief Free condition.
- *
- * @param condition Condition
- */
-void nvCondition_free(nvCondition *cond);
-
-/**
- * @brief Wait for condition to be signaled.
- *
- * @param cond Condition
- */
-void nvCondition_wait(nvCondition *cond, nvMutex *mutex);
-
-/**
- * @brief Signal condition.
- *
- * @param cond Condition
- */
-void nvCondition_signal(nvCondition *cond);
-
-
-/**
- * @brief Data that is passed to thread worker function.
- */
-typedef struct {
- nv_uint64 id; /**< Thread's ID. */
- void *data; /**< User data. */
-} nvThreadWorkerData;
-
-/**
- * @brief Cross-platform thread implementation.
- */
-typedef struct {
- nv_uint64 id; /**< Unique identity number of the thread. */
- nvThreadWorkerData *worker_data; /**< Data that is going to be passed to worker function. */
-
- void *_handle; /**< Win32 API object handle. */
-} nvThread;
-
-// Thread worker function type
-typedef int ( *nvThreadWorker)(nvThreadWorkerData *);
-
-/**
- * @brief Create a new thread and start executing the worker function.
- *
- * @param func Worker function
- * @param data Data to pass to worker function
- * @return nvThread *
- */
-nvThread *nvThread_create(nvThreadWorker func, void *data);
-
-/**
- * @brief Free thread.
- *
- * @param thread Thread
- */
-void nvThread_free(nvThread *thread);
-
-/**
- * @brief Join the thread and wait until the worker is finished.
- *
- * @param thread Thread
- */
-void nvThread_join(nvThread *thread);
-
-/**
- * @brief Join multiple threads and wait until all of the workers are finished.
- *
- * This uses WaitForMultipleObjects API on Windows.
- *
- * @param threads Array of thread pointers
- * @param length Length of the array
- */
-void nvThread_join_multiple(nvThread **threads, size_t length);
-
-
-/**
- * @brief Task executor.
- *
- * The task executor is a background thread pool that continuously runs,
- * ready to execute tasks whenever they are assigned.
- */
-typedef struct {
- nvArray *threads; /**< Array of threads. */
- nvArray *data; /**< Array of thread data. */
-} nvTaskExecutor;
-
-// Task executor task callback function type
-typedef int ( *nvTaskCallback)(void *);
-
-/**
- * @brief Task struct.
- *
- * You don't manually create this. It is created when tasks are added using
- * @ref nvTaskExecutor_add_task or @ref nvTaskExecutor_add_task_to functions.
- */
-typedef struct {
- nvTaskCallback task_func;
- void *data;
-} nvTask;
-
-/**
- * @brief Task executor thread data.
- *
- * This struct is passed to main pool threads of the task executor.
- */
-typedef struct {
- bool is_active; /**< Is this thread still running? */
- bool is_busy; /**< Is this thread currently executing a task? */
- bool task_arrived; /**< Did the task arrive to thread? */
- nvTask *task; /**< Task assigned to this thread. */
- nvMutex *task_mutex; /**< Task mutex. */
- nvCondition *task_event; /**< Signaled when a new task is assigned.
- Listened by the executor thread. */
- nvCondition *done_event; /**< Signaled when the thread finishes executing task.
- Should be listened by other threads. */
-} nvTaskExecutorData;
-
-/**
- * @brief Create new task executor.
- *
- * @param size Number of executor threads to initialize
- * @return nvTaskExecutor *
- */
-nvTaskExecutor *nvTaskExecutor_new(size_t size);
-
-/**
- * @brief Free the task executor and its threads.
- *
- * @param task_executor Task executor
- */
-void nvTaskExecutor_free(nvTaskExecutor *task_executor);
-
-/**
- * @brief Stop the task executor and wait for thread pool to finish.
- *
- * You cannot reinitialize the task executor after stopping it.
- *
- * @param task_executor Task executor
- */
-void nvTaskExecutor_close(nvTaskExecutor *task_executor);
-
-/**
- * @brief Add a task to an available thread.
- *
- * Returns false if it fails to find an available thread or fails to allocate task.
- *
- * @param task_executor Task executor
- * @param task_func Task callback function
- * @param task_data Data that is passed to task callback
- * @return bool
- */
-bool nvTaskExecutor_add_task(
- nvTaskExecutor *task_executor,
- nvTaskCallback task_func,
- void *task_data
-);
-
-/**
- * @brief Add a task to a specific thread in the pool.
- *
- * Returns false if the thread is busy or fails to allocate task.
- *
- * @param task_executor Task executor
- * @param task_func Task callback function
- * @param task_data Data that is passed to task callback
- * @param thread_no Index of the thread in the pool
- * @return bool
- */
-bool nvTaskExecutor_add_task_to(
- nvTaskExecutor *task_executor,
- nvTaskCallback task_func,
- void *task_data,
- size_t thread_no
-);
-
-/**
- * @brief Wait for all tasks to be executed.
- *
- * @param task_executor Task executor
- */
-void nvTaskExecutor_wait_tasks(nvTaskExecutor *task_executor);
-
-
-#endif
\ No newline at end of file
diff --git a/include/novaphysics/types.h b/include/novaphysics/types.h
new file mode 100644
index 0000000..1be01a3
--- /dev/null
+++ b/include/novaphysics/types.h
@@ -0,0 +1,91 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#ifndef NOVAPHYSICS_TYPES_H
+#define NOVAPHYSICS_TYPES_H
+
+#include
+#include
+
+
+/**
+ * @file types.h
+ *
+ * @brief Nova Physics type definitions.
+ */
+
+
+/*
+ Nova Physics floating-point type.
+
+ Double-precision mode can be used for bigger worlds and higher accuracy.
+ But it might be slower depending on the arch since all operations will
+ be done with doubles.
+
+ See build instructions on how to enable double precision and other options.
+*/
+
+#ifdef NV_USE_DOUBLE_PRECISION
+
+ typedef double nv_float;
+
+ #define nv_fabs fabs
+ #define nv_fmin fmin
+ #define nv_fmax fmax
+ #define nv_pow pow
+ #define nv_exp exp
+ #define nv_sqrt sqrt
+ #define nv_sin sin
+ #define nv_cos cos
+ #define nv_atan2 atan2
+ #define nv_floor floor
+
+#else
+
+ typedef float nv_float;
+
+ #define nv_fabs fabsf
+ #define nv_fmin fminf
+ #define nv_fmax fmaxf
+ #define nv_pow powf
+ #define nv_exp expf
+ #define nv_sqrt sqrtf
+ #define nv_sin sinf
+ #define nv_cos cosf
+ #define nv_atan2 atan2f
+ #define nv_floor floorf
+
+#endif
+
+
+/*
+ Nova Physics integer types.
+*/
+
+typedef int8_t nv_int8;
+typedef int16_t nv_int16;
+typedef int32_t nv_int32;
+typedef int64_t nv_int64;
+typedef uint8_t nv_uint8;
+typedef uint16_t nv_uint16;
+typedef uint32_t nv_uint32;
+typedef uint64_t nv_uint64;
+
+
+/*
+ Nova Physics boolean type.
+*/
+
+typedef int nv_bool;
+#define true 1
+#define false 0
+
+
+#endif
\ No newline at end of file
diff --git a/include/novaphysics/vector.h b/include/novaphysics/vector.h
index ce20933..9b3c996 100644
--- a/include/novaphysics/vector.h
+++ b/include/novaphysics/vector.h
@@ -11,9 +11,6 @@
#ifndef NOVAPHYSICS_VECTOR_H
#define NOVAPHYSICS_VECTOR_H
-#include
-#include
-#include
#include "novaphysics/internal.h"
@@ -34,52 +31,13 @@ typedef struct {
/**
- * @brief Initialize vector
+ * @brief Initialize nvVector2 literal.
*
* @param x X component
* @param y Y component
* @return nvVector2
*/
-#define NV_VEC2(x, y) ((nvVector2){(x), (y)})
-
-/**
- * @brief Initialize and store vector on HEAP.
- *
- * @param x X component
- * @param y Y component
- * @return nvVector2 *
- */
-static inline nvVector2 *NV_VEC2_NEW(nv_float x, nv_float y) {
- nvVector2 *vector_heap = NV_NEW(nvVector2);
- vector_heap->x = x;
- vector_heap->y = y;
- return vector_heap;
-}
-
-/**
- * @brief Cast `void *` to @ref nvVector2.
- *
- * This is useful for directly passing indexed data from @ref nvArray
- *
- * @param x Vector
- * @return nvVector2
- */
-#define NV_TO_VEC2(x) (*(nvVector2 *)(x))
-
-/*
- Utility macro to cast void * to nvVector2 *
- This is useful for modifying vector element of nvArray
-*/
-
-/**
- * @brief Cast `void *` to @ref nvVector2 pointer.
- *
- * This is useful for modifying vector elements of @ref nvArray
- *
- * @param x Vector
- * @return nvVector2 *
- */
-#define NV_TO_VEC2P(x) ((nvVector2 *)(x))
+#define NV_VECTOR2(x, y) ((nvVector2){(x), (y)})
/**
@@ -93,9 +51,9 @@ static const nvVector2 nvVector2_zero = {0.0, 0.0};
*
* @param a Left-hand vector
* @param b Right-hand vector
- * @return bool
+ * @return nv_bool
*/
-static inline bool nvVector2_eq(nvVector2 a, nvVector2 b) {
+static inline nv_bool nvVector2_eq(nvVector2 a, nvVector2 b) {
return (a.x == b.x && a.y == b.y);
}
@@ -107,7 +65,7 @@ static inline bool nvVector2_eq(nvVector2 a, nvVector2 b) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_add(nvVector2 a, nvVector2 b) {
- return NV_VEC2(a.x + b.x, a.y + b.y);
+ return NV_VECTOR2(a.x + b.x, a.y + b.y);
}
/**
@@ -118,7 +76,7 @@ static inline nvVector2 nvVector2_add(nvVector2 a, nvVector2 b) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_sub(nvVector2 a, nvVector2 b) {
- return NV_VEC2(a.x - b.x, a.y - b.y);
+ return NV_VECTOR2(a.x - b.x, a.y - b.y);
}
/**
@@ -129,7 +87,7 @@ static inline nvVector2 nvVector2_sub(nvVector2 a, nvVector2 b) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_mul(nvVector2 v, nv_float s) {
- return NV_VEC2(v.x * s, v.y * s);
+ return NV_VECTOR2(v.x * s, v.y * s);
}
/**
@@ -140,7 +98,7 @@ static inline nvVector2 nvVector2_mul(nvVector2 v, nv_float s) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_div(nvVector2 v, nv_float s) {
- return NV_VEC2(v.x / s, v.y / s);
+ return NV_VECTOR2(v.x / s, v.y / s);
}
/**
@@ -150,7 +108,7 @@ static inline nvVector2 nvVector2_div(nvVector2 v, nv_float s) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_neg(nvVector2 v) {
- return NV_VEC2(-v.x, -v.y);
+ return NV_VECTOR2(-v.x, -v.y);
}
/**
@@ -163,7 +121,7 @@ static inline nvVector2 nvVector2_neg(nvVector2 v) {
static inline nvVector2 nvVector2_rotate(nvVector2 v, nv_float a) {
nv_float c = nv_cos(a);
nv_float s = nv_sin(a);
- return NV_VEC2(c * v.x - s * v.y, s * v.x + c * v.y);
+ return NV_VECTOR2(c * v.x - s * v.y, s * v.x + c * v.y);
}
/**
@@ -174,7 +132,7 @@ static inline nvVector2 nvVector2_rotate(nvVector2 v, nv_float a) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_perp(nvVector2 v) {
- return NV_VEC2(-v.y, v.x);
+ return NV_VECTOR2(-v.y, v.x);
}
/**
@@ -184,7 +142,7 @@ static inline nvVector2 nvVector2_perp(nvVector2 v) {
* @return nvVector2
*/
static inline nvVector2 nvVector2_perpr(nvVector2 v) {
- return NV_VEC2(v.y, -v.x);
+ return NV_VECTOR2(v.y, -v.x);
}
/**
@@ -261,5 +219,27 @@ static inline nvVector2 nvVector2_normalize(nvVector2 v) {
return nvVector2_div(v, nvVector2_len(v));
}
+/**
+ * @brief Lerp between two vectors.
+ *
+ * @param a First vector
+ * @param b Second vector
+ * @param t Interpolation amount [0, 1]
+ * @return nvVector2
+ */
+static inline nvVector2 nvVector2_lerp(nvVector2 a, nvVector2 b, nv_float t) {
+ return NV_VECTOR2((1.0 - t) * a.x + t * b.x, (1.0 - t) * a.y + t * b.y);
+}
+
+/**
+ * @brief Is the vector a zero vector?
+ *
+ * @param v Vector
+ * @return nv_bool
+ */
+static inline nv_bool nvVector2_is_zero(nvVector2 v) {
+ return v.x == 0.0 && v.y == 0.0;
+}
+
#endif
\ No newline at end of file
diff --git a/meson.build b/meson.build
new file mode 100644
index 0000000..3ee13af
--- /dev/null
+++ b/meson.build
@@ -0,0 +1,187 @@
+project(
+ 'nova-physics',
+ ['c', 'cpp'],
+ license: 'MIT',
+ license_files: 'LICENSE',
+ default_options: [
+ 'c_std=c99',
+ 'cpp_std=c++11',
+ 'warning_level=1',
+ 'default_library=static'
+ ]
+)
+
+
+compiler = meson.get_compiler('c')
+
+cpp_args = []
+
+if compiler.get_id() == 'msvc'
+ c_args = ['/arch:AVX2', '/D_CRT_SECURE_NO_WARNINGS']
+ link_args = []
+
+ #c_args += ['/wd4305', '/wd4244']
+ c_args += ['/wd4305']
+
+ if get_option('enable_profiler')
+ c_args += '/DNV_ENABLE_PROFILER'
+ endif
+
+ if get_option('use_doubles')
+ c_args += '/DNV_USE_DOUBLE_PRECISION'
+ endif
+
+ if get_option('use_tracy')
+ c_args += '/DTRACY_ENABLE'
+ cpp_args += '/DTRACY_ENABLE'
+ link_args += ['ws2_32.lib', 'wsock32.lib', 'dbghelp.lib']
+ endif
+else
+ # -march=mavx2 ?
+ c_args = ['-march=native']
+ link_args = ['-lm']
+
+ # When you target C99, you also have to specify POSIX clock
+ # https://raspberrypi.stackexchange.com/a/95480
+ c_args += '-D_POSIX_C_SOURCE=200809L'
+
+ if get_option('enable_profiler')
+ c_args += '-DNV_ENABLE_PROFILER'
+ endif
+
+ if get_option('use_doubles')
+ c_args += '-DNV_USE_DOUBLE_PRECISION'
+ endif
+
+ if get_option('use_tracy')
+ c_args += '-DTRACY_ENABLE'
+ cpp_args += '-DTRACY_ENABLE'
+ link_args += ['-lws2_32', '-lwsock32', '-ldbghelp']
+ endif
+endif
+
+
+nova_src = [
+ 'src/core/array.c',
+ 'src/core/error.c',
+ 'src/core/hashmap.c',
+ 'src/core/pool.c',
+ 'src/constraints/constraint.c',
+ 'src/constraints/contact_constraint.c',
+ 'src/constraints/distance_constraint.c',
+ 'src/constraints/hinge_constraint.c',
+ 'src/constraints/spline_constraint.c',
+ 'src/body.c',
+ 'src/broadphase.c',
+ 'src/bvh.c',
+ 'src/collision.c',
+ 'src/contact.c',
+ 'src/narrowphase.c',
+ 'src/space.c',
+ 'src/shape.c'
+]
+
+nova_includes = ['include']
+
+if get_option('use_tracy')
+ nova_src += 'src/tracy/TracyClient.cpp'
+ nova_includes += 'src/tracy'
+endif
+
+libnova = library(
+ 'nova',
+ sources: nova_src,
+ include_directories: nova_includes,
+ c_args: c_args,
+ cpp_args: cpp_args,
+ link_args: link_args,
+ version: '1.0.0',
+)
+
+python = find_program('python3', 'python')
+
+if get_option('build_examples')
+
+ r = run_command(python, 'scripts/install_wraps.py')
+ if r.returncode() != 0
+ error('install_wraps.py script failed.\n', r.stderr())
+ endif
+
+ examples_src = [
+ 'examples/main.c',
+ 'external/glad/glad.c'
+ ]
+ examples_includes = ['external', 'include']
+
+ if get_option('use_tracy')
+ examples_includes += 'src/tracy'
+ endif
+
+ sdl2_dep = dependency('sdl2')
+ opengl_dep = dependency('gl')
+
+ if compiler.get_id() == 'msvc'
+ sdl2_main_dep = dependency('sdl2main')
+ examples_deps = [sdl2_dep, sdl2_main_dep, opengl_dep]
+ else
+ examples_deps = [sdl2_dep, opengl_dep]
+ endif
+
+ executable(
+ 'examples',
+ sources: examples_src,
+ include_directories: examples_includes,
+ c_args: c_args,
+ link_args: link_args,
+ dependencies: examples_deps,
+ link_with: libnova
+ )
+
+ r = run_command(python, 'scripts/copy_assets.py')
+ if r.returncode() != 0
+ error('copy_assets.py script failed.\n', r.stderr())
+ endif
+
+endif
+
+
+if get_option('build_benchmarks')
+
+ benchmarks_src = ['benchmarks/main.c']
+ benchmarks_includes = ['include']
+
+ if get_option('use_tracy')
+ benchmarks_includes += 'src/tracy'
+ endif
+
+ executable(
+ 'benchmarks',
+ sources: benchmarks_src,
+ include_directories: benchmarks_includes,
+ c_args: c_args,
+ link_args: link_args,
+ link_with: libnova
+ )
+
+endif
+
+
+if get_option('build_tests')
+
+ tests_src = ['tests/main.c']
+ tests_includes = ['include']
+
+ if get_option('use_tracy')
+ tests_includes += 'src/tracy'
+ endif
+
+ executable(
+ 'tests',
+ sources: tests_src,
+ include_directories: tests_includes,
+ c_args: c_args,
+ link_args: link_args,
+ link_with: libnova
+ )
+
+endif
\ No newline at end of file
diff --git a/meson.options b/meson.options
new file mode 100644
index 0000000..99163a2
--- /dev/null
+++ b/meson.options
@@ -0,0 +1,48 @@
+option(
+ 'build_examples',
+ type: 'boolean',
+ value: true,
+ description: 'Build example demos, installs SDL2. On by default.'
+)
+
+option(
+ 'build_benchmarks',
+ type: 'boolean',
+ value: false,
+ description: 'Build benchmarks. Off by default.'
+)
+
+option(
+ 'build_tests',
+ type: 'boolean',
+ value: true,
+ description: 'Build unit tests. On by default.'
+)
+
+option(
+ 'enable_profiler',
+ type: 'boolean',
+ value: true,
+ description: 'Enable built-in profiler. (Defines NV_ENABLE_PROFILER, on by default)'
+)
+
+option(
+ 'enable_simd',
+ type: 'boolean',
+ value: true,
+ description: 'Enable usage of any SIMD extension. (Defines NV_ENABLE_SIMD, on by default)'
+)
+
+option(
+ 'use_doubles',
+ type: 'boolean',
+ value: false,
+ description: 'Use double-precision mode. (Defines NV_USE_DOUBLE_PRECISION, off by default)'
+)
+
+option(
+ 'use_tracy',
+ type: 'boolean',
+ value: false,
+ description: 'Build with Tracy profiler.'
+)
\ No newline at end of file
diff --git a/nova_builder.py b/nova_builder.py
deleted file mode 100644
index 320e3bd..0000000
--- a/nova_builder.py
+++ /dev/null
@@ -1,2110 +0,0 @@
-"""
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-
- Nova Physics Engine Build System
- --------------------------------
- Build & package Nova Physics
- Build & run examples
- Build & run benchmarks
- Build & run unit tests
-
- This script requires Python 3.9+ and is one-file
- with no dependencies for convenience and portability.
-"""
-
-from typing import Union, Optional
-
-import sys
-import os
-import stat
-import subprocess
-import platform
-import shutil
-import json
-import tarfile
-import zipfile
-import io
-import urllib.error
-import urllib.request
-import multiprocessing
-from abc import ABC, abstractmethod
-from pathlib import Path
-from enum import Enum
-from time import perf_counter, time, gmtime
-
-
-IS_WIN = platform.system() == "Windows"
-
-
-# Fix windows terminal
-if IS_WIN:
- subprocess.run("", shell=True)
- # This import won't be used anywhere else
- from ctypes import windll
- k = windll.kernel32
- k.SetConsoleMode(k.GetStdHandle(-11), 7) # -11 = stdout
-
-
-SEGFAULT_CODES = (
- 3221225477, # This can also mean a network error, but irrevelant in our case
- 11,
- -11,
- 134,
- 139
-)
-
-
-class FG:
- """
- ANSI escape codes for terminal foreground colors.
- """
-
- black = "\033[30m"
- darkgray = "\033[90m"
- lightgray = "\033[37m"
- white = "\033[97m"
- red = "\033[31m"
- orange = "\033[33m"
- yellow = "\033[93m"
- green = "\033[32m"
- blue = "\033[34m"
- cyan = "\033[36m"
- purple = "\033[35m"
- magenta = "\033[95m"
- lightred = "\033[91m"
- lightgreen = "\033[92m"
- lightblue = "\033[94m"
- lightcyan = "\033[96m"
-
- @staticmethod
- def rgb(r: int, g: int, b: int) -> str:
- return f"\033[38;2;{r};{g};{b}m"
-
-class BG:
- """
- ANSI escape codes for terminal background colors.
- """
-
- black = "\033[40m"
- darkgray = "\033[100m"
- lightgray = "\033[47m"
- white = "\033[107m"
- red = "\033[41m"
- orange = "\033[43m"
- yellow = "\033[103m"
- green = "\033[42m"
- blue = "\033[44m"
- cyan = "\033[46m"
- purple = "\033[45m"
- magenta = "\033[105m"
- lightred = "\033[101m"
- lightgreen = "\033[102m"
- lightblue = "\033[104m"
- lightcyan = "\033[106m"
-
- @staticmethod
- def rgb(r: int, g: int, b: int) -> str:
- return f"\033[48;2;{r};{g};{b}m"
-
-# Other ANSI escape codes for graphic modes
-# (some doesn't work on some terminals)
-class Style:
- """
- Other ANSI escape codes for graphic modes.
- Some doesn't work on some terminals.
- """
-
- bold = "\033[01m"
- underline = "\033[04m"
- reverse = "\033[07m"
- strike = "\033[09m"
-
-RESET = "\033[0m"
-
-def format_colors(string: str, no_ansi: bool = False) -> str:
- """ Format string with color codes. """
-
- # This could be shortened with loops but meh..
- pairs = {
- "{RESET}": RESET,
- "{FG.black}": FG.black,
- "{FG.darkgray}": FG.darkgray,
- "{FG.lightgray}": FG.lightgray,
- "{FG.white}": FG.white,
- "{FG.red}": FG.red,
- "{FG.orange}": FG.orange,
- "{FG.yellow}": FG.yellow,
- "{FG.green}": FG.green,
- "{FG.blue}": FG.blue,
- "{FG.cyan}": FG.cyan,
- "{FG.purple}": FG.purple,
- "{FG.magenta}": FG.magenta,
- "{FG.lightred}": FG.lightred,
- "{FG.lightgreen}": FG.lightgreen,
- "{FG.lightblue}": FG.lightblue,
- "{FG.lightcyan}": FG.lightcyan,
- "{BG.black}": BG.black,
- "{BG.darkgray}": BG.darkgray,
- "{BG.lightgray}": BG.lightgray,
- "{BG.white}": BG.white,
- "{BG.red}": BG.red,
- "{BG.orange}": BG.orange,
- "{BG.yellow}": BG.yellow,
- "{BG.green}": BG.green,
- "{BG.blue}": BG.blue,
- "{BG.cyan}": BG.cyan,
- "{BG.purple}": BG.purple,
- "{BG.magenta}": BG.magenta,
- "{BG.lightred}": BG.lightred,
- "{BG.lightgreen}": BG.lightgreen,
- "{BG.lightblue}": BG.lightblue,
- "{BG.lightcyan}": BG.lightcyan,
- "{Style.reverse}": Style.reverse
- }
-
- for key in pairs:
- if no_ansi:
- string = string.replace(key, pairs[key])
-
- else:
- string = string.replace(key, "")
-
- return string
-
-
-class ProgressBar:
- """
- Simplistic progress bar.
- """
-
- def __init__(self,
- template: str,
- minvalue: Optional[float] = 0.0,
- maxvalue: Optional[float] = 1.0,
- value: Optional[float] = None
- ) -> None:
- self.template = template
- self.minvalue = minvalue
- self.maxvalue = maxvalue
- self.value = self.minvalue if value is None else value
- self.start_time = time()
- self.bar_length = 30
- self.mbps = 0.0
-
- def _render(self) -> str:
- """ Render the progress bar string. """
-
- render = self.template
-
- normval = self.minvalue + self.value * (self.maxvalue - self.minvalue)
- fpercent = normval * 100
- percent = round(fpercent)
-
- elapsed = gmtime(time() - self.start_time)
-
- remaining = gmtime(((time() - self.start_time) / self.value) * self.maxvalue)
-
- render = render.replace("{fpercent}", f"{fpercent}")
- render = render.replace("{percent}", f"{percent}")
-
- render = render.replace("{mbps}", f"{round(self.mbps, 2)}")
-
- render = render.replace("{ela.hours}", f"{elapsed.tm_hour}")
- render = render.replace("{ela.mins}", f"{elapsed.tm_min}")
- render = render.replace("{ela.secs}", f"{elapsed.tm_sec}")
-
- render = render.replace("{rem.hours}", f"{remaining.tm_hour}")
- render = render.replace("{rem.mins}", f"{remaining.tm_min}")
- render = render.replace("{rem.secs}", f"{remaining.tm_sec}")
-
- render = render.replace("{progress}", f"[{'='*int(normval * self.bar_length): <{self.bar_length}}]")
-
- return render
-
- def progress(self, increment: float) -> None:
- """ Advance the progress bar. """
-
- self.value += increment
-
- print(f"{self._render()}\033[1G\033[1A")
-
- def clear(self) -> None:
- """ Clear the last output of progress bar. """
- print(f"{' ' * 100}\033[1G\033[1A")
-
-
-def error(messages: Union[list, str], no_color: bool = False) -> None:
- """ Log error message and abort. """
-
- if isinstance(messages, str):
- msg = f"{{FG.red}}{{Style.reverse}} FAIL {{RESET}} {messages}\n"
- print(format_colors(msg, no_color))
- raise SystemExit(1)
-
- else:
- msg = f"{{FG.red}}{{Style.reverse}} FAIL {{RESET}} {messages[0]}\n"
-
- for line in messages[1:]:
- msg += f" {line}\n"
-
- print(format_colors(msg, no_color))
-
- raise SystemExit(1)
-
-def success(messages: Union[list, str], no_color: bool = False) -> None:
- """ Log success message. """
-
- if isinstance(messages, str):
- msg = f"{{FG.lightgreen}}{{Style.reverse}} DONE {{RESET}} {messages}\n"
- print(format_colors(msg, no_color))
-
- else:
- msg = f"{{FG.lightgreen}}{{Style.reverse}} DONE {{RESET}} {messages[0]}\n"
-
- for line in messages[1:]:
- msg += f" {line}\n"
-
- print(format_colors(msg, no_color))
-
-def info(messages: Union[list, str], no_color: bool = False) -> None:
- """ Log information message. """
-
- if isinstance(messages, str):
- msg = f"{{FG.cyan}}{{Style.reverse}} INFO {{RESET}} {messages}"
- print(format_colors(msg, no_color))
-
- else:
- msg = f"{{FG.cyan}}{{Style.reverse}} INFO {{RESET}} {messages[0]}"
-
- for line in messages[1:]:
- msg += f" {line}\n"
-
- print(format_colors(msg, no_color))
-
-
-def get_output(cmd: str) -> str:
- """ Run check_output, return empty string on error. """
-
- try:
- return subprocess.check_output(
- cmd, shell=True, stderr=subprocess.DEVNULL
- ).decode("utf-8").strip()
-
- except:
- return ""
-
-
-class Platform:
- """
- Platform specific information gatherer.
-
- Attributes
- ----------
- is_64 Whether the system architechure is 64-bit or not.
- system Most basic name that represents the system.
- name Name of the system.
- min_name Shortened name (without release versions, etc..)
-
- Possible configurations on different platforms:
-
- Attribute | Windows | Manjaro | Ubuntu | MacOS | Other Linux
- ----------+-----------------+------------+--------------+--------+------------------
- system | Windows | Linux | Linux | Darwin | Linux
- name | Windows 10 Home | Manjaro 23 | Ubuntu 20.04 | ? | release + version
- min_name | Windows | Manjaro | Ubuntu | ? | Linux
- """
-
- def __init__(self) -> None:
- self.is_64 = "64" in platform.architecture()[0]
-
- self.system = platform.system()
-
- if IS_WIN:
- # Some possible edition outputs:
- # Core, CoreSingleLanguage, Ultimate
- edition = platform.win32_edition()
-
- if "Core" in edition:
- edition = "Home"
-
- self.name = f"Windows {platform.release()} {edition}"
- self.min_name = "Windows"
-
- else:
- # These will be overwritten with gathered info
- self.name = platform.release() + platform.version()
- self.min_name = f"Unknown Linux"
-
- lsb_fields = self.parse_lsb_release()
-
- # Manjaro Linux
- if "manjaro" in platform.platform().lower():
- self.name = "Manjaro"
- if "Release" in lsb_fields: self.name += f" {lsb_fields['Release']}"
- self.min_name = "Manjaro"
-
- # Ubuntu
- elif "ubuntu" in platform.version().lower():
- self.name = "Ubuntu"
- if "Description" in lsb_fields: self.name += lsb_fields["Description"].replace("Ubuntu", "")
- self.min_name = "Ubuntu"
-
- else:
- os_release = self.parse_os_release()
-
- if "ID" in os_release:
- # Fedora
- if os_release["ID"].lower() == "fedora":
- self.min_name = "Fedora"
- if "PRETTY_NAME" in os_release: self.name = os_release["PRETTY_NAME"]
- else: self.name = self.min_name
-
- @staticmethod
- def parse_lsb_release() -> dict:
- """
- Parse "lsb_release -a" command that is found in most Linux distros
- by default to get more detailed system information.
- """
-
- out = get_output("lsb_release -a")
-
- if len(out) == 0: return {}
-
- fields = {}
-
- for line in out.split("\n"):
- split = line.split(":")
- if len(split) <= 1: continue
- fields[split[0].strip()] = split[1].strip()
-
- return fields
-
- @staticmethod
- def parse_os_release() -> dict:
- """
- Parse "cat /etc/os_release" command that is found in most Linux distros
- to get more detailed system information, in case lsb_release doesn't exist.
- """
-
- out = get_output("cat /etc/os-release")
-
- if len(out) == 0: return {}
-
- fields = {}
-
- for line in out.split("\n"):
- split = line.split("=")
- if len(split) <= 1: continue
- fields[split[0].strip()] = split[1].strip()
-
- return fields
-
-
-PLATFORM = Platform()
-
-
-BASE_PATH = Path(os.getcwd())
-
-SRC_PATH = BASE_PATH / "src"
-INCLUDE_PATH = BASE_PATH / "include"
-
-BUILD_PATH = BASE_PATH / "build"
-DEPS_PATH = BASE_PATH / "deps"
-CACHE_PATH = BASE_PATH / "cache"
-
-EXAMPLES_PATH = BASE_PATH / "examples"
-BENCHS_PATH = BASE_PATH / "benchmarks"
-TESTS_PATH = BASE_PATH / "tests"
-
-
-def get_nova_version() -> str:
- """ Get Nova Phyiscs Engine version number. """
-
- with open(INCLUDE_PATH / "novaphysics" / "novaphysics.h", "r") as header_file:
- content = header_file.readlines()
- major, minor, patch = 0, 0, 0
-
- for line in content:
- if line.startswith("#define NV_VERSION_MAJOR"):
- major = int(line[24:].strip())
-
- elif line.startswith("#define NV_VERSION_MINOR"):
- minor = int(line[24:].strip())
-
- elif line.startswith("#define NV_VERSION_PATCH"):
- patch = int(line[24:].strip())
-
- return f"{major}.{minor}.{patch}"
-
-
-def remove_readonly(action, name, exc) -> None:
- """ Overwrites READ-ONLY files as WRITE-ONLY and removes them. """
- os.chmod(name, stat.S_IWRITE)
- os.remove(name)
-
-def remove_dir(path: Path) -> None:
- """ Remove directory with its contents recursively. """
- shutil.rmtree(path, onerror=remove_readonly)
-
-def copy_dir(
- src_path: Path,
- dst_path: Path,
- symlinks: bool = False,
- ignore: bool = None
- ) -> None:
- """ Copy one directory's content into another one recursively. """
-
- for item in os.listdir(src_path):
- try:
- s = os.path.join(src_path, item)
- d = os.path.join(dst_path, item)
- if os.path.isdir(s):
- shutil.copytree(s, d, symlinks, ignore)
- else:
- shutil.copy2(s, d)
- except:
- pass
-
-def copy_dlls(src_dir: Path, dst_dir: Path) -> None:
- """ Copy DLL files from one directory to another. """
-
- for item in os.listdir(src_dir):
- s = os.path.join(src_dir, item)
- if os.path.isfile(s):
- if item.endswith(".dll"):
- shutil.copyfile(s, dst_dir / item)
-
-
-class CLI:
- """
- Class that parses and handles command line arguments and commands.
- """
-
- def __init__(self) -> None:
- self.commands = {}
- self.arguments = {}
- self.extra_arguments = []
-
- @property
- def command_count(self) -> int:
- return sum(int(self.check_command(command)) for command in self.commands)
-
- @property
- def argument_count(self) -> int:
- return sum(int(self.check_argument(argument)) for argument in self.arguments)
-
- def add_command(self, command: str, doc: str) -> bool:
- """ Add a command. """
- self.commands[command] = {
- "doc": doc,
- "passed": False
- }
-
- def add_argument(self,
- argument: Union[str, tuple[str, str]],
- doc: str,
- accepts_value: bool = False,
- accepts_suffix: bool = False,
- value: Union[None, str, int] = None
- ) -> None:
- """ Add an argument. """
-
- self.arguments[argument] = {
- "doc": doc,
- "passed": False,
- "accepts_value": accepts_value,
- "accepts_suffix": accepts_suffix,
- "value": value
- }
-
- def check_command(self, command: str) -> bool:
- """ Check if the command is passed. """
- return self.commands[command]["passed"]
-
- def check_argument(self, argument: Union[str, tuple[str, str]]) -> bool:
- """ Check if the argument is passed. """
-
- for arg in self.arguments:
- if isinstance(arg, str):
- if arg == argument:
- return self.arguments[arg]["passed"]
-
- elif isinstance(arg, tuple):
- if argument in arg or argument == arg:
- return self.arguments[arg]["passed"]
-
- def get_argument(self,
- argument: Union[str, tuple[str, str]]
- ) -> Union[None, str, int]:
- """ Get the value of argument. """
-
- for arg in self.arguments:
- if isinstance(arg, str):
- if arg == argument:
- return self.arguments[arg]["value"]
-
- elif isinstance(arg, tuple):
- if argument in arg or argument == arg:
- return self.arguments[arg]["value"]
-
- def parse(self) -> None:
- """ Parse command line. """
-
- for arg in sys.argv[1:]:
- if self._set_argument(arg):
- continue
-
- if self._set_command(arg):
- continue
-
- self.extra_arguments.append(arg)
-
- def usage(self) -> str:
- """ Generate usage manual. """
-
- script_name = sys.argv[0].replace(".py", "")
- man = \
- f"{{FG.orange}}Usage:{{RESET}} {script_name} [arguments] [extra arguments...]\n" + \
- "\n" + \
- "{FG.orange}Commands:{RESET}\n"
-
- GAP = 20
-
- for command in self.commands:
- command_l = command.ljust(GAP)
- man += f" {{FG.lightcyan}}{command_l}{{RESET}} {self.commands[command]['doc']}\n"
-
- man += "\n{FG.orange}Arguments:{RESET}\n"
-
- for argument in self.arguments:
- if isinstance(argument, tuple):
- option_l = f"{{FG.lightcyan}}{argument[0]} {{FG.darkgray}}| {{FG.lightcyan}}{argument[1]}{{RESET}}"
- option_l = option_l.ljust(GAP + 48)
-
- else:
- option_l = f"{{FG.lightcyan}}{argument.ljust(GAP)}{{RESET}}"
-
- man += f" {option_l} {self.arguments[argument]['doc']}\n"
-
- return man
-
- def _set_command(self, raw: str) -> bool:
- """ Check if the command exists and set it. """
-
- for cmd in self.commands:
- if raw == cmd:
- self.commands[cmd]["passed"] = True
- return True
-
- return False
-
- def _set_argument(self, raw: str) -> bool:
- """ Check if the argument exists and set it. """
-
- for arg in self.arguments:
- if isinstance(arg, str):
- if raw.startswith(arg):
- parsed = self._parse_argument(raw, arg, self.arguments[arg])
- if not parsed["valid"]: continue
- self.arguments[arg]["passed"] = True
- self.arguments[arg]["value"] = parsed["value"]
- return True
-
- elif isinstance(arg, tuple):
- if raw.startswith(arg[0]) or raw.startswith(arg[1]):
- parsed = self._parse_argument(raw, arg, self.arguments[arg])
- if not parsed["valid"]: continue
- self.arguments[arg]["passed"] = True
- self.arguments[arg]["value"] = parsed["value"]
- return True
-
- return False
-
- def _parse_argument(self,
- raw: str,
- argument: Union[str, tuple[str, str]],
- context: dict
- ) -> dict:
-
- dash = 0
- if raw.startswith("-"): dash = 1
- elif raw.startswith("--"): dash = 2
-
- if context["accepts_value"]:
- if "=" in raw:
- s = raw.split("=")
- arg = s[0]
- val = s[1]
-
- return {"valid": self._is_valid(arg, argument), "value": val}
-
- else:
- return {"valid": self._is_valid(raw, argument), "value": None}
-
- elif context["accepts_suffix"]:
- raw_ = raw[dash:]
- # Do you have a better solution to parse suffix values? Cuz I don't
- if any(char.isdigit() for char in raw_):
- letters = []
- digits = []
-
- for char in raw_:
- if char.isalpha(): letters.append(char)
- elif char.isdigit(): digits.append(char)
-
- letters = "".join(letters)
- digits = int("".join(digits))
-
- return {
- "valid": self._is_valid(f"{'-'*dash}{letters}", argument),
- "value": digits
- }
-
- else:
- return {"valid": self._is_valid(raw, argument), "value": None}
-
- else:
- return {"valid": self._is_valid(raw, argument), "value": None}
-
- def _is_valid(self,
- argument: str,
- original: Union[str, tuple[str, str]]
- ) -> bool:
- if isinstance(original, str):
- return argument == original
-
- elif isinstance(original, tuple):
- if argument == original[0]: return True
- elif argument == original[1]: return True
-
-
-class DependencyManager:
- """
- Class to download & manage build dependencies.
- """
-
- def __init__(self, cli: CLI) -> None:
- self.cli = cli
- self.no_color = not self.cli.check_argument("-n")
-
- self.chunk_size = 4 * 1024
-
- # Don't forget to update versions
- SDL2_VER = "2.28.5"
- TTF_VER = "2.20.2"
-
- # Library and DLL files are Windows only
- self.dependencies = {
- "SDL2": {
- "url": f"https://github.com/libsdl-org/SDL/releases/download/release-{SDL2_VER}/SDL2-devel-{SDL2_VER}-mingw.tar.gz",
-
- "include": {
- "satisfied": False,
- "path": DEPS_PATH / "include" / "SDL2",
- "archive-path": f"SDL2-{SDL2_VER}/x86_64-w64-mingw32/include/SDL2"
- },
-
- "lib-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x64" / "SDL2",
- "archive-path": f"SDL2-{SDL2_VER}/x86_64-w64-mingw32/lib"
- },
-
- "lib-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x86" / "SDL2",
- "archive-path": f"SDL2-{SDL2_VER}/i686-w64-mingw32/lib"
- },
-
- "bin-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x64" / "SDL2",
- "archive-path": f"SDL2-{SDL2_VER}/x86_64-w64-mingw32/bin"
- },
-
- "bin-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x86" / "SDL2",
- "archive-path": f"SDL2-{SDL2_VER}/i686-w64-mingw32/bin"
- }
- },
-
- "SDL2-MSVC": {
- "url": f"https://github.com/libsdl-org/SDL/releases/download/release-{SDL2_VER}/SDL2-devel-{SDL2_VER}-VC.zip",
-
- "include": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "include" / "SDL2-MSVC",
- "archive-path": f"SDL2-{SDL2_VER}/include"
- },
-
- "lib-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x64" / "SDL2-MSVC",
- "archive-path": f"SDL2-{SDL2_VER}/lib/x64"
- },
-
- "lib-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x86" / "SDL2-MSVC",
- "archive-path": f"SDL2-{SDL2_VER}/lib/x86"
- },
-
- "bin-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x64" / "SDL2-MSVC",
- "archive-path": f"SDL2-{SDL2_VER}/lib/x64"
- },
-
- "bin-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x86" / "SDL2-MSVC",
- "archive-path": f"SDL2-{SDL2_VER}/lib/x86"
- }
- },
-
- "SDL2_ttf": {
- "url": f"https://github.com/libsdl-org/SDL_ttf/releases/download/release-{TTF_VER}/SDL2_ttf-devel-{TTF_VER}-mingw.tar.gz",
-
- "include": {
- "satisfied": False,
- "path": DEPS_PATH / "include" / "SDL2",
- "archive-path": f"SDL2_ttf-{TTF_VER}/x86_64-w64-mingw32/include/SDL2"
- },
-
- "lib-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x64" / "SDL2_ttf",
- "archive-path": f"SDL2_ttf-{TTF_VER}/x86_64-w64-mingw32/lib"
- },
-
- "lib-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x86" / "SDL2_ttf",
- "archive-path": f"SDL2_ttf-{TTF_VER}/i686-w64-mingw32/lib"
- },
-
- "bin-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x64" / "SDL2_ttf",
- "archive-path": f"SDL2_ttf-{TTF_VER}/x86_64-w64-mingw32/bin"
- },
-
- "bin-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x86" / "SDL2_ttf",
- "archive-path": f"SDL2_ttf-{TTF_VER}/i686-w64-mingw32/bin"
- }
- },
-
- "SDL2_ttf-MSVC": {
- "url": f"https://github.com/libsdl-org/SDL_ttf/releases/download/release-{TTF_VER}/SDL2_ttf-devel-{TTF_VER}-VC.zip",
-
- "include": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "include" / "SDL2-MSVC",
- "archive-path": f"SDL2_ttf-{TTF_VER}/include"
- },
-
- "lib-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x64" / "SDL2_ttf-MSVC",
- "archive-path": f"SDL2_ttf-{TTF_VER}/lib/x64"
- },
-
- "lib-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "lib-x86" / "SDL2_ttf-MSVC",
- "archive-path": f"SDL2_ttf-{TTF_VER}/lib/x86"
- },
-
- "bin-x64": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x64" / "SDL2_ttf-MSVC",
- "archive-path": f"SDL2_ttf-{TTF_VER}/lib/x64"
- },
-
- "bin-x86": {
- "satisfied": not IS_WIN,
- "path": DEPS_PATH / "bin-x86" / "SDL2_ttf-MSVC",
- "archive-path": f"SDL2_ttf-{TTF_VER}/lib/x86"
- }
- }
- }
-
- def download(self, url: str) -> bytes:
- """ Download & return the data. """
-
- try:
- response = urllib.request.urlopen(url)
-
- except urllib.error.HTTPError as e:
- error(
- f"{{FG.lightcyan}}{url}{{RESET}} responsed with code {{FG.lightred}}{e.code}{{RESET}}.",
- self.no_color
- )
-
- size = int(response.info()["Content-Length"])
-
- template = f"{{progress}} {{FG.yellow}}{{percent}}%{{RESET}} {{FG.magenta}}{{mbps}}Mbps{{RESET}} ETA {{FG.lightblue}}{{ela.hours}}:{{ela.mins}}:{{ela.secs}}{{RESET}} RTA {{FG.lightblue}}{{rem.hours}}:{{rem.mins}}:{{rem.secs}}{{RESET}}"
- template = format_colors(template, self.no_color)
- bar = ProgressBar(template)
-
- fp = io.BytesIO()
- dl = 0
- start = perf_counter()
- while True:
- chunk = response.read(self.chunk_size)
- dl += len(chunk)
- if not chunk: break
- fp.write(chunk)
-
- mbps = dl / (perf_counter() - start) / (2 ** 17)
-
- bar.mbps = mbps
- bar.progress(self.chunk_size / size)
-
- bar.clear()
-
- fp.seek(0)
- return fp.read()
-
- def extract(self, data: bytes, path: Path) -> None:
- """ Extract archive data to path. """
-
- try:
- with tarfile.open(mode="r:gz", fileobj=io.BytesIO(data)) as tar:
- tar.extractall(path)
-
- except tarfile.ReadError:
- with zipfile.ZipFile(io.BytesIO(data)) as zip:
- zip.extractall(path)
-
- except Exception as e:
- raise e
-
- def check(self) -> None:
- """ Check if dependencies satisfy. """
-
- for dep in self.dependencies:
- for pack in self.dependencies[dep]:
- if pack == "url": continue
-
- if os.path.exists(self.dependencies[dep][pack]["path"]):
- self.dependencies[dep][pack]["satisfied"] = True
-
- def missing(self, dep_: Optional[str] = None) -> int:
- """ Return number of missing dependencies. """
-
- deps = 0
-
- for dep in self.dependencies:
- if dep_ is not None and dep != dep_: continue
-
- for pack in self.dependencies[dep]:
- if pack == "url": continue
-
- if not self.dependencies[dep][pack]["satisfied"]:
- deps += 1
-
- return deps
-
- def clean(self) -> None:
- """ Clean temporary repositories. """
-
- for dep_name in self.dependencies:
- temp_dir = DEPS_PATH / f"_{dep_name}"
- if os.path.exists(temp_dir):
- remove_dir(temp_dir)
-
- def satisfy(self) -> None:
- """ Download, extract and organize all dependencies. """
-
- # Don't need to continue if all deps are satisfied
- if self.missing() == 0:
- return
-
- if not os.path.exists(DEPS_PATH):
- os.mkdir(DEPS_PATH)
-
- if not os.path.exists(DEPS_PATH / "include"):
- os.mkdir(DEPS_PATH / "include")
-
- if not os.path.exists(DEPS_PATH / "lib-x64"):
- os.mkdir(DEPS_PATH / "lib-x64")
-
- if not os.path.exists(DEPS_PATH / "lib-x86"):
- os.mkdir(DEPS_PATH / "lib-x86")
-
- if not os.path.exists(DEPS_PATH / "bin-x64"):
- os.mkdir(DEPS_PATH / "bin-x64")
-
- if not os.path.exists(DEPS_PATH / "bin-x86"):
- os.mkdir(DEPS_PATH / "bin-x86")
-
- start = time()
-
- self.clean()
-
- for dep_name in self.dependencies:
- temp_dir = DEPS_PATH / f"_{dep_name}"
-
- dep = self.dependencies[dep_name]
-
- if self.missing(dep_name):
- info(f"Downloading {{FG.lightcyan}}{dep['url']}{{RESET}}", self.no_color)
-
- self.extract(
- self.download(dep["url"]),
- temp_dir
- )
-
- if not dep["include"]["satisfied"]:
- info(
- f"Extracting {{FG.yellow}}{temp_dir / dep['include']['archive-path']}{{RESET}}",
- self.no_color
- )
-
- if not os.path.exists(dep["include"]["path"]):
- os.mkdir(dep["include"]["path"])
-
- copy_dir(
- temp_dir / dep["include"]["archive-path"],
- dep["include"]["path"]
- )
-
- if IS_WIN:
- if not dep["lib-x64"]["satisfied"]:
- info(
- f"Extracting {{FG.yellow}}{temp_dir / dep['lib-x64']['archive-path']}{{RESET}}",
- self.no_color
- )
-
- if not os.path.exists(dep["lib-x64"]["path"]):
- os.mkdir(dep["lib-x64"]["path"])
-
- copy_dir(
- temp_dir / dep["lib-x64"]["archive-path"],
- dep["lib-x64"]["path"]
- )
-
- if not dep["lib-x86"]["satisfied"]:
- info(
- f"Extracting {{FG.yellow}}{temp_dir / dep['lib-x86']['archive-path']}{{RESET}}",
- self.no_color
- )
-
- if not os.path.exists(dep["lib-x86"]["path"]):
- os.mkdir(dep["lib-x86"]["path"])
-
- copy_dir(
- temp_dir / dep["lib-x86"]["archive-path"],
- dep["lib-x86"]["path"]
- )
-
- if not dep["bin-x64"]["satisfied"]:
- info(
- f"Extracting {{FG.yellow}}{temp_dir / dep['bin-x64']['archive-path']}{{RESET}}",
- self.no_color
- )
-
- if not os.path.exists(dep["bin-x64"]["path"]):
- os.mkdir(dep["bin-x64"]["path"])
-
- copy_dir(
- temp_dir / dep["bin-x64"]["archive-path"],
- dep["bin-x64"]["path"]
- )
-
- if not dep["bin-x86"]["satisfied"]:
- info(
- f"Extracting {{FG.yellow}}{temp_dir / dep['bin-x86']['archive-path']}{{RESET}}",
- self.no_color
- )
-
- if not os.path.exists(dep["bin-x86"]["path"]):
- os.mkdir(dep["bin-x86"]["path"])
-
- copy_dir(
- temp_dir / dep["bin-x86"]["archive-path"],
- dep["bin-x86"]["path"]
- )
-
- self.clean()
-
- end = time() - start
-
- success(
- f"Downloaded & extracted all dependencies in {{FG.lightblue}}{round(end, 3)}{{RESET}} seconds.\n",
- self.no_color
- )
-
-
-class CompilerType(Enum):
- """
- Supported compilers.
- """
-
- GCC = 0
- MSVC = 1
- CLANG = 2
-
-
-COMMON_MSVC_DEV_PROMPTS = (
- "C:/Program Files (x86)/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2022/Professional/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2022/Professional/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2022/Enterprise/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2022/BuildTools/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2019/Community/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2019/Professional/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2019/BuildTools/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2017/Community/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2017/Professional/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2017/Enterprise/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files/Microsoft Visual Studio/2017/BuildTools/VC/Auxiliary/Build/vcvarsall.bat",
- "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/vcvarsall.bat"
- "C:/Program Files/Microsoft Visual Studio 14.0/VC/vcvarsall.bat"
-)
-
-MSVC_DEV_PROMPT = None
-
-
-def detect_compilers() -> dict[CompilerType, str]:
- """ Detect available compilers on the system. """
-
- global MSVC_DEV_PROMPT
-
- gcc_path = shutil.which("gcc")
- gcc_invoker = None
- if gcc_path is not None:
- gcc_invoker = f"\"{gcc_path}\""
-
- for common_path in COMMON_MSVC_DEV_PROMPTS:
- if os.path.exists(common_path):
- MSVC_DEV_PROMPT = common_path
- break
-
- msvc_invoker = None
- if MSVC_DEV_PROMPT is not None:
- msvc_invoker = "cl.exe"
-
- return {
- CompilerType.GCC: gcc_invoker,
- CompilerType.MSVC: msvc_invoker,
- CompilerType.CLANG: None
- }
-
-
-COMPILER_ARGS = {
- CompilerType.GCC: {
- "debug": "-g3",
- "optimization": (
- "-O1", "-O2", "-O3"
- ),
- "warnings": "-Wall",
- "define": "-D",
- "include": "-I",
- "library": "-L",
- "link": "-l",
- "invoke-avx": "-march=native"
- },
-
- CompilerType.MSVC: {
- "debug": "/Zi",
- "optimization": (
- "/O1", "/O2", "/Ox"
- ),
- "warnings": "/W3",
- "define": "/D",
- "include": "/I",
- "library": "/LIBPATH:",
- "link": "",
- "invoke-avx": "/arch:AVX"
- }
-}
-
-
-class Compiler(ABC):
- """
- Base compiler class.
- """
-
- def __init__(self,
- type_: CompilerType,
- invoker: str,
- no_color: bool = False,
- force_x86: bool = False
- ) -> None:
- self.type = type_
- self.invoker = invoker
- self.no_color = no_color
- self.force_x86 = force_x86
- self.fetch_version()
-
- def build_cache(self) -> None:
- """ Build object file cache. """
-
- self.cached_sources = {}
- if os.path.exists(CACHE_PATH / "cached_sources.json"):
- with open(CACHE_PATH / "cached_sources.json", "r", encoding="utf-8") as file:
- self.cached_sources = json.load(file)
-
- @abstractmethod
- def fetch_version(self) -> str:
- """ Fetch compiler version on the system. """
- ...
-
- @abstractmethod
- def _build_compile_command(self,
- sources_arg: str,
- include_arg: str,
- args_arg: str,
- define_arg: str
- ) -> str:
- """ Generate compilation command. """
- ...
-
- @abstractmethod
- def _build_linkage_command(self,
- binary_path: str,
- objects_arg: str,
- library_arg: str,
- linkage_arg: str,
- args_arg: str
- ) -> str:
- """ Generate linkage command. """
- ...
-
- def compile(self,
- source_paths: list[Path] = [],
- include_paths: list[Path] = [],
- library_paths: list[Path] = [],
- linkage_args: list[str] = [],
- defines: list[str] = [],
- compile_args: list[str] = [],
- link_args: list[str] = [],
- binary: Optional[str] = None,
- process_count: int = 1,
- verbose: bool = False
- ) -> None:
- """ Compile. """
-
- if os.path.exists(BUILD_PATH):
- shutil.rmtree(BUILD_PATH)
-
- os.mkdir(BUILD_PATH)
-
- if not os.path.exists(CACHE_PATH):
- os.mkdir(CACHE_PATH)
-
- os.chdir(CACHE_PATH)
-
- if self.type == CompilerType.MSVC:
- for i in range(len(linkage_args)):
- linkage_args[i] = linkage_args[i] + ".lib"
-
- if not IS_WIN:
- linkage_args.append("m") # Required on Linux for math.h
-
- include_arg = f" {COMPILER_ARGS[self.type]['include']}".join([str(include_path) for include_path in include_paths])
- if len(include_arg) > 0: include_arg = COMPILER_ARGS[self.type]['include'] + include_arg
-
- library_arg = f" {COMPILER_ARGS[self.type]['library']}".join([str(library_path) for library_path in library_paths])
- if len(library_arg) > 0: library_arg = COMPILER_ARGS[self.type]['library'] + library_arg
-
- linkage_arg = f" {COMPILER_ARGS[self.type]['link']}".join(linkage_args)
- if len(linkage_arg) > 0: linkage_arg = COMPILER_ARGS[self.type]['link'] + linkage_arg
-
- define_arg = f" {COMPILER_ARGS[self.type]['define']}".join(defines)
- if len(define_arg) > 0: define_arg = COMPILER_ARGS[self.type]['define'] + define_arg
-
- compile_args_arg = " ".join(compile_args)
- link_args_arg = " ".join(link_args)
-
- # Detect modified source files
- new_source_paths = []
- for source_path in source_paths:
- src = str(source_path)
-
- if src in self.cached_sources:
- mtime = os.path.getmtime(src)
-
- if self.cached_sources[src] != mtime:
- self.cached_sources[src] = mtime
- new_source_paths.append(source_path)
-
- else:
- self.cached_sources[src] = os.path.getmtime(src)
- new_source_paths.append(source_path)
-
- # Compile if there is any changed source file
- start = perf_counter()
-
- if len(new_source_paths) == 0:
- if verbose:
- info(f"No source to compile.", self.no_color)
-
- else:
- if verbose:
- info(f"There are {len(new_source_paths)} changed source files to compile.", self.no_color)
-
- processes = []
- targets = [[] for _ in range(process_count)]
-
- # Distribute sources across multiple processes evenly
- i = 0
- for source_path in new_source_paths:
- targets[i].append(source_path)
- i += 1
- if i > len(targets) - 1: i = 0
-
- for sub_sources in targets:
- if len(sub_sources) == 0: continue
-
- sources_arg = " ".join([str(source_path) for source_path in sub_sources])
- compile_command = self._build_compile_command(
- sources_arg,
- include_arg,
- define_arg,
- compile_args_arg
- )
-
- if verbose: print(compile_command, "\n")
- processes.append(subprocess.Popen(compile_command))
-
- for process in processes:
- process.communicate()
-
- for process in processes:
- if process.returncode != 0:
- error(f"Compilation failed with return code {process.returncode}.", self.no_color)
-
- # Link object files if binary name is given
- if binary is not None:
- if IS_WIN:
- binary_path = f"{binary}.exe"
- else:
- binary_path = f"./{binary}"
-
- object_paths = self.get_object_paths()
-
- objects_arg = " ".join([str(object_path) for object_path in object_paths])
- linkage_command = self._build_linkage_command(
- binary_path,
- objects_arg,
- library_arg,
- linkage_arg,
- link_args_arg
- )
-
- if verbose: print(linkage_command, "\n")
- out = subprocess.run(linkage_command)
- if out.returncode != 0:
- error(f"Linkage failed with return code {out.returncode}.", self.no_color)
-
- end = perf_counter()
- comp_time = end - start
-
- # Update cache data if the compilation is sucessful
- with open(CACHE_PATH / "cached_sources.json", "w", encoding="utf-8") as file:
- file.write(json.dumps(self.cached_sources))
-
- success(f"Compilation is done in {{FG.blue}}{round(comp_time, 3)}{{RESET}} seconds.", self.no_color)
-
- os.chdir(BASE_PATH)
-
- @abstractmethod
- def generate_library(self, library_path: Path, verbose: bool = False) -> int:
- """ Generate static library from object files. """
- ...
-
- def get_object_paths(self) -> list[Path]:
- """ Gather cached object files. """
-
- object_ext = ".o" if self.type in (CompilerType.GCC, CompilerType.CLANG) else ".obj"
-
- object_paths = []
-
- for name in os.listdir(CACHE_PATH):
- file = CACHE_PATH / name
- if os.path.isfile(file) and name.endswith(object_ext):
- object_paths.append(file)
-
- return object_paths
-
-
-class CompilerGCC(Compiler):
- def __init__(self,
- invoker: str,
- no_color: bool = False,
- force_x86: bool = False
- ) -> None:
- super().__init__(CompilerType.GCC, invoker, no_color, force_x86)
-
- def fetch_version(self) -> str:
- version = get_output(f"{self.invoker} -dumpfullversion -dumpversion")
- if version != "": return version
- else: return "Unknown"
-
- def _build_compile_command(self,
- sources_arg: str,
- include_arg: str,
- args_arg: str,
- define_arg: str
- ) -> str:
-
- compile_command = f"{self.invoker} -c {sources_arg} {include_arg} {args_arg} {define_arg}"
- return " ".join(compile_command.split())
-
- def _build_linkage_command(self,
- binary_path: str,
- objects_arg: str,
- library_arg: str,
- linkage_arg: str,
- args_arg: str
- ) -> str:
-
- linkage_command = f"{self.invoker} -o {binary_path} {objects_arg} {library_arg} {linkage_arg} {args_arg}"
- return " ".join(linkage_command.split())
-
- def generate_library(self, library_path: Path, verbose: bool = False) -> int:
- objects = ' '.join([str(o) for o in self.get_object_paths()])
- lib_cmd = f"ar rc {str(library_path) + '.a'} {objects}"
-
- if verbose:
- print(lib_cmd, "\n")
-
- return subprocess.run(lib_cmd).returncode
-
-
-class CompilerMSVC(Compiler):
- def __init__(self,
- invoker: str,
- no_color: bool = False,
- force_x86: bool = False
- ) -> None:
- super().__init__(CompilerType.MSVC, invoker, no_color, force_x86)
-
- if PLATFORM.is_64 and not self.force_x86:
- self.dev_arg = "x86_amd64"
-
- else:
- self.dev_arg = "x86"
-
- def fetch_version(self) -> str:
- version = "Unknown"
-
- if "2022" in MSVC_DEV_PROMPT: version = "2022"
- elif "2019" in MSVC_DEV_PROMPT: version = "2019"
- elif "2017" in MSVC_DEV_PROMPT: version = "2017"
- elif "2015" in MSVC_DEV_PROMPT: version = "2015"
-
- return version
-
- def _build_compile_command(self,
- sources_arg: str,
- include_arg: str,
- args_arg: str,
- define_arg: str
- ) -> str:
-
- compile_command = f"\"{MSVC_DEV_PROMPT}\" {self.dev_arg} & {self.invoker} /nologo /c {sources_arg} {include_arg} {args_arg} {define_arg}"
- return " ".join(compile_command.split())
-
- def _build_linkage_command(self,
- binary_path: str,
- objects_arg: str,
- library_arg: str,
- linkage_arg: str,
- args_arg: str
- ) -> str:
-
- linkage_command = f"\"{MSVC_DEV_PROMPT}\" {self.dev_arg} & link.exe /OUT:{binary_path} {objects_arg} {library_arg} {linkage_arg} {args_arg}"
- return " ".join(linkage_command.split())
-
- def generate_library(self, library_path: Path, verbose: bool = False) -> int:
- objects = ' '.join([str(o) for o in self.get_object_paths()])
- lib_cmd = f"\"{MSVC_DEV_PROMPT}\" {self.dev_arg} & lib /NOLOGO /OUT:{str(library_path) + '.lib'} {objects}"
-
- if verbose:
- print(lib_cmd, "\n")
-
- return subprocess.run(lib_cmd).returncode
-
-
-def main():
- """ Entry point of the CLI. """
-
- if not os.path.exists(CACHE_PATH):
- os.mkdir(CACHE_PATH)
-
- cli = CLI()
-
- cli.add_command("build", "Build static library")
- cli.add_command("examples", "Run example demos")
- cli.add_command("bench", "Run a benchmark from benchmarks directory")
- cli.add_command("tests", "Run unit tests")
-
- cli.add_argument(("-h", "--help"), "Print usage manual")
- cli.add_argument(("-q", "--quiet"), "Do not log any build logs")
- cli.add_argument(("-v", "--verbose"), "Get build logs as verbose as possible")
- cli.add_argument(("-f", "--float"), "Use single-precision floating point numbers")
- cli.add_argument("--no-color", "Disable coloring with ANSI escape codes")
- cli.add_argument("--clear", "Clear cached code and configuration")
- cli.add_argument(
- "--target",
- "Specify a target compiler instead of detecting one",
- accepts_value=True
- )
- cli.add_argument("--force-deps", "Force download all dependencies (for example demos)")
- cli.add_argument("--enable-tracy", "Enable Tracy profiler")
- cli.add_argument("--no-profiler", "Disable built-in profiler")
- cli.add_argument("--no-simd", "Disable SIMD vectorization")
- cli.add_argument("--m32", "Build for x86")
- cli.add_argument("-g", "Compile for debugging")
- cli.add_argument(
- "-O",
- "Set optimization level (default is 3)",
- accepts_suffix=True,
- value=3
- )
- cli.add_argument(
- "-j",
- "Parallel compilation on multiple processes (defaults to CPU count)",
- accepts_suffix=True,
- value=multiprocessing.cpu_count()
- )
- cli.add_argument("-w", "Enable all warnings")
-
- cli.parse()
-
- NO_COLOR = not cli.get_argument("-n")
-
- print(format_colors("{FG.magenta}Nova Physics Engine Build System{RESET}", NO_COLOR))
- print(format_colors("Manual: {FG.cyan}https://github.com/kadir014/nova-physics/blob/main/BUILDING.md{RESET}", NO_COLOR))
- print()
-
- if not BASE_PATH.name.startswith("nova-physics"):
- error(
- [
- "Make sure you are in the Nova Physics directory!",
- f"This script is ran at {{FG.yellow}}{BASE_PATH.absolute()}{{RESET}}"
- ], NO_COLOR
- )
-
- builder_command = None
-
- if cli.check_command("build"):
- builder_command = "build"
-
- elif cli.check_command("examples"):
- builder_command = "examples"
-
- elif cli.check_command("bench"):
- builder_command = "bench"
-
- elif cli.check_command("tests"):
- builder_command = "tests"
-
- if cli.check_argument("--clear"):
- remove_dir(CACHE_PATH)
- os.mkdir(CACHE_PATH)
-
- if cli.check_argument("-O"):
- optimization = cli.get_argument("-O")
-
- if optimization < 1 or optimization > 3:
- error("Optimization value must be in range [1, 3].", NO_COLOR)
-
- if cli.check_argument("-j"):
- parallel_comp = cli.get_argument("-j")
-
- if parallel_comp <= 0:
- error("-j argument value can't be smaller than 1.", NO_COLOR)
-
- help_arg = cli.check_argument("-h")
-
- if cli.command_count == 0 or help_arg:
- if not help_arg and len(cli.extra_arguments) > 0:
- error(
- (
- f"Unknown command: {cli.extra_arguments[0]}",
- "Run 'python nova_builder.py' without any arguments to see usage manual."
- ),
- NO_COLOR
- )
-
- print(format_colors(cli.usage(), NO_COLOR))
-
- else:
- # Remove example.c from cache, so example headers can be compiled
- if os.path.exists(CACHE_PATH / "cached_sources.json"):
- with open(CACHE_PATH / "cached_sources.json", "r", encoding="utf-8") as file:
- cached_sources = json.load(file)
-
- if str(EXAMPLES_PATH / "example.c") in cached_sources:
- cached_sources[str(EXAMPLES_PATH / "example.c")] = 0.0
-
- with open(CACHE_PATH / "cached_sources.json", "w", encoding="utf-8") as file:
- file.write(json.dumps(cached_sources))
-
- detected = detect_compilers()
- target = cli.get_argument("--target")
-
- if target is None:
- if detected[CompilerType.GCC]:
- compiler = CompilerGCC(detected[CompilerType.GCC], not cli.check_argument("-n"), cli.check_argument("--m32"))
-
- elif detected[CompilerType.MSVC]:
- compiler = CompilerMSVC(detected[CompilerType.MSVC], not cli.check_argument("-n"), cli.check_argument("--m32"))
-
- else:
- error(f"Could not find a compiler on your system.", NO_COLOR)
-
- elif target.lower() == "gcc":
- if detected[CompilerType.GCC] is None:
- error("Targeted compiler is not available on the system.", NO_COLOR)
-
- compiler = CompilerGCC(detected[CompilerType.GCC], not cli.check_argument("-n"))
-
- elif target.lower() == "msvc":
- if detected[CompilerType.MSVC] is None:
- error("Targeted compiler is not available on the system.", NO_COLOR)
-
- compiler = CompilerMSVC(detected[CompilerType.MSVC], not cli.check_argument("-n"))
-
- else:
- error(f"Unknown compiler target: '{target}'", NO_COLOR)
-
- info(
- f"Compiler: {{FG.yellow}}{compiler.type.name}{{RESET}} {{FG.lightcyan}}{compiler.fetch_version()}{{RESET}}",
- NO_COLOR
- )
- info(
- f"Platform: {{FG.yellow}}{PLATFORM.name}{{RESET}}, {('32-bit', '64-bit')[PLATFORM.is_64]}\n",
- NO_COLOR
- )
-
- clear_cache = False
-
- current_config = {
- "compiler": str(compiler.type),
- "debug": cli.check_argument("-g"),
- "enable-tracy": cli.check_argument("--enable-tracy"),
- "no-profiler": cli.check_argument("--no-profiler"),
- "no-simd": cli.check_argument("--no-simd"),
- "x86": cli.check_argument("--m32"),
- "command": builder_command
- }
-
- # Config was never cached, cache now
- if not os.path.exists(CACHE_PATH / "cached_config.json"):
- with open(CACHE_PATH / "cached_config.json", "w+") as file:
- file.write(json.dumps(current_config))
-
- # Config was cached, check if the current config is the same
- # if not, clear all the cache and update the config
- else:
- with open(CACHE_PATH / "cached_config.json", "r", encoding="utf-8") as file:
- cached_config = json.load(file)
-
- clear_cache = cached_config != current_config
-
- if clear_cache:
- if cli.check_argument("-v"):
- info("Compilaton configuration has been changed. Clearing & updating cache.", NO_COLOR)
-
- remove_dir(CACHE_PATH)
- os.mkdir(CACHE_PATH)
-
- with open(CACHE_PATH / "cached_config.json", "w+") as file:
- file.write(json.dumps(current_config))
-
- elif cli.check_argument("-v"):
- info("Compilaton configuration is the same.", NO_COLOR)
-
- compiler.build_cache()
-
- if cli.check_command("build"):
- build(cli, compiler)
-
- elif cli.check_command("examples"):
- examples(cli, compiler)
-
- elif cli.check_command("bench"):
- benchmark(cli, compiler)
-
- elif cli.check_command("tests"):
- tests(cli, compiler)
-
-def build(cli: CLI, compiler: Compiler):
- NO_COLOR = not cli.get_argument("-n")
-
- source_paths = []
- include_paths = [INCLUDE_PATH]
- linkage_args = []
- defines = []
- compile_args = []
- link_args = []
-
- if cli.check_argument("--enable-tracy"):
- TRACY_PATH = SRC_PATH / "tracy"
- source_paths.append(TRACY_PATH / "TracyClient.cpp")
- include_paths.append(TRACY_PATH)
- defines.append("TRACY_ENABLE")
- # Tracy needs all this libraries
- linkage_args += ["stdc++", "ws2_32", "wsock32", "dbghelp"]
-
- for name in os.listdir(SRC_PATH):
- if os.path.isfile(SRC_PATH / name):
- source_paths.append(SRC_PATH / name)
-
- if cli.check_argument("-f"):
- defines.append("NV_USE_FLOAT")
-
- if not cli.check_argument("--no-profiler"):
- defines.append("NV_PROFILE")
-
- if not cli.check_argument("--no-simd"):
- defines.append("NV_USE_SIMD")
-
- if compiler.type == CompilerType.GCC and cli.check_argument("--m32"):
- compile_args.append("-m32")
-
- if cli.check_argument("-g"):
- compile_args.append(COMPILER_ARGS[compiler.type]["debug"])
-
- else:
- compile_args.append(f"{COMPILER_ARGS[compiler.type]['optimization'][cli.get_argument('-O')-1]}")
-
- if cli.check_argument("-w"):
- compile_args.append(COMPILER_ARGS[compiler.type]["warnings"])
-
- compile_args.append(COMPILER_ARGS[compiler.type]["invoke-avx"])
-
- info("Compilation started", NO_COLOR)
-
- compiler.compile(
- source_paths=source_paths,
- include_paths=include_paths,
- linkage_args=linkage_args,
- defines=defines,
- compile_args=compile_args,
- link_args=link_args,
- process_count=cli.get_argument("-j"),
- verbose=cli.check_argument("-v")
- )
-
- info("Generating library", NO_COLOR)
-
- if compiler.type == CompilerType.GCC:
- library_name = "libnova"
-
- elif compiler.type == CompilerType.MSVC:
- library_name = "nova"
-
- start = perf_counter()
- out = compiler.generate_library(BUILD_PATH / library_name)
- lib_time = perf_counter() - start
-
- if out == 0:
- success(
- f"Library generation is done in {{FG.blue}}{round(lib_time, 3)}{{RESET}} seconds.",
- NO_COLOR
- )
-
- else:
- print()
- error(f"Library generation failed with return code {out.returncode}.", NO_COLOR)
-
-def examples(cli: CLI, compiler: Compiler):
- NO_COLOR = not cli.get_argument("-n")
-
- if cli.check_argument("--force-deps"):
- if os.path.exists(BASE_PATH / "deps"):
- remove_dir(BASE_PATH / "deps")
-
- dm = DependencyManager(cli)
-
- info("Checking dependencies.", NO_COLOR)
-
- dm.check()
-
- deps = dm.missing()
- if (deps == 0):
- success("All dependencies are satisfied.", NO_COLOR)
-
- else:
- info(f"Missing {deps} dependency files.", NO_COLOR)
-
- dm.satisfy()
-
- source_paths = [EXAMPLES_PATH / "example.c"]
- include_paths = [INCLUDE_PATH, DEPS_PATH / "include"]
- linkage_args = ["SDL2main", "SDL2", "SDL2_ttf"]
- defines = []
- compile_args = []
- link_args = []
-
- if not cli.check_argument("--m32") and PLATFORM.is_64:
- dep_lib = "lib-x64"
- dep_bin = "bin-x64"
-
- else:
- dep_lib = "lib-x86"
- dep_bin = "bin-x86"
-
- if compiler.type == CompilerType.GCC:
- library_paths = [DEPS_PATH / dep_lib / "SDL2", DEPS_PATH / dep_lib / "SDL2_ttf"]
-
- elif compiler.type == CompilerType.MSVC:
- library_paths = [DEPS_PATH / dep_lib / "SDL2-MSVC", DEPS_PATH / dep_lib / "SDL2_ttf-MSVC"]
-
- if IS_WIN and compiler.type == CompilerType.GCC:
- linkage_args.insert(0, "mingw32")
-
- if compiler.type == CompilerType.MSVC:
- defines.append("SDL_MAIN_HANDLED")
- defines.append("_CRT_SECURE_NO_WARNINGS") # Disable security warnings for sprintf
- link_args.append("/SUBSYSTEM:CONSOLE")
-
- if cli.check_argument("--enable-tracy"):
- TRACY_PATH = SRC_PATH / "tracy"
- source_paths.append(TRACY_PATH / "TracyClient.cpp")
- include_paths.append(TRACY_PATH)
- defines.append("TRACY_ENABLE")
- # Tracy needs all this libraries
- linkage_args += ["stdc++", "ws2_32", "wsock32", "dbghelp"]
-
- for name in os.listdir(SRC_PATH):
- if os.path.isfile(SRC_PATH / name):
- source_paths.append(SRC_PATH / name)
-
- if cli.check_argument("-f"):
- defines.append("NV_USE_FLOAT")
-
- if not cli.check_argument("--no-profiler"):
- defines.append("NV_PROFILE")
-
- if not cli.check_argument("--no-simd"):
- defines.append("NV_USE_SIMD")
-
- if cli.check_argument("-g"):
- compile_args.append(COMPILER_ARGS[compiler.type]["debug"])
-
- else:
- compile_args.append(f"{COMPILER_ARGS[compiler.type]['optimization'][cli.get_argument('-O')-1]}")
-
- if cli.check_argument("-w"):
- compile_args.append(COMPILER_ARGS[compiler.type]["warnings"])
-
- compile_args.append(COMPILER_ARGS[compiler.type]["invoke-avx"])
-
- info("Compilation started", NO_COLOR)
-
- compiler.compile(
- source_paths=source_paths,
- include_paths=include_paths,
- library_paths=library_paths,
- linkage_args=linkage_args,
- defines=defines,
- compile_args=compile_args,
- link_args=link_args,
- process_count=cli.get_argument("-j"),
- binary="nova",
- verbose=cli.check_argument("-v"),
- )
-
- os.mkdir(BUILD_PATH / "assets")
- for *_, files in os.walk(EXAMPLES_PATH / "assets"):
- for file in files:
- if not file.startswith("example"):
- shutil.copyfile(
- EXAMPLES_PATH / "assets" / file,
- BUILD_PATH / "assets" / file
- )
-
- if IS_WIN:
- binary = "nova.exe"
-
- else:
- binary = "./nova"
-
- os.replace(CACHE_PATH / binary, BUILD_PATH / binary)
-
- if IS_WIN:
- if compiler.type == CompilerType.GCC:
- copy_dlls(DEPS_PATH / dep_bin / "SDL2", BUILD_PATH)
- copy_dlls(DEPS_PATH / dep_bin / "SDL2_ttf", BUILD_PATH)
-
- elif compiler.type in (CompilerType.MSVC, CompilerType.CLANG):
- copy_dlls(DEPS_PATH / dep_bin / "SDL2-MSVC", BUILD_PATH)
- copy_dlls(DEPS_PATH / dep_bin / "SDL2_ttf-MSVC", BUILD_PATH)
-
- # Run the example
- # We have to change directory to get assets working
- info("Running the example demos", NO_COLOR)
-
- os.chdir(BUILD_PATH)
-
- out = subprocess.run(binary, shell=True)
-
- if out.returncode == 0:
- success(f"Example demos exited with code {out.returncode}.", NO_COLOR)
-
- elif out.returncode in SEGFAULT_CODES:
- error(
- [
- f"Segmentation fault occured in the example demos. Exit code: {out.returncode}",
- f"Please report this at {{FG.lightcyan}}https://github.com/kadir014/nova-physics/issues{{RESET}}"
- ],
- NO_COLOR
- )
-
- else:
- error(f"Example demos exited with code {out.returncode}", NO_COLOR)
-
-def benchmark(cli: CLI, compiler: Compiler):
- NO_COLOR = not cli.get_argument("-n")
-
- if len(cli.extra_arguments) == 0:
- cmd_example = "{FG.darkgray}(eg. {FG.magenta}nova_builder {FG.yellow}bench {RESET}boxes{FG.darkgray})"
- error(
- f"You have to enter a benchmark name. {cmd_example}{{RESET}}",
- NO_COLOR
- )
-
- if cli.extra_arguments[0].endswith(".c"):
- bench = BENCHS_PATH / cli.extra_arguments[0]
- else:
- bench = BENCHS_PATH / (cli.extra_arguments[0] + ".c")
-
- if not os.path.exists(bench):
- error(
- [
- f"Benchmark file {{FG.lightblue}}{bench}{{RESET}} is not found.",
- "Make sure you are in the Nova Physics directory!"
- ],
- NO_COLOR
- )
-
- source_paths = [bench]
- include_paths = [INCLUDE_PATH]
- library_paths = []
- linkage_args = []
- defines = []
- compile_args = []
- link_args = []
-
- if cli.check_argument("--enable-tracy"):
- TRACY_PATH = SRC_PATH / "tracy"
- source_paths.append(TRACY_PATH / "TracyClient.cpp")
- include_paths.append(TRACY_PATH)
- defines.append("TRACY_ENABLE")
- # Tracy needs all this libraries
- linkage_args += ["stdc++", "ws2_32", "wsock32", "dbghelp"]
-
- for name in os.listdir(SRC_PATH):
- if os.path.isfile(SRC_PATH / name):
- source_paths.append(SRC_PATH / name)
-
- if cli.check_argument("-f"):
- defines.append("NV_USE_FLOAT")
-
- if not cli.check_argument("--no-profiler"):
- defines.append("NV_PROFILE")
-
- if not cli.check_argument("--no-simd"):
- defines.append("NV_USE_SIMD")
-
- if cli.check_argument("-g"):
- compile_args.append(COMPILER_ARGS[compiler.type]["debug"])
-
- else:
- compile_args.append(f"{COMPILER_ARGS[compiler.type]['optimization'][cli.get_argument('-O')-1]}")
-
- if cli.check_argument("-w"):
- compile_args.append(COMPILER_ARGS[compiler.type]["warnings"])
-
- compile_args.append(COMPILER_ARGS[compiler.type]["invoke-avx"])
-
- info("Compilation started", NO_COLOR)
-
- compiler.compile(
- source_paths=source_paths,
- include_paths=include_paths,
- library_paths=library_paths,
- linkage_args=linkage_args,
- defines=defines,
- compile_args=compile_args,
- link_args=link_args,
- process_count=cli.get_argument("-j"),
- binary="nova",
- verbose=cli.check_argument("-v"),
- )
-
- if IS_WIN:
- binary = "nova.exe"
-
- else:
- binary = "./nova"
-
- os.replace(CACHE_PATH / binary, BUILD_PATH / binary)
-
- info("Running the benchmarks", NO_COLOR)
-
- os.chdir(BUILD_PATH)
-
- out = subprocess.run(binary, shell=True)
-
- if out.returncode == 0:
- success(f"Benchmark exited with code {out.returncode}.", NO_COLOR)
-
- elif out.returncode in SEGFAULT_CODES:
- error(
- [
- f"Segmentation fault occured in the benchmark. Exit code: {out.returncode}",
- f"Please report this at {{FG.lightcyan}}https://github.com/kadir014/nova-physics/issues{{RESET}}"
- ],
- NO_COLOR
- )
-
- else:
- error(f"Benchmark exited with code {out.returncode}", NO_COLOR)
-
-def tests(cli: CLI, compiler: Compiler):
- NO_COLOR = not cli.get_argument("-n")
-
- source_paths = [TESTS_PATH / "tests.c"]
- include_paths = [INCLUDE_PATH]
- library_paths = []
- linkage_args = []
- defines = []
- compile_args = []
- link_args = []
-
- if cli.check_argument("--enable-tracy"):
- TRACY_PATH = SRC_PATH / "tracy"
- source_paths.append(TRACY_PATH / "TracyClient.cpp")
- include_paths.append(TRACY_PATH)
- defines.append("TRACY_ENABLE")
- # Tracy needs all this libraries
- linkage_args += ["stdc++", "ws2_32", "wsock32", "dbghelp"]
-
- for name in os.listdir(SRC_PATH):
- if os.path.isfile(SRC_PATH / name):
- source_paths.append(SRC_PATH / name)
-
- if cli.check_argument("-f"):
- defines.append("NV_USE_FLOAT")
-
- if not cli.check_argument("--no-profiler"):
- defines.append("NV_PROFILE")
-
- if not cli.check_argument("--no-simd"):
- defines.append("NV_USE_SIMD")
-
- if cli.check_argument("-g"):
- compile_args.append(COMPILER_ARGS[compiler.type]["debug"])
-
- else:
- compile_args.append(f"{COMPILER_ARGS[compiler.type]['optimization'][cli.get_argument('-O')-1]}")
-
- if cli.check_argument("-w"):
- compile_args.append(COMPILER_ARGS[compiler.type]["warnings"])
-
- compile_args.append(COMPILER_ARGS[compiler.type]["invoke-avx"])
-
- info("Compilation started", NO_COLOR)
-
- compiler.compile(
- source_paths=source_paths,
- include_paths=include_paths,
- library_paths=library_paths,
- linkage_args=linkage_args,
- defines=defines,
- compile_args=compile_args,
- link_args=link_args,
- process_count=cli.get_argument("-j"),
- binary="nova",
- verbose=cli.check_argument("-v"),
- )
-
- if IS_WIN:
- binary = "nova.exe"
-
- else:
- binary = "./nova"
-
- os.replace(CACHE_PATH / binary, BUILD_PATH / binary)
-
- info("Running the tests", NO_COLOR)
-
- os.chdir(BUILD_PATH)
-
- try:
- start = perf_counter()
- out = subprocess.check_output(binary, shell=True)
- elapsed = perf_counter() - start
-
- outs = out.decode("utf-8").split("\n")
- for i, line in enumerate(outs):
-
- if line.startswith("[PASSED]"):
- outs[i] = format_colors("[{FG.lightgreen}PASSED{RESET}]", NO_COLOR) + line[8:]
-
- elif line.startswith("[FAILED]"):
- outs[i] = format_colors("[{FG.lightred}FAILED{RESET}]", NO_COLOR) + line[8:]
-
- elif line.startswith("total:"):
- test_count = int(line[6:])
-
- elif line.startswith("fails:"):
- fail_count = int(line[6:])
-
- outs = outs[:-3]
-
- success_msg = f"Ran {{FG.yellow}}{test_count}{{RESET}} tests in {{FG.blue}}{round(elapsed, 3)}{{RESET}} seconds."
- success(success_msg, NO_COLOR)
- if fail_count == 0:
- info(f"{{FG.lightgreen}}{fail_count}{{RESET}} failed tests.", NO_COLOR)
- else:
- info(f"{{FG.lightred}}{fail_count}{{RESET}} failed tests.", NO_COLOR)
-
- print()
- print("\n".join(outs))
-
- except subprocess.CalledProcessError as e:
- if e.returncode in SEGFAULT_CODES:
- error(
- [
- f"Segmentation fault occured in the tests. Exit code: {e.returncode}",
- f"Please report this at {{FG.lightcyan}}https://github.com/kadir014/nova-physics/issues{{RESET}}"
- ],
- NO_COLOR
- )
-
- else:
- error(f"Tests exited with code {e.returncode}", NO_COLOR)
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/scripts/copy_assets.py b/scripts/copy_assets.py
new file mode 100644
index 0000000..9735ba8
--- /dev/null
+++ b/scripts/copy_assets.py
@@ -0,0 +1,7 @@
+import os
+import shutil
+
+
+if not os.path.exists("build/assets"):
+ print("Copying assets directory.")
+ shutil.copytree("examples/assets", "build/assets", dirs_exist_ok=True)
\ No newline at end of file
diff --git a/scripts/install_wraps.py b/scripts/install_wraps.py
new file mode 100644
index 0000000..1a76dd3
--- /dev/null
+++ b/scripts/install_wraps.py
@@ -0,0 +1,15 @@
+import subprocess
+import os
+
+
+if not os.path.exists("subprojects"):
+ os.mkdir("subprojects")
+
+
+wraps = [
+ "sdl2",
+]
+
+for wrap in wraps:
+ print(f"Installing wrap: {wrap}")
+ subprocess.run(f"meson wrap install {wrap}", shell=True)
\ No newline at end of file
diff --git a/src/body.c b/src/body.c
index 9788dcb..ce926ce 100644
--- a/src/body.c
+++ b/src/body.c
@@ -11,7 +11,7 @@
#include
#include "novaphysics/internal.h"
#include "novaphysics/body.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
#include "novaphysics/math.h"
#include "novaphysics/aabb.h"
#include "novaphysics/constants.h"
@@ -21,128 +21,240 @@
/**
* @file body.c
*
- * @brief Body struct and methods.
- *
- * This module defines body enums, body struct and its methods.
+ * @brief Rigid body implementation.
*/
-nvBody *nvBody_new(
- nvBodyType type,
- nvShape *shape,
- nvVector2 position,
- nv_float angle,
- nvMaterial material
-) {
- nvBody *body = NV_NEW(nvBody);
- if (!body) return NULL;
+// Skip non-dynamic bodies
+#define _NV_ONLY_DYNAMIC {if ((body)->type != nvRigidBodyType_DYNAMIC) return;}
+#define _NV_ONLY_DYNAMIC0 {if ((body)->type != nvRigidBodyType_DYNAMIC) return 0;}
+
+
+nvRigidBody *nvRigidBody_new(nvRigidBodyInitializer init) {
+ nvRigidBody *body = NV_NEW(nvRigidBody);
+ NV_MEM_CHECK(body);
+
+ body->user_data = init.user_data;
body->space = NULL;
- body->type = type;
- body->shape = shape;
+ body->type = init.type;
- body->position = position;
- body->angle = angle;
+ body->shapes = nvArray_new();
+ if (!body->shapes) {
+ NV_FREE(body);
+ return NULL;
+ }
- body->linear_velocity = nvVector2_zero;
- body->angular_velocity = 0.0;
+ body->origin = init.position;
+ body->position = init.position;
+ body->angle = init.angle;
- body->linear_damping = 0.002;
- body->angular_damping = 0.002;
+ body->linear_velocity = init.linear_velocity;
+ body->angular_velocity = init.angular_velocity;
+
+ body->linear_damping_scale = 1.0;
+ body->angular_damping_scale = 1.0;
body->force = nvVector2_zero;
body->torque = 0.0;
body->gravity_scale = 1.0;
+ body->com = nvVector2_zero;
- body->material = material;
-
- body->is_sleeping = false;
- body->sleep_timer = 0;
+ body->material = init.material;
- body->is_attractor = false;
-
- body->enable_collision = true;
+ body->collision_enabled = true;
body->collision_group = 0;
body->collision_category = 0b11111111111111111111111111111111;
body->collision_mask = 0b11111111111111111111111111111111;
- body->_cache_aabb = false;
- body->_cache_transform = false;
- body->_cached_aabb = (nvAABB){0.0, 0.0, 0.0, 0.0};
-
- nvBody_calc_mass_and_inertia(body);
+ body->cache_aabb = false;
+ body->cache_transform = false;
+ body->cached_aabb = (nvAABB){0.0, 0.0, 0.0, 0.0};
return body;
}
-void nvBody_free(void *body) {
- if (body == NULL) return;
- nvBody *b = (nvBody *)body;
+void nvRigidBody_free(nvRigidBody *body) {
+ if (!body) return;
- nvShape_free(b->shape);
+ for (size_t i = 0; i < body->shapes->size; i++) {
+ nvShape_free(body->shapes->data[i]);
+ }
+ nvArray_free(body->shapes);
- free(b);
+ NV_FREE(body);
}
-void nvBody_calc_mass_and_inertia(nvBody *body) {
- // -Wmaybe-uninitialized
+static int nvRigidBody_accumulate_mass(nvRigidBody *body) {
body->mass = 0.0;
+ body->invmass = 0.0;
body->inertia = 0.0;
+ body->invinertia = 0.0;
- switch (body->type) {
- case nvBodyType_DYNAMIC:
- switch (body->shape->type) {
- case nvShapeType_CIRCLE:
- body->mass = nv_circle_area(body->shape->radius) * body->material.density;
- body->inertia = nv_circle_inertia(body->mass, body->shape->radius);
- break;
-
- case nvShapeType_POLYGON:
- body->mass = nv_polygon_area(body->shape->vertices) * body->material.density;
- body->inertia = nv_polygon_inertia(body->mass, body->shape->vertices);
- break;
- }
+ _NV_ONLY_DYNAMIC0;
+
+ // Accumulate mass information from shapes
- body->invmass = 1.0 / body->mass;
- body->invinertia = 1.0 / body->inertia;
+ nvVector2 local_com = nvVector2_zero;
+ for (size_t i = 0; i < body->shapes->size; i++) {
+ nvShape *shape = body->shapes->data[i];
- break;
+ nvShapeMassInfo mass_info = nvShape_calculate_mass(shape, body->material.density);
+
+ body->mass += mass_info.mass;
+ body->inertia += mass_info.inertia;
+ local_com = nvVector2_add(local_com, nvVector2_mul(mass_info.center, mass_info.mass));
+ }
- case nvBodyType_STATIC:
- body->mass = 0.0;
- body->inertia = 0.0;
- body->invmass = 0.0;
- body->invinertia = 0.0;
-
- break;
+ if (body->mass == 0.0) {
+ nv_set_error("Dynamic bodies can't have 0 mass.");
+ return 1;
}
+
+ // Calculate center of mass and center the inertia
+
+ body->invmass = 1.0 / body->mass;
+ local_com = nvVector2_mul(local_com, body->invmass);
+
+ body->inertia -= body->mass * nvVector2_dot(local_com, local_com);
+ if (body->inertia == 0.0) {
+ nv_set_error("Invalid mass.");
+ return 1;
+ }
+ body->invinertia = 1.0 / body->inertia;
+
+ body->com = local_com;
+ body->position = nvVector2_add(nvVector2_rotate(body->com, body->angle), body->origin);
+
+ return 0;
+}
+
+void nvRigidBody_set_user_data(nvRigidBody *body, void *data) {
+ body->user_data = data;
+}
+
+void *nvRigidBody_get_user_data(const nvRigidBody *body) {
+ return body->user_data;
+}
+
+nvSpace *nvRigidBody_get_space(const nvRigidBody *body) {
+ return body->space;
+}
+
+nv_uint32 nvRigidBody_get_id(const nvRigidBody *body) {
+ return body->id;
+}
+
+int nvRigidBody_set_type(nvRigidBody *body, nvRigidBodyType type) {
+ nvRigidBodyType old_type = body->type;
+ body->type = type;
+
+ // If the body was static from start the mass info might have not been calculated
+ if (old_type == nvRigidBodyType_STATIC && type == nvRigidBodyType_DYNAMIC)
+ return nvRigidBody_accumulate_mass(body);
+
+ return 0;
+}
+
+nvRigidBodyType nvRigidBody_get_type(const nvRigidBody *body) {
+ return body->type;
+}
+
+void nvRigidBody_set_position(nvRigidBody *body, nvVector2 new_position) {
+ body->position = new_position;
+ body->origin = nvVector2_add(nvVector2_rotate(body->com, body->angle), body->position);
+ body->cache_aabb = false;
+ body->cache_transform = false;
+}
+
+nvVector2 nvRigidBody_get_position(const nvRigidBody *body) {
+ return body->position;
+}
+
+void nvRigidBody_set_angle(nvRigidBody *body, nv_float new_angle) {
+ body->angle = new_angle;
+ body->origin = nvVector2_add(nvVector2_rotate(body->com, body->angle), body->position);
+ body->cache_aabb = false;
+ body->cache_transform = false;
+}
+
+nv_float nvRigidBody_get_angle(const nvRigidBody *body) {
+ return body->angle;
+}
+
+void nvRigidBody_set_linear_velocity(nvRigidBody *body, nvVector2 new_velocity) {
+ body->linear_velocity = new_velocity;
+}
+
+nvVector2 nvRigidBody_get_linear_velocity(const nvRigidBody *body) {
+ return body->linear_velocity;
}
-void nvBody_set_mass(nvBody *body, nv_float mass) {
- if (body->type == nvBodyType_STATIC) return;
+void nvRigidBody_set_angular_velocity(nvRigidBody *body, nv_float new_velocity) {
+ body->angular_velocity = new_velocity;
+}
+
+nv_float nvRigidBody_get_angular_velocity(const nvRigidBody *body) {
+ return body->angular_velocity;
+}
+
+void nvRigidBody_set_linear_damping_scale(nvRigidBody *body, nv_float scale) {
+ body->linear_damping_scale = scale;
+}
+
+nv_float nvRigidBody_get_linear_damping_scale(const nvRigidBody *body) {
+ return body->linear_damping_scale;
+}
+
+void nvRigidBody_set_angular_damping_scale(nvRigidBody *body, nv_float scale) {
+ body->angular_damping_scale = scale;
+}
+
+nv_float nvRigidBody_get_angular_damping_scale(const nvRigidBody *body) {
+ return body->angular_damping_scale;
+}
+
+void nvRigidBody_set_gravity_scale(nvRigidBody *body, nv_float scale) {
+ body->gravity_scale = scale;
+}
- if (mass == 0.0) NV_ERROR("Can't set mass of a dynamic body to 0\n");
+nv_float nvRigidBody_get_gravity_scale(const nvRigidBody *body) {
+ return body->gravity_scale;
+}
+
+void nvRigidBody_set_material(nvRigidBody *body, nvMaterial material) {
+ body->material = material;
+ nvRigidBody_accumulate_mass(body);
+}
+
+nvMaterial nvRigidBody_get_material(const nvRigidBody *body) {
+ return body->material;
+}
+
+int nvRigidBody_set_mass(nvRigidBody *body, nv_float mass) {
+ _NV_ONLY_DYNAMIC0;
+
+ if (mass == 0.0) {
+ nv_set_error("Can't set mass of a dynamic body to 0. Use a static body instead.");
+ return 1;
+ }
body->mass = mass;
body->invmass = 1.0 / body->mass;
- switch (body->shape->type) {
- case nvShapeType_CIRCLE:
- body->inertia = nv_circle_inertia(body->mass, body->shape->radius);
- break;
+ // TODO: Recalculate inertia from shapes with updated mass?
- case nvShapeType_POLYGON:
- body->inertia = nv_polygon_inertia(body->mass, body->shape->vertices);
- break;
- }
+ return 0;
+}
- body->invinertia = 1.0 / body->inertia;
+nv_float nvRigidBody_get_mass(const nvRigidBody *body) {
+ return body->mass;
}
-void nvBody_set_inertia(nvBody *body, nv_float inertia) {
- if (body->type == nvBodyType_STATIC) return;
+void nvRigidBody_set_inertia(nvRigidBody *body, nv_float inertia) {
+ _NV_ONLY_DYNAMIC;
if (inertia == 0.0) {
body->inertia = 0.0;
@@ -154,127 +266,103 @@ void nvBody_set_inertia(nvBody *body, nv_float inertia) {
}
}
-void nvBody_reset_velocities(nvBody *body) {
- body->linear_velocity = nvVector2_zero;
- body->angular_velocity = 0.0;
- body->force = nvVector2_zero;
- body->torque = 0.0;
+nv_float nvRigidBody_get_inertia(const nvRigidBody *body) {
+ return body->inertia;
}
-void nvBody_integrate_accelerations(
- nvBody *body,
- nvVector2 gravity,
- nv_float dt
-) {
- if (body->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body);
- return;
- }
- NV_TRACY_ZONE_START;
-
- /*
- Integrate linear acceleration
-
- a = F * (1/M) + g
- v = a * Δt
- */
- nvVector2 linear_acceleration = nvVector2_add(
- nvVector2_mul(body->force, body->invmass), nvVector2_mul(gravity, body->gravity_scale));
+void nvRigidBody_set_collision_group(nvRigidBody *body, nv_uint32 group) {
+ body->collision_group = group;
+}
- body->linear_velocity = nvVector2_add(
- body->linear_velocity, nvVector2_mul(linear_acceleration, dt));
+nv_uint32 nvRigidBody_get_collision_group(const nvRigidBody *body) {
+ return body->collision_group;
+}
- /*
- Integrate angular acceleration
-
- α = T * (1/I)
- ω = α * Δt
- */
- nv_float angular_acceleration = body->torque * body->invinertia;
- body->angular_velocity += angular_acceleration * dt;
+void nvRigidBody_set_collision_category(nvRigidBody *body, nv_uint32 category) {
+ body->collision_category = category;
+}
- /*
- Dampen velocities
+nv_uint32 nvRigidBody_get_collision_category(const nvRigidBody *body) {
+ return body->collision_category;
+}
- v *= kᵥ (linear damping)
- ω *= kₐ (angular damping)
- */
- nv_float kv = nv_pow(0.98, body->linear_damping);
- nv_float ka = nv_pow(0.98, body->angular_damping);
- body->linear_velocity = nvVector2_mul(body->linear_velocity, kv);
- body->angular_velocity *= ka;
+void nvRigidBody_set_collision_mask(nvRigidBody *body, nv_uint32 mask) {
+ body->collision_mask = mask;
+}
- NV_TRACY_ZONE_END;
+nv_uint32 nvRigidBody_get_collision_mask(const nvRigidBody *body) {
+ return body->collision_mask;
}
-void nvBody_integrate_velocities(nvBody *body, nv_float dt) {
- if (body->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body);
- return;
- }
- NV_TRACY_ZONE_START;
+int nvRigidBody_add_shape(nvRigidBody *body, nvShape *shape) {
+ if (nvArray_add(body->shapes, shape)) return 1;
- /*
- Integrate linear velocity
+ if (nvRigidBody_accumulate_mass(body)) return 2;
- x = v * Δt
- */
- body->position = nvVector2_add(body->position, nvVector2_mul(body->linear_velocity, dt));
+ return 0;
+}
- /*
- Integrate angular velocity
+int nvRigidBody_remove_shape(nvRigidBody *body, nvShape *shape) {
+ if (nvArray_remove(body->shapes, shape) == (size_t)(-1)) return 1;
- θ = ω * Δt
- */
- body->angle += body->angular_velocity * dt;
+ if (nvRigidBody_accumulate_mass(body)) return 2;
- // Reset forces
- body->force = nvVector2_zero;
- body->torque = 0.0;
+ // Remove contacts
+ void *map_val;
+ size_t map_iter = 0;
+ while (nvHashMap_iter(body->space->contacts, &map_iter, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
- NV_TRACY_ZONE_END;
-}
+ for (size_t i = 0; i < body->shapes->size; i++) {
+ nvShape *shape = body->shapes->data[i];
-void nvBody_apply_attraction(nvBody *body, nvBody *attractor, nv_float dt) {
- nv_float distance = nvVector2_dist2(body->position, attractor->position);
- nvVector2 direction = nvVector2_sub(attractor->position, body->position);
- direction = nvVector2_normalize(direction);
+ if (
+ (pcp->body_a == body && shape == pcp->shape_a) ||
+ (pcp->body_b == body && shape == pcp->shape_b)
+ ) {
+ nvPersistentContactPair_remove(body->space, pcp);
+ break;
+ }
+ }
+ }
- // Fg = (G * Mᴬ * Mᴮ) / d²
- nv_float G = NV_GRAV_CONST * NV_GRAV_SCALE;
- nv_float force_mag = (G * body->mass * attractor->mass) / distance;
- nvVector2 force = nvVector2_mul(direction, force_mag * dt);
+ return 0;
+}
- nvBody_apply_force(body, force);
+nv_bool nvRigidBody_iter_shapes(nvRigidBody *body, nvShape **shape, size_t *index) {
+ *shape = body->shapes->data[(*index)++];
+ return (*index <= body->shapes->size);
}
-void nvBody_apply_force(nvBody *body, nvVector2 force) {
- if (body->type == nvBodyType_STATIC) return;
+void nvRigidBody_apply_force(nvRigidBody *body, nvVector2 force) {
+ _NV_ONLY_DYNAMIC;
body->force = nvVector2_add(body->force, force);
-
- nvBody_awake(body);
}
-void nvBody_apply_force_at(
- nvBody *body,
+void nvRigidBody_apply_force_at(
+ nvRigidBody *body,
nvVector2 force,
nvVector2 position
) {
- if (body->type == nvBodyType_STATIC) return;
+ _NV_ONLY_DYNAMIC;
body->force = nvVector2_add(body->force, force);
body->torque += nvVector2_cross(position, force);
+}
+
+void nvRigidBody_apply_torque(nvRigidBody *body, nv_float torque) {
+ _NV_ONLY_DYNAMIC;
- nvBody_awake(body);
+ body->torque += torque;
}
-void nvBody_apply_impulse(
- nvBody *body,
+void nvRigidBody_apply_impulse(
+ nvRigidBody *body,
nvVector2 impulse,
nvVector2 position
) {
- if (body->type == nvBodyType_STATIC) return;
+ _NV_ONLY_DYNAMIC;
/*
v -= J * (1/M)
@@ -287,131 +375,121 @@ void nvBody_apply_impulse(
body->angular_velocity += nvVector2_cross(position, impulse) * body->invinertia;
}
-void nvBody_sleep(nvBody *body) {
- if (body->type != nvBodyType_STATIC) {
- body->is_sleeping = true;
- body->linear_velocity = nvVector2_zero;
- body->angular_velocity = 0.0;
- body->force = nvVector2_zero;
- body->torque = 0.0;
- }
+void nvRigidBody_enable_collisions(nvRigidBody *body) {
+ body->collision_enabled = true;
}
-void nvBody_awake(nvBody *body) {
- body->is_sleeping = false;
- body->sleep_timer = 0;
+void nvRigidBody_disable_collisions(nvRigidBody *body) {
+ body->collision_enabled = false;
+}
+
+void nvRigidBody_reset_velocities(nvRigidBody *body) {
+ nvRigidBody_set_linear_velocity(body, nvVector2_zero);
+ nvRigidBody_set_angular_velocity(body, 0.0);
+ body->force = nvVector2_zero;
+ body->torque = 0.0;
}
-nvAABB nvBody_get_aabb(nvBody *body) {
+nvAABB nvRigidBody_get_aabb(nvRigidBody *body) {
NV_TRACY_ZONE_START;
- if (body->_cache_aabb) {
+ if (body->cache_aabb) {
NV_TRACY_ZONE_END;
- return body->_cached_aabb;
+ return body->cached_aabb;
}
- else {
- body->_cache_aabb = true;
-
- nv_float min_x;
- nv_float min_y;
- nv_float max_x;
- nv_float max_y;
-
- switch (body->shape->type) {
- case nvShapeType_CIRCLE:
- body->_cached_aabb = (nvAABB){
- body->position.x - body->shape->radius,
- body->position.y - body->shape->radius,
- body->position.x + body->shape->radius,
- body->position.y + body->shape->radius
- };
-
- NV_TRACY_ZONE_END;
- return body->_cached_aabb;
-
- case nvShapeType_POLYGON:
- min_x = NV_INF;
- min_y = NV_INF;
- max_x = -NV_INF;
- max_y = -NV_INF;
-
- nvBody_local_to_world(body);
-
- for (size_t i = 0; i < body->shape->trans_vertices->size; i++) {
- nvVector2 v = NV_TO_VEC2(body->shape->trans_vertices->data[i]);
- if (v.x < min_x) min_x = v.x;
- if (v.x > max_x) max_x = v.x;
- if (v.y < min_y) min_y = v.y;
- if (v.y > max_y) max_y = v.y;
- }
-
- body->_cached_aabb = (nvAABB){min_x, min_y, max_x, max_y};
-
- NV_TRACY_ZONE_END;
- return body->_cached_aabb;
-
- default:
- NV_TRACY_ZONE_END;
- NV_ERROR("Unknown shape type.");
- return (nvAABB){0.0, 0.0, 0.0, 0.0};
- }
+ body->cache_aabb = true;
+
+ nvTransform xform = (nvTransform){body->origin, body->angle};
+ nvAABB total_aabb = nvShape_get_aabb(body->shapes->data[0], xform);
+ for (size_t i = 1; i < body->shapes->size; i++) {
+ total_aabb = nvAABB_merge(total_aabb, nvShape_get_aabb(body->shapes->data[i], xform));
}
+ body->cached_aabb = total_aabb;
+
NV_TRACY_ZONE_END;
+ return total_aabb;
}
-nv_float nvBody_get_kinetic_energy(nvBody *body) {
+nv_float nvRigidBody_get_kinetic_energy(const nvRigidBody *body) {
// 1/2 * M * v²
return 0.5 * body->mass * nvVector2_len2(body->linear_velocity);
}
-nv_float nvBody_get_rotational_energy(nvBody *body) {
+nv_float nvRigidBody_get_rotational_energy(const nvRigidBody *body) {
// 1/2 * I * ω²
- return 0.5 * body->inertia * fabs(body->angular_velocity);
+ return 0.5 * body->inertia * nv_fabs(body->angular_velocity);
}
-void nvBody_set_is_attractor(nvBody *body, bool is_attractor) {
- if (body->is_attractor != is_attractor) {
- body->is_attractor = is_attractor;
-
- if (body->is_attractor) {
- nvArray_add(body->space->attractors, body);
- }
- else {
- nvArray_remove(body->space->attractors, body);
- }
+void nvRigidBody_integrate_accelerations(
+ nvRigidBody *body,
+ nvVector2 gravity,
+ nv_float dt
+) {
+ if (body->type == nvRigidBodyType_STATIC) {
+ nvRigidBody_reset_velocities(body);
+ return;
}
-}
+ NV_TRACY_ZONE_START;
-bool nvBody_get_is_attractor(nvBody *body) {
- return body->is_attractor;
-}
+ // Semi-Implicit Euler Integration
+
+ /*
+ Integrate linear acceleration
-void nvBody_local_to_world(nvBody *body) {
- NV_TRACY_ZONE_START;
+ a = F * (1/M) + g
+ v = a * Δt
+ */
+ nvVector2 linear_acceleration = nvVector2_add(
+ nvVector2_mul(body->force, body->invmass), nvVector2_mul(gravity, body->gravity_scale));
- if (body->_cache_transform) {
- NV_TRACY_ZONE_END;
+ body->linear_velocity = nvVector2_add(
+ body->linear_velocity, nvVector2_mul(linear_acceleration, dt));
+
+ /*
+ Integrate angular acceleration
+
+ α = T * (1/I)
+ ω = α * Δt
+ */
+ nv_float angular_acceleration = body->torque * body->invinertia;
+ body->angular_velocity += angular_acceleration * dt;
+
+ // Dampen velocities
+ nv_float kv = nv_pow(0.99, body->linear_damping_scale * body->space->settings.linear_damping);
+ nv_float ka = nv_pow(0.99, body->angular_damping_scale * body->space->settings.angular_damping);
+ body->linear_velocity = nvVector2_mul(body->linear_velocity, kv);
+ body->angular_velocity *= ka;
+
+ NV_TRACY_ZONE_END;
+}
+
+void nvRigidBody_integrate_velocities(nvRigidBody *body, nv_float dt) {
+ if (body->type == nvRigidBodyType_STATIC) {
+ nvRigidBody_reset_velocities(body);
return;
}
+ NV_TRACY_ZONE_START;
- else {
- body->_cache_transform = true;
-
- for (size_t i = 0; i < body->shape->vertices->size; i++) {
- nvVector2 new = nvVector2_add(body->position,
- nvVector2_rotate(
- NV_TO_VEC2(body->shape->vertices->data[i]),
- body->angle
- )
- );
-
- nvVector2 *trans = NV_TO_VEC2P(body->shape->trans_vertices->data[i]);
- trans->x = new.x;
- trans->y = new.y;
- }
- }
+ // Semi-Implicit Euler Integration
+
+ /*
+ Integrate linear velocity
+
+ x = v * Δt
+ */
+ body->position = nvVector2_add(body->position, nvVector2_mul(body->linear_velocity, dt));
+
+ /*
+ Integrate angular velocity
+
+ θ = ω * Δt
+ */
+ body->angle += body->angular_velocity * dt;
+
+ body->force = nvVector2_zero;
+ body->torque = 0.0;
NV_TRACY_ZONE_END;
}
\ No newline at end of file
diff --git a/src/broadphase.c b/src/broadphase.c
index 5ca90f0..a3644c0 100644
--- a/src/broadphase.c
+++ b/src/broadphase.c
@@ -8,17 +8,11 @@
*/
-#include
-#include "novaphysics/internal.h"
#include "novaphysics/broadphase.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
#include "novaphysics/aabb.h"
-#include "novaphysics/body.h"
-#include "novaphysics/math.h"
-#include "novaphysics/resolution.h"
#include "novaphysics/space.h"
#include "novaphysics/bvh.h"
-#include "novaphysics/threading.h"
/**
@@ -31,31 +25,23 @@
/**
* @brief Early-out from checking collisions.
*/
-static inline bool nvBroadPhase_early_out(nvSpace *space, nvBody *a, nvBody *b) {
- // Same body or B's ID is higher
- // Latter is done in order to avoid checking same pairs twice
+static inline nv_bool nvBroadPhase_early_out(
+ nvSpace *space,
+ nvRigidBody *a,
+ nvRigidBody *b
+) {
+ // Same body or already checked
if (a->id >= b->id)
return true;
// One of the bodies have collision detection disabled
- if (!a->enable_collision || !b->enable_collision)
+ if (!a->collision_enabled || !b->collision_enabled)
return true;
// Two static bodies do not need to interact
- if (a->type == nvBodyType_STATIC && b->type == nvBodyType_STATIC)
+ if (a->type == nvRigidBodyType_STATIC && b->type == nvRigidBodyType_STATIC)
return true;
- if (space->sleeping) {
- // Both bodies are asleep
- if (a->is_sleeping && b->is_sleeping)
- return true;
-
- // One body is asleep and other is static
- if ((a->is_sleeping && b->type == nvBodyType_STATIC) ||
- (b->is_sleeping && a->type == nvBodyType_STATIC))
- return true;
- }
-
// Bodies share the same non-zero group
if (a->collision_group == b->collision_group && a->collision_group != 0)
return true;
@@ -65,347 +51,202 @@ static inline bool nvBroadPhase_early_out(nvSpace *space, nvBody *a, nvBody *b)
(b->collision_mask & a->collision_category) == 0)
return true;
- return false;
-}
-
-
-void nvBroadPhase_brute_force(nvSpace *space) {
- nvHashMap_clear(space->broadphase_pairs);
-
- for (size_t i = 0; i < space->bodies->size; i++) {
- nvBody *a = (nvBody *)space->bodies->data[i];
- nvAABB abox = nvBody_get_aabb(a);
-
- for (size_t j = 0; j < space->bodies->size; j++) {
- nvBody *b = (nvBody *)space->bodies->data[j];
-
- if (nvBroadPhase_early_out(space, a, b)) continue;
-
- nv_uint32 id_pair = nv_pair(a->id, b->id);
+ // TODO: There must be a more efficient way
+ for (size_t i = 0; i < space->constraints->size; i++) {
+ nvConstraint *cons = space->constraints->data[i];
- nvAABB bbox = nvBody_get_aabb(b);
-
- if (nv_collide_aabb_x_aabb(abox, bbox)) {
- nvHashMap_set(space->broadphase_pairs, &(nvBroadPhasePair){.a=a, .b=b, .id_pair=id_pair});
- }
+ if (
+ cons->ignore_collision &&
+ ((a == cons->a && b == cons->b) || (a == cons->b && b == cons->a))
+ ) {
+ return true;
}
}
+
+ return false;
}
-void nvBroadPhase_SHG(nvSpace *space) {
+void nv_broadphase_brute_force(nvSpace *space) {
NV_TRACY_ZONE_START;
-
- nvHashMap_clear(space->broadphase_pairs);
- nvSHG_place(space->shg, space->bodies);
+ nvMemoryPool_clear(space->broadphase_pairs);
for (size_t i = 0; i < space->bodies->size; i++) {
- nvBody *a = (nvBody *)space->bodies->data[i];
- nvAABB abox = nvBody_get_aabb(a);
-
- nv_int16 min_x = (nv_int16)(abox.min_x / space->shg->cell_width);
- nv_int16 min_y = (nv_int16)(abox.min_y / space->shg->cell_height);
- nv_int16 max_x = (nv_int16)(abox.max_x / space->shg->cell_width);
- nv_int16 max_y = (nv_int16)(abox.max_y / space->shg->cell_height);
-
- for (nv_int16 y = min_y; y < max_y + 1; y++) {
- for (nv_int16 x = min_x; x < max_x + 1; x++) {
+ nvRigidBody *a = (nvRigidBody *)space->bodies->data[i];
+ nvTransform xform_a = (nvTransform){a->origin, a->angle};
+ nvAABB abox = nvRigidBody_get_aabb(a);
- nv_uint32 neighbors[8];
- bool neighbor_flags[8];
- nvSHG_get_neighbors(space->shg, x, y, neighbors, neighbor_flags);
-
- for (size_t j = 0; j < 9; j++) {
- nvArray *cell;
-
- // Own cell
- if (j == 8) {
- cell = nvSHG_get(space->shg, nv_pair(x, y));
- if (!cell) continue;
- }
- // Neighbor cells
- else {
- if (!neighbor_flags[j]) continue;
+ for (size_t j = 0; j < space->bodies->size; j++) {
+ nvRigidBody *b = (nvRigidBody *)space->bodies->data[j];
- cell = nvSHG_get(space->shg, neighbors[j]);
- if (!cell) continue;
- }
+ if (nvBroadPhase_early_out(space, a, b)) continue;
- for (size_t k = 0; k < cell->size; k++) {
- nvBody *b = (nvBody *)cell->data[k];
+ nvBroadPhasePair pair = {a, b};
- if (nvBroadPhase_early_out(space, a, b)) continue;
+ nvTransform xform_b = (nvTransform){b->origin, b->angle};
+ nvAABB bbox = nvRigidBody_get_aabb(b);
- nv_uint32 id_pair = nv_pair(a->id, b->id);
+ // First check the body AABB, then check every shape AABB
+ // TODO: Improve this & use in BVH as well
+ nv_bool overlaps = false;
+ if (nv_collide_aabb_x_aabb(abox, bbox)) {
+ for (size_t k = 0; k < a->shapes->size; k++) {
+ nvShape *shape_a = a->shapes->data[k];
+ nvAABB sabox = nvShape_get_aabb(shape_a, xform_a);
- nvAABB bbox = nvBody_get_aabb(b);
+ for (size_t l = 0; l < b->shapes->size; l++) {
+ nvShape *shape_b = b->shapes->data[l];
+ nvAABB sbbox = nvShape_get_aabb(shape_b, xform_b);
- if (nv_collide_aabb_x_aabb(abox, bbox)) {
- nvHashMap_set(space->broadphase_pairs, &(nvBroadPhasePair){.a=a, .b=b, .id_pair=id_pair});
+ if (nv_collide_aabb_x_aabb(sabox, sbbox)) {
+ overlaps = true;
+ break;
}
}
+
+ if (overlaps)
+ break;
}
}
- }
- }
-
- NV_TRACY_ZONE_END;
-}
-
-
-typedef struct {
- struct nvSpace *space;
- nvArray *bodies;
- nv_uint8 task_id;
-} SHGWorkerData;
-
-
-static int nvBroadPhase_SHG_task(void *data) {
- NV_TRACY_ZONE_START;
-
- nvSpace *space = (((SHGWorkerData *)data))->space;
- nvArray *bodies = ((SHGWorkerData *)data)->bodies;
- nv_uint8 task_id = ((SHGWorkerData *)data)->task_id;
-
- for (size_t i = 0; i < bodies->size; i++) {
- nvBody *a = (nvBody *)bodies->data[i];
- nvAABB abox = nvBody_get_aabb(a);
-
- nv_int16 min_x = (nv_int16)(abox.min_x / space->shg->cell_width);
- nv_int16 min_y = (nv_int16)(abox.min_y / space->shg->cell_height);
- nv_int16 max_x = (nv_int16)(abox.max_x / space->shg->cell_width);
- nv_int16 max_y = (nv_int16)(abox.max_y / space->shg->cell_height);
-
- for (nv_int16 y = min_y; y < max_y + 1; y++) {
- for (nv_int16 x = min_x; x < max_x + 1; x++) {
-
- nv_uint32 neighbors[8];
- bool neighbor_flags[8];
- nvSHG_get_neighbors(space->shg, x, y, neighbors, neighbor_flags);
-
- for (size_t j = 0; j < 9; j++) {
- nvArray *cell;
- // Own cell
- if (j == 8) {
- cell = nvSHG_get(space->shg, nv_pair(x, y));
- if (!cell) continue;
- }
- // Neighbor cells
- else {
- if (!neighbor_flags[j]) continue;
-
- cell = nvSHG_get(space->shg, neighbors[j]);
- if (!cell) continue;
- }
-
- for (size_t k = 0; k < cell->size; k++) {
- nvBody *b = (nvBody *)cell->data[k];
-
- if (nvBroadPhase_early_out(space, a, b)) continue;
-
- nv_uint32 id_pair = nv_pair(a->id, b->id);
-
- nvAABB bbox = nvBody_get_aabb(b);
-
- if (nv_collide_aabb_x_aabb(abox, bbox)) {
- nvBroadPhasePair pair = {
- .a = a,
- .b = b,
- .id_pair = id_pair
- };
-
- nvHashMap_set(space->mt_shg_pairs->data[task_id], &pair);
- }
- }
- }
+ if (overlaps) {
+ nvMemoryPool_add(space->broadphase_pairs, &pair);
}
}
}
NV_TRACY_ZONE_END;
- return 0;
}
-void nvBroadPhase_SHG_parallel(nvSpace *space) {
+void nv_broadphase_BVH(nvSpace *space) {
NV_TRACY_ZONE_START;
-
- nvSHG_place(space->shg, space->bodies);
-
- for (size_t i = 0; i < space->thread_count; i++) {
- nvHashMap_clear(space->mt_shg_pairs->data[i]);
- nvArray_clear(space->mt_shg_bins->data[i], NULL);
- }
- // Add bodies to bins for individual threads
+ nvMemoryPool_clear(space->broadphase_pairs);
- nvAABB dyn_aabb = {NV_INF, NV_INF, -NV_INF, -NV_INF};
+ nvPrecisionTimer timer;
+ NV_PROFILER_START(timer);
+ // Prepare median splitting coords
for (size_t i = 0; i < space->bodies->size; i++) {
- nvBody *body = space->bodies->data[i];
- if (body->type == nvBodyType_STATIC) continue;
- nvAABB aabb = nvBody_get_aabb(body);
-
- dyn_aabb.min_x = nv_fmin(dyn_aabb.min_x, aabb.min_x);
- dyn_aabb.min_y = nv_fmin(dyn_aabb.min_y, aabb.min_y);
- dyn_aabb.max_x = nv_fmax(dyn_aabb.max_x, aabb.max_x);
- dyn_aabb.max_y = nv_fmax(dyn_aabb.max_y, aabb.max_y);
+ nvRigidBody *body = space->bodies->data[i];
+ nvAABB aabb = nvRigidBody_get_aabb(body);
+ body->bvh_median_x = (aabb.min_x + aabb.max_x) * 0.5;
+ body->bvh_median_y = (aabb.min_y + aabb.max_y) * 0.5;
}
- nv_float q = (dyn_aabb.max_x - dyn_aabb.min_x) / (nv_float)space->thread_count;
- for (size_t i = 0; i < space->bodies->size; i++) {
- nvBody *body = space->bodies->data[i];
- if (body->type == nvBodyType_STATIC) continue;
- nvAABB aabb = nvBody_get_aabb(body);
-
- for (size_t j = 0; j < space->thread_count; j++) {
- if (j == 0) {
- if (
- aabb.max_x >= dyn_aabb.min_x &&
- body->position.x <= q + dyn_aabb.min_x
- ) {
- nvArray_add(space->mt_shg_bins->data[j], body);
- break;
- }
- }
-
- else if (j == (space->thread_count - 1)) {
- if (
- aabb.min_x <= dyn_aabb.max_x &&
- body->position.x > q * (nv_float)(space->thread_count - 1) + dyn_aabb.min_x
- ) {
- nvArray_add(space->mt_shg_bins->data[j], body);
- break;
- }
- }
-
- else {
- if (
- body->position.x > q * (nv_float)(j) + dyn_aabb.min_x &&
- body->position.x <= q * (nv_float)(j + 1) + dyn_aabb.min_x
- ) {
- nvArray_add(space->mt_shg_bins->data[j], body);
- break;
- }
- }
- }
- }
+ // Build the tree top-down
+ nvBVHNode *bvh = nvBVHTree_new(space->bodies);
+ NV_PROFILER_STOP(timer, space->profiler.bvh_build);
- q = space->shg->bounds.max_x / (nv_float)space->thread_count;
+ NV_PROFILER_START(timer);
for (size_t i = 0; i < space->bodies->size; i++) {
- nvBody *body = space->bodies->data[i];
- if (body->type == nvBodyType_DYNAMIC) continue;
- nvAABB aabb = nvBody_get_aabb(body);
-
- for (size_t j = 0; j < space->thread_count; j++) {
- if (j == 0) {
- if (
- aabb.max_x >= space->shg->bounds.min_x &&
- body->position.x <= q
- ) {
- nvArray_add(space->mt_shg_bins->data[j], body);
- break;
- }
- }
-
- else if (j == (space->thread_count - 1)) {
- if (
- aabb.min_x <= space->shg->bounds.max_x &&
- body->position.x > q * (nv_float)(space->thread_count - 1)
- ) {
- nvArray_add(space->mt_shg_bins->data[j], body);
- break;
- }
- }
+ nvRigidBody *a = space->bodies->data[i];
+ nvAABB aabb = nvRigidBody_get_aabb(a);
- else {
- if (
- body->position.x > q * (nv_float)(j) &&
- body->position.x <= q * (nv_float)(j + 1)
- ) {
- nvArray_add(space->mt_shg_bins->data[j], body);
- break;
- }
- }
+ nv_bool is_combined;
+ nvArray *collided = nvBVHNode_collide(bvh, aabb, &is_combined);
+ if (!collided) {
+ if (is_combined) nvArray_free(collided);
+ continue;
}
- }
-
- #ifdef NV_COMPILER_MSVC
-
- SHGWorkerData *data = malloc(sizeof(SHGWorkerData) * space->thread_count);
-
- #else
- SHGWorkerData data[space->thread_count];
+ for (size_t j = 0; j < collided->size; j++) {
+ nvRigidBody *b = collided->data[j];
- #endif
- for (size_t i = 0; i < space->thread_count; i++) {
- data[i] = (SHGWorkerData){
- .space=space,
- .bodies=space->mt_shg_bins->data[i],
- .task_id=i
- };
- }
+ if (nvBroadPhase_early_out(space, a, b)) continue;
- for (size_t i = 0; i < space->thread_count; i++)
- nvTaskExecutor_add_task_to(
- space->task_executor,
- nvBroadPhase_SHG_task,
- &data[i],
- i
- );
+ nvAABB bbox = nvRigidBody_get_aabb(b);
- nvTaskExecutor_wait_tasks(space->task_executor);
+ nvBroadPhasePair pair = {a, b};
- #ifdef NV_COMPILER_MSVC
+ if (nv_collide_aabb_x_aabb(aabb, bbox)) {
+ nvMemoryPool_add(space->broadphase_pairs, &pair);
+ }
+ }
- free(data);
+ if (is_combined) nvArray_free(collided);
+ }
+ NV_PROFILER_STOP(timer, space->profiler.bvh_traverse);
- #endif
+ NV_PROFILER_START(timer);
+ nvBVHTree_free(bvh);
+ NV_PROFILER_STOP(timer, space->profiler.bvh_free);
NV_TRACY_ZONE_END;
}
-
-void nvBroadPhase_BVH(nvSpace *space) {
+void nv_broadphase_finalize(nvSpace *space) {
NV_TRACY_ZONE_START;
- nvHashMap_clear(space->broadphase_pairs);
+ /*
+ Keeping the removed contacts in the main iteration then actually removing
+ them in another iteration is way more performant than modifying the map
+ in single iteration. Resetting the iterator causes very bad performance spikes
+ in large scenes.
+ */
+
+ nvHashMap_clear(space->removed_contacts);
+
+ void *map_val;
+ size_t map_iter = 0;
+ while (nvHashMap_iter(space->contacts, &map_iter, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
+
+ nvRigidBody *a = pcp->body_a;
+ nvRigidBody *b = pcp->body_b;
+ nvAABB abox = nvRigidBody_get_aabb(a);
+ nvAABB bbox = nvRigidBody_get_aabb(b);
+
+ if (!nv_collide_aabb_x_aabb(abox, bbox)) {
+ for (size_t k = 0; k < a->shapes->size; k++) {
+ nvShape *shape_a = a->shapes->data[k];
+
+ for (size_t l = 0; l < b->shapes->size; l++) {
+ nvShape *shape_b = b->shapes->data[l];
+
+ nvPersistentContactPair *key = &(nvPersistentContactPair){.shape_a=shape_a, .shape_b=shape_b};
+
+ nvPersistentContactPair *pcp = nvHashMap_get(space->contacts, key);
+ if (pcp) {
+ for (size_t c = 0; c < pcp->contact_count; c++) {
+ nvContact *contact = &pcp->contacts[c];
+
+ nvContactEvent event = {
+ .body_a = pcp->body_a,
+ .body_b = pcp->body_b,
+ .shape_a = pcp->shape_a,
+ .shape_b = pcp->shape_b,
+ .normal = pcp->normal,
+ .penetration = contact->separation,
+ .position = nvVector2_add(pcp->body_a->position, contact->anchor_a),
+ .normal_impulse = {contact->solver_info.normal_impulse},
+ .friction_impulse = {contact->solver_info.tangent_impulse},
+ .id = contact->id
+ };
- nvPrecisionTimer timer;
-
- NV_PROFILER_START(timer);
- nvBVHNode *bvh_tree = nvBVHTree_new(space->bodies);
- NV_PROFILER_STOP(timer, space->profiler.bvh_build);
-
- NV_PROFILER_START(timer);
- for (size_t i = 0; i < space->bodies->size; i++) {
- nvBody *a = space->bodies->data[i];
- nvAABB aabb = a->_cached_aabb;
+ if (space->listener && !contact->remove_invoked) {
+ if (space->listener->on_contact_removed)
+ space->listener->on_contact_removed(space, event, space->listener_arg);
+ contact->remove_invoked = true;
+ };
+ }
- bool is_combined;
- nvArray *collided = nvBVHNode_collide(bvh_tree, aabb, &is_combined);
- if (!collided) {
- if (is_combined) nvArray_free(collided);
- continue;
+ nvHashMap_set(space->removed_contacts, pcp);
+ }
+ }
+ }
}
+ }
- for (size_t j = 0; j < collided->size; j++) {
- nvBody *b = collided->data[j];
-
- if (nvBroadPhase_early_out(space, a, b)) continue;
-
- nvHashMap_set(space->broadphase_pairs, &(nvBroadPhasePair){.a=a, .b=b});
- }
+ // Actually remove all "removed" contacts
+ map_val = NULL;
+ map_iter = 0;
+ while (nvHashMap_iter(space->removed_contacts, &map_iter, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
- if (is_combined) nvArray_free(collided);
+ nvHashMap_remove(space->contacts, pcp);
}
- NV_PROFILER_STOP(timer, space->profiler.bvh_traverse);
-
- NV_PROFILER_START(timer);
- nvBVHTree_free(bvh_tree);
- NV_PROFILER_STOP(timer, space->profiler.bvh_destroy);
NV_TRACY_ZONE_END;
}
\ No newline at end of file
diff --git a/src/bvh.c b/src/bvh.c
index 96cdb22..08bff7f 100644
--- a/src/bvh.c
+++ b/src/bvh.c
@@ -22,7 +22,7 @@
*/
-nvBVHNode *nvBVHNode_new(bool is_leaf, nvArray *bodies) {
+nvBVHNode *nvBVHNode_new(nv_bool is_leaf, nvArray *bodies) {
nvBVHNode *node = NV_NEW(nvBVHNode);
if (!node) return NULL;
@@ -35,7 +35,7 @@ nvBVHNode *nvBVHNode_new(bool is_leaf, nvArray *bodies) {
}
void nvBVHNode_free(nvBVHNode *node) {
- if (node == NULL) return;
+ if (!node) return;
nvArray_free(node->bodies);
@@ -44,19 +44,19 @@ void nvBVHNode_free(nvBVHNode *node) {
nvBVHNode_free(node->right);
}
- free(node);
+ NV_FREE(node);
}
void nvBVHNode_build_aabb(nvBVHNode *node) {
- if (node == NULL) return;
- if (node->bodies == NULL) return;
+ if (!node) return;
+ if (!node->bodies) return;
if (node->bodies->size > 0) {
node->aabb = (nvAABB){NV_INF, NV_INF, -NV_INF, -NV_INF};
for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
- nvAABB aabb = nvBody_get_aabb(body);
+ nvRigidBody *body = node->bodies->data[i];
+ nvAABB aabb = nvRigidBody_get_aabb(body);
node->aabb.min_x = nv_fmin(node->aabb.min_x, aabb.min_x);
node->aabb.min_y = nv_fmin(node->aabb.min_y, aabb.min_y);
@@ -67,7 +67,7 @@ void nvBVHNode_build_aabb(nvBVHNode *node) {
}
void nvBVHNode_subdivide(nvBVHNode *node) {
- if (node == NULL) return;
+ if (!node) return;
if (node->is_leaf) return;
nv_float width = node->aabb.max_x - node->aabb.min_x;
@@ -76,19 +76,21 @@ void nvBVHNode_subdivide(nvBVHNode *node) {
nvArray *lefts = nvArray_new();
nvArray *rights = nvArray_new();
- // Split along the longest axis
+ // Current splitting method is midway trough the longest axis
+
if (width > height) {
nv_float split = 0.0;
for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
- split += body->position.x;
+ nvRigidBody *body = node->bodies->data[i];
+ split += body->bvh_median_x;
}
split /= (nv_float)node->bodies->size;
for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
+ nvRigidBody *body = node->bodies->data[i];
+ nv_float c = body->bvh_median_x;
- if (body->position.x <= split)
+ if (c <= split)
nvArray_add(lefts, body);
else
nvArray_add(rights, body);
@@ -97,15 +99,16 @@ void nvBVHNode_subdivide(nvBVHNode *node) {
else {
nv_float split = 0.0;
for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
- split += body->position.y;
+ nvRigidBody *body = node->bodies->data[i];;
+ split += body->bvh_median_y;
}
split /= (nv_float)node->bodies->size;
for (size_t i = 0; i < node->bodies->size; i++) {
- nvBody *body = node->bodies->data[i];
+ nvRigidBody *body = node->bodies->data[i];
+ nv_float c = body->bvh_median_y;
- if (body->position.y <= split)
+ if (c <= split)
nvArray_add(lefts, body);
else
nvArray_add(rights, body);
@@ -120,8 +123,8 @@ void nvBVHNode_subdivide(nvBVHNode *node) {
return;
}
- bool left_leaf = lefts->size <= NV_BVH_LEAF_THRESHOLD;
- bool right_leaf = rights->size <= NV_BVH_LEAF_THRESHOLD;
+ nv_bool left_leaf = lefts->size <= NV_BVH_LEAF_THRESHOLD;
+ nv_bool right_leaf = rights->size <= NV_BVH_LEAF_THRESHOLD;
node->left = nvBVHNode_new(left_leaf, lefts);
node->right = nvBVHNode_new(right_leaf, rights);
@@ -134,9 +137,9 @@ void nvBVHNode_subdivide(nvBVHNode *node) {
nvBVHNode_subdivide(node->right);
}
-nvArray *nvBVHNode_collide(nvBVHNode *node, nvAABB aabb, bool *is_combined) {
+nvArray *nvBVHNode_collide(nvBVHNode *node, nvAABB aabb, nv_bool *is_combined) {
*is_combined = false;
- if (node == NULL) return NULL;
+ if (!node) return NULL;
if (node->is_leaf) {
if (nv_collide_aabb_x_aabb(node->aabb, aabb)) {
@@ -149,23 +152,23 @@ nvArray *nvBVHNode_collide(nvBVHNode *node, nvAABB aabb, bool *is_combined) {
}
if (nv_collide_aabb_x_aabb(node->aabb, aabb)) {
- bool is_left_combined;
- bool is_right_combined;
+ nv_bool is_left_combined;
+ nv_bool is_right_combined;
nvArray *left = nvBVHNode_collide(node->left, aabb, &is_left_combined);
nvArray *right = nvBVHNode_collide(node->right, aabb, &is_right_combined);
- if (left == NULL) {
+ if (!left) {
if (is_right_combined) *is_combined = true;
return right;
}
- else if (right == NULL) {
+ else if (!right) {
if (is_left_combined) *is_combined = true;
return left;
}
else {
- nvArray* combined = nvArray_new();
+ nvArray *combined = nvArray_new();
for (size_t i = 0; i < left->size; i++)
nvArray_add(combined, left->data[i]);
@@ -185,7 +188,7 @@ nvArray *nvBVHNode_collide(nvBVHNode *node, nvAABB aabb, bool *is_combined) {
}
size_t nvBVHNode_size(nvBVHNode *node) {
- if (node == NULL) return 0;
+ if (!node) return 0;
if (node->is_leaf) return 0;
else {
size_t a = nvBVHNode_size(node->left);
@@ -208,5 +211,5 @@ void nvBVHTree_free(nvBVHNode *root) {
nvBVHNode_free(root->left);
nvBVHNode_free(root->right);
- free(root);
+ NV_FREE(root);
}
\ No newline at end of file
diff --git a/src/collision.c b/src/collision.c
index f57e4c2..4914eca 100644
--- a/src/collision.c
+++ b/src/collision.c
@@ -8,10 +8,8 @@
*/
-#include
-#include
#include "novaphysics/collision.h"
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
#include "novaphysics/math.h"
#include "novaphysics/constants.h"
#include "novaphysics/aabb.h"
@@ -20,231 +18,732 @@
/**
* @file collision.c
*
- * @brief Collision detection functions.
+ * @brief Collision detection and contact point generation functions.
*/
-nvResolution nv_collide_circle_x_circle(nvBody *a, nvBody *b) {
- nvResolution res = {
- .collision = false,
- .a = a,
- .b = b,
- .normal = nvVector2_zero,
- .depth = 0.0
+nvPersistentContactPair nv_collide_circle_x_circle(
+ nvShape *circle_a,
+ nvTransform xform_a,
+ nvShape *circle_b,
+ nvTransform xform_b
+) {
+ nvPersistentContactPair pcp = {
+ .contact_count = 0,
+ .normal = nvVector2_zero
};
- nv_float dist2 = nvVector2_dist2(b->position, a->position);
- nv_float dist = nv_sqrt(dist2);
- nv_float radii = a->shape->radius + b->shape->radius;
- nv_float radii2 = radii * radii;
+ // Transform circle centers
+ nvVector2 ca = nvVector2_add(nvVector2_rotate(circle_a->circle.center, xform_a.angle), xform_a.position);
+ nvVector2 cb = nvVector2_add(nvVector2_rotate(circle_b->circle.center, xform_b.angle), xform_b.position);
+
+ nvVector2 delta = nvVector2_sub(cb, ca);
+ nv_float dist = nvVector2_len(delta);
+ nv_float radii = circle_a->circle.radius + circle_b->circle.radius;
+
+ // Distance is over radii combined, not colliding
+ if (dist > radii) return pcp;
+
+ if (dist == 0.0)
+ pcp.normal = NV_DEGENERATE_NORMAL;
+ else
+ pcp.normal = nvVector2_div(delta, dist);
+
+ // Midway contact
+ nvVector2 a_support = nvVector2_add(ca, nvVector2_mul(pcp.normal, circle_a->circle.radius));
+ nvVector2 b_support = nvVector2_add(cb, nvVector2_mul(pcp.normal, -circle_b->circle.radius));
+ nvVector2 contact = nvVector2_mul(nvVector2_add(a_support, b_support), 0.5);
+
+ pcp.contact_count = 1;
+ pcp.contacts[0].separation = -(radii - dist);
+ pcp.contacts[0].id = 0;
+ pcp.contacts[0].anchor_a = nvVector2_sub(contact, xform_a.position);
+ pcp.contacts[0].anchor_b = nvVector2_sub(contact, xform_b.position);
+ pcp.contacts[0].is_persisted = false;
+ pcp.contacts[0].remove_invoked = false;
+ pcp.contacts[0].solver_info = nvContactSolverInfo_zero;
+
+ return pcp;
+}
- // Circles aren't colliding
- if (dist2 >= radii2) return res;
+nv_bool nv_collide_circle_x_point(
+ nvShape *circle,
+ nvTransform xform,
+ nvVector2 point
+) {
+ nvVector2 c = nvVector2_add(xform.position, nvVector2_rotate(circle->circle.center, xform.angle));
+ nvVector2 delta = nvVector2_sub(c, point);
+ return nvVector2_len2(delta) <= circle->circle.radius * circle->circle.radius;
+}
- res.collision = true;
+/**
+ * @brief Project circle onto axis and return extreme points.
+ */
+static inline void nv_project_circle(
+ nvVector2 center,
+ nv_float radius,
+ nvVector2 axis,
+ nv_float *min_out,
+ nv_float *max_out
+) {
+ nvVector2 a = nvVector2_mul(nvVector2_normalize(axis), radius);
+
+ nvVector2 p1 = nvVector2_add(center, a);
+ nvVector2 p2 = nvVector2_sub(center, a);
+
+ nv_float min = nvVector2_dot(p1, axis);
+ nv_float max = nvVector2_dot(p2, axis);
+
+ if (min > max) {
+ nv_float temp = max;
+ max = min;
+ min = temp;
+ }
- nvVector2 normal = nvVector2_sub(b->position, a->position);
- // If the bodies are in the exact same position, direct the normal upwards
- if (nvVector2_len2(normal) == 0.0) normal = NV_VEC2(0.0, 1.0);
- else normal = nvVector2_normalize(normal);
+ *min_out = min;
+ *max_out = max;
+}
- res.normal = normal;
- res.depth = radii - dist;
+/**
+ * @brief Project polygon onto axis and return extreme points.
+ */
+static inline void nv_project_polyon(
+ nvVector2 *vertices,
+ size_t num_vertices,
+ nvVector2 axis,
+ nv_float *min_out,
+ nv_float *max_out
+) {
+ nv_float min = NV_INF;
+ nv_float max = -NV_INF;
+
+ for (size_t i = 0; i < num_vertices; i++) {
+ nv_float projection = nvVector2_dot(vertices[i], axis);
+
+ if (projection < min) min = projection;
+
+ if (projection > max) max = projection;
+ }
- return res;
+ *min_out = min;
+ *max_out = max;
}
-bool nv_collide_circle_x_point(nvBody *circle, nvVector2 point) {
- return nvVector2_len2(
- nvVector2_sub(circle->position, point)) <= circle->shape->radius * circle->shape->radius;
+/**
+ * @brief Find closest vertex of the polygon to the circle.
+ */
+static inline nvVector2 nv_polygon_closest_vertex_to_circle(
+ nvVector2 center,
+ nvVector2 *vertices,
+ size_t num_vertices
+) {
+ size_t closest = 0;
+ nv_float min_dist = NV_INF;
+
+ for (size_t i = 0; i < num_vertices; i++) {
+ nv_float dist = nvVector2_dist2(vertices[i], center);
+
+ if (dist < min_dist) {
+ min_dist = dist;
+ closest = i;
+ }
+ }
+
+ return vertices[closest];
}
+/**
+ * @brief Perpendicular distance between point and line segment.
+ */
+static inline void nv_point_segment_dist(
+ nvVector2 center,
+ nvVector2 a,
+ nvVector2 b,
+ nv_float *dist_out,
+ nvVector2 *contact_out
+) {
+ nvVector2 ab = nvVector2_sub(b, a);
+ nvVector2 ap = nvVector2_sub(center, a);
+
+ nv_float projection = nvVector2_dot(ap, ab);
+ nv_float ab_len = nvVector2_len2(ab);
+ nv_float dist = projection / ab_len;
+ nvVector2 contact;
-nvResolution nv_collide_polygon_x_circle(nvBody *polygon, nvBody *circle) {
- nvResolution res = {
- .collision = false,
- .a = polygon,
- .b = circle,
- .normal = nvVector2_zero,
- .depth = NV_INF
- };
+ if (dist <= 0.0) contact = a;
- nvBody_local_to_world(polygon);
- nvArray *vertices = polygon->shape->trans_vertices;
+ else if (dist >= 1.0) contact = b;
- size_t n = vertices->size;
+ else contact = nvVector2_add(a, nvVector2_mul(ab, dist));
+
+ *dist_out = nvVector2_dist2(center, contact);
+ *contact_out = contact;
+}
+
+nvPersistentContactPair nv_collide_polygon_x_circle(
+ nvShape *polygon,
+ nvTransform xform_poly,
+ nvShape *circle,
+ nvTransform xform_circle,
+ nv_bool flip_anchors
+) {
+ nvPolygon poly = polygon->polygon;
+ nvCircle circ = circle->circle;
+ nvPolygon_transform(polygon, xform_poly);
+ nvVector2 p = nv_polygon_centroid(poly.xvertices, poly.num_vertices);
+ nvVector2 c = nvVector2_add(xform_circle.position, nvVector2_rotate(circ.center, xform_circle.angle));
+ size_t n = poly.num_vertices;
+ nvVector2 *vertices = poly.xvertices;
+ nv_float separation = NV_INF;
+ nvVector2 normal = nvVector2_zero;
+
+ nvPersistentContactPair pcp = {
+ .contact_count = 0,
+ .normal = nvVector2_zero
+ };
nv_float min_a, min_b, max_a, max_b;
+ // Check each axes of polygon edges x circle
+
for (size_t i = 0; i < n; i++) {
- nvVector2 va = NV_TO_VEC2(vertices->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices->data[(i + 1) % n]);
+ nvVector2 va = vertices[i];
+ nvVector2 vb = vertices[(i + 1) % n];
nvVector2 edge = nvVector2_sub(vb, va);
nvVector2 axis = nvVector2_normalize(nvVector2_perp(edge));
- nv_project_polyon(vertices, axis, &min_a, &max_a);
- nv_project_circle(circle->position, circle->shape->radius, axis, &min_b, &max_b);
+ nv_project_polyon(vertices, n, axis, &min_a, &max_a);
+ nv_project_circle(c, circ.radius, axis, &min_b, &max_b);
// Doesn't collide
if (min_a >= max_b || min_b >= max_a) {
- return res;
+ return pcp;
}
nv_float axis_depth = nv_fmin(max_b - min_a, max_a - min_b);
- if (axis_depth < res.depth) {
- res.depth = axis_depth;
- res.normal = axis;
+ if (axis_depth < separation) {
+ separation = axis_depth;
+ normal = axis;
}
}
- nvVector2 cp = nv_polygon_closest_vertex_to_circle(circle->position, vertices);
-
- nvVector2 axis = nvVector2_normalize(nvVector2_sub(cp, circle->position));
+ nvVector2 cp = nv_polygon_closest_vertex_to_circle(c, vertices, n);
+ nvVector2 axis = nvVector2_normalize(nvVector2_sub(cp, c));
- nv_project_polyon(vertices, axis, &min_a, &max_a);
- nv_project_circle(circle->position, circle->shape->radius, axis, &min_b, &max_b);
+ nv_project_polyon(vertices, n, axis, &min_a, &max_a);
+ nv_project_circle(c, circ.radius, axis, &min_b, &max_b);
// Doesn't collide
if (min_a >= max_b || min_b >= max_a) {
- return res;
+ return pcp;
}
nv_float axis_depth = nv_fmin(max_b - min_a, max_a - min_b);
- if (axis_depth < res.depth) {
- res.depth = axis_depth;
- res.normal = axis;
+ if (axis_depth < separation) {
+ separation = axis_depth;
+ normal = axis;
}
+ separation = -separation;
- nvVector2 direction = nvVector2_sub(polygon->position, circle->position);
+ // Flip normal
+ if (nvVector2_dot(nvVector2_sub(p, c), normal) > 0.0) {
+ normal = nvVector2_neg(normal);
+ }
+ if (flip_anchors) {
+ normal = nvVector2_neg(normal);
+ }
+
+ // Get the contact on the closest edge
+ nv_float dist;
+ nv_float min_dist = NV_INF;
+ nvVector2 contact;
+ nvVector2 new_contact;
+ for (size_t i = 0; i < n; i++) {
+ nvVector2 va = vertices[i];
+ nvVector2 vb = vertices[(i + 1) % n];
+
+ nv_point_segment_dist(c, va, vb, &dist, &new_contact);
+
+ if (dist < min_dist) {
+ min_dist = dist;
+ contact = new_contact;
+ }
+ }
+
+ // Midpoint contact
+ nvVector2 circle_contact = nvVector2_add(contact, nvVector2_mul(normal, separation));
+ nvVector2 half_contact = nvVector2_mul(nvVector2_add(contact, circle_contact), 0.5);
- if (nvVector2_dot(direction, res.normal) > 0.0)
- res.normal = nvVector2_neg(res.normal);
+ nvVector2 poly_anchor = nvVector2_sub(half_contact, xform_poly.position);
+ nvVector2 circle_anchor = nvVector2_sub(half_contact, xform_circle.position);
- res.collision = true;
+ pcp.normal = normal;
+ pcp.contact_count = 1;
+ pcp.contacts[0].id = 0;
+ pcp.contacts[0].is_persisted = false;
+ pcp.contacts[0].remove_invoked = false;
+ pcp.contacts[0].solver_info = nvContactSolverInfo_zero;
+ pcp.contacts[0].separation = separation;
+
+ if (flip_anchors) {
+ pcp.contacts[0].anchor_a = circle_anchor;
+ pcp.contacts[0].anchor_b = poly_anchor;
+ }
+ else {
+ pcp.contacts[0].anchor_a = poly_anchor;
+ pcp.contacts[0].anchor_b = circle_anchor;
+ }
- return res;
+ return pcp;
}
-nvResolution nv_collide_polygon_x_polygon(nvBody *a, nvBody *b) {
- nvResolution res = {
- .collision = false,
- .a = a,
- .b = b,
- .normal = nvVector2_zero,
- .depth = NV_INF
- };
- nvBody_local_to_world(a);
- nvBody_local_to_world(b);
- nvArray *vertices_a = a->shape->trans_vertices;
- nvArray *vertices_b = b->shape->trans_vertices;
- size_t na = vertices_a->size;
- size_t nb = vertices_b->size;
+static nvPersistentContactPair clip_polygons(
+ nvPolygon a,
+ nvPolygon b,
+ int edge_a,
+ int edge_b,
+ nv_bool flip
+) {
+ /*
+ https://box2d.org/files/ErinCatto_ContactManifolds_GDC2007.pdf
+ -
+ Also see nv_collide_polygon_x_polygon for the reference.
+ */
+
+ // Reference polygon
+ nvPolygon ref_polygon;
+ int i11, i12;
+
+ // Incident polygon
+ nvPolygon inc_polygon;
+ int i21, i22;
+
+ if (flip) {
+ ref_polygon = b;
+ inc_polygon = a;
+ i11 = edge_b;
+ i12 = edge_b + 1 < b.num_vertices ? edge_b + 1 : 0;
+ i21 = edge_a;
+ i22 = edge_a + 1 < a.num_vertices ? edge_a + 1 : 0;
+ }
+ else {
+ ref_polygon = a;
+ inc_polygon = b;
+ i11 = edge_a;
+ i12 = edge_a + 1 < a.num_vertices ? edge_a + 1 : 0;
+ i21 = edge_b;
+ i22 = edge_b + 1 < b.num_vertices ? edge_b + 1 : 0;
+ }
- size_t i;
+ nvVector2 normal = ref_polygon.normals[i11];
+ nvVector2 tangent = nvVector2_perp(normal);
+
+ // Reference edge vertices
+ nvVector2 v11 = ref_polygon.vertices[i11];
+ nvVector2 v12 = ref_polygon.vertices[i12];
+
+ // Incident edge vertices
+ nvVector2 v21 = inc_polygon.vertices[i21];
+ nvVector2 v22 = inc_polygon.vertices[i22];
+
+ nv_float lower1 = 0.0;
+ nv_float upper1 = nvVector2_dot(nvVector2_sub(v12, v11), tangent);
+ nv_float upper2 = nvVector2_dot(nvVector2_sub(v21, v11), tangent);
+ nv_float lower2 = nvVector2_dot(nvVector2_sub(v22, v11), tangent);
+ nv_float d = upper2 - lower2;
+
+ nvVector2 v_lower;
+ if (lower2 < lower1 && upper2 - lower2 > NV_FLOAT_EPSILON)
+ v_lower = nvVector2_lerp(v22, v21, (lower1 - lower2) / d);
+ else
+ v_lower = v22;
+
+ nvVector2 v_upper;
+ if (upper2 > upper1 && upper2 - lower2 > NV_FLOAT_EPSILON)
+ v_upper = nvVector2_lerp(v22, v21, (upper1 - lower2) / d);
+ else
+ v_upper = v21;
+
+ nv_float separation_lower = nvVector2_dot(nvVector2_sub(v_lower, v11), normal);
+ nv_float separation_upper = nvVector2_dot(nvVector2_sub(v_upper, v11), normal);
+
+ // Put contact points at midpoint
+ nv_float lower_mid_scale = -separation_lower * 0.5;
+ nv_float upper_mid_scale = -separation_upper * 0.5;
+ v_lower = NV_VECTOR2(
+ v_lower.x + lower_mid_scale * normal.x,
+ v_lower.y + lower_mid_scale * normal.y
+ );
+ v_upper = NV_VECTOR2(
+ v_upper.x + upper_mid_scale * normal.x,
+ v_upper.y + upper_mid_scale * normal.y
+ );
+
+ nvPersistentContactPair pcp;
+
+ if (!flip) {
+ pcp.normal = normal;
+
+ pcp.contacts[0].anchor_a = v_lower;
+ pcp.contacts[0].separation = separation_lower;
+ pcp.contacts[0].id = nv_u32pair(i11, i22);
+
+ pcp.contacts[1].anchor_a = v_upper;
+ pcp.contacts[1].separation = separation_upper;
+ pcp.contacts[1].id = nv_u32pair(i12, i21);
+
+ pcp.contact_count = 2;
+ }
+ else {
+ pcp.normal = nvVector2_neg(normal);
- nv_float min_a, max_a, min_b, max_b;
+ pcp.contacts[0].anchor_a = v_upper;
+ pcp.contacts[0].separation = separation_upper;
+ pcp.contacts[0].id = nv_u32pair(i21, i12);
- for (i = 0; i < na; i++) {
- nvVector2 va = NV_TO_VEC2(vertices_a->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices_a->data[(i + 1) % na]);
+ pcp.contacts[1].anchor_a = v_lower;
+ pcp.contacts[1].separation = separation_lower;
+ pcp.contacts[1].id = nv_u32pair(i22, i11);
- nvVector2 edge = nvVector2_sub(vb, va);
- nvVector2 axis = nvVector2_normalize(nvVector2_perpr(edge));
+ pcp.contact_count = 2;
+ }
- nv_project_polyon(vertices_a, axis, &min_a, &max_a);
- nv_project_polyon(vertices_b, axis, &min_b, &max_b);
+ return pcp;
+}
- // Doesn't collide
- if (min_a >= max_b || min_b >= max_a) {
- return res;
+static void find_max_separation(
+ int *edge,
+ nv_float *separation,
+ nvPolygon a,
+ nvPolygon b
+) {
+ /*
+ Find the max separation between two polygons using edge normals of first polygon.
+ See nv_collide_polygon_x_polygon for the reference.
+ */
+
+ int best_index = 0;
+ nv_float max_separation = -NV_INF;
+
+ for (int i = 0; i < a.num_vertices; i++) {
+ nvVector2 n = a.normals[i];
+ nvVector2 v1 = a.vertices[i];
+
+ nv_float si = NV_INF;
+ for (int j = 0; j < b.num_vertices; j++) {
+ nv_float sij = nvVector2_dot(n, nvVector2_sub(b.vertices[j], v1));
+ if (sij < si)
+ si = sij;
}
- nv_float axis_depth = nv_fmin(max_b - min_a, max_a - min_b);
-
- if (axis_depth < res.depth) {
- res.depth = axis_depth;
- res.normal = axis;
+ if (si > max_separation) {
+ max_separation = si;
+ best_index = i;
}
}
- for (i = 0; i < nb; i++) {
- nvVector2 va = NV_TO_VEC2(vertices_b->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices_b->data[(i + 1) % nb]);
+ *edge = best_index;
+ *separation = max_separation;
+}
- nvVector2 edge = nvVector2_sub(vb, va);
- nvVector2 axis = nvVector2_normalize(nvVector2_perpr(edge));
+static nvPersistentContactPair SAT(nvPolygon a, nvPolygon b) {
+ /*
+ See nv_collide_polygon_x_polygon for the reference.
+ */
- nv_project_polyon(vertices_a, axis, &min_a, &max_a);
- nv_project_polyon(vertices_b, axis, &min_b, &max_b);
+ nvPersistentContactPair pcp;
+ pcp.contact_count = 0;
+ pcp.normal = nvVector2_zero;
- // Doesn't collide
- if (min_a >= max_b || min_b >= max_a) {
- return res;
- }
+ int edge_a = 0;
+ nv_float separation_a;
+ find_max_separation(&edge_a, &separation_a, a, b);
- nv_float axis_depth = nv_fmin(max_b - min_a, max_a - min_b);
+ int edge_b = 0;
+ nv_float separation_b;
+ find_max_separation(&edge_b, &separation_b, b, a);
- if (axis_depth < res.depth) {
- res.depth = axis_depth;
- res.normal = axis;
+ // Shapes are only overlapping if both separations are negative
+ if (separation_a > 0.0 || separation_b > 0.0) return pcp;
+
+ nv_bool flip;
+
+ if (separation_b > separation_a) {
+ flip = true;
+ nvVector2 search_dir = b.normals[edge_b];
+ nv_float min_dot = NV_INF;
+ edge_a = 0;
+
+ // Find the incident edge on polygon A
+ for (int i = 0; i < a.num_vertices; i++) {
+ nv_float dot = nvVector2_dot(search_dir, a.normals[i]);
+ if (dot < min_dot) {
+ min_dot = dot;
+ edge_a = i;
+ }
+ }
+ }
+ else {
+ flip = false;
+ nvVector2 search_dir = a.normals[edge_a];
+ nv_float min_dot = NV_INF;
+ edge_b = 0;
+
+ // Find the incident edge on polygon B
+ for (int i = 0; i < b.num_vertices; i++) {
+ nv_float dot = nvVector2_dot(search_dir, b.normals[i]);
+ if (dot < min_dot) {
+ min_dot = dot;
+ edge_b = i;
+ }
}
}
- nvVector2 center_a = nvVector2_add(nv_polygon_centroid(a->shape->vertices), a->position);
- nvVector2 center_b = nvVector2_add(nv_polygon_centroid(b->shape->vertices), b->position);
+ return clip_polygons(a, b, edge_a, edge_b, flip);
+}
- if (nvVector2_dot(nvVector2_sub(center_b, center_a), res.normal) < 0.0)
- res.normal = nvVector2_neg(res.normal);
+nvPersistentContactPair nv_collide_polygon_x_polygon(
+ nvShape *polygon_a,
+ nvTransform xform_a,
+ nvShape *polygon_b,
+ nvTransform xform_b
+) {
+ /*
+ Box2D V3's one-shot contact point generation algorithm for convex polygons.
+ https://github.com/erincatto/box2c/blob/main/src/manifold.c
- res.collision = true;
+ Corner rounding and GJK is not included, Nova only uses SAT.
+ */
- return res;
-}
+ // TODO: Number of trig calls could definitely be lowered
+
+ nvPolygon a = polygon_a->polygon;
+ nvPolygon b = polygon_b->polygon;
+
+ nvVector2 origin = a.vertices[0];
+
+ // Shift polygon A to origin
+ nvTransform xform_a_translated = {
+ nvVector2_add(xform_a.position, nvVector2_rotate(origin, xform_a.angle)),
+ xform_a.angle
+ };
+ // Inverse multiply transforms
+ nvTransform xform;
+ {
+ nv_float sa = nv_sin(xform_a_translated.angle);
+ nv_float ca = nv_cos(xform_a_translated.angle);
+ nv_float sb = nv_sin(xform_b.angle);
+ nv_float cb = nv_cos(xform_b.angle);
+
+ // Inverse rotate
+ nvVector2 d = nvVector2_sub(xform_b.position, xform_a_translated.position);
+ nvVector2 p = NV_VECTOR2(ca * d.x + sa * d.y, -sa * d.x + ca * d.y);
+
+ // Inverse multiply rotations
+ nv_float is = ca * sb - sa * cb;
+ nv_float ic = ca * cb + sa * sb;
+ nv_float ia = nv_atan2(is, ic);
+
+ xform = (nvTransform){p, ia};
+ }
-bool nv_collide_polygon_x_point(nvBody *polygon, nvVector2 point) {
- // https://stackoverflow.com/a/48760556
+ nvPolygon a_local;
+ a_local.num_vertices = a.num_vertices;
+ a_local.vertices[0] = nvVector2_zero;
+ a_local.normals[0] = a.normals[0];
+ for (size_t i = 1; i < a_local.num_vertices; i++) {
+ a_local.vertices[i] = nvVector2_sub(a.vertices[i], origin);
+ a_local.normals[i] = a.normals[i];
+ }
- nvBody_local_to_world(polygon);
- nvArray *vertices = polygon->shape->trans_vertices;
+ nvPolygon b_local;
+ b_local.num_vertices = b.num_vertices;
+ for (size_t i = 0; i < b_local.num_vertices; i++) {
+ nvVector2 xv = nvVector2_add(nvVector2_rotate(b.vertices[i], xform.angle), xform.position);
- size_t n = vertices->size;
- size_t i = 0;
- size_t j = n - 1;
- bool inside = false;
+ b_local.vertices[i] = xv;
+ b_local.normals[i] = nvVector2_rotate(b.normals[i], xform.angle);
+ }
- while (i < n) {
- nvVector2 vi = NV_TO_VEC2(vertices->data[i]);
- nvVector2 vj = NV_TO_VEC2(vertices->data[j]);
+ nvPersistentContactPair pcp = SAT(a_local, b_local);
- nvVector2 diri = nvVector2_normalize(nvVector2_sub(vi, polygon->position));
- nvVector2 dirj = nvVector2_normalize(nvVector2_sub(vj, polygon->position));
+ if (pcp.contact_count > 0) {
+ pcp.normal = nvVector2_rotate(pcp.normal, xform_a.angle);
- vi = nvVector2_add(vi, nvVector2_mul(diri, 0.1));
- vj = nvVector2_add(vj, nvVector2_mul(dirj, 0.1));
+ for (size_t i = 0; i < pcp.contact_count; i++) {
+ nvContact *contact = &pcp.contacts[i];
- if ((vi.y > point.y) != (vj.y > point.y) && (point.x < (vj.x - vi.x) *
- (point.y - vi.y) / (vj.y - vi.y) + vi.x )) {
- inside = !inside;
- }
+ contact->anchor_a = nvVector2_rotate(
+ nvVector2_add(contact->anchor_a, origin), xform_a.angle);
+ contact->anchor_b = nvVector2_add(
+ contact->anchor_a, nvVector2_sub(xform_a.position, xform_b.position));
+ contact->is_persisted = false;
+ contact->remove_invoked = false;
- j = i;
- i += 1;
+ contact->solver_info = nvContactSolverInfo_zero;
+ }
}
- return inside;
+ return pcp;
+}
+
+nv_bool nv_collide_polygon_x_point(
+ nvShape *polygon,
+ nvTransform xform,
+ nvVector2 point
+) {
+ /*
+ Algorithm from "Real-Time Collision Detection", Christer Ericson
+ Chapter 5, Page 202
+ */
+
+ nvPolygon_transform(polygon, xform);
+ nvVector2 *vertices = polygon->polygon.xvertices;
+ size_t n = polygon->polygon.num_vertices;
+
+ // Do binary search over polygon vertices to find the fan triangle
+ // (v[0], v[low], v[high]) the point p lies within the near sides of
+ int low = 0;
+ int high = (int)n;
+ do {
+ int mid = (low + high) / 2;
+ if (nv_triangle_winding((nvVector2[3]){vertices[0], vertices[mid], point}) == 1)
+ low = mid;
+ else
+ high = mid;
+ } while (low + 1 < high);
+
+ // If point outside last (or first) edge, then it is not inside the n-gon
+ if (low == 0 || high == n) return false;
+
+ // p is inside the polygon if it is left of
+ // the directed edge from v[low] to v[high]
+ return nv_triangle_winding((nvVector2[3]){vertices[low], vertices[high], point}) == 1;
}
-bool nv_collide_aabb_x_aabb(nvAABB a, nvAABB b) {
+nv_bool nv_collide_aabb_x_aabb(nvAABB a, nvAABB b) {
return (!(a.max_x <= b.min_x || b.max_x <= a.min_x ||
a.max_y <= b.min_y || b.max_y <= a.min_y));
}
-bool nv_collide_aabb_x_point(nvAABB aabb, nvVector2 point) {
+nv_bool nv_collide_aabb_x_point(nvAABB aabb, nvVector2 point) {
return (aabb.min_x <= point.x && point.x <= aabb.max_x &&
aabb.min_y <= point.y && point.y <= aabb.max_y);
+}
+
+
+nv_bool nv_collide_ray_x_circle(
+ nvRayCastResult *result,
+ nvVector2 origin,
+ nvVector2 dir,
+ nv_float maxsq,
+ nvShape *shape,
+ nvTransform xform
+) {
+ // https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection.html
+
+ nvCircle circle = shape->circle;
+ nvVector2 center = nvVector2_add(nvVector2_rotate(circle.center, xform.angle), xform.position);
+ nv_float rsq = circle.radius * circle.radius;
+ nvVector2 delta = nvVector2_sub(center, origin);
+
+ nv_float tca = nvVector2_dot(delta, dir);
+ nv_float d2 = nvVector2_dot(delta, delta) - tca * tca;
+ if (d2 > rsq) return false;
+ nv_float thc = nv_sqrt(rsq - d2);
+ nv_float t0 = tca - thc;
+ nv_float t1 = tca + thc;
+
+ if (t0 > t1) {
+ nv_float temp = t0;
+ t0 = t1;
+ t1 = temp;
+ }
+
+ if (t0 < 0.0) {
+ t0 = t1;
+ if (t0 < 0.0) return false; // Intersection behind ray origin
+ }
+
+ nv_float t = t0;
+
+ nvVector2 hitpoint = nvVector2_add(origin, nvVector2_mul(dir, t));
+
+ // Out of ray's range
+ if (nvVector2_len2(nvVector2_sub(hitpoint, origin)) > maxsq) return false;
+
+ *result = (nvRayCastResult){
+ .position = hitpoint,
+ .normal = nvVector2_normalize(nvVector2_sub(hitpoint, center)),
+ .shape = shape
+ };
+ return true;
+}
+
+nv_bool nv_collide_ray_x_polygon(
+ nvRayCastResult *result,
+ nvVector2 origin,
+ nvVector2 dir,
+ nv_float maxsq,
+ nvShape *shape,
+ nvTransform xform
+) {
+ // https://rootllama.wordpress.com/2014/06/20/ray-line-segment-intersection-test-in-2d/
+ // https://stackoverflow.com/a/29020182
+
+ nvPolygon poly = shape->polygon;
+
+ nvVector2 hits[NV_POLYGON_MAX_VERTICES];
+ size_t normal_idxs[NV_POLYGON_MAX_VERTICES];
+ size_t hit_count = 0;
+
+ nvPolygon_transform(shape, xform);
+ for (size_t i = 0; i < poly.num_vertices; i++) {
+ nvVector2 va = poly.xvertices[i];
+ nvVector2 vb = poly.xvertices[(i + 1) % poly.num_vertices];
+
+ nvVector2 v1 = nvVector2_sub(origin, va);
+ nvVector2 v2 = nvVector2_sub(vb, va);
+ nvVector2 v3 = nvVector2_perp(dir);
+
+ nv_float dot = nvVector2_dot(v2, v3);
+ if (nv_fabs(dot) < NV_FLOAT_EPSILON) continue;;
+
+ nv_float t1 = nvVector2_cross(v2, v1) / dot;
+ nv_float t2 = nvVector2_dot(v1, v3) / dot;
+
+ if (t1 >= 0.0 && (t2 >= 0.0 && t2 <= 1.0)) {
+ hits[hit_count++] = nvVector2_add(origin, nvVector2_mul(dir, t1));
+ normal_idxs[hit_count - 1] = i;
+ }
+ }
+
+ if (hit_count == 0) return false;
+
+ nvVector2 closest_hit;
+ nvVector2 normal;
+ nv_float min_dist = NV_INF;
+ for (size_t i = 0; i < hit_count; i++) {
+ nv_float dist = nvVector2_len2(nvVector2_sub(hits[i], origin));
+ if (dist < min_dist) {
+ min_dist = dist;
+ closest_hit = hits[i];
+ normal = poly.normals[normal_idxs[i]];
+ }
+ }
+
+ // Out of ray's range
+ if (min_dist > maxsq) return false;
+
+ *result = (nvRayCastResult){
+ .position = closest_hit,
+ .normal = nvVector2_rotate(normal, xform.angle),
+ .shape = shape
+ };
+ return true;
}
\ No newline at end of file
diff --git a/src/constraint.c b/src/constraint.c
deleted file mode 100644
index dc02065..0000000
--- a/src/constraint.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/internal.h"
-#include "novaphysics/constraint.h"
-#include "novaphysics/space.h"
-#include "novaphysics/spring.h"
-#include "novaphysics/distance_joint.h"
-#include "novaphysics/hinge_joint.h"
-
-
-/**
- * @file constraint.c
- *
- * @brief Base constraint definition.
- */
-
-
-void nvConstraint_free(void *cons) {
- if (cons == NULL) return;
- nvConstraint *c = (nvConstraint *)cons;
-
- free(c->def);
- free(c);
-}
-
-void nvConstraint_presolve(
- nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-) {
- switch (cons->type) {
- case nvConstraintType_SPRING:
- nvSpring_presolve(space, cons, inv_dt);
- break;
-
- case nvConstraintType_DISTANCEJOINT:
- nvDistanceJoint_presolve(space, cons, inv_dt);
- break;
-
- case nvConstraintType_HINGEJOINT:
- nvHingeJoint_presolve(space, cons, inv_dt);
- break;
- }
-}
-
-
-void nvConstraint_solve(nvConstraint *cons, nv_float inv_dt) {
- switch (cons->type) {
-
- case nvConstraintType_SPRING:
- nvSpring_solve(cons);
- break;
-
- case nvConstraintType_DISTANCEJOINT:
- nvDistanceJoint_solve(cons);
- break;
-
- case nvConstraintType_HINGEJOINT:
- nvHingeJoint_solve(cons, inv_dt);
- break;
- }
-}
\ No newline at end of file
diff --git a/src/constraints/constraint.c b/src/constraints/constraint.c
new file mode 100644
index 0000000..5043b8f
--- /dev/null
+++ b/src/constraints/constraint.c
@@ -0,0 +1,84 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/internal.h"
+#include "novaphysics/constraints/constraint.h"
+#include "novaphysics/space.h"
+#include "novaphysics/constraints/distance_constraint.h"
+#include "novaphysics/constraints/hinge_constraint.h"
+#include "novaphysics/constraints/spline_constraint.h"
+
+
+/**
+ * @file constraints/constraint.c
+ *
+ * @brief Base constraint definition.
+ */
+
+
+void nvConstraint_free(nvConstraint *cons) {
+ if (!cons) return;
+
+ NV_FREE(cons->def);
+ NV_FREE(cons);
+}
+
+void nvConstraint_presolve(
+ nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+) {
+ switch (cons->type) {
+ case nvConstraintType_DISTANCE:
+ nvDistanceConstraint_presolve(space, cons, dt, inv_dt);
+ break;
+
+ case nvConstraintType_HINGE:
+ nvHingeConstraint_presolve(space, cons, dt, inv_dt);
+ break;
+
+ case nvConstraintType_SPLINE:
+ nvSplineConstraint_presolve(space, cons, dt, inv_dt);
+ break;
+ }
+}
+
+void nvConstraint_warmstart(nvSpace *space, nvConstraint *cons) {
+ switch (cons->type) {
+ case nvConstraintType_DISTANCE:
+ nvDistanceConstraint_warmstart(space, cons);
+ break;
+
+ case nvConstraintType_HINGE:
+ nvHingeConstraint_warmstart(space, cons);
+ break;
+
+ case nvConstraintType_SPLINE:
+ nvSplineConstraint_warmstart(space, cons);
+ break;
+ }
+}
+
+void nvConstraint_solve(nvConstraint *cons, nv_float inv_dt) {
+ switch (cons->type) {
+ case nvConstraintType_DISTANCE:
+ nvDistanceConstraint_solve(cons);
+ break;
+
+ case nvConstraintType_HINGE:
+ nvHingeConstraint_solve(cons, inv_dt);
+ break;
+
+ case nvConstraintType_SPLINE:
+ nvSplineConstraint_solve(cons);
+ break;
+ }
+}
\ No newline at end of file
diff --git a/src/constraints/contact_constraint.c b/src/constraints/contact_constraint.c
new file mode 100644
index 0000000..aad9cbd
--- /dev/null
+++ b/src/constraints/contact_constraint.c
@@ -0,0 +1,223 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/internal.h"
+#include "novaphysics/constraints/contact_constraint.h"
+#include "novaphysics/vector.h"
+#include "novaphysics/math.h"
+#include "novaphysics/constants.h"
+#include "novaphysics/space.h"
+
+
+/**
+ * @file constraints/contact_constraint.c
+ *
+ * @brief Contact constraint solver functions.
+ */
+
+
+void nv_contact_presolve(
+ nvSpace *space,
+ nvPersistentContactPair *pcp,
+ nv_float inv_dt
+) {
+ NV_TRACY_ZONE_START;
+
+ nvRigidBody *a = pcp->body_a;
+ nvRigidBody *b = pcp->body_b;
+ nvVector2 normal = pcp->normal;
+ nvVector2 tangent = nvVector2_perpr(normal);
+
+ // Mixed restitution
+ nv_float e = nv_mix_coefficients(
+ a->material.restitution,
+ b->material.restitution,
+ space->settings.restitution_mix
+ );
+
+ // Mixed friction
+ nv_float friction = nv_mix_coefficients(
+ a->material.friction,
+ b->material.friction,
+ space->settings.friction_mix
+ );
+
+ for (size_t i = 0; i < pcp->contact_count; i++) {
+ nvContact *contact = &pcp->contacts[i];
+ if (contact->separation > 0.0) continue;
+ nvContactSolverInfo *solver_info = &contact->solver_info;
+
+ solver_info->friction = friction;
+
+ // Relative velocity at contact
+ nvVector2 rv = nv_calc_relative_velocity(
+ a->linear_velocity, a->angular_velocity, contact->anchor_a,
+ b->linear_velocity, b->angular_velocity, contact->anchor_b
+ );
+
+ // Restitution * normal velocity at first impact
+ nv_float vn = nvVector2_dot(rv, normal);
+
+ // Restitution bias
+ solver_info->velocity_bias = 0.0;
+ if (vn < -1.0) {
+ solver_info->velocity_bias = e * vn;
+ }
+
+ // Effective masses
+ solver_info->mass_normal = 1.0 / nv_calc_mass_k(
+ normal,
+ contact->anchor_a, contact->anchor_b,
+ a->invmass, b->invmass,
+ a->invinertia, b->invinertia
+ );
+ solver_info->mass_tangent = 1.0 / nv_calc_mass_k(
+ tangent,
+ contact->anchor_a, contact->anchor_b,
+ a->invmass, b->invmass,
+ a->invinertia, b->invinertia
+ );
+
+ if (space->settings.contact_position_correction == nvContactPositionCorrection_BAUMGARTE) {
+ // Position error is fed back to the velocity constraint as a bias value
+ nv_float correction = nv_fmin(contact->separation + space->settings.penetration_slop, 0.0);
+ solver_info->position_bias = space->settings.baumgarte * inv_dt * correction;
+
+ // Perfect restitution + baumgarte leads to overshooting
+ if (solver_info->velocity_bias < solver_info->position_bias)
+ solver_info->velocity_bias -= solver_info->position_bias;
+ }
+ else if (space->settings.contact_position_correction == nvContactPositionCorrection_NGS) {
+ }
+ }
+
+ NV_TRACY_ZONE_END;
+}
+
+void nv_contact_warmstart(nvSpace *space, nvPersistentContactPair *pcp) {
+ NV_TRACY_ZONE_START;
+
+ nvRigidBody *a = pcp->body_a;
+ nvRigidBody *b = pcp->body_b;
+ nvVector2 normal = pcp->normal;
+ nvVector2 tangent = nvVector2_perpr(normal);
+
+ for (size_t i = 0; i < pcp->contact_count; i++) {
+ nvContact *contact = &pcp->contacts[i];
+ if (contact->separation > 0.0) continue;
+ // No need to apply warmstarting if this contact is just created
+ if (!contact->is_persisted) continue;
+ nvContactSolverInfo *solver_info = &contact->solver_info;
+
+ if (space->settings.warmstarting) {
+ nvVector2 impulse = nvVector2_add(
+ nvVector2_mul(normal, solver_info->normal_impulse),
+ nvVector2_mul(tangent, solver_info->tangent_impulse)
+ );
+
+ nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), contact->anchor_a);
+ nvRigidBody_apply_impulse(b, impulse, contact->anchor_b);
+ }
+ else {
+ solver_info->normal_impulse = 0.0;
+ solver_info->tangent_impulse = 0.0;
+ }
+ }
+
+ NV_TRACY_ZONE_END;
+}
+
+void nv_contact_solve_velocity(nvPersistentContactPair *pcp) {
+ NV_TRACY_ZONE_START;
+
+ nvRigidBody *a = pcp->body_a;
+ nvRigidBody *b = pcp->body_b;
+ nvVector2 normal = pcp->normal;
+ nvVector2 tangent = nvVector2_perpr(normal);
+
+ /*
+ In an iterative solver what is applied the last affects the result more.
+ So we solve normal impulse after tangential impulse because
+ non-penetration is more important.
+ */
+
+ // Solve friction
+ for (size_t i = 0; i < pcp->contact_count; i++) {
+ nvContact *contact = &pcp->contacts[i];
+ //if (contact->separation > 0.0) continue;
+ nvContactSolverInfo *solver_info = &contact->solver_info;
+
+ // Don't bother calculating friction if the coefficent is 0
+ if (solver_info->friction == 0.0) continue;
+
+ // Relative velocity at contact
+ nvVector2 rv = nv_calc_relative_velocity(
+ a->linear_velocity, a->angular_velocity, contact->anchor_a,
+ b->linear_velocity, b->angular_velocity, contact->anchor_b
+ );
+
+ // Tangential impulse magnitude
+ nv_float lambda = -nvVector2_dot(rv, tangent) * solver_info->mass_tangent;
+
+ // Accumulate tangential impulse
+ nv_float f = solver_info->normal_impulse * solver_info->friction;
+ nv_float lambda0 = solver_info->tangent_impulse;
+ // Clamp lambda between friction limits
+ solver_info->tangent_impulse = nv_fmax(-f, nv_fmin(lambda0 + lambda, f));
+ lambda = solver_info->tangent_impulse - lambda0;
+
+ nvVector2 impulse = nvVector2_mul(tangent, lambda);
+
+ // Apply tangential impulse
+ nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), contact->anchor_a);
+ nvRigidBody_apply_impulse(b, impulse, contact->anchor_b);
+ }
+
+ // Solve penetration
+ for (size_t i = 0; i < pcp->contact_count; i++) {
+ nvContact *contact = &pcp->contacts[i];
+ if (contact->separation > 0.0) continue;
+ nvContactSolverInfo *solver_info = &contact->solver_info;
+
+ // Relative velocity at contact
+ nvVector2 rv = nv_calc_relative_velocity(
+ a->linear_velocity, a->angular_velocity, contact->anchor_a,
+ b->linear_velocity, b->angular_velocity, contact->anchor_b
+ );
+
+ nv_float vn = nvVector2_dot(rv, normal);
+
+ // Normal impulse magnitude
+ nv_float lambda = -(vn + solver_info->velocity_bias + solver_info->position_bias);
+ lambda *= solver_info->mass_normal;
+
+ // Accumulate normal impulse
+ nv_float lambda0 = solver_info->normal_impulse;
+ // Clamp lambda because we only want to solve penetration
+ solver_info->normal_impulse = nv_fmax(lambda0 + lambda, 0.0);
+ lambda = solver_info->normal_impulse - lambda0;
+
+ nvVector2 impulse = nvVector2_mul(normal, lambda);
+
+ // Apply normal impulse
+ nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), contact->anchor_a);
+ nvRigidBody_apply_impulse(b, impulse, contact->anchor_b);
+ }
+
+ NV_TRACY_ZONE_END;
+}
+
+void nv_contact_solve_position(nvPersistentContactPair *pcp) {
+ // TODO: Finish the NGS iterations early if there is no collision?
+
+ NV_TRACY_ZONE_START;
+
+ NV_TRACY_ZONE_END;
+}
\ No newline at end of file
diff --git a/src/constraints/distance_constraint.c b/src/constraints/distance_constraint.c
new file mode 100644
index 0000000..04fad56
--- /dev/null
+++ b/src/constraints/distance_constraint.c
@@ -0,0 +1,290 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/constraints/distance_constraint.h"
+#include "novaphysics/space.h"
+
+
+/**
+ * @file constraints/distance_constraint.c
+ *
+ * @brief Distance constraint solver.
+ */
+
+
+nvConstraint *nvDistanceConstraint_new(nvDistanceConstraintInitializer init) {
+ if (init.length < 0.0) {
+ nv_set_error("Distance constraint length can't be negative.");
+ return NULL;
+ }
+
+ nvConstraint *cons = NV_NEW(nvConstraint);
+ NV_MEM_CHECK(cons);
+
+ if (!init.a && !init.b) {
+ nv_set_error("Both bodies can't be NULL.");
+ NV_FREE(cons);
+ return NULL;
+ }
+
+ cons->a = init.a;
+ cons->b = init.b;
+ cons->type = nvConstraintType_DISTANCE;
+ cons->ignore_collision = false;
+
+ cons->def = NV_NEW(nvDistanceConstraint);
+ if (!cons->def) {
+ nv_set_error("Failed to allocate memory.");
+ NV_FREE(cons);
+ return NULL;
+ }
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+
+ dist_cons->length = init.length;
+ dist_cons->anchor_a = init.anchor_a;
+ dist_cons->anchor_b = init.anchor_b;
+ dist_cons->max_force = init.max_force;
+ dist_cons->spring = init.spring;
+ dist_cons->hertz = init.hertz;
+ dist_cons->damping = init.damping;
+
+ dist_cons->xanchor_a = nvVector2_zero;
+ dist_cons->xanchor_b = nvVector2_zero;
+ dist_cons->normal = nvVector2_zero;
+ dist_cons->bias = 0.0;
+ dist_cons->mass = 0.0;
+ dist_cons->impulse = 0.0;
+ dist_cons->max_impulse = 0.0;
+ dist_cons->bias_rate = 0.0;
+ dist_cons->mass_coeff = 0.0;
+ dist_cons->impulse_coeff = 0.0;
+
+ return cons;
+}
+
+nvRigidBody *nvDistanceConstraint_get_body_a(const nvConstraint *cons) {
+ return cons->a;
+}
+
+nvRigidBody *nvDistanceConstraint_get_body_b(const nvConstraint *cons) {
+ return cons->b;
+}
+
+void nvDistanceConstraint_set_length(nvConstraint *cons, nv_float length) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->length = length;
+}
+
+nv_float nvDistanceConstraint_get_length(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->length;
+}
+
+void nvDistanceConstraint_set_anchor_a(nvConstraint *cons, nvVector2 anchor_a) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->anchor_a = anchor_a;
+}
+
+nvVector2 nvDistanceConstraint_get_anchor_a(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->anchor_a;
+}
+
+void nvDistanceConstraint_set_anchor_b(nvConstraint *cons, nvVector2 anchor_b) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->anchor_b = anchor_b;
+}
+
+nvVector2 nvDistanceConstraint_get_anchor_b(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->anchor_b;
+}
+
+void nvDistanceConstraint_set_max_force(nvConstraint *cons, nv_float max_force) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->max_force = max_force;
+}
+
+nv_float nvDistanceConstraint_get_max_force(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->max_force;
+}
+
+void nvDistanceConstraint_set_spring(nvConstraint *cons, nv_bool spring) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->spring = true;
+}
+
+nv_bool nvDistanceConstraint_get_spring(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->spring;
+}
+
+void nvDistanceConstraint_set_hertz(nvConstraint *cons, nv_float hertz) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->hertz = hertz;
+}
+
+nv_float nvDistanceConstraint_get_hertz(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->hertz;
+}
+
+void nvDistanceConstraint_set_damping(nvConstraint *cons, nv_float damping) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ dist_cons->damping = damping;
+}
+
+nv_float nvDistanceConstraint_get_damping(const nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ return dist_cons->damping;
+}
+
+void nvDistanceConstraint_presolve(
+ nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+ nvRigidBody *b = cons->b;
+
+ // Transformed anchor points
+ nvVector2 rpa, rpb;
+ nv_float invmass_a, invmass_b, invinertia_a, invinertia_b;
+
+ // If a body is NULL count them as static bodies
+
+ if (!a) {
+ dist_cons->xanchor_a = nvVector2_zero;
+ rpa = dist_cons->anchor_a;
+ invmass_a = invinertia_a = 0.0;
+ } else {
+ dist_cons->xanchor_a = nvVector2_rotate(dist_cons->anchor_a, a->angle);
+ rpa = nvVector2_add(dist_cons->xanchor_a, a->position);
+ invmass_a = a->invmass;
+ invinertia_a = a->invinertia;
+ }
+
+ if (!b) {
+ dist_cons->xanchor_b = nvVector2_zero;
+ rpb = dist_cons->anchor_b;
+ invmass_b = invinertia_b = 0.0;
+ } else {
+ dist_cons->xanchor_b = nvVector2_rotate(dist_cons->anchor_b, b->angle);
+ rpb = nvVector2_add(dist_cons->xanchor_b, b->position);
+ invmass_b = b->invmass;
+ invinertia_b = b->invinertia;
+ }
+
+ nvVector2 delta = nvVector2_sub(rpb, rpa);
+ dist_cons->normal = nvVector2_normalize(delta);
+ nv_float offset = nvVector2_len(delta) - dist_cons->length;
+
+ // Baumgarte stabilization bias
+ dist_cons->bias = space->settings.baumgarte * inv_dt * offset;
+
+ // Constraint effective mass
+ dist_cons->mass = 1.0 / nv_calc_mass_k(
+ dist_cons->normal,
+ dist_cons->xanchor_a, dist_cons->xanchor_b,
+ invmass_a, invmass_b,
+ invinertia_a, invinertia_b
+ );
+
+ dist_cons->max_impulse = dist_cons->max_force * dt;
+
+ /*
+ Soft-constraint formulation
+ https://box2d.org/files/ErinCatto_SoftConstraints_GDC2011.pdf
+ https://box2d.org/posts/2024/02/solver2d/
+ */
+ if (dist_cons->spring) {
+ nv_float zeta = dist_cons->damping;
+ nv_float omega = 2.0 * NV_PI * dist_cons->hertz;
+ nv_float a1 = 2.0 * zeta + omega * (1.0 / inv_dt);
+ nv_float a2 = (1.0 / inv_dt) * omega * a1;
+ nv_float a3 = 1.0 / (1.0 + a2);
+ dist_cons->bias_rate = omega / a1;
+ dist_cons->mass_coeff = a2 * a3;
+ dist_cons->impulse_coeff = a3;
+ }
+ else {
+ dist_cons->bias_rate = 1.0;
+ dist_cons->mass_coeff = 1.0;
+ dist_cons->impulse_coeff = 0.0;
+ }
+}
+
+void nvDistanceConstraint_warmstart(nvSpace *space, nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+ nvRigidBody *b = cons->b;
+
+ if (space->settings.warmstarting) {
+ nvVector2 impulse = nvVector2_mul(dist_cons->normal, dist_cons->impulse);
+
+ if (a) nvRigidBody_apply_impulse(cons->a, nvVector2_neg(impulse), dist_cons->xanchor_a);
+ if (b) nvRigidBody_apply_impulse(cons->b, impulse, dist_cons->xanchor_b);
+ }
+ else {
+ dist_cons->impulse = 0.0;
+ }
+}
+
+void nvDistanceConstraint_solve(nvConstraint *cons) {
+ nvDistanceConstraint *dist_cons = (nvDistanceConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+ nvRigidBody *b = cons->b;
+
+ nvVector2 linear_velocity_a, linear_velocity_b;
+ nv_float angular_velocity_a, angular_velocity_b;
+
+ if (!a) {
+ linear_velocity_a = nvVector2_zero;
+ angular_velocity_a = 0.0;
+ } else {
+ linear_velocity_a = a->linear_velocity;
+ angular_velocity_a = a->angular_velocity;
+ }
+
+ if (!b) {
+ linear_velocity_b = nvVector2_zero;
+ angular_velocity_b = 0.0;
+ } else {
+ linear_velocity_b = b->linear_velocity;
+ angular_velocity_b = b->angular_velocity;
+ }
+
+ nvVector2 rv = nv_calc_relative_velocity(
+ linear_velocity_a, angular_velocity_a, dist_cons->xanchor_a,
+ linear_velocity_b, angular_velocity_b, dist_cons->xanchor_b
+ );
+
+ nv_float vn = nvVector2_dot(rv, dist_cons->normal);
+
+ // Constraint impulse magnitude
+ nv_float lambda = (dist_cons->bias * dist_cons->bias_rate + vn);
+ lambda *= dist_cons->mass * -dist_cons->mass_coeff;
+ lambda -= dist_cons->impulse_coeff * dist_cons->impulse;
+
+ // Accumulate impulse
+ nv_float limit = dist_cons->max_impulse;
+ nv_float lambda0 = dist_cons->impulse;
+ dist_cons->impulse = nv_fclamp(lambda0 + lambda, -limit, limit);
+ lambda = dist_cons->impulse - lambda0;
+
+ nvVector2 impulse = nvVector2_mul(dist_cons->normal, lambda);
+
+ // Apply constraint impulse
+ if (a) nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), dist_cons->xanchor_a);
+ if (b) nvRigidBody_apply_impulse(b, impulse, dist_cons->xanchor_b);
+}
\ No newline at end of file
diff --git a/src/constraints/hinge_constraint.c b/src/constraints/hinge_constraint.c
new file mode 100644
index 0000000..6d476dd
--- /dev/null
+++ b/src/constraints/hinge_constraint.c
@@ -0,0 +1,349 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/constraints/hinge_constraint.h"
+#include "novaphysics/space.h"
+
+
+/**
+ * @file constraints/hinge_constraint.c
+ *
+ * @brief Hinge constraint solver.
+ */
+
+
+nvConstraint *nvHingeConstraint_new(nvHingeConstraintInitializer init) {
+ nvConstraint *cons = NV_NEW(nvConstraint);
+ NV_MEM_CHECK(cons);
+
+ if (!init.a && !init.b) {
+ nv_set_error("Both bodies can't be NULL.");
+ NV_FREE(cons);
+ return NULL;
+ }
+
+ cons->a = init.a;
+ cons->b = init.b;
+ cons->type = nvConstraintType_HINGE;
+ cons->ignore_collision = false;
+
+ cons->def = NV_NEW(nvHingeConstraint);
+ if (!cons->def) {
+ nv_set_error("Failed to allocate memory.");
+ NV_FREE(cons);
+ return NULL;
+ }
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+
+ hinge_cons->anchor = init.anchor;
+ hinge_cons->enable_limits = init.enable_limits;
+ hinge_cons->lower_limit = init.lower_limit;
+ hinge_cons->upper_limit = init.upper_limit;
+ hinge_cons->max_force = init.max_force;
+ hinge_cons->angle = 0.0;
+
+ nv_float angle_a, angle_b;
+ if (init.a) {
+ hinge_cons->anchor_a = nvVector2_sub(init.anchor, init.a->position);
+ angle_a = init.a->angle;
+ }
+ else {
+ hinge_cons->anchor_a = init.anchor;
+ angle_a = 0.0;
+ }
+ if (init.b) {
+ hinge_cons->anchor_b = nvVector2_sub(init.anchor, init.b->position);
+ angle_b = init.b->angle;
+ }
+ else {
+ hinge_cons->anchor_b = init.anchor;
+ angle_b = 0.0;
+ }
+
+ hinge_cons->reference_angle = angle_b - angle_a;
+ hinge_cons->lower_impulse = 0.0;
+ hinge_cons->upper_impulse = 0.0;
+ hinge_cons->lower_bias = 0.0;
+ hinge_cons->upper_bias = 0.0;
+ hinge_cons->axial_mass = 0.0;
+ hinge_cons->xanchor_a = nvVector2_zero;
+ hinge_cons->xanchor_b = nvVector2_zero;
+ hinge_cons->normal = nvVector2_zero;
+ hinge_cons->bias = 0.0;
+ hinge_cons->mass = 0.0;
+ hinge_cons->impulse = 0.0;
+ hinge_cons->max_impulse = 0.0;
+
+ return cons;
+}
+
+nvRigidBody *nvHingeConstraint_get_body_a(const nvConstraint *cons) {
+ return cons->a;
+}
+
+nvRigidBody *nvHingeConstraint_get_body_b(const nvConstraint *cons) {
+ return cons->b;
+}
+
+void nvHingeConstraint_set_anchor(nvConstraint *cons, nvVector2 anchor) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ hinge_cons->anchor = anchor;
+
+ if (cons->a) {
+ hinge_cons->anchor_a = nvVector2_sub(hinge_cons->anchor, cons->a->position);
+ }
+ else {
+ hinge_cons->anchor_a = hinge_cons->anchor;
+ }
+ if (cons->b) {
+ hinge_cons->anchor_b = nvVector2_sub(hinge_cons->anchor, cons->b->position);
+ }
+ else {
+ hinge_cons->anchor_b = hinge_cons->anchor;
+ }
+}
+
+nvVector2 nvHingeConstraint_get_anchor(const nvConstraint *cons) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ return hinge_cons->anchor;
+}
+
+void nvHingeConstraint_set_limits(nvConstraint *cons, nv_bool limits) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ hinge_cons->enable_limits = limits;
+}
+
+nv_bool nvHingeConstraint_get_limits(const nvConstraint *cons) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ return hinge_cons->enable_limits;
+}
+
+void nvHingeConstraint_set_upper_limit(nvConstraint *cons, nv_float upper_limit) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ hinge_cons->upper_limit = upper_limit;
+}
+
+nv_float nvHingeConstraint_get_upper_limit(const nvConstraint *cons) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ return hinge_cons->upper_limit;
+}
+
+void nvHingeConstraint_set_lower_limit(nvConstraint *cons, nv_float lower_limit) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ hinge_cons->lower_limit = lower_limit;
+}
+
+nv_float nvHingeConstraint_get_lower_limit(const nvConstraint *cons) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ return hinge_cons->lower_limit;
+}
+
+void nvHingeConstraint_set_max_force(nvConstraint *cons, nv_float max_force) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ hinge_cons->max_force = max_force;
+}
+
+nv_float nvHingeConstraint_get_max_force(const nvConstraint *cons) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ return hinge_cons->max_force;
+}
+
+void nvHingeConstraint_presolve(
+ nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+ nvRigidBody *b = cons->b;
+
+ // Transformed anchor points
+ nvVector2 rpa, rpb;
+ nv_float invmass_a, invmass_b, invinertia_a, invinertia_b;
+
+ // If a body is NULL count them as static bodies
+
+ if (!a) {
+ hinge_cons->xanchor_a = nvVector2_zero;
+ rpa = hinge_cons->anchor_a;
+ invmass_a = invinertia_a = 0.0;
+ } else {
+ hinge_cons->xanchor_a = nvVector2_rotate(hinge_cons->anchor_a, a->angle);
+ rpa = nvVector2_add(hinge_cons->xanchor_a, a->position);
+ invmass_a = a->invmass;
+ invinertia_a = a->invinertia;
+ }
+
+ if (!b) {
+ hinge_cons->xanchor_b = nvVector2_zero;
+ rpb = hinge_cons->anchor_b;
+ invmass_b = invinertia_b = 0.0;
+ } else {
+ hinge_cons->xanchor_b = nvVector2_rotate(hinge_cons->anchor_b, b->angle);
+ rpb = nvVector2_add(hinge_cons->xanchor_b, b->position);
+ invmass_b = b->invmass;
+ invinertia_b = b->invinertia;
+ }
+
+ // If delta is 0 point constraint is ensured
+ nvVector2 delta = nvVector2_sub(rpb, rpa);
+ if (nvVector2_len2(delta) == 0.0) hinge_cons->normal = nvVector2_zero;
+ else hinge_cons->normal = nvVector2_normalize(delta);
+ nv_float offset = nvVector2_len(delta);
+
+ // Baumgarte position correction bias
+ hinge_cons->bias = space->settings.baumgarte * inv_dt * offset;
+
+ // Point constraint effective mass
+ hinge_cons->mass = 1.0 / nv_calc_mass_k(
+ hinge_cons->normal,
+ hinge_cons->xanchor_a, hinge_cons->xanchor_b,
+ invmass_a, invmass_b,
+ invinertia_a, invinertia_b
+ );
+
+ hinge_cons->max_impulse = hinge_cons->max_force * dt;
+
+ hinge_cons->axial_mass = 1.0 / (invinertia_a + invinertia_b);
+
+ nv_float angle_a, angle_b;
+ if (a) angle_a = a->angle;
+ else angle_a = 0.0;
+ if (b) angle_b = b->angle;
+ else angle_b = 0.0;
+
+ hinge_cons->angle = angle_b - angle_a - hinge_cons->reference_angle;
+
+ // Angular limit constraints
+ // C = θb - θa - θr - θl
+ // Cdot = wb - wa
+ // Jacobian = [1, -1]
+
+ nv_float lower_c = hinge_cons->angle - hinge_cons->lower_limit;
+ hinge_cons->lower_bias = nv_fmax(lower_c, 0.0) * space->settings.baumgarte * inv_dt;
+
+ nv_float upper_c = hinge_cons->upper_limit - hinge_cons->angle;
+ hinge_cons->upper_bias = nv_fmax(upper_c, 0.0) * 0.2 * inv_dt;
+}
+
+void nvHingeConstraint_warmstart(nvSpace *space, nvConstraint *cons) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+ nvRigidBody *b = cons->b;
+
+ if (space->settings.warmstarting) {
+ nvVector2 impulse = nvVector2_mul(hinge_cons->normal, hinge_cons->impulse);
+ nv_float axial_impulse = hinge_cons->lower_impulse - hinge_cons->upper_impulse;
+
+ if (a) {
+ nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), hinge_cons->xanchor_a);
+ a->angular_velocity -= a->invinertia * axial_impulse;
+ }
+ if (b) {
+ nvRigidBody_apply_impulse(b, impulse, hinge_cons->xanchor_b);
+ b->angular_velocity += b->invinertia * axial_impulse;
+ }
+
+ }
+ else {
+ hinge_cons->impulse = 0.0;
+ hinge_cons->upper_impulse = 0.0;
+ hinge_cons->lower_impulse = 0.0;
+ }
+}
+
+void nvHingeConstraint_solve(nvConstraint *cons, nv_float inv_dt) {
+ nvHingeConstraint *hinge_cons = (nvHingeConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+ nvRigidBody *b = cons->b;
+
+ // Solve angular limits
+ if (hinge_cons->enable_limits) {
+ nv_float cdot, wa, wb, lambda, lambda0;
+
+ if (a) wa = a->angular_velocity;
+ else wa = 0.0;
+ if (b) wb = b->angular_velocity;
+ else wb = 0.0;
+
+ // TODO: Calculate angular limit errors in presolve?
+
+ // Solve lower limit
+ cdot = wb - wa;
+ lambda = (cdot + hinge_cons->lower_bias) * -hinge_cons->axial_mass;
+
+ // Accumulate lower impulse
+ lambda0 = hinge_cons->lower_impulse;
+ hinge_cons->lower_impulse = nv_fmax(hinge_cons->lower_impulse + lambda, 0.0);
+ lambda = hinge_cons->lower_impulse - lambda0;
+
+ // Apply lower impulse
+ if (a) a->angular_velocity -= lambda * a->invinertia;
+ if (b) b->angular_velocity += lambda * b->invinertia;
+
+ // Solve upper limit
+ cdot = wa - wb;
+ lambda = (cdot + hinge_cons->upper_bias) * -hinge_cons->axial_mass;
+
+ // Accumulate upper impulse
+ lambda0 = hinge_cons->upper_impulse;
+ hinge_cons->upper_impulse = nv_fmax(hinge_cons->upper_impulse + lambda, 0.0);
+ lambda = hinge_cons->upper_impulse - lambda0;
+
+ // Apply upper impulse
+ if (a) a->angular_velocity += lambda * a->invinertia;
+ if (b) b->angular_velocity -= lambda * b->invinertia;
+ }
+
+ // Solve point constraint
+ // TODO: Skip if point constraint is ensured?
+
+ nvVector2 linear_velocity_a, linear_velocity_b;
+ nv_float angular_velocity_a, angular_velocity_b;
+
+ if (!a) {
+ linear_velocity_a = nvVector2_zero;
+ angular_velocity_a = 0.0;
+ } else {
+ linear_velocity_a = a->linear_velocity;
+ angular_velocity_a = a->angular_velocity;
+ }
+
+ if (!b) {
+ linear_velocity_b = nvVector2_zero;
+ angular_velocity_b = 0.0;
+ } else {
+ linear_velocity_b = b->linear_velocity;
+ angular_velocity_b = b->angular_velocity;
+ }
+
+ nvVector2 rv = nv_calc_relative_velocity(
+ linear_velocity_a, angular_velocity_a, hinge_cons->xanchor_a,
+ linear_velocity_b, angular_velocity_b, hinge_cons->xanchor_b
+ );
+
+ nv_float vn = nvVector2_dot(rv, hinge_cons->normal);
+
+ // Point constraint impulse magnitude
+ nv_float lambda = -(hinge_cons->bias + vn) * hinge_cons->mass;
+
+ // Accumulate impulse
+ nv_float limit = hinge_cons->max_impulse;
+ nv_float lambda0 = hinge_cons->impulse;
+ hinge_cons->impulse = nv_fclamp(lambda0 + lambda, -limit, limit);
+ lambda = hinge_cons->impulse - lambda0;
+
+ nvVector2 impulse = nvVector2_mul(hinge_cons->normal, lambda);
+
+ // Apply point constraint impulse
+ if (a) nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), hinge_cons->xanchor_a);
+ if (b) nvRigidBody_apply_impulse(b, impulse, hinge_cons->xanchor_b);
+}
\ No newline at end of file
diff --git a/src/constraints/spline_constraint.c b/src/constraints/spline_constraint.c
new file mode 100644
index 0000000..1417f83
--- /dev/null
+++ b/src/constraints/spline_constraint.c
@@ -0,0 +1,315 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/constraints/spline_constraint.h"
+#include "novaphysics/space.h"
+
+
+/**
+ * @file constraints/spline_constraint.c
+ *
+ * @brief Spline constraint solver.
+ */
+
+
+nvConstraint *nvSplineConstraint_new(nvSplineConstraintInitializer init) {
+ nvConstraint *cons = NV_NEW(nvConstraint);
+ NV_MEM_CHECK(cons);
+
+ if (!init.body) {
+ nv_set_error("The body can't be NULL.");
+ NV_FREE(cons);
+ return NULL;
+ }
+
+ cons->a = init.body;
+ cons->b = NULL;
+ cons->type = nvConstraintType_SPLINE;
+ cons->ignore_collision = false;
+
+ cons->def = NV_NEW(nvSplineConstraint);
+ if (!cons->def) {
+ nv_set_error("Failed to allocate memory.");
+ NV_FREE(cons);
+ return NULL;
+ }
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+
+ spline_cons->anchor_a = nvVector2_sub(init.anchor, init.body->position);
+ spline_cons->anchor_b = init.anchor;
+ spline_cons->max_force = init.max_force;
+
+ spline_cons->xanchor_a = nvVector2_zero;
+ spline_cons->xanchor_b = nvVector2_zero;
+ spline_cons->normal = nvVector2_zero;
+ spline_cons->bias = 0.0;
+ spline_cons->mass = 0.0;
+ spline_cons->impulse = 0.0;
+ spline_cons->max_impulse = 0.0;
+
+ return cons;
+}
+
+nvRigidBody *nvSplineConstraint_get_body(const nvConstraint *cons) {
+ return cons->a;
+}
+
+void nvSplineConstraint_set_anchor(nvConstraint *cons, nvVector2 anchor) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ spline_cons->anchor = anchor;
+
+ spline_cons->anchor_a = nvVector2_sub(spline_cons->anchor, cons->a->position);
+ spline_cons->anchor_b = spline_cons->anchor;
+}
+
+nvVector2 nvSplineConstraint_get_anchor(const nvConstraint *cons) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ return spline_cons->anchor;
+}
+
+void nvSplineConstraint_set_max_force(nvConstraint *cons, nv_float max_force) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ spline_cons->max_force = max_force;
+}
+
+nv_float nvSplineConstraint_get_max_force(const nvConstraint *cons) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ return spline_cons->max_force;
+}
+
+int nvSplineConstraint_set_control_points(
+ nvConstraint *cons,
+ nvVector2 *points,
+ size_t num_points
+) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+
+ if (num_points < 4) {
+ nv_set_error("Spline path needs at least 4 control points.");
+ return 1;
+ }
+
+ spline_cons->num_controls = num_points;
+ for (size_t i = 0; i < num_points; i++) {
+ spline_cons->controls[i] = points[i];
+ }
+
+ return 0;
+}
+
+nvVector2 *nvSplineConstraint_get_control_points(const nvConstraint *cons) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ return spline_cons->controls;
+}
+
+size_t nvSplineConstraint_get_number_of_control_points(const nvConstraint *cons) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ return spline_cons->num_controls;
+}
+
+static inline nvVector2 catmull_rom(
+ nvVector2 p0,
+ nvVector2 p1,
+ nvVector2 p2,
+ nvVector2 p3,
+ double t
+) {
+ nv_float t2 = t * t;
+ nv_float t3 = t2 * t;
+
+ double x = 0.5 * ((2.0 * p1.x) +
+ (-p0.x + p2.x) * t +
+ (2.0 * p0.x - 5.0 * p1.x + 4.0 * p2.x - p3.x) * t2 +
+ (-p0.x + 3.0 * p1.x - 3.0 * p2.x + p3.x) * t3);
+
+ double y = 0.5 * ((2 * p1.y) +
+ (-p0.y + p2.y) * t +
+ (2.0 * p0.y - 5.0 * p1.y + 4.0 * p2.y - p3.y) * t2 +
+ (-p0.y + 3.0 * p1.y - 3.0 * p2.y + p3.y) * t3);
+
+ return NV_VECTOR2(x, y);
+}
+
+static inline double gss_for_t(
+ nvVector2 p0,
+ nvVector2 p1,
+ nvVector2 p2,
+ nvVector2 p3,
+ nvVector2 p,
+ double tolerance
+) {
+ /*
+ Perform Golden-section search to find the closest t value to desired
+ point on the spline function.
+ https://en.wikipedia.org/wiki/Golden-section_search
+ */
+
+ // Start t range at [0, 1] and search iteratively
+ double a = 0.0;
+ double b = 1.0;
+ double t1 = b - (b - a) * NV_INV_PHI;
+ double t2 = a + (b - a) * NV_INV_PHI;
+
+ while (fabs(b - a) > tolerance) {
+ nvVector2 v1 = catmull_rom(p0, p1, p2, p3, t1);
+ nvVector2 v2 = catmull_rom(p0, p1, p2, p3, t2);
+
+ if (nvVector2_dist2(v1, p) < nvVector2_dist2(v2, p)) {
+ b = t2;
+ } else {
+ a = t1;
+ }
+
+ t1 = b - (b - a) * NV_INV_PHI;
+ t2 = a + (b - a) * NV_INV_PHI;
+ }
+
+ return (a + b) / 2.0;
+}
+
+static nvVector2 spline_closest(
+ nvSplineConstraint *spline,
+ nvVector2 point
+) {
+ nvVector2 *controls = spline->controls;
+ size_t num_controls = spline->num_controls;
+ size_t num_segments = num_controls - 3;
+
+ size_t sample_per_segment = NV_SPLINE_CONSTRAINT_SAMPLES / num_segments;
+
+ nvVector2 segment0;
+ nvVector2 segment1;
+ nvVector2 segment2;
+ nvVector2 segment3;
+ nv_float min_dist = NV_INF;
+
+ // Find the closest segment with sampling
+
+ for (size_t i = 0; i < num_segments; i++) {
+ for (size_t j = 0; j < sample_per_segment; j++) {
+ double t = (double)j / (double)(sample_per_segment - 1);
+ nvVector2 p0 = controls[i];
+ nvVector2 p1 = controls[i + 1];
+ nvVector2 p2 = controls[i + 2];
+ nvVector2 p3 = controls[i + 3];
+ nvVector2 p = catmull_rom(p0, p1, p2, p3, t);
+
+ nv_float dist = nvVector2_dist2(p, point);
+ if (dist < min_dist) {
+ min_dist = dist;
+ segment0 = p0;
+ segment1 = p1;
+ segment2 = p2;
+ segment3 = p3;
+ }
+ }
+ }
+
+ // Find the closest point with golden-section search on the segment
+
+ double t = gss_for_t(segment0, segment1, segment2, segment3, point, NV_SPLINE_CONSTRAINT_TOLERANCE);
+ return catmull_rom(segment0, segment1, segment2, segment3, t);
+}
+
+void nvSplineConstraint_presolve(
+ nvSpace *space,
+ nvConstraint *cons,
+ nv_float dt,
+ nv_float inv_dt
+) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+
+ // Transformed anchor points
+ nvVector2 rpa, rpb;
+ nv_float invmass_a, invmass_b, invinertia_a, invinertia_b;
+
+ spline_cons->xanchor_a = nvVector2_rotate(spline_cons->anchor_a, a->angle);
+ rpa = nvVector2_add(spline_cons->xanchor_a, a->position);
+ invmass_a = a->invmass;
+ invinertia_a = a->invinertia;
+
+ nvVector2 spline_point = spline_closest(spline_cons, rpa);
+
+ spline_cons->xanchor_b = nvVector2_zero;
+ rpb = spline_point;
+ invmass_b = invinertia_b = 0.0;
+
+ // If delta is 0 point constraint is ensured
+ nvVector2 delta = nvVector2_sub(rpb, rpa);
+ if (nvVector2_len2(delta) == 0.0) spline_cons->normal = nvVector2_zero;
+ else spline_cons->normal = nvVector2_normalize(delta);
+ nv_float offset = nvVector2_len(delta);
+
+ // Baumgarte stabilization bias
+ spline_cons->bias = space->settings.baumgarte * inv_dt * offset;
+
+ // Constraint effective mass
+ spline_cons->mass = 1.0 / nv_calc_mass_k(
+ spline_cons->normal,
+ spline_cons->xanchor_a, spline_cons->xanchor_b,
+ invmass_a, invmass_b,
+ invinertia_a, invinertia_b
+ );
+
+ spline_cons->max_impulse = spline_cons->max_force * dt;
+}
+
+void nvSplineConstraint_warmstart(nvSpace *space, nvConstraint *cons) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+
+ if (space->settings.warmstarting) {
+ nvVector2 impulse = nvVector2_mul(spline_cons->normal, spline_cons->impulse);
+
+ nvRigidBody_apply_impulse(cons->a, nvVector2_neg(impulse), spline_cons->xanchor_a);
+ }
+ else {
+ spline_cons->impulse = 0.0;
+ }
+}
+
+void nvSplineConstraint_solve(nvConstraint *cons) {
+ nvSplineConstraint *spline_cons = (nvSplineConstraint *)cons->def;
+ nvRigidBody *a = cons->a;
+
+ // Skip if constraint is already ensured
+ if (nvVector2_is_zero(spline_cons->normal))
+ return;
+
+ nvVector2 linear_velocity_a, linear_velocity_b;
+ nv_float angular_velocity_a, angular_velocity_b;
+
+ linear_velocity_a = a->linear_velocity;
+ angular_velocity_a = a->angular_velocity;
+
+ linear_velocity_b = nvVector2_zero;
+ angular_velocity_b = 0.0;
+
+ nvVector2 rv = nv_calc_relative_velocity(
+ linear_velocity_a, angular_velocity_a, spline_cons->xanchor_a,
+ linear_velocity_b, angular_velocity_b, spline_cons->xanchor_b
+ );
+
+ nv_float vn = nvVector2_dot(rv, spline_cons->normal);
+
+ // Constraint impulse magnitude
+ nv_float lambda = -(spline_cons->bias + vn) * spline_cons->mass;
+
+ // Accumulate impulse
+ nv_float limit = spline_cons->max_impulse;
+ nv_float lambda0 = spline_cons->impulse;
+ spline_cons->impulse = nv_fclamp(lambda0 + lambda, -limit, limit);
+ lambda = spline_cons->impulse - lambda0;
+
+ nvVector2 impulse = nvVector2_mul(spline_cons->normal, lambda);
+
+ // Apply constraint impulse
+ nvRigidBody_apply_impulse(a, nvVector2_neg(impulse), spline_cons->xanchor_a);
+}
\ No newline at end of file
diff --git a/src/contact.c b/src/contact.c
index 0790694..9235f05 100644
--- a/src/contact.c
+++ b/src/contact.c
@@ -8,319 +8,63 @@
*/
-#include "novaphysics/internal.h"
-#include "novaphysics/matrix.h"
#include "novaphysics/contact.h"
-#include "novaphysics/collision.h"
-#include "novaphysics/array.h"
-#include "novaphysics/constants.h"
-#include "novaphysics/math.h"
+#include "novaphysics/space.h"
/**
* @file contact.c
*
- * @brief Contact point calculation functions.
+ * @brief Collision and contact information.
*/
-void nv_contact_circle_x_circle(nvResolution *res) {
- nvVector2 dir = nvVector2_sub(res->b->position, res->a->position);
- // If the bodies are in the exact same position, direct the normal upwards
- if (nvVector2_len2(dir) == 0.0) dir = NV_VEC2(0.0, 1.0);
- dir = nvVector2_normalize(dir);
+nv_bool nvPersistentContactPair_penetrating(nvPersistentContactPair *pcp) {
+ nv_bool penetrating = false;
- nvVector2 ap = nvVector2_add(res->a->position, nvVector2_mul(dir, res->a->shape->radius));
- nvVector2 bp = nvVector2_add(res->b->position, nvVector2_mul(dir, -res->b->shape->radius));
- nvVector2 cp = nvVector2_mul(nvVector2_add(ap, bp), 0.5);
-
- res->contact_count = 1;
- res->contacts[0] = (nvContact){.position = cp};
-}
-
-void nv_contact_polygon_x_circle(nvResolution *res) {
- nvBody *polygon;
- nvBody *circle;
-
- if (res->a->shape->type == nvShapeType_POLYGON) {
- polygon = res->a;
- circle = res->b;
- } else {
- polygon = res->b;
- circle = res->a;
- }
-
- nvVector2 cp;
- nv_float min_dist = NV_INF;
-
- nvBody_local_to_world(polygon);
- nvArray *vertices = polygon->shape->trans_vertices;
- size_t n = vertices->size;
-
- nv_float dist;
- nvVector2 contact;
-
- for (size_t i = 0; i < n; i++) {
- nvVector2 va = NV_TO_VEC2(vertices->data[i]);
- nvVector2 vb = NV_TO_VEC2(vertices->data[(i + 1) % n]);
-
- nv_point_segment_dist(circle->position, va, vb, &dist, &contact);
-
- if (dist < min_dist) {
- min_dist = dist;
- cp = contact;
- }
- }
-
- res->contact_count = 1;
- res->contacts[0] = (nvContact){.position = cp};
-}
-
-
-nv_float _find_axis_least_penetration(
- size_t *face,
- nvBody *a,
- nvBody *b,
- nvMat2x2 au,
- nvMat2x2 bu
-) {
- nv_float best_depth = -NV_INF;
- size_t best_i = -1;
-
- for (size_t i = 0; i < a->shape->vertices->size; i++) {
-
- // Get face normal from body A
- nvVector2 n = NV_TO_VEC2(a->shape->normals->data[i]);
- nvVector2 nw = nvMat2x2_mulv(au, n);
-
- // Transform face normal into body B's model space
- nvMat2x2 b_ut = nvMat2x2_transpose(bu);
- n = nvMat2x2_mulv(b_ut, nw);
-
- // Get support point from body B along -n
- nvVector2 s = nv_polygon_support(b->shape->vertices, nvVector2_neg(n));
-
- // Get vertex on face from body A, transformed into body B's model space
- nvVector2 v = NV_TO_VEC2(a->shape->vertices->data[i]);
- v = nvVector2_add(nvMat2x2_mulv(au, v), a->position);
- v = nvVector2_sub(v, b->position);
- v = nvMat2x2_mulv(b_ut, v);
-
- // Compute penetration depth (in body B's model space)
- nv_float depth = nvVector2_dot(n, nvVector2_sub(s, v));
-
- if (depth > best_depth) {
- best_depth = depth;
- best_i = i;
- }
+ for (size_t c = 0; c < pcp->contact_count; c++) {
+ nvContact contact = pcp->contacts[c];
+
+ if (contact.separation < 0.0) {
+ penetrating = true;
+ break;
+ }
}
- *face = best_i;
- return best_depth;
+ return penetrating;
}
-static inline void _find_incident_face(
- nvVector2 *face,
- nvBody *ref,
- nvBody *inc,
- nvMat2x2 refu,
- nvMat2x2 incu,
- size_t ref_i
-) {
- nvVector2 ref_normal = NV_TO_VEC2(ref->shape->normals->data[ref_i]);
-
- // Calculate nmormal in incident's frame of reference
- ref_normal = nvMat2x2_mulv(refu, ref_normal);
- nvMat2x2 b_ut = nvMat2x2_transpose(incu);
- ref_normal = nvMat2x2_mulv(b_ut, ref_normal);
-
- // Find the "most anti-normal" face on incident shape
- size_t inc_face = 0;
- nv_float min_dot = NV_INF;
-
- for (size_t i = 0; i < inc->shape->vertices->size; i++) {
- nv_float dot = nvVector2_dot(ref_normal, NV_TO_VEC2(inc->shape->normals->data[i]));
-
- if (dot < min_dot) {
- min_dot = dot;
- inc_face = i;
- }
- }
-
- // Assign face vertices for inc_face
- face[0] = nvVector2_add(nvMat2x2_mulv(incu, NV_TO_VEC2(inc->shape->vertices->data[inc_face])), inc->position);
- inc_face = inc_face + 1 >= inc->shape->vertices->size ? 0 : inc_face + 1;
- face[1] = nvVector2_add(nvMat2x2_mulv(incu, NV_TO_VEC2(inc->shape->vertices->data[inc_face])), inc->position);
+nv_uint64 nvPersistentContactPair_hash(void *item) {
+ nvPersistentContactPair *pcp = (nvPersistentContactPair *)item;
+ return nvPersistentContactPair_key(pcp->shape_a, pcp->shape_b);
}
-static inline size_t _clip_segment_to_line(
- nvVector2 n,
- nv_float c,
- nvVector2 *face
+void nvPersistentContactPair_remove(
+ nvSpace *space,
+ nvPersistentContactPair *pcp
) {
- size_t sp = 0;
- nvVector2 out[2] = {face[0], face[1]};
-
- // Retrieve distances from each endpoint to the line
- // d = ax + by - c
- nv_float d1 = nvVector2_dot(n, face[0]) - c;
- nv_float d2 = nvVector2_dot(n, face[1]) - c;
-
- // If negative (behind plane), clip
- if (d1 <= 0.0) {
- out[sp] = face[0];
- sp++;
- }
-
- if (d2 <= 0.0) {
- out[sp] = face[1];
- sp++;
- }
-
- // If the points are on different sides of the plane
- if (d1 * d2 < 0.0) {
- // Push intersection point
- nv_float alpha = d1 / (d1 - d2);
-
- // f0 + a * (f1 - f0)
- out[sp] = nvVector2_add(
- face[0],
- nvVector2_mul(
- nvVector2_sub(face[1], face[0]),
- alpha
- )
- );
- sp++;
- }
-
- // Assign our new converted values
- face[0] = out[0];
- face[1] = out[1];
-
- if (sp == 3) NV_ERROR("there can't be 3 points???");
-
- return sp;
-}
-
-void nv_contact_polygon_x_polygon(nvResolution *res) {
- /*
- Erin Catto's GDC talk about polygon clipping for contact generation:
- https://box2d.org/files/ErinCatto_ContactManifolds_GDC2007.pdf
-
- Box2D-Lite's implementation:
- https://github.com/erincatto/box2d-lite/blob/master/src/Collide.cpp
-
- Randy Gaul's implementation:
- https://github.com/RandyGaul/ImpulseEngine/blob/master/Collision.cpp
- */
-
- nvBody *a = res->a;
- nvBody *b = res->b;
-
- // Rotation matrices
- nvMat2x2 au = nvMat2x2_from_angle(a->angle);
- nvMat2x2 bu = nvMat2x2_from_angle(b->angle);
- nvMat2x2 refu;
- nvMat2x2 incu;
-
- // Check for a separating axis with body A's faces
- size_t face_a;
- nv_float depth_a = _find_axis_least_penetration(&face_a, a, b, au, bu);
- if (depth_a >= 0.0) {
- res->collision = false;
- return;
- }
-
- // Check for a separating axis with body B's faces
- size_t face_b;
- nv_float depth_b = _find_axis_least_penetration(&face_b, b, a, bu, au);
- if (depth_b >= 0.0) {
- res->collision = false;
- return;
- }
-
- size_t ref_i;
- bool flip; // Always point from body A to body B
-
- nvBody *ref; // Reference body
- nvBody *inc; // Incident body
-
- // Determine which shapes contains reference face
- if (nv_bias_greater_than(depth_a, depth_b)) {
- ref = a;
- inc = b;
- refu = au;
- incu = bu;
- ref_i = face_a;
- flip = false;
- }
- else {
- ref = b;
- inc = a;
- refu = bu;
- incu = au;
- ref_i = face_b;
- flip = true;
- }
-
- // World space incident face
- nvVector2 inc_face[2];
- _find_incident_face(inc_face, ref, inc, refu, incu, ref_i);
-
- // Setup reference face vertices
- nvVector2 v1 = NV_TO_VEC2(ref->shape->vertices->data[ref_i]);
- ref_i = ref_i + 1 == ref->shape->vertices->size ? 0 : ref_i + 1;
- nvVector2 v2 = NV_TO_VEC2(ref->shape->vertices->data[ref_i]);
-
- // Transform vertices to world space
- v1 = nvVector2_add(nvMat2x2_mulv(refu, v1), ref->position);
- v2 = nvVector2_add(nvMat2x2_mulv(refu, v2), ref->position);
-
- // Calculate reference face side normal in world space
- nvVector2 side_normal = nvVector2_normalize(nvVector2_sub(v2, v1));
-
- nvVector2 ref_normal = nvVector2_perpr(side_normal);
-
- // ax + by = c (c is distance from origin)
- nv_float c = nvVector2_dot(ref_normal, v1);
- nv_float neg_side = -nvVector2_dot(side_normal, v1);
- nv_float pos_side = nvVector2_dot(side_normal, v2);
-
- // Clip incident face to reference face side planes
- // Due to floating point errors it's possible to not have required points
- if (_clip_segment_to_line(nvVector2_neg(side_normal), neg_side, inc_face) < 2) {
- res->collision = false;
- return;
- }
- if (_clip_segment_to_line(side_normal, pos_side, inc_face) < 2) {
- res->collision = false;
- return;
- }
-
- res->normal = flip ? nvVector2_neg(ref_normal) : ref_normal;
-
- // Keep points behind reference face
- nv_uint8 cp = 0;
-
- nv_float separation = nvVector2_dot(ref_normal, inc_face[0]) - c;
- if (separation < 0.0) {
- res->contacts[cp] = (nvContact){.position = inc_face[0]};
- res->depth = -separation;
- cp++;
- }
- else
- res->depth = 0.0;
-
- separation = nvVector2_dot(ref_normal, inc_face[1]) - c;
- if (separation <= 0.0) {
- res->contacts[cp] = (nvContact){.position = inc_face[1]};
- res->depth += -separation;
- cp++;
-
- // Average penetration depth
- res->depth /= (nv_float)cp;
+ for (size_t c = 0; c < pcp->contact_count; c++) {
+ nvContact *contact = &pcp->contacts[c];
+
+ nvContactEvent event = {
+ .body_a = pcp->body_a,
+ .body_b = pcp->body_b,
+ .shape_a = pcp->shape_a,
+ .shape_b = pcp->shape_b,
+ .normal = pcp->normal,
+ .penetration = contact->separation,
+ .position = nvVector2_add(pcp->body_a->position, contact->anchor_a),
+ .normal_impulse = {contact->solver_info.normal_impulse},
+ .friction_impulse = {contact->solver_info.tangent_impulse},
+ .id = contact->id
+ };
+
+ if (space->listener && !contact->remove_invoked) {
+ if (space->listener->on_contact_removed)
+ space->listener->on_contact_removed(space, event, space->listener_arg);
+ contact->remove_invoked = true;
+ };
}
- if (cp > 0) res->collision = true;
- res->contact_count = cp;
+ nvHashMap_remove(space->contacts, pcp);
}
\ No newline at end of file
diff --git a/src/contact_solver.c b/src/contact_solver.c
deleted file mode 100644
index 724f949..0000000
--- a/src/contact_solver.c
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include
-#include "novaphysics/internal.h"
-#include "novaphysics/contact_solver.h"
-#include "novaphysics/constraint.h"
-#include "novaphysics/spring.h"
-#include "novaphysics/distance_joint.h"
-#include "novaphysics/vector.h"
-#include "novaphysics/math.h"
-#include "novaphysics/resolution.h"
-#include "novaphysics/constants.h"
-#include "novaphysics/space.h"
-#include "novaphysics/debug.h"
-
-
-/**
- * @file contact_solver.c
- *
- * @brief Contact solver functions.
- */
-
-
-void nv_presolve_contact(
- nvSpace *space,
- nvResolution *res,
- nv_float inv_dt
-) {
- NV_TRACY_ZONE_START;
-
- nvBody *a = res->a;
- nvBody *b = res->b;
- nvVector2 normal = res->normal;
- nvVector2 tangent = nvVector2_perpr(normal);
-
- // Mixed restitution
- nv_float e = nv_mix_coefficients(
- a->material.restitution,
- b->material.restitution,
- space->mix_restitution
- );
-
- // Mixed friction
- res->friction = nv_mix_coefficients(
- a->material.friction,
- b->material.friction,
- space->mix_friction
- );
-
- for (size_t i = 0; i < res->contact_count; i++) {
- nvContact *contact = &res->contacts[i];
-
- contact->ra = nvVector2_sub(contact->position, a->position);
- contact->rb = nvVector2_sub(contact->position, b->position);
-
- // Relative velocity at contact
- nvVector2 rv = nv_calc_relative_velocity(
- a->linear_velocity, a->angular_velocity, contact->ra,
- b->linear_velocity, b->angular_velocity, contact->rb
- );
-
- // Restitution * normal velocity at first impact
- nv_float cn = nvVector2_dot(rv, normal);
-
- // Restitution bias
- contact->velocity_bias = 0.0;
- if (cn < -1.0) {
- contact->velocity_bias = e * cn;
- }
-
- contact->mass_normal = 1.0 / nv_calc_mass_k(
- normal,
- contact->ra, contact->rb,
- a->invmass, b->invmass,
- a->invinertia, b->invinertia
- );
-
- contact->mass_tangent = 1.0 / nv_calc_mass_k(
- tangent,
- contact->ra, contact->rb,
- a->invmass, b->invmass,
- a->invinertia, b->invinertia
- );
-
- if (space->position_correction == nvPositionCorrection_BAUMGARTE) {
- // Position error is fed back to the velocity constraint as a bias
- // value in the Baumgarte stabilization method.
- nv_float correction = nv_fmin(-res->depth + NV_POSITION_CORRECTION_SLOP, 0.0);
- contact->position_bias = NV_BAUMGARTE * correction * inv_dt;
- }
- else if (space->position_correction == nvPositionCorrection_NGS) {
- contact->position_bias = res->depth > 0.0f ? 1.0f : 0.0f;
- contact->a_angle0 = a->angle;
- contact->b_angle0 = b->angle;
- contact->adjusted_depth = res->depth - nvVector2_dot(nvVector2_sub(contact->rb, contact->ra), normal);
- }
- }
-
- NV_TRACY_ZONE_END;
-}
-
-void nv_warmstart(nvSpace *space, nvResolution *res) {
- NV_TRACY_ZONE_START;
-
- nvBody *a = res->a;
- nvBody *b = res->b;
- nvVector2 normal = res->normal;
- nvVector2 tangent = nvVector2_perpr(normal);
-
- for (size_t i = 0; i < res->contact_count; i++) {
- nvContact *contact = &res->contacts[i];
-
- if (space->warmstarting && res->state == nvResolutionState_NORMAL) {
- nvVector2 impulse = nvVector2_add(
- nvVector2_mul(normal, contact->jn),
- nvVector2_mul(tangent, contact->jt)
- );
-
- nvBody_apply_impulse(a, nvVector2_neg(impulse), contact->ra);
- nvBody_apply_impulse(b, impulse, contact->rb);
- }
-
- if (!space->warmstarting) {
- contact->jn = 0.0;
- contact->jt = 0.0;
- }
- }
-
- NV_TRACY_ZONE_END;
-}
-
-void nv_solve_velocity(nvResolution *res) {
- NV_TRACY_ZONE_START;
-
- nvBody *a = res->a;
- nvBody *b = res->b;
- nvVector2 normal = res->normal;
- nvVector2 tangent = nvVector2_perpr(normal);
- size_t i;
-
- // In an iterative solver what is applied the last affects the result more.
- // So we solve normal impulse after tangential impulse because
- // non-penetration is more important.
-
- // Solve friction
- for (i = 0; i < res->contact_count; i++) {
- // Don't bother calculating friction if the coefficent is 0
- if (res->friction == 0.0) continue;
-
- nvContact *contact = &res->contacts[i];
-
- // Relative velocity at contact
- nvVector2 rv = nv_calc_relative_velocity(
- a->linear_velocity, a->angular_velocity, contact->ra,
- b->linear_velocity, b->angular_velocity, contact->rb
- );
-
- // Tangential lambda (tangential impulse magnitude)
- nv_float jt = -nvVector2_dot(rv, tangent) * contact->mass_tangent;
-
- // Accumulate tangential impulse
- nv_float f = contact->jn * res->friction;
- nv_float jt0 = contact->jt;
- // Clamp lambda between friction limits
- contact->jt = nv_fmax(-f, nv_fmin(jt0 + jt, f));
- jt = contact->jt - jt0;
-
- nvVector2 impulse = nvVector2_mul(tangent, jt);
-
- // Apply tangential impulse
- nvBody_apply_impulse(a, nvVector2_neg(impulse), contact->ra);
- nvBody_apply_impulse(b, impulse, contact->rb);
- }
-
- // Solve penetration
- for (i = 0; i < res->contact_count; i++) {
- nvContact *contact = &res->contacts[i];
-
- // Relative velocity at contact
- nvVector2 rv = nv_calc_relative_velocity(
- a->linear_velocity, a->angular_velocity, contact->ra,
- b->linear_velocity, b->angular_velocity, contact->rb
- );
-
- nv_float cn = nvVector2_dot(rv, normal);
-
- // Normal lambda (normal impulse magnitude)
- //nv_float jn = -(cn + contact->velocity_bias + contact->position_bias) * contact->mass_normal;
-
- //-cp->normalMass * (vn + cp->biasCoefficient * cp->separation * inv_dt)
- nv_float jn = -(cn + contact->position_bias * -res->depth) * contact->mass_normal;
-
- // Accumulate normal impulse
- nv_float jn0 = contact->jn;
- // Clamp lambda because we only want to solve penetration
- contact->jn = nv_fmax(jn0 + jn, 0.0);
- jn = contact->jn - jn0;
-
- nvVector2 impulse = nvVector2_mul(normal, jn);
-
- // Apply normal impulse
- nvBody_apply_impulse(a, nvVector2_neg(impulse), contact->ra);
- nvBody_apply_impulse(b, impulse, contact->rb);
- }
-
- NV_TRACY_ZONE_END;
-}
-
-void nv_solve_position(nvResolution *res) {
- // TODO: Finish the NGS iterations early if there is no collision?
-
- NV_TRACY_ZONE_START;
-
- nvBody *a = res->a;
- nvBody *b = res->b;
-
- for (size_t i = 0; i < res->contact_count; i++) {
- nvContact contact = res->contacts[i];
-
- nvVector2 ra = nvVector2_rotate(contact.ra, a->angle - contact.a_angle0);
- nvVector2 rb = nvVector2_rotate(contact.rb, b->angle - contact.b_angle0);
-
- // Current separation
- nvVector2 d = nvVector2_add(nvVector2_sub(b->position, a->position), nvVector2_sub(rb, ra));
- nv_float depth = nvVector2_dot(d, res->normal) - res->depth;
-
- // nv_float mass_normal = nv_calc_mass_k(
- // res->normal,
- // ra, rb,
- // a->invmass, b->invmass,
- // a->invinertia, b->invinertia
- // );
-
- // if (mass_normal == 0.0) printf("a\n");
-
- nv_float rna = nvVector2_cross(ra, res->normal);
- nv_float rnb = nvVector2_cross(rb, res->normal);
- nv_float mass_normal = a->invmass + b->invmass + a->invinertia * rna * rna + b->invinertia * rnb * rnb;
-
- nv_float correction = nv_fmin(0.0, depth + NV_POSITION_CORRECTION_SLOP);
- nv_float position_bias = -NV_BAUMGARTE * correction;
-
- // Normal pseudo lambda
- nv_float jp = position_bias / mass_normal;
-
- nvVector2 impulse = nvVector2_mul(res->normal, jp);
-
- // Apply pseudo-impulse
- a->position = nvVector2_sub(a->position, nvVector2_mul(impulse, a->invmass));
- a->angle -= nvVector2_cross(ra, impulse) * a->invinertia;
-
- b->position = nvVector2_add(b->position, nvVector2_mul(impulse, b->invmass));
- b->angle += nvVector2_cross(rb, impulse) * b->invinertia;
- }
-
- NV_TRACY_ZONE_END;
-}
\ No newline at end of file
diff --git a/src/array.c b/src/core/array.c
similarity index 68%
rename from src/array.c
rename to src/core/array.c
index 505dab8..1d872b8 100644
--- a/src/array.c
+++ b/src/core/array.c
@@ -8,11 +8,11 @@
*/
-#include "novaphysics/array.h"
+#include "novaphysics/core/array.h"
/**
- * @file array.c
+ * @file core/array.c
*
* @brief Type-generic dynamically growing array implementation.
*/
@@ -20,43 +20,44 @@
nvArray *nvArray_new() {
nvArray *array = NV_NEW(nvArray);
- if (!array) return NULL;
+ NV_MEM_CHECK(array);
array->size = 0;
array->max = 0;
- array->data = (void **)malloc(sizeof(void *));
- if (!array->data) {
- free(array);
- return NULL;
- }
+ array->data = (void **)NV_MALLOC(sizeof(void *));
+ if (!array->data) NV_FREE(array);
+ NV_MEM_CHECK(array->data);
return array;
}
void nvArray_free(nvArray *array) {
- free(array->data);
- array->data = NULL;
- array->size = 0;
- free(array);
+ if (!array) return;
+
+ NV_FREE(array->data);
+ NV_FREE(array);
}
-void nvArray_free_each(nvArray *array, void (free_func)(void *)) {
+void nvArray_free_each(nvArray *array, nvArray_free_each_callback free_func) {
for (size_t i = 0; i < array->size; i++)
free_func(array->data[i]);
}
-void nvArray_add(nvArray *array, void *elem) {
+int nvArray_add(nvArray *array, void *elem) {
// Only reallocate when max capacity is reached
if (array->size == array->max) {
array->size++;
array->max++;
- array->data = (void **)realloc(array->data, array->size * sizeof(void *));
+ array->data = NV_REALLOC(array->data, array->size * sizeof(void *));
+ NV_MEM_CHECKI(array->data);
}
else {
array->size++;
}
array->data[array->size - 1] = elem;
+
+ return 0;
}
void *nvArray_pop(nvArray *array, size_t index) {
@@ -90,7 +91,7 @@ size_t nvArray_remove(nvArray *array, void *elem) {
return -1;
}
-void nvArray_clear(nvArray *array, void (free_func)(void *)) {
+int nvArray_clear(nvArray *array, void (free_func)(void *)) {
/*
We can set array->max to 0 and reallocate but
not doing it might be more efficient for the developer
@@ -98,17 +99,22 @@ void nvArray_clear(nvArray *array, void (free_func)(void *)) {
Maybe a separate parameter for this?
*/
- if (array->size == 0) return;
+ if (array->size == 0) return 0;
if (!free_func) {
while (array->size > 0) {
- nvArray_pop(array, 0);
+ if (!nvArray_pop(array, 0))
+ return 1;
}
}
else {
while (array->size > 0) {
- free_func(nvArray_pop(array, 0));
+ void *p = nvArray_pop(array, 0);
+ if (!p) return 1;
+ free_func(p);
}
}
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/core/error.c b/src/core/error.c
new file mode 100644
index 0000000..9b83557
--- /dev/null
+++ b/src/core/error.c
@@ -0,0 +1,25 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/core/error.h"
+
+
+/**
+ * @file core/error.c
+ *
+ * @brief Error handling.
+ */
+
+
+char _nv_error_buffer[NV_ERROR_BUFFER_SIZE] = "";
+
+char *nv_get_error() {
+ return _nv_error_buffer;
+}
\ No newline at end of file
diff --git a/src/hashmap.c b/src/core/hashmap.c
similarity index 91%
rename from src/hashmap.c
rename to src/core/hashmap.c
index 34fc3b3..fcffdc2 100644
--- a/src/hashmap.c
+++ b/src/core/hashmap.c
@@ -8,15 +8,14 @@
*/
-#include
#include "novaphysics/internal.h"
-#include "novaphysics/hashmap.h"
+#include "novaphysics/core/hashmap.h"
#include "novaphysics/constants.h"
#include "novaphysics/math.h"
/**
- * @file hashmap.c
+ * @file core/hashmap.c
*
* @brief Hash map implementation.
*
@@ -41,7 +40,7 @@ static inline nv_uint64 _nvHashMap_clip(nv_uint64 hash) {
return hash & 0xFFFFFFFFFFFF;
}
-static inline bool _nvHashMap_resize(nvHashMap *hashmap, size_t new_cap) {
+static inline nv_bool _nvHashMap_resize(nvHashMap *hashmap, size_t new_cap) {
nvHashMap *hashmap2 = nvHashMap_new(hashmap->elsize, new_cap, hashmap->hash_func);
if (!hashmap2) return false;
@@ -70,7 +69,7 @@ static inline bool _nvHashMap_resize(nvHashMap *hashmap, size_t new_cap) {
}
}
- free(hashmap->buckets);
+ NV_FREE(hashmap->buckets);
hashmap->buckets = hashmap2->buckets;
hashmap->nbuckets = hashmap2->nbuckets;
@@ -78,7 +77,7 @@ static inline bool _nvHashMap_resize(nvHashMap *hashmap, size_t new_cap) {
hashmap->growat = hashmap2->growat;
hashmap->shrinkat = hashmap2->shrinkat;
- free(hashmap2);
+ NV_FREE(hashmap2);
return true;
}
@@ -103,8 +102,8 @@ nvHashMap *nvHashMap_new(
}
size_t size = sizeof(nvHashMap)+bucketsz*2;
- nvHashMap *hashmap = malloc(size);
- if (!hashmap) return NULL;
+ nvHashMap *hashmap = NV_MALLOC(size);
+ NV_MEM_CHECK(hashmap);
hashmap->count = 0;
hashmap->oom = false;
@@ -117,9 +116,10 @@ nvHashMap *nvHashMap_new(
hashmap->nbuckets = cap;
hashmap->mask = hashmap->nbuckets - 1;
- hashmap->buckets = malloc(hashmap->bucketsz * hashmap->nbuckets);
+ hashmap->buckets = NV_MALLOC(hashmap->bucketsz * hashmap->nbuckets);
if (!hashmap->buckets) {
- free(hashmap);
+ NV_FREE(hashmap);
+ nv_set_error("Failed to allocate memory.");
return NULL;
}
memset(hashmap->buckets, 0, hashmap->bucketsz * hashmap->nbuckets);
@@ -132,8 +132,8 @@ nvHashMap *nvHashMap_new(
}
void nvHashMap_free(nvHashMap *hashmap) {
- free(hashmap->buckets);
- free(hashmap);
+ NV_FREE(hashmap->buckets);
+ NV_FREE(hashmap);
}
void nvHashMap_clear(nvHashMap *hashmap) {
@@ -141,9 +141,9 @@ void nvHashMap_clear(nvHashMap *hashmap) {
hashmap->count = 0;
if (hashmap->nbuckets != hashmap->cap) {
- void *new_buckets = malloc(hashmap->bucketsz*hashmap->cap);
+ void *new_buckets = NV_MALLOC(hashmap->bucketsz*hashmap->cap);
if (new_buckets) {
- free(hashmap->buckets);
+ NV_FREE(hashmap->buckets);
hashmap->buckets = new_buckets;
}
hashmap->nbuckets = hashmap->cap;
@@ -166,7 +166,7 @@ void *nvHashMap_set(nvHashMap *hashmap, void *item) {
// Does adding one more entry overflow memory?
hashmap->oom = false;
if (hashmap->count == hashmap->growat) {
- if (!_nvHashMap_resize(hashmap, hashmap->nbuckets*(1<growpower))) {
+ if (!_nvHashMap_resize(hashmap, hashmap->nbuckets * (1<growpower))) {
hashmap->oom = true;
NV_TRACY_ZONE_END;
return NULL;
@@ -293,7 +293,7 @@ void *nvHashMap_remove(nvHashMap *hashmap, void *key) {
NV_TRACY_ZONE_END;
}
-bool nvHashMap_iter(nvHashMap *hashmap, size_t *index, void **item) {
+nv_bool nvHashMap_iter(nvHashMap *hashmap, size_t *index, void **item) {
NV_TRACY_ZONE_START;
nvHashMapBucket *bucket;
diff --git a/src/core/pool.c b/src/core/pool.c
new file mode 100644
index 0000000..eb09464
--- /dev/null
+++ b/src/core/pool.c
@@ -0,0 +1,61 @@
+/*
+
+ This file is a part of the Nova Physics Engine
+ project and distributed under the MIT license.
+
+ Copyright © Kadir Aksoy
+ https://github.com/kadir014/nova-physics
+
+*/
+
+#include "novaphysics/core/pool.h"
+
+
+/**
+ * @file core/pool.c
+ *
+ * @brief Fixed-size memory pool implementation.
+ */
+
+
+nvMemoryPool *nvMemoryPool_new(size_t chunk_size, size_t initial_num_chunks) {
+ nvMemoryPool *pool = NV_NEW(nvMemoryPool);
+ NV_MEM_CHECK(pool);
+
+ pool->current_size = 0;
+ pool->chunk_size = chunk_size;
+ pool->pool_size = chunk_size * initial_num_chunks;
+ pool->pool = NV_MALLOC(pool->pool_size);
+ NV_MEM_CHECK(pool->pool);
+
+ return pool;
+}
+
+void nvMemoryPool_free(nvMemoryPool *pool) {
+ NV_FREE(pool->pool);
+ NV_FREE(pool);
+}
+
+int nvMemoryPool_add(nvMemoryPool *pool, void *chunk) {
+ // Expand the bool if necessary
+ if (pool->current_size * pool->chunk_size >= pool->pool_size) {
+ size_t new_pool_size = pool->pool_size * 2;
+ void *new_pool = NV_REALLOC(pool->pool, new_pool_size);
+ NV_MEM_CHECKI(new_pool);
+
+ pool->pool = new_pool;
+ pool->pool_size = new_pool_size;
+ }
+
+ memcpy(
+ (char *)pool->pool + (pool->current_size++) * pool->chunk_size,
+ chunk,
+ pool->chunk_size
+ );
+
+ return 0;
+}
+
+void nvMemoryPool_clear(nvMemoryPool *pool) {
+ pool->current_size = 0;
+}
\ No newline at end of file
diff --git a/src/distance_joint.c b/src/distance_joint.c
deleted file mode 100644
index 5acdf25..0000000
--- a/src/distance_joint.c
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/distance_joint.h"
-#include "novaphysics/space.h"
-
-
-/**
- * @file distance_joint.c
- *
- * @brief Distance joint implementation.
- */
-
-
-nvConstraint *nvDistanceJoint_new(
- nvBody *a,
- nvBody *b,
- nvVector2 anchor_a,
- nvVector2 anchor_b,
- nv_float length
-) {
- nvConstraint *cons = NV_NEW(nvConstraint);
- if (!cons) return NULL;
-
- cons->a = a;
- cons->b = b;
- cons->type = nvConstraintType_DISTANCEJOINT;
-
- cons->def = (void *)NV_NEW(nvDistanceJoint);
- if (!cons->def) return NULL;
- nvDistanceJoint *dist_joint = (nvDistanceJoint *)cons->def;
-
- dist_joint->length = length;
- dist_joint->anchor_a = anchor_a;
- dist_joint->anchor_b = anchor_b;
-
- dist_joint->ra = nvVector2_zero;
- dist_joint->rb = nvVector2_zero;
- dist_joint->normal = nvVector2_zero;
- dist_joint->bias = 0.0;
- dist_joint->mass = 0.0;
- dist_joint->jc = 0.0;
-
- return cons;
-}
-
-void nvDistanceJoint_presolve(
- nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-) {
- nvDistanceJoint *dist_joint = (nvDistanceJoint *)cons->def;
- nvBody *a = cons->a;
- nvBody *b = cons->b;
-
- // Transform anchor points
- nvVector2 rpa, rpb;
- nv_float invmass_a, invmass_b, invinertia_a, invinertia_b;
-
- if (a == NULL) {
- dist_joint->ra = nvVector2_zero;
- rpa = dist_joint->anchor_a;
- invmass_a = invinertia_a = 0.0;
- } else {
- dist_joint->ra = nvVector2_rotate(dist_joint->anchor_a, a->angle);
- rpa = nvVector2_add(dist_joint->ra, a->position);
- invmass_a = a->invmass;
- invinertia_a = a->invinertia;
- }
-
- if (b == NULL) {
- dist_joint->rb = nvVector2_zero;
- rpb = dist_joint->anchor_b;
- invmass_b = invinertia_b = 0.0;
- } else {
- dist_joint->rb = nvVector2_rotate(dist_joint->anchor_b, b->angle);
- rpb = nvVector2_add(dist_joint->rb, b->position);
- invmass_b = b->invmass;
- invinertia_b = b->invinertia;
- }
-
- nvVector2 delta = nvVector2_sub(rpb, rpa);
- dist_joint->normal = nvVector2_normalize(delta);
- nv_float offset = nvVector2_len(delta) - dist_joint->length;
-
- // Baumgarte position correction bias
- dist_joint->bias = -NV_BAUMGARTE * inv_dt * offset;
-
- // Constraint effective mass
- dist_joint->mass = 1.0 / nv_calc_mass_k(
- dist_joint->normal,
- dist_joint->ra, dist_joint->rb,
- invmass_a, invmass_b,
- invinertia_a, invinertia_b
- );
-
- if (space->warmstarting) {
- nvVector2 impulse = nvVector2_mul(dist_joint->normal, dist_joint->jc);
-
- if (a) nvBody_apply_impulse(cons->a, nvVector2_neg(impulse), dist_joint->ra);
- if (b) nvBody_apply_impulse(cons->b, impulse, dist_joint->rb);
- }
- else {
- dist_joint->jc = 0.0;
- }
-}
-
-void nvDistanceJoint_solve(nvConstraint *cons) {
- nvDistanceJoint *dist_joint = (nvDistanceJoint *)cons->def;
- nvBody *a = cons->a;
- nvBody *b = cons->b;
-
- nvVector2 linear_velocity_a, linear_velocity_b;
- nv_float angular_velocity_a, angular_velocity_b;
-
- if (a == NULL) {
- linear_velocity_a = nvVector2_zero;
- angular_velocity_a = 0.0;
- } else {
- linear_velocity_a = a->linear_velocity;
- angular_velocity_a = a->angular_velocity;
- }
-
- if (b == NULL) {
- linear_velocity_b = nvVector2_zero;
- angular_velocity_b = 0.0;
- } else {
- linear_velocity_b = b->linear_velocity;
- angular_velocity_b = b->angular_velocity;
- }
-
- nvVector2 rv = nv_calc_relative_velocity(
- linear_velocity_a, angular_velocity_a, dist_joint->ra,
- linear_velocity_b, angular_velocity_b, dist_joint->rb
- );
-
- nv_float rn = nvVector2_dot(rv, dist_joint->normal);
-
- // Normal constraint lambda (impulse magnitude)
- nv_float jc = (dist_joint->bias - rn) * dist_joint->mass;
-
- // Accumulate impulse
- nv_float jc_max = NV_INF;//5000 * (1.0 / 60.0);
-
- nv_float jc0 = dist_joint->jc;
- dist_joint->jc = nv_fclamp(jc0 + jc, -jc_max, jc_max);
- jc = dist_joint->jc - jc0;
-
- nvVector2 impulse = nvVector2_mul(dist_joint->normal, jc);
-
- // Apply constraint impulse
- if (a != NULL) nvBody_apply_impulse(a, nvVector2_neg(impulse), dist_joint->ra);
- if (b != NULL) nvBody_apply_impulse(b, impulse, dist_joint->rb);
-}
\ No newline at end of file
diff --git a/src/hinge_joint.c b/src/hinge_joint.c
deleted file mode 100644
index 3e11191..0000000
--- a/src/hinge_joint.c
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/hinge_joint.h"
-#include "novaphysics/space.h"
-
-
-/**
- * @file hinge_joint.c
- *
- * @brief Hinge joint implementation.
- */
-
-
-nvConstraint *nvHingeJoint_new(
- nvBody *a,
- nvBody *b,
- nvVector2 anchor
-) {
- nvConstraint *cons = NV_NEW(nvConstraint);
- if (!cons) return NULL;
-
- cons->a = a;
- cons->b = b;
- cons->type = nvConstraintType_HINGEJOINT;
-
- cons->def = (void *)NV_NEW(nvHingeJoint);
- if (!cons->def) return NULL;
- nvHingeJoint *hinge_joint = (nvHingeJoint *)cons->def;
-
- hinge_joint->enable_limits = false;
- hinge_joint->lower_limit = 0.0;
- hinge_joint->upper_limit = 0.0;
- hinge_joint->angle = 0.0;
-
- hinge_joint->anchor = anchor;
- nv_float angle_a, angle_b;
- if (a) {
- hinge_joint->anchor_a = nvVector2_sub(anchor, a->position);
- angle_a = a->angle;
- }
- else {
- hinge_joint->anchor_a = anchor;
- angle_a = 0.0;
- }
- if (b) {
- hinge_joint->anchor_b = nvVector2_sub(anchor, b->position);
- angle_b = b->angle;
- }
- else {
- hinge_joint->anchor_b = anchor;
- angle_b = 0.0;
- }
-
- hinge_joint->reference_angle = angle_b - angle_a;
- hinge_joint->lower_impulse = 0.0;
- hinge_joint->upper_impulse = 0.0;
- hinge_joint->axial_mass = 0.0;
- hinge_joint->ra = nvVector2_zero;
- hinge_joint->rb = nvVector2_zero;
- hinge_joint->normal = nvVector2_zero;
- hinge_joint->bias = 0.0;
- hinge_joint->mass = 0.0;
- hinge_joint->jc = 0.0;
-
- return cons;
-}
-
-void nvHingeJoint_presolve(
- nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-) {
- nvHingeJoint *hinge_joint = (nvHingeJoint *)cons->def;
- nvBody *a = cons->a;
- nvBody *b = cons->b;
-
- // Transform anchor points
- nvVector2 rpa, rpb;
- nv_float invmass_a, invmass_b, invinertia_a, invinertia_b;
-
- if (a == NULL) {
- hinge_joint->ra = nvVector2_zero;
- rpa = hinge_joint->anchor_a;
- invmass_a = invinertia_a = 0.0;
- } else {
- hinge_joint->ra = nvVector2_rotate(hinge_joint->anchor_a, a->angle);
- rpa = nvVector2_add(hinge_joint->ra, a->position);
- invmass_a = a->invmass;
- invinertia_a = a->invinertia;
- }
-
- if (b == NULL) {
- hinge_joint->rb = nvVector2_zero;
- rpb = hinge_joint->anchor_b;
- invmass_b = invinertia_b = 0.0;
- } else {
- hinge_joint->rb = nvVector2_rotate(hinge_joint->anchor_b, b->angle);
- rpb = nvVector2_add(hinge_joint->rb, b->position);
- invmass_b = b->invmass;
- invinertia_b = b->invinertia;
- }
-
- nvVector2 delta = nvVector2_sub(rpb, rpa);
- if (nvVector2_len2(delta) == 0.0) hinge_joint->normal = nvVector2_zero;
- else hinge_joint->normal = nvVector2_normalize(delta);
- nv_float offset = nvVector2_len(delta);
-
- // Baumgarte position correction bias
- hinge_joint->bias = -NV_BAUMGARTE * inv_dt * offset;
-
- // Distance constraint effective mass
- hinge_joint->mass = 1.0 / nv_calc_mass_k(
- hinge_joint->normal,
- hinge_joint->ra, hinge_joint->rb,
- invmass_a, invmass_b,
- invinertia_a, invinertia_b
- );
-
- hinge_joint->axial_mass = 1.0 / (invinertia_a + invinertia_b);
-
- nv_float angle_a, angle_b;
- if (a) angle_a = a->angle;
- else angle_a = 0.0;
- if (b) angle_b = b->angle;
- else angle_b = 0.0;
-
- hinge_joint->angle = angle_b - angle_a - hinge_joint->reference_angle;
-
- if (space->warmstarting) {
- nvVector2 impulse = nvVector2_mul(hinge_joint->normal, hinge_joint->jc);
- nv_float axial_impulse = hinge_joint->lower_impulse - hinge_joint->upper_impulse;
-
- if (a) {
- nvBody_apply_impulse(a, nvVector2_neg(impulse), hinge_joint->ra);
- a->angular_velocity -= a->invinertia * axial_impulse;
- }
- if (b) {
- nvBody_apply_impulse(b, impulse, hinge_joint->rb);
- b->angular_velocity += b->invinertia * axial_impulse;
- }
-
- }
- else {
- hinge_joint->jc = 0.0;
- hinge_joint->upper_impulse = 0.0;
- hinge_joint->lower_impulse = 0.0;
- }
-}
-
-void nvHingeJoint_solve(nvConstraint *cons, nv_float inv_dt) {
- nvHingeJoint *hinge_joint = (nvHingeJoint *)cons->def;
- nvBody *a = cons->a;
- nvBody *b = cons->b;
-
- // Solve angular limits
- if (hinge_joint->enable_limits) {
- nv_float c, wr, wa, wb, impulse, impulse0;
-
- if (a) wa = a->angular_velocity;
- else wa = 0.0;
- if (b) wb = b->angular_velocity;
- else wb = 0.0;
-
- // Solve lower limit
-
- c = hinge_joint->angle - hinge_joint->lower_limit;
- wr = wb - wa;
- impulse = -hinge_joint->axial_mass * (wr + nv_fmax(c, 0.0) * inv_dt);
-
- // Accumulate lower impulse
- impulse0 = hinge_joint->lower_impulse;
- hinge_joint->lower_impulse = nv_fmax(hinge_joint->lower_impulse + impulse, 0.0);
- impulse = hinge_joint->lower_impulse - impulse0;
-
- // Apply lower impulse
- if (a) a->angular_velocity -= impulse * a->invinertia;
- if (b) b->angular_velocity += impulse * b->invinertia;
-
- // Solve upper limmit
-
- c = hinge_joint->upper_limit - hinge_joint->angle;
- wr = wa - wb;
- impulse = -hinge_joint->axial_mass * (wr + nv_fmax(c, 0.0) * inv_dt);
-
- // Accumulate upper impulse
- impulse0 = hinge_joint->upper_impulse;
- hinge_joint->upper_impulse = nv_fmax(hinge_joint->upper_impulse + impulse, 0.0);
- impulse = hinge_joint->upper_impulse - impulse0;
-
- // Apply upper impulse
- if (a) a->angular_velocity += impulse * a->invinertia;
- if (b) b->angular_velocity -= impulse * b->invinertia;
- }
-
- // Solve distance constraintt
-
- nvVector2 linear_velocity_a, linear_velocity_b;
- nv_float angular_velocity_a, angular_velocity_b;
-
- if (a == NULL) {
- linear_velocity_a = nvVector2_zero;
- angular_velocity_a = 0.0;
- } else {
- linear_velocity_a = a->linear_velocity;
- angular_velocity_a = a->angular_velocity;
- }
-
- if (b == NULL) {
- linear_velocity_b = nvVector2_zero;
- angular_velocity_b = 0.0;
- } else {
- linear_velocity_b = b->linear_velocity;
- angular_velocity_b = b->angular_velocity;
- }
-
- nvVector2 rv = nv_calc_relative_velocity(
- linear_velocity_a, angular_velocity_a, hinge_joint->ra,
- linear_velocity_b, angular_velocity_b, hinge_joint->rb
- );
-
- nv_float rn = nvVector2_dot(rv, hinge_joint->normal);
-
- // Normal position constraint lambda (impulse magnitude)
- nv_float jc = (hinge_joint->bias - rn) * hinge_joint->mass;
-
- // Accumulate impulse
- nv_float jc_max = NV_INF;//5000 * (1.0 / 60.0);
-
- nv_float jc0 = hinge_joint->jc;
- hinge_joint->jc = nv_fclamp(jc0 + jc, -jc_max, jc_max);
- jc = hinge_joint->jc - jc0;
-
- nvVector2 impulse = nvVector2_mul(hinge_joint->normal, jc);
-
- // Apply position impulse
- if (a != NULL) nvBody_apply_impulse(a, nvVector2_neg(impulse), hinge_joint->ra);
- if (b != NULL) nvBody_apply_impulse(b, impulse, hinge_joint->rb);
-}
\ No newline at end of file
diff --git a/src/narrowphase.c b/src/narrowphase.c
index b247771..ca442b8 100644
--- a/src/narrowphase.c
+++ b/src/narrowphase.c
@@ -11,6 +11,9 @@
#include "novaphysics/internal.h"
#include "novaphysics/narrowphase.h"
#include "novaphysics/space.h"
+#include "novaphysics/math.h"
+#include "novaphysics/contact.h"
+#include "novaphysics/collision.h"
/**
@@ -20,128 +23,223 @@
*/
-void nv_narrow_phase(nvSpace *space) {
- void *map_val;
- size_t l = 0;
- while (nvHashMap_iter(space->broadphase_pairs, &l, &map_val)) {
- nvBroadPhasePair *pair = map_val;
-
- nvResolution *res_value;
- res_value = nvHashMap_get(space->res, &(nvResolution){.a=pair->a, .b=pair->b});
- bool res_exists = (res_value == NULL) ? false : true;
-
- nv_narrow_phase_between_pair(space, pair, res_exists, res_value);
- }
-}
-
-
-void nv_narrow_phase_between_pair(
- nvSpace *space,
- nvBroadPhasePair *pair,
- bool res_exists,
- nvResolution *found_res
+static void generate_contact_pair(
+ nvPersistentContactPair *pcp,
+ nvRigidBody *body_a,
+ nvRigidBody *body_b,
+ nvShape *shape_a,
+ nvShape *shape_b
) {
NV_TRACY_ZONE_START;
- nvBody *a = pair->a;
- nvBody *b = pair->b;
-
- nvResolution res;
- res.collision = false;
-
- if (a->shape->type == nvShapeType_CIRCLE && b->shape->type == nvShapeType_CIRCLE)
- res = nv_collide_circle_x_circle(a, b);
-
- else if (a->shape->type == nvShapeType_CIRCLE && b->shape->type == nvShapeType_POLYGON)
- res = nv_collide_polygon_x_circle(b, a);
-
- else if (a->shape->type == nvShapeType_POLYGON && b->shape->type == nvShapeType_CIRCLE)
- res = nv_collide_polygon_x_circle(a, b);
-
- else if (a->shape->type == nvShapeType_POLYGON && b->shape->type == nvShapeType_POLYGON) {
- res.a = a;
- res.b = b;
- nv_contact_polygon_x_polygon(&res);
+ nvTransform xform_a = {body_a->origin, body_a->angle};
+ nvTransform xform_b = {body_b->origin, body_b->angle};
+ pcp->contact_count = 0;
+
+ if (shape_a->type == nvShapeType_POLYGON && shape_b->type == nvShapeType_POLYGON) {
+ *pcp = nv_collide_polygon_x_polygon(
+ shape_a,
+ xform_a,
+ shape_b,
+ xform_b
+ );
+ }
+ else if (shape_a->type == nvShapeType_CIRCLE && shape_b->type == nvShapeType_CIRCLE) {
+ *pcp = nv_collide_circle_x_circle(
+ shape_a,
+ xform_a,
+ shape_b,
+ xform_b
+ );
+ }
+ else if (shape_a->type == nvShapeType_CIRCLE && shape_b->type == nvShapeType_POLYGON) {
+ *pcp = nv_collide_polygon_x_circle(
+ shape_b,
+ xform_b,
+ shape_a,
+ xform_a,
+ true
+ );
+ }
+ else if (shape_a->type == nvShapeType_POLYGON && shape_b->type == nvShapeType_CIRCLE) {
+ *pcp = nv_collide_polygon_x_circle(
+ shape_a,
+ xform_a,
+ shape_b,
+ xform_b,
+ false
+ );
}
- if (res.collision) {
- if (a->shape->type == nvShapeType_CIRCLE && b->shape->type == nvShapeType_CIRCLE)
- nv_contact_circle_x_circle(&res);
-
- else if (a->shape->type == nvShapeType_CIRCLE && b->shape->type == nvShapeType_POLYGON)
- nv_contact_polygon_x_circle(&res);
-
- else if (a->shape->type == nvShapeType_POLYGON && b->shape->type == nvShapeType_CIRCLE)
- nv_contact_polygon_x_circle(&res);
-
- /*
- If one body is asleep and other is not, wake up the asleep body
- depending on the awake body's motion.
- */
- if (space->sleeping) {
- if (a->is_sleeping && (!b->is_sleeping && b->type != nvBodyType_STATIC)) {
- nv_float linear = nvVector2_len2(b->linear_velocity) * (1.0 / 60.0);
- nv_float angular = b->angular_velocity * (1.0 / 60.0);
- nv_float total_energy = linear + angular;
+ pcp->body_a = body_a;
+ pcp->body_b = body_b;
+ pcp->shape_a = shape_a;
+ pcp->shape_b = shape_b;
- if (total_energy > space->wake_energy_threshold)
- nvBody_awake(a);
- }
+ NV_TRACY_ZONE_END;
+}
- if (b->is_sleeping && (!a->is_sleeping && a->type != nvBodyType_STATIC)) {
- nv_float linear = nvVector2_len2(a->linear_velocity) * (1.0 / 60.0);
- nv_float angular = a->angular_velocity * (1.0 / 60.0);
- nv_float total_energy = linear + angular;
- if (total_energy > space->wake_energy_threshold)
- nvBody_awake(b);
- }
- }
+void nv_narrow_phase(nvSpace *space) {
+ NV_TRACY_ZONE_START;
- /*
- If the resolution between bodies already exists then
- just update it. Else, create a new resolution.
- */
- if (res_exists) {
- found_res->normal = res.normal;
- found_res->depth = res.depth;
- found_res->collision = res.collision;
- found_res->contact_count = res.contact_count;
- found_res->contacts[0].position = res.contacts[0].position;
- found_res->contacts[1].position = res.contacts[1].position;
-
- if (found_res->state == nvResolutionState_CACHED) {
- found_res->lifetime = space->collision_persistence;
- found_res->state = nvResolutionState_FIRST;
- }
- else if (found_res->state == nvResolutionState_FIRST) {
- found_res->state = nvResolutionState_NORMAL;
+ for (size_t i = 0; i < space->broadphase_pairs->current_size; i++) {
+ void *pool_i = (char *)space->broadphase_pairs->pool + i * space->broadphase_pairs->chunk_size;
+ nvRigidBody *body_a = ((nvBroadPhasePair *)pool_i)->a;
+ nvRigidBody *body_b = ((nvBroadPhasePair *)pool_i)->b;
+
+ if (!body_a || !body_b) continue;
+
+ nvVector2 com_a = nvVector2_rotate(body_a->com, body_a->angle);
+ nvVector2 com_b = nvVector2_rotate(body_b->com, body_b->angle);
+
+ for (size_t j = 0; j < body_a->shapes->size; j++) {
+ nvShape *shape_a = body_a->shapes->data[j];
+
+ for (size_t k = 0; k < body_b->shapes->size; k++) {
+ nvShape *shape_b = body_b->shapes->data[k];
+
+ nvPersistentContactPair *old_pcp = nvHashMap_get(space->contacts, &(nvPersistentContactPair){.shape_a=shape_a, .shape_b=shape_b});
+
+ // Contact already exists, check the collision and update the contact info
+ if (old_pcp) {
+ nvPersistentContactPair pcp;
+ generate_contact_pair(&pcp, body_a, body_b, shape_a, shape_b);
+
+ nvContactEvent persisted_queue[6];
+ nvContactEvent removed_queue[6];
+ size_t persisted_queue_size = 0;
+ size_t removed_queue_size = 0;
+
+ // Match contact solver info for warm-starting
+ for (size_t c = 0; c < pcp.contact_count; c++) {
+ nvContact *contact = &pcp.contacts[c];
+
+ // Contacts relative to center of mass
+ contact->anchor_a = nvVector2_sub(contact->anchor_a, com_a);
+ contact->anchor_b = nvVector2_sub(contact->anchor_b, com_b);
+
+ for (size_t old_c = 0; old_c < old_pcp->contact_count; old_c++) {
+ nvContact old_contact = old_pcp->contacts[old_c];
+
+ if (old_contact.id == contact->id) {
+ contact->is_persisted = true;
+ contact->remove_invoked = old_contact.remove_invoked;
+
+ if (space->settings.warmstarting)
+ contact->solver_info = old_contact.solver_info;
+
+ if (space->listener) {
+ nvContactEvent event = {
+ .body_a = body_a,
+ .body_b = body_b,
+ .shape_a = shape_a,
+ .shape_b = shape_b,
+ .normal = pcp.normal,
+ .penetration = contact->separation,
+ .position = nvVector2_add(body_a->position, contact->anchor_a),
+ .normal_impulse = {contact->solver_info.normal_impulse},
+ .friction_impulse = {contact->solver_info.tangent_impulse},
+ .id = contact->id
+ };
+
+ // If the contact is penetrating call persisted event callback
+ // Else call removed callback once
+
+ if (contact->separation < 0.0) {
+ if (space->listener->on_contact_persisted)
+ persisted_queue[persisted_queue_size++] = event;
+ contact->remove_invoked = false;
+ }
+ else if (!contact->remove_invoked) {
+ if (space->listener->on_contact_removed)
+ removed_queue[removed_queue_size++] = event;
+ contact->remove_invoked = true;
+ };
+ }
+ }
+ }
+ }
+
+ // All the contacts are now removed but old pair had contacts
+ // So call removed event callbacks
+ if (pcp.contact_count == 0 && old_pcp->contact_count > 0) {
+ for (size_t old_c = 0; old_c < old_pcp->contact_count; old_c++) {
+ nvContact *contact = &old_pcp->contacts[old_c];
+
+ nvContactEvent event = {
+ .body_a = body_a,
+ .body_b = body_b,
+ .shape_a = shape_a,
+ .shape_b = shape_b,
+ .normal = pcp.normal,
+ .penetration = contact->separation,
+ .position = nvVector2_add(body_a->position, contact->anchor_a),
+ .normal_impulse = {contact->solver_info.normal_impulse},
+ .friction_impulse = {contact->solver_info.tangent_impulse},
+ .id = contact->id
+ };
+
+ if (space->listener && !contact->remove_invoked) {
+ if (space->listener->on_contact_removed)
+ removed_queue[removed_queue_size++] = event;
+ contact->remove_invoked = true;
+ };
+ }
+ }
+
+ nvHashMap_set(space->contacts, &pcp);
+
+ // Adding events to queue and calling them after setting the hashmap
+ // so the events can remove contacts
+ for (size_t qi = 0; qi < persisted_queue_size; qi++)
+ space->listener->on_contact_persisted(space, persisted_queue[qi], space->listener_arg);
+ for (size_t qi = 0; qi < removed_queue_size; qi++)
+ space->listener->on_contact_removed(space, removed_queue[qi], space->listener_arg);
+ }
+
+ // Contact doesn't exists, register the new contact info
+ else {
+ nvPersistentContactPair pcp;
+ generate_contact_pair(&pcp, body_a, body_b, shape_a, shape_b);
+
+ for (size_t c = 0; c < pcp.contact_count; c++) {
+ nvContact *contact = &pcp.contacts[c];
+
+ // Contacts relative to center of mass
+ contact->anchor_a = nvVector2_sub(contact->anchor_a, com_a);
+ contact->anchor_b = nvVector2_sub(contact->anchor_b, com_b);
+ }
+
+ nvHashMap_set(space->contacts, &pcp);
+
+ // Event after hashmap set so the event can remove the contact just after
+ for (size_t c = 0; c < pcp.contact_count; c++) {
+ nvContact *contact = &pcp.contacts[c];
+
+ if (
+ space->listener &&
+ space->listener->on_contact_added &&
+ contact->separation < 0.0
+ ) {
+ nvContactEvent event = {
+ .body_a = body_a,
+ .body_b = body_b,
+ .shape_a = shape_a,
+ .shape_b = shape_b,
+ .normal = pcp.normal,
+ .penetration = contact->separation,
+ .position = nvVector2_add(body_a->position, contact->anchor_a),
+ .normal_impulse = {contact->solver_info.normal_impulse},
+ .friction_impulse = {contact->solver_info.tangent_impulse},
+ .id = contact->id
+ };
+ space->listener->on_contact_added(space, event, space->listener_arg);
+ }
+ }
+ }
}
}
- else {
- nvResolution res_new;
- res_new.a = res.a;
- res_new.b = res.b;
- res_new.normal = res.normal;
- res_new.depth = res.depth;
- res_new.collision = res.collision;
- res_new.contact_count = res.contact_count;
- res_new.contacts[0] = res.contacts[0];
- res_new.contacts[1] = res.contacts[1];
- res_new.contacts[0].jn = 0.0;
- res_new.contacts[1].jn = 0.0;
- res_new.contacts[0].jt = 0.0;
- res_new.contacts[1].jt = 0.0;
- res_new.state = nvResolutionState_FIRST;
- res_new.lifetime = space->collision_persistence;
-
- nvHashMap_set(space->res, &res_new);
- }
- }
-
- // If the pair is actually not colliding, update the resolution state
- else if (res_exists) {
- nvResolution_update(space, found_res);
}
NV_TRACY_ZONE_END;
diff --git a/src/resolution.c b/src/resolution.c
deleted file mode 100644
index b72a262..0000000
--- a/src/resolution.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/resolution.h"
-#include "novaphysics/space.h"
-#include "novaphysics/hashmap.h"
-#include "novaphysics/threading.h"
-
-
-/**
- * @file resolution.c
- *
- * @brief Collision resolution data structure.
- */
-
-
-void nvResolution_update(nvSpace *space, nvResolution *res) {
- switch (res->state) {
- case nvResolutionState_FIRST:
- case nvResolutionState_NORMAL:
- res->state = nvResolutionState_CACHED;
- res->collision = false;
- break;
-
- case nvResolutionState_CACHED:
- if (res->lifetime <= 0) {
- nvHashMap_remove(space->res, &(nvResolution){.a=res->a, .b=res->b});
- }
- else {
- res->lifetime--;
- }
- break;
- }
-}
\ No newline at end of file
diff --git a/src/shape.c b/src/shape.c
index 2e47dd7..5ce1ee2 100644
--- a/src/shape.c
+++ b/src/shape.c
@@ -8,109 +8,239 @@
*/
+#include "novaphysics/internal.h"
#include "novaphysics/shape.h"
-#include "novaphysics/vector.h"
-#include "novaphysics/math.h"
/**
* @file shape.c
*
- * @brief Shape struct and methods.
- *
- * This module implements ShapeType enum, Shape struct and its methods.
+ * @brief Collision shape implementations.
*/
-nvShape *nvCircleShape_new(nv_float radius) {
+/*
+ Cheap solution, but it works..!
+ No one would need over 4 billion shapes... right?
+*/
+static nv_uint32 id_counter;
+
+
+nvShape *nvCircleShape_new(nvVector2 center, nv_float radius) {
nvShape *shape = NV_NEW(nvShape);
- if (!shape) return NULL;
+ NV_MEM_CHECK(shape);
+ shape->id = id_counter++;
shape->type = nvShapeType_CIRCLE;
+ nvCircle *circle = &shape->circle;
- shape->radius = radius;
+ circle->center = center;
+ circle->radius = radius;
return shape;
}
-nvShape *nvPolygonShape_new(nvArray *vertices) {
+nvShape *nvPolygonShape_new(
+ nvVector2 *vertices,
+ size_t num_vertices,
+ nvVector2 offset
+) {
+ if (num_vertices > NV_POLYGON_MAX_VERTICES) {
+ nv_set_error("Exceeds maximum number of vertices per convex polygon shape.");
+ return NULL;
+ }
+
+ if (num_vertices < 3) {
+ nv_set_error("Cannot create a polygon shape with fewer than 3 vertices.");
+ return NULL;
+ }
+
nvShape *shape = NV_NEW(nvShape);
- if (!shape) return NULL;
+ NV_MEM_CHECK(shape);
+
+ shape->id = id_counter++;
shape->type = nvShapeType_POLYGON;
+ nvPolygon *polygon = &shape->polygon;
+ polygon->num_vertices = num_vertices;
- shape->vertices = vertices;
+ for (size_t i = 0; i < num_vertices; i++)
+ polygon->vertices[i] = nvVector2_add(vertices[i], offset);
- shape->trans_vertices = nvArray_new();
- for (size_t i = 0; i < shape->vertices->size; i++)
- nvArray_add(shape->trans_vertices, NV_VEC2_NEW(0.0, 0.0));
+ for (size_t i = 0; i < num_vertices; i++)
+ polygon->xvertices[i] = nvVector2_zero;
- shape->normals = nvArray_new();
- for (size_t i = 0; i < shape->vertices->size; i++) {
- nvVector2 va = NV_TO_VEC2(shape->vertices->data[i]);
- nvVector2 vb = NV_TO_VEC2(shape->vertices->data[(i + 1) % shape->vertices->size]);
+ for (size_t i = 0; i < num_vertices; i++) {
+ nvVector2 va = polygon->vertices[i];
+ nvVector2 vb = polygon->vertices[(i + 1) % num_vertices];
- nvVector2 face = nvVector2_sub(vb, va);
- nvVector2 normal = nvVector2_normalize(nvVector2_perpr(face));
+ nvVector2 edge = nvVector2_sub(vb, va);
+ nvVector2 normal = nvVector2_normalize(nvVector2_perpr(edge));
- nvArray_add(shape->normals, NV_VEC2_NEW(normal.x, normal.y));
+ polygon->normals[i] = normal;
}
return shape;
}
-nvShape *nvRectShape_new(nv_float width, nv_float height) {
+nvShape *nvRectShape_new(nv_float width, nv_float height, nvVector2 offset) {
nv_float w = width / 2.0;
nv_float h = height / 2.0;
- nvArray *vertices = nvArray_new();
- nvArray_add(vertices, NV_VEC2_NEW(-w, -h));
- nvArray_add(vertices, NV_VEC2_NEW( w, -h));
- nvArray_add(vertices, NV_VEC2_NEW( w, h));
- nvArray_add(vertices, NV_VEC2_NEW(-w, h));
+ nvVector2 vertices[4] = {
+ NV_VECTOR2(-w, -h),
+ NV_VECTOR2( w, -h),
+ NV_VECTOR2( w, h),
+ NV_VECTOR2(-w, h)
+ };
- return nvPolygonShape_new(vertices);
+ return nvPolygonShape_new(vertices, 4, offset);
}
-nvShape *nvNGonShape_new(size_t n, nv_float radius) {
- NV_ASSERT(n >= 3, "Cannot create a polygon with vertices lesser than 3.\n");
+nvShape *nvNGonShape_new(size_t n, nv_float radius, nvVector2 offset) {
+ if (n < 3) {
+ nv_set_error("Cannot create a polygon shape with fewer than 3 vertices.");
+ return NULL;
+ }
+ if (n > NV_POLYGON_MAX_VERTICES) {
+ nv_set_error("Too many polygon vertices (check NV_POLYGON_MAX_VERTICES).");
+ return NULL;
+ }
- nvArray *vertices = nvArray_new();
- nvVector2 arm = NV_VEC2(radius / 2.0, 0.0);
+ nvVector2 vertices[NV_POLYGON_MAX_VERTICES];
+ nvVector2 arm = NV_VECTOR2(radius, 0.0);
for (size_t i = 0; i < n; i++) {
- nvArray_add(vertices, NV_VEC2_NEW(arm.x, arm.y));
+ vertices[i] = arm;
arm = nvVector2_rotate(arm, 2.0 * NV_PI / (nv_float)n);
}
- return nvPolygonShape_new(vertices);
+ return nvPolygonShape_new(vertices, n, offset);
}
-nvShape *nvConvexHullShape_new(nvArray *points) {
- nvArray *vertices = nv_generate_convex_hull(points);
+nvShape *nvConvexHullShape_new(
+ nvVector2 *points,
+ size_t num_points,
+ nvVector2 offset,
+ nv_bool center
+){
+ if (num_points < 3) {
+ nv_set_error("Cannot create a polygon shape with fewer than 3 vertices.");
+ return NULL;
+ }
- // Transform hull vertices so the center of gravity is at center
- nvVector2 hull_centroid = nv_polygon_centroid(vertices);
+ nvVector2 vertices[NV_POLYGON_MAX_VERTICES];
+ size_t num_vertices = nv_generate_convex_hull(points, num_points, vertices);
- for (size_t i = 0; i < vertices->size; i++) {
- nvVector2 new_vert = nvVector2_sub(NV_TO_VEC2(vertices->data[i]), hull_centroid);
- nvVector2 *current_vert = NV_TO_VEC2P(vertices->data[i]);
- current_vert->x = new_vert.x;
- current_vert->y = new_vert.y;
+ if (center) {
+ nvVector2 hull_centroid = nv_polygon_centroid(vertices, num_vertices);
+ for (size_t i = 0; i < num_vertices; i++) {
+ vertices[i] = nvVector2_sub(vertices[i], hull_centroid);
+ }
}
- return nvPolygonShape_new(vertices);
+ return nvPolygonShape_new(vertices, num_vertices, offset);
}
void nvShape_free(nvShape *shape) {
- if (shape->type == nvShapeType_POLYGON) {
- nvArray_free_each(shape->vertices, free);
- nvArray_free(shape->vertices);
- nvArray_free_each(shape->trans_vertices, free);
- nvArray_free(shape->trans_vertices);
- nvArray_free_each(shape->normals, free);
- nvArray_free(shape->normals);
+ if (!shape) return;
+
+ NV_FREE(shape);
+}
+
+nvAABB nvShape_get_aabb(nvShape *shape, nvTransform xform) {
+ NV_TRACY_ZONE_START;
+
+ nv_float min_x;
+ nv_float min_y;
+ nv_float max_x;
+ nv_float max_y;
+
+ nvAABB aabb;
+
+ // TODO: Do not inflate AABBs here.
+ nv_float inflate = 0.00;
+
+ switch (shape->type) {
+ case nvShapeType_CIRCLE: {
+ nvVector2 c = nvVector2_add(nvVector2_rotate(shape->circle.center, xform.angle), xform.position);
+ aabb = (nvAABB){
+ c.x - shape->circle.radius,
+ c.y - shape->circle.radius,
+ c.x + shape->circle.radius,
+ c.y + shape->circle.radius
+ };
+
+ NV_TRACY_ZONE_END;
+ return nvAABB_inflate(aabb, inflate);
+ }
+ case nvShapeType_POLYGON: {
+ min_x = NV_INF;
+ min_y = NV_INF;
+ max_x = -NV_INF;
+ max_y = -NV_INF;
+
+ nvPolygon_transform(shape, xform);
+
+ for (size_t i = 0; i < shape->polygon.num_vertices; i++) {
+ nvVector2 v = shape->polygon.xvertices[i];
+ if (v.x < min_x) min_x = v.x;
+ if (v.x > max_x) max_x = v.x;
+ if (v.y < min_y) min_y = v.y;
+ if (v.y > max_y) max_y = v.y;
+ }
+
+ aabb = (nvAABB){min_x, min_y, max_x, max_y};
+
+ NV_TRACY_ZONE_END;
+ return nvAABB_inflate(aabb, inflate);
+ }
+ default:
+ NV_TRACY_ZONE_END;
+ return (nvAABB){0.0, 0.0, 0.0, 0.0};
+ }
+}
+
+nvShapeMassInfo nvShape_calculate_mass(nvShape *shape, nv_float density) {
+ nv_float mass, inertia;
+
+ switch (shape->type) {
+ case nvShapeType_CIRCLE: {
+ nvCircle circle = shape->circle;
+
+ mass = nv_circle_area(circle.radius) * density;
+ inertia = nv_circle_inertia(mass, circle.radius, circle.center);
+
+ return (nvShapeMassInfo){mass, inertia, circle.center};
+ }
+ case nvShapeType_POLYGON: {
+ nvPolygon polygon = shape->polygon;
+
+ mass = nv_polygon_area(polygon.vertices, polygon.num_vertices) * density;
+ inertia = nv_polygon_inertia(mass, polygon.vertices, polygon.num_vertices);
+ nvVector2 centroid = nv_polygon_centroid(polygon.vertices, polygon.num_vertices);
+
+ return (nvShapeMassInfo){mass, inertia, centroid};
+ }
+ default:
+ nv_set_error("Invalid shape.");
+ return (nvShapeMassInfo){-1.0, -1.0, NV_VECTOR2(-1.0, -1.0)};
+ }
+}
+
+void nvPolygon_transform(nvShape *shape, nvTransform xform) {
+ NV_TRACY_ZONE_START;
+
+ for (size_t i = 0; i < shape->polygon.num_vertices; i++) {
+ nvVector2 new = nvVector2_add(xform.position,
+ nvVector2_rotate(
+ shape->polygon.vertices[i],
+ xform.angle
+ )
+ );
+
+ shape->polygon.xvertices[i] = new;
}
- free(shape);
+ NV_TRACY_ZONE_END;
}
\ No newline at end of file
diff --git a/src/shg.c b/src/shg.c
deleted file mode 100644
index 105c81c..0000000
--- a/src/shg.c
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include
-#include "novaphysics/internal.h"
-#include "novaphysics/shg.h"
-#include "novaphysics/body.h"
-#include "novaphysics/debug.h"
-
-
-/**
- * @file shg.c
- *
- * @brief Spatial Hash Grid implementation.
- */
-
-
-// Hashing function for SHG cells
-static nv_uint64 nvSHG_hash(void *item) {
- nvSHGEntry *entry = (nvSHGEntry *)item;
- return (nv_uint64)nv_hash(entry->xy_pair);
-}
-
-
-nvSHG *nvSHG_new(
- nvAABB bounds,
- nv_float cell_width,
- nv_float cell_height
-) {
- nvSHG *shg = NV_NEW(nvSHG);
- if (!shg) return NULL;
-
- shg->bounds = bounds;
- shg->cols = (nv_uint32)((bounds.max_x - bounds.min_x) / cell_width);
- shg->rows = (nv_uint32)((bounds.max_y - bounds.min_y) / cell_height);
- shg->cell_width = cell_width;
- shg->cell_height = cell_height;
-
- shg->map = nvHashMap_new(sizeof(nvSHGEntry), 0, nvSHG_hash);
- if (!shg->map) return NULL;
-
- return shg;
-}
-
-void nvSHG_free(nvSHG *shg) {
- if (!shg) return;
-
- size_t iter = 0;
- void *item;
- while (nvHashMap_iter(shg->map, &iter, &item)) {
- nvSHGEntry *entry = (nvSHGEntry *)item;
- if (entry->cell != NULL) free((entry)->cell);
- }
- nvHashMap_free(shg->map);
- free(shg);
-}
-
-nvArray *nvSHG_get(nvSHG *shg, nv_uint32 key) {
- nvSHGEntry *entry = (nvSHGEntry *)nvHashMap_get(shg->map, &(nvSHGEntry){.xy_pair=key});
- if (entry == NULL) return NULL;
- else return entry->cell;
-}
-
-void nvSHG_place(nvSHG *shg, nvArray *bodies) {
- NV_TRACY_ZONE_START;
-
- size_t iter = 0;
- void *item;
-
- // Free each array from previous frame
- while (nvHashMap_iter(shg->map, &iter, &item)) {
- nvSHGEntry *entry = (nvSHGEntry *)item;
- nvArray_free((entry)->cell);
- }
-
- nvHashMap_clear(shg->map);
-
- for (nv_uint32 i = 0; i < bodies->size; i++) {
- nvBody *body = (nvBody *)bodies->data[i];
- nvAABB aabb = nvBody_get_aabb(body);
-
- /*
- Spread AABB to exceeding cells
-
- min
- [ ] ---- [ ]
- | |
- | |
- [ ] ---- [ ]
- max
- */
-
- nv_int16 min_x = (nv_int16)(aabb.min_x / shg->cell_width);
- nv_int16 min_y = (nv_int16)(aabb.min_y / shg->cell_height);
- nv_int16 max_x = (nv_int16)(aabb.max_x / shg->cell_width);
- nv_int16 max_y = (nv_int16)(aabb.max_y / shg->cell_height);
-
- for (nv_int16 y = min_y; y < max_y + 1; y++) {
- for (nv_int16 x = min_x; x < max_x + 1; x++) {
-
- // Don't insert outside of the borders
- if (0 <= x && x < (signed)shg->cols && 0 <= y && y < (signed)shg->rows) {
- nv_uint32 pair = nv_pair(x, y);
-
- nvSHGEntry *entry = (nvSHGEntry *)nvHashMap_get(shg->map, &(nvSHGEntry){.xy_pair=pair});
-
- // If grid doesn't exist, create it
- if (entry == NULL) {
- nvArray *new_cell = nvArray_new();
- nvArray_add(new_cell, body);
- nvHashMap_set(shg->map, &(nvSHGEntry){.xy_pair=pair, .cell=new_cell});
- }
-
- // If grid exists, add body to it
- else {
- nvArray_add(entry->cell, body);
- }
- }
-
- }
- }
- }
-
- NV_TRACY_ZONE_END;
-}
-
-void nvSHG_get_neighbors(
- nvSHG *shg,
- nv_int16 x0,
- nv_int16 y0,
- nv_uint32 neighbors[],
- bool neighbor_flags[]
-) {
- /*
- One cell has 8 neighbor cells
-
- [ ][ ][ ]
- [ ][X][ ]
- [ ][ ][ ]
-
- Depending on the position, neighbors change
- to keep them inside the boundaries
-
- Corner case: Border case:
- [X][ ] [ ][ ]
- [ ][ ] [X][ ]
- [ ][ ]
- */
-
- NV_TRACY_ZONE_START;
-
- // Initialize flag array
- for (size_t j = 0; j < 8; j++)
- neighbor_flags[j] = false;
-
- size_t i = 0;
-
- // TODO: This might be optimized
- for (nv_int16 y1 = -1; y1 < 2; y1++) {
- for (nv_int16 x1 = -1; x1 < 2; x1++) {
-
- nv_int16 x = (signed)x0 + x1;
- nv_int16 y = (signed)y0 + y1;
-
- // Skip current cell
- if (x == x0 && y == y0) continue;
-
- // Skip cells outside the boundaries
- if (0 <= x && x < (signed)shg->cols && 0 <= y && y < (signed)shg->rows) {
- neighbors[i] = nv_pair(x, y);
- neighbor_flags[i] = true;
- i++;
- }
- }
- }
-
- NV_TRACY_ZONE_END;
-}
\ No newline at end of file
diff --git a/src/space.c b/src/space.c
index 9b222ef..057a27d 100644
--- a/src/space.c
+++ b/src/space.c
@@ -8,19 +8,13 @@
*/
-#include
-#include "novaphysics/internal.h"
#include "novaphysics/space.h"
#include "novaphysics/constants.h"
#include "novaphysics/body.h"
#include "novaphysics/collision.h"
#include "novaphysics/contact.h"
-#include "novaphysics/contact_solver.h"
#include "novaphysics/math.h"
-#include "novaphysics/constraint.h"
#include "novaphysics/narrowphase.h"
-#include "novaphysics/debug.h"
-#include "novaphysics/space_step.h"
/**
@@ -30,70 +24,69 @@
*/
+#define ITER_BODIES(iter) for (size_t iter = 0; iter < space->bodies->size; iter++)
+
+
nvSpace *nvSpace_new() {
nvSpace *space = NV_NEW(nvSpace);
if (!space) return NULL;
space->bodies = nvArray_new();
- space->awake_bodies = nvArray_new();
- space->attractors = nvArray_new();
space->constraints = nvArray_new();
- space->_removed_bodies = nvArray_new();
- space->_killed_bodies = nvArray_new();
-
- space->res = nvHashMap_new(sizeof(nvResolution), 0, _nvSpace_resolution_hash);
-
- space->gravity = NV_VEC2(0.0, NV_GRAV_EARTH);
-
- space->sleeping = false;
- space->sleep_energy_threshold = 0.02;
- space->wake_energy_threshold = space->sleep_energy_threshold / 1.3;
- space->sleep_timer_threshold = 60;
-
- space->warmstarting = true;
- space->collision_persistence = NV_COLLISION_PERSISTENCE;
- space->position_correction = nvPositionCorrection_BAUMGARTE;
+ nvSpace_set_gravity(space, NV_VECTOR2(0.0, NV_GRAV_EARTH));
- space->shg = NULL;
- nvSpace_set_broadphase(space, nvBroadPhaseAlg_SHG);
+ space->settings = (nvSpaceSettings){
+ .baumgarte = 0.2,
+ .penetration_slop = 0.05,
+ .contact_position_correction = nvContactPositionCorrection_BAUMGARTE,
+ .velocity_iterations = 8,
+ .position_iterations = 4,
+ .substeps = 1,
+ .linear_damping = 0.0005,
+ .angular_damping = 0.0005,
+ .warmstarting = true,
+ .restitution_mix = nvCoefficientMix_SQRT,
+ .friction_mix = nvCoefficientMix_SQRT
+ };
- space->broadphase_pairs = nvHashMap_new(sizeof(nvBroadPhasePair), 0, _nvSpace_broadphase_pair_hash);
+ nvSpace_set_broadphase(space, nvBroadPhaseAlg_BRUTE_FORCE);
- space->kill_bounds = (nvAABB){-1e4, -1e4, 1e4, 1e4};
- space->use_kill_bounds = true;
+ space->broadphase_pairs = nvMemoryPool_new(sizeof(nvBroadPhasePair), NV_BPH_POOL_INITIAL_SIZE);
+ space->contacts = nvHashMap_new(sizeof(nvPersistentContactPair), 0, nvPersistentContactPair_hash);
+ space->removed_contacts = nvHashMap_new(sizeof(nvPersistentContactPair), 0, nvPersistentContactPair_hash);
- space->mix_restitution = nvCoefficientMix_SQRT;
- space->mix_friction = nvCoefficientMix_SQRT;
-
- space->callback_user_data = NULL;
- space->before_collision = NULL;
- space->after_collision = NULL;
+ space->listener = NULL;
+ space->listener_arg = NULL;
nvProfiler_reset(&space->profiler);
- space->multithreading = false;
- space->task_executor = NULL;
- space->mt_shg_bins = NULL;
- space->mt_shg_pairs = NULL;
- space->thread_count = 0;
-
- space->_id_counter = 0;
+ space->id_counter = 1;
return space;
}
void nvSpace_free(nvSpace *space) {
- nvSpace_clear(space);
- nvArray_free_each(space->bodies, nvBody_free);
+ if (!space) return;
+
+ nvSpace_clear(space, true);
nvArray_free(space->bodies);
- nvArray_free(space->awake_bodies);
- nvArray_free(space->attractors);
- nvArray_free_each(space->constraints, nvConstraint_free);
nvArray_free(space->constraints);
- nvHashMap_free(space->res);
+ nvMemoryPool_free(space->broadphase_pairs);
+ nvHashMap_free(space->contacts);
+ nvHashMap_free(space->removed_contacts);
+
+ NV_FREE(space->listener);
- free(space);
+ NV_FREE(space);
+}
+
+void nvSpace_set_gravity(nvSpace *space, nvVector2 gravity) {
+ space->gravity = gravity;
+}
+
+nvVector2 nvSpace_get_gravity(const nvSpace *space) {
+ return space->gravity;
}
void nvSpace_set_broadphase(nvSpace *space, nvBroadPhaseAlg broadphase_alg_type) {
@@ -102,99 +95,162 @@ void nvSpace_set_broadphase(nvSpace *space, nvBroadPhaseAlg broadphase_alg_type)
space->broadphase_algorithm = nvBroadPhaseAlg_BRUTE_FORCE;
return;
- case nvBroadPhaseAlg_SHG:
- space->broadphase_algorithm = nvBroadPhaseAlg_SHG;
-
- // Default SHG configuration
- nvAABB bounds = {.min_x=0.0, .min_y=0.0, .max_x=128.0, .max_y=72.0};
- nv_float cell_size = 3.5;
-
- nvSpace_set_SHG(space, bounds, cell_size, cell_size);
-
- return;
-
case nvBroadPhaseAlg_BVH:
space->broadphase_algorithm = nvBroadPhaseAlg_BVH;
return;
}
}
-void nvSpace_set_SHG(
+nvBroadPhaseAlg nvSpace_get_broadphase(const nvSpace *space) {
+ return space->broadphase_algorithm;
+}
+
+nvSpaceSettings *nvSpace_get_settings(nvSpace *space) {
+ return &space->settings;
+}
+
+nvProfiler nvSpace_get_profiler(const nvSpace *space) {
+ return space->profiler;
+}
+
+int nvSpace_set_contact_listener(
nvSpace *space,
- nvAABB bounds,
- nv_float cell_width,
- nv_float cell_height
+ nvContactListener listener,
+ void *user_arg
) {
- if (space->broadphase_algorithm == nvBroadPhaseAlg_SHG) {
- nvSHG_free(space->shg);
- space->shg = nvSHG_new(bounds, cell_width, cell_height);
- }
+ space->listener = NV_NEW(nvContactListener);
+ NV_MEM_CHECKI(space->listener);
+ *space->listener = listener;
+ space->listener_arg = user_arg;
+ return 0;
+}
+
+nvContactListener *nvSpace_get_contact_listener(const nvSpace *space) {
+ return space->listener;
}
-void nvSpace_clear(nvSpace *space) {
- nvArray_clear(space->bodies, nvBody_free);
- nvArray_clear(space->awake_bodies, NULL);
- nvArray_clear(space->attractors, NULL);
- nvArray_clear(space->constraints, nvConstraint_free);
- nvHashMap_clear(space->res);
+int nvSpace_clear(nvSpace *space, nv_bool free_all) {
+ if (free_all) {
+ if (nvArray_clear(space->bodies, (void (*)(void *))nvRigidBody_free)) return 1;
+ if (nvArray_clear(space->constraints, (void (*)(void *))nvConstraint_free)) return 1;
+ nvMemoryPool_clear(space->broadphase_pairs);
+ nvHashMap_clear(space->contacts);
+ }
+ else {
+ if (nvArray_clear(space->bodies, NULL)) return 1;
+ if (nvArray_clear(space->constraints, NULL)) return 1;
+ nvMemoryPool_clear(space->broadphase_pairs);
+ nvHashMap_clear(space->contacts);
+ }
+ return 0;
}
-void nvSpace_add(nvSpace *space, nvBody *body) {
- NV_ASSERT(body->space != space, "You can't add the same body to the same space multiple times.");
+int nvSpace_add_rigidbody(nvSpace *space, nvRigidBody *body) {
+ if (body->space == space) {
+ nv_set_error("Can't add same body to same space more than once.");
+ return 2;
+ }
+
+ if (nvArray_add(space->bodies, body))
+ return 1;
- nvArray_add(space->bodies, body);
body->space = space;
- body->id = space->_id_counter;
- space->_id_counter++;
+ body->id = space->id_counter++;
+
+ return 0;
}
-void nvSpace_remove(nvSpace *space, nvBody *body) {
- nvArray_add(space->_removed_bodies, body);
+int nvSpace_remove_rigidbody(nvSpace *space, nvRigidBody *body) {
+ if (nvArray_remove(space->bodies, body) == (size_t)(-1)) return 1;
+
+ // Remove broadphase pairs
+ // This could break contacts if a remove call is made in an event callback
+ for (size_t i = 0; i < space->broadphase_pairs->current_size; i++) {
+ void *pool_i = (char *)space->broadphase_pairs->pool + i * space->broadphase_pairs->chunk_size;
+ nvBroadPhasePair *pair = (nvBroadPhasePair *)pool_i;
+ nvRigidBody *body_a = pair->a;
+ nvRigidBody *body_b = pair->b;
+
+ if (body_a == body || body_b == body) {
+ pair->a = NULL;
+ pair->b = NULL;
+ }
+ }
+
+ // Remove contacts
+ void *map_val;
+ size_t map_iter = 0;
+ while (nvHashMap_iter(body->space->contacts, &map_iter, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
+
+ if (pcp->body_a == body || pcp->body_b == body) {
+ nvPersistentContactPair_remove(body->space, pcp);
+ map_iter = 0;
+ continue;
+ }
+ }
+
+ // Remove constraints
+ nvArray *removed_constraints = nvArray_new();
+ for (size_t i = 0; i < space->constraints->size; i++) {
+ nvConstraint *cons = space->constraints->data[i];
+
+ if (cons->a == body || cons->b == body)
+ nvArray_add(removed_constraints, cons);
+ }
+ for (size_t i = 0; i < removed_constraints->size; i++) {
+ nvArray_remove(space->constraints, removed_constraints->data[i]);
+ }
+
+ return 0;
}
-void nvSpace_kill(nvSpace *space, nvBody *body) {
- nvArray_add(space->_killed_bodies, body);
+int nvSpace_add_constraint(nvSpace *space, nvConstraint *cons) {
+ // TODO: This is inefficient
+ for (size_t i = 0; i < space->constraints->size; i++) {
+ nvConstraint *lcons = space->constraints->data[i];
+
+ if (lcons == cons) {
+ nv_set_error("Can't add same constraint to same space more than once.");
+ return 2;
+ }
+ }
+
+ return nvArray_add(space->constraints, cons);
}
-void nvSpace_add_constraint(nvSpace *space, nvConstraint *cons) {
- nvArray_add(space->constraints, cons);
+int nvSpace_remove_constraint(nvSpace *space, nvConstraint *cons) {
+ if (nvArray_remove(space->constraints, cons) == (size_t)(-1))
+ return 1;
+ return 0;
}
-void nvSpace_step(
- nvSpace *space,
- nv_float dt,
- size_t velocity_iters,
- size_t position_iters,
- size_t constraint_iters,
- size_t substeps
-) {
+nv_bool nvSpace_iter_bodies(nvSpace *space, nvRigidBody **body, size_t *index) {
+ *body = space->bodies->data[(*index)++];
+ return (*index <= space->bodies->size);
+}
+
+nv_bool nvSpace_iter_constraints(nvSpace *space, nvConstraint **cons, size_t *index) {
+ *cons = space->constraints->data[(*index)++];
+ return (*index <= space->constraints->size);
+}
+
+void nvSpace_step(nvSpace *space, nv_float dt) {
+ if (dt == 0.0 || space->settings.substeps <= 0) return;
+ nv_uint32 substeps = space->settings.substeps;
+ nv_uint32 velocity_iters = space->settings.velocity_iterations;
+
/*
Simulation route
----------------
- 1. Integrate accelerations
- 2. Broad-phase
- 3. Update resolutions
- 4. Narrow-phase
- 5. Solve contact velocity constraints (PGS)
- 6. Solve joint constraints (Baumgarte)
- 7. Integrate velocities
- 8. Position correction (NGS)
- 9. Rest bodies
-
-
- Nova Physics uses semi-implicit Euler integration:
-
- Linear:
- v = a * Δt
- x = v * Δt
-
- Angular:
- ω = α * Δt
- θ = ω * Δt
+ 1. Broadphase
+ 2. Narrowphase
+ 3. Integrate accelerations
+ 4. Solve constraints (PGS + Baumgarte)
+ 5. Integrate velocities
+ 6. Contact position correction (NGS)
*/
- if (dt == 0.0 || substeps <= 0) return;
-
NV_TRACY_ZONE_START;
nvPrecisionTimer step_timer;
@@ -202,215 +258,120 @@ void nvSpace_step(
nvPrecisionTimer timer;
- size_t i, j, k, l;
+ // For iterating contacts hashmap
+ size_t l;
void *map_val;
dt /= (nv_float)substeps;
nv_float inv_dt = 1.0 / dt;
- for (k = 0; k < substeps; k++) {
-
- // TODO: Instead of clearing and filling this array every frame, update it when individual bodies are slept & awaken
- nvArray_clear(space->awake_bodies, NULL);
- for (i = 0; i < space->bodies->size; i++) {
- nvBody *body = space->bodies->data[i];
-
- if (!body->is_sleeping) {
- nvArray_add(space->awake_bodies, body);
- }
- }
-
+ for (nv_uint32 substep = 0; substep < substeps; substep++) {
/*
Integrate accelerations
-----------------------
Apply forces, gravity, integrate accelerations (update velocities) and apply damping.
+ We do this step first to reset body caches.
*/
NV_PROFILER_START(timer);
- #if defined(NV_AVX) && defined(NV_USE_SIMD)
+ ITER_BODIES(body_i) {
+ nvRigidBody *body = (nvRigidBody *)space->bodies->data[body_i];
- _nvSpace_integrate_accelerations_AVX(
- space,
- dt
- );
-
- #else
-
- for (i = 0; i < space->awake_bodies->size; i++) {
- _nvSpace_integrate_accelerations(space, dt, i);
- }
-
- #endif
+ nvRigidBody_integrate_accelerations(body, space->gravity, dt);
+ }
NV_PROFILER_STOP(timer, space->profiler.integrate_accelerations);
/*
- Broad-phase
- -----------
- Generate possible collision pairs with the choosen broad-phase algorithm.
+ Broadphase
+ ----------
+ Generate possible collision pairs with the choosen broadphase algorithm.
*/
NV_PROFILER_START(timer);
switch (space->broadphase_algorithm) {
case nvBroadPhaseAlg_BRUTE_FORCE:
- nvBroadPhase_brute_force(space);
- break;
-
- case nvBroadPhaseAlg_SHG:
- if (space->multithreading)
- nvBroadPhase_SHG_parallel(space);
-
- else
- nvBroadPhase_SHG(space);
-
+ nv_broadphase_brute_force(space);
break;
case nvBroadPhaseAlg_BVH:
- nvBroadPhase_BVH(space);
+ nv_broadphase_BVH(space);
break;
}
-
- // Combine separate pairs from parallel broadphase into one
- if (space->multithreading) {
- nvHashMap_clear(space->broadphase_pairs);
-
- for (i = 0; i < space->thread_count; i++) {
- l = 0;
- while (nvHashMap_iter((nvHashMap *)space->mt_shg_pairs->data[i], &l, &map_val)) {
- nvBroadPhasePair *pair = map_val;
- nvHashMap_set(space->broadphase_pairs, pair);
- }
- }
- }
NV_PROFILER_STOP(timer, space->profiler.broadphase);
- /*
- Update resolutions
- ------------------
- Update the collision resolutions from last frame for collision persistence.
- */
- l = 0;
NV_PROFILER_START(timer);
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = (nvResolution *)map_val;
- nvBody *a = res->a;
- nvBody *b = res->b;
-
- nvBody *pair_a, *pair_b;
- if (a->id < b->id) {
- pair_a = a;
- pair_b = b;
- }
- else {
- pair_a = b;
- pair_b = a;
- }
- nv_uint32 id_pair = nv_pair(pair_a->id, pair_b->id);
-
- if (!nvHashMap_get(space->broadphase_pairs, &(nvBroadPhasePair){.a=pair_a, .b=pair_b, .id_pair=id_pair})) {
- nvResolution_update(space, res);
- continue;
- }
-
- nvAABB abox = nvBody_get_aabb(a);
- nvAABB bbox = nvBody_get_aabb(b);
-
- // Even though the AABBs could be colliding, if the resolution is cached update it
- if (res->state == nvResolutionState_CACHED) {
- if (res->lifetime <= 0) {
- nvHashMap_remove(space->res, &(nvResolution){.a=a, .b=b});
- }
-
- else {
- res->lifetime--;
- }
- }
-
- else if (!nv_collide_aabb_x_aabb(abox, bbox)) {
- nvResolution_update(space, res);
- }
- }
- NV_PROFILER_STOP(timer, space->profiler.update_resolutions);
+ nv_broadphase_finalize(space);
+ NV_PROFILER_STOP(timer, space->profiler.broadphase_finalize);
/*
- Narrow-phase
+ Narrowphase
------------
Do narrow-phase checks between possible collision pairs and
- update collision resolutions.
+ create & update contact pairs.
*/
NV_PROFILER_START(timer);
nv_narrow_phase(space);
NV_PROFILER_STOP(timer, space->profiler.narrowphase);
/*
- PGS / Projected Gauss-Seidel
- ----------------------------
- Prepare contact velocity constraints, warm-start and solve iteratively
- */
+ Solve constraints (PGS + Baumgarte)
+ -----------------------------------
+ Prepare velocity constraints, warm-start and solve iteratively.
+ Use baumgarte depending on the position correction setting.
- // Call callback before resolving collisions
- if (space->before_collision != NULL)
- space->before_collision(space, space->callback_user_data);
+ Sequential Impulses / PGS + Baumgarte:
+ https://box2d.org/files/ErinCatto_SequentialImpulses_GDC2006.pdf
+ */
- // Prepare for solving contact constraints
- l = 0;
+ // Prepare constraints for solving
NV_PROFILER_START(timer);
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = map_val;
- if (res->state == nvResolutionState_CACHED) continue;
- nv_presolve_contact(space, res, inv_dt);
+ for (size_t i = 0; i < space->constraints->size; i++) {
+ nvConstraint_presolve(
+ space,
+ (nvConstraint *)space->constraints->data[i],
+ dt,
+ inv_dt
+ );
}
- // Apply accumulated impulses
l = 0;
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = map_val;
- if (res->state == nvResolutionState_CACHED) continue;
- nv_warmstart(space, res);
+ while (nvHashMap_iter(space->contacts, &l, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
+ nv_contact_presolve(space, pcp, inv_dt);
}
- NV_PROFILER_STOP(timer, space->profiler.presolve_collisions);
+ NV_PROFILER_STOP(timer, space->profiler.presolve);
- // Solve velocity constraints iteratively
+ // Warmstart constraints
NV_PROFILER_START(timer);
- for (i = 0; i < velocity_iters; i++) {
- l = 0;
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = map_val;
- if (res->state == nvResolutionState_CACHED) continue;
- nv_solve_velocity(res);
- }
- }
- NV_PROFILER_STOP(timer, space->profiler.solve_velocities);
-
- // Call callback after resolving collisions
- if (space->after_collision != NULL)
- space->after_collision(space, space->callback_user_data);
-
- /*
- Solve joint constraints (Baumgarte)
- -----------------------------------
- Solve joint constraints iteratively and apply sequential impulses.
- */
-
- // Prepare joint constraints for solving
- NV_PROFILER_START(timer);
- for (i = 0; i < space->constraints->size; i++) {
- nvConstraint_presolve(
+ for (size_t i = 0; i < space->constraints->size; i++) {
+ nvConstraint_warmstart(
space,
- (nvConstraint *)space->constraints->data[i],
- inv_dt
+ (nvConstraint *)space->constraints->data[i]
);
}
- NV_PROFILER_STOP(timer, space->profiler.presolve_constraints);
- // Solve joint constraints iteratively
+ l = 0;
+ while (nvHashMap_iter(space->contacts, &l, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
+ nv_contact_warmstart(space, pcp);
+ }
+ NV_PROFILER_STOP(timer, space->profiler.warmstart);
+
+ // Solve constraints iteratively
NV_PROFILER_START(timer);
- for (i = 0; i < constraint_iters; i++) {
- for (j = 0; j < space->constraints->size; j++) {
+ for (size_t i = 0; i < velocity_iters; i++) {
+ for (size_t j = 0; j < space->constraints->size; j++) {
nvConstraint_solve(
(nvConstraint *)space->constraints->data[j],
inv_dt
);
}
+
+ l = 0;
+ while (nvHashMap_iter(space->contacts, &l, &map_val)) {
+ nvPersistentContactPair *pcp = map_val;
+ nv_contact_solve_velocity(pcp);
+ }
}
- NV_PROFILER_STOP(timer, space->profiler.solve_constraints);
+ NV_PROFILER_STOP(timer, space->profiler.solve_velocities);
/*
Integrate velocities
@@ -418,174 +379,85 @@ void nvSpace_step(
Integrate velocities (update positions) and check out-of-bound bodies.
*/
NV_PROFILER_START(timer);
- #if defined(NV_AVX) && defined(NV_USE_SIMD)
-
- _nvSpace_integrate_velocities_AVX(space, dt);
-
- #else
-
- for (i = 0; i < space->awake_bodies->size; i++) {
- _nvSpace_integrate_velocities(space, dt, i);
- }
-
- #endif
- NV_PROFILER_STOP(timer, space->profiler.integrate_velocities);
-
- /*
- NGS / Non-Linear Gauss-Seidel
- -----------------------------
- Solve position error with pseudo-velocities.
- */
- NV_PROFILER_START(timer);
- if (space->position_correction == nvPositionCorrection_NGS) {
- for (i = 0; i < position_iters; i++) {
- l = 0;
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = map_val;
- if (res->state == nvResolutionState_CACHED) continue;
- nv_solve_position(res);
- }
- }
- }
- NV_PROFILER_STOP(timer, space->profiler.solve_positions);
+ ITER_BODIES(body_i) {
+ nvRigidBody *body = (nvRigidBody *)space->bodies->data[body_i];
- /*
- Rest bodies
- -----------
- Detect bodies with mimimal energy and rest (sleep) them.
- */
- if (space->sleeping) {
- for (i = 0; i < space->bodies->size; i++) {
- nvBody *body = (nvBody *)space->bodies->data[i];
-
- nv_float linear = nvVector2_len2(body->linear_velocity) * dt;
- nv_float angular = body->angular_velocity * dt;
- nv_float total_energy = linear + angular;
+ nvRigidBody_integrate_velocities(body, dt);
- if (total_energy <= space->sleep_energy_threshold / substeps) {
- body->sleep_timer++;
+ body->origin = nvVector2_sub(body->position, nvVector2_rotate(body->com, body->angle));
- if (body->sleep_timer > space->sleep_timer_threshold * substeps) {
- nvBody_sleep(body);
- body->sleep_timer = 0;
- }
- }
- else {
- if (body->sleep_timer > 0) body->sleep_timer--;
- }
+ // Reset caches
+ if (body->type != nvRigidBodyType_STATIC) {
+ body->cache_aabb = false;
+ body->cache_transform = false;
}
}
+ NV_PROFILER_STOP(timer, space->profiler.integrate_velocities);
}
-
- // Actually remove all killed & removed bodies from the arrays
-
- NV_PROFILER_START(timer);
-
- for (i = 0; i < space->_removed_bodies->size; i++) {
- nvBody *body = (nvBody *)space->_removed_bodies->data[i];
-
- l = 0;
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = map_val;
- if (res->a == body) {
- nvHashMap_remove(space->res, res);
- l = 0;
- }
- else if (res->b == body) {
- nvHashMap_remove(space->res, res);
- l = 0;
- }
- }
-
- nvArray_remove(space->bodies, body);
- }
-
- for (i = 0; i < space->_killed_bodies->size; i++) {
- nvBody *body = (nvBody *)space->_killed_bodies->data[i];
-
- l = 0;
- while (nvHashMap_iter(space->res, &l, &map_val)) {
- nvResolution *res = map_val;
- if (res->a == body) {
- nvHashMap_remove(space->res, res);
- l = 0;
- }
- else if (res->b == body) {
- nvHashMap_remove(space->res, res);
- l = 0;
- }
- }
-
- nvArray_remove(space->bodies, body);
- nvBody_free(body);
- }
-
- nvArray_clear(space->_removed_bodies, NULL);
- nvArray_clear(space->_killed_bodies, NULL);
-
- NV_PROFILER_STOP(timer, space->profiler.remove_bodies);
+
NV_PROFILER_STOP(step_timer, space->profiler.step);
NV_TRACY_ZONE_END;
NV_TRACY_FRAMEMARK;
}
-void nvSpace_enable_sleeping(nvSpace *space) {
- space->sleeping = true;
-}
-
-void nvSpace_disable_sleeping(nvSpace *space) {
- space->sleeping = false;
- for (size_t i = 0; i < space->bodies->size; i++)
- nvBody_awake((nvBody *)space->bodies->data[i]);
-}
-
-void nvSpace_enable_multithreading(nvSpace *space, size_t threads) {
- if (space->multithreading) return;
-
- size_t thread_count = (threads == 0) ? nv_get_cpu_count() : threads;
- space->thread_count = thread_count;
+void nvSpace_cast_ray(
+ nvSpace *space,
+ nvVector2 from,
+ nvVector2 to,
+ nvRayCastResult *results_array,
+ size_t *num_hits,
+ size_t capacity
+) {
+ /*
+ TODO
+ Ray checking order:
+ BVH (or current bph) -> Shape AABBs -> Individual shapes
+ */
+ *num_hits = 0;
- space->task_executor = nvTaskExecutor_new(thread_count);
+ nvVector2 delta = nvVector2_sub(to, from);
+ nvVector2 dir = nvVector2_normalize(delta);
+ nv_float maxsq = nvVector2_len2(delta);
- space->mt_shg_bins = nvArray_new();
- space->mt_shg_pairs = nvArray_new();
- for (size_t i = 0; i < thread_count; i++) {
- nvArray_add(
- space->mt_shg_pairs,
- nvHashMap_new(sizeof(nvBroadPhasePair), 0, _nvSpace_broadphase_pair_hash)
- );
+ ITER_BODIES(body_i) {
+ nvRigidBody *body = space->bodies->data[body_i];
+ nvTransform xform = {body->origin, body->angle};
- nvArray_add(space->mt_shg_bins, nvArray_new());
- }
+ nvRayCastResult closest_result;
+ nv_float min_dist = NV_INF;
+ nv_float any_hit = false;
- space->multithreading = true;
+ for (size_t shape_i = 0; shape_i < body->shapes->size; shape_i++) {
+ nvShape *shape = body->shapes->data[shape_i];
- // Busy wait until all the task executor threads are initialized
- for (size_t i = 0; i < space->task_executor->threads->size; i++) {
- nvTaskExecutorData *data = space->task_executor->data->data[i];
+ nvRayCastResult result;
+ nv_bool hit;
- while (!data->is_active) {}
- }
-}
+ switch (shape->type) {
+ case nvShapeType_CIRCLE:
+ hit = nv_collide_ray_x_circle(&result, from, dir, maxsq, shape, xform);
+ break;
-void nvSpace_disable_multithreading(nvSpace *space) {
- if (!space->multithreading) return;
+ case nvShapeType_POLYGON:
+ hit = nv_collide_ray_x_polygon(&result, from, dir, maxsq, shape, xform);
+ break;
+ }
- nvTaskExecutor_close(space->task_executor);
- nvTaskExecutor_free(space->task_executor);
- space->task_executor = NULL;
+ if (hit) {
+ any_hit = true;
+ nv_float dist = nvVector2_dist2(from, result.position);
+ if (dist < min_dist) {
+ min_dist = dist;
+ closest_result = result;
+ }
+ }
+ }
- for (size_t i = 0; i < space->thread_count; i++) {
- nvHashMap_clear(space->mt_shg_pairs->data[i]);
- nvArray_clear(space->mt_shg_bins->data[i], NULL);
+ if (any_hit) {
+ closest_result.body = body;
+ results_array[(*num_hits)++] = closest_result;
+ if ((*num_hits) == capacity) break;
+ }
}
- nvArray_free(space->mt_shg_bins);
- nvArray_free(space->mt_shg_pairs);
- space->mt_shg_bins = NULL;
- space->mt_shg_pairs = NULL;
-
- space->thread_count = 0;
-
- space->multithreading = false;
}
\ No newline at end of file
diff --git a/src/space_step.c b/src/space_step.c
deleted file mode 100644
index c72b97d..0000000
--- a/src/space_step.c
+++ /dev/null
@@ -1,872 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/internal.h"
-#include "novaphysics/space_step.h"
-#include "novaphysics/space.h"
-
-
-/**
- * @file space_step.c
- *
- * @brief Internal functions the space uses in a simulation step.
- */
-
-
-nv_uint64 _nvSpace_resolution_hash(void *item) {
- nvResolution *res = (nvResolution *)item;
- return (nv_uint64)nv_hash(nv_pair(res->a->id, res->b->id));
-}
-
-nv_uint64 _nvSpace_broadphase_pair_hash(void *item) {
- nvBroadPhasePair *pair = item;
- return (nv_uint64)nv_hash(nv_pair(pair->a->id, pair->b->id));
-}
-
-
-void _nvSpace_integrate_accelerations(
- nvSpace *space,
- nv_float dt,
- size_t i
-) {
- nvBody *body = (nvBody *)space->awake_bodies->data[i];
-
- if (body->type != nvBodyType_STATIC) {
- body->_cache_aabb = false;
- body->_cache_transform = false;
- }
-
- // Apply attractive forces
- for (size_t j = 0; j < space->attractors->size; j++) {
- nvBody *attractor = (nvBody *)space->attractors->data[j];
-
- if (body == attractor) continue;
-
- nvBody_apply_attraction(body, attractor, dt);
- }
-
- nvBody_integrate_accelerations(body, space->gravity, dt);
-}
-
-
-void _nvSpace_integrate_velocities(
- nvSpace *space,
- nv_float dt,
- size_t i
-) {
- nvBody *body = (nvBody *)space->awake_bodies->data[i];
-
- nvBody_integrate_velocities(body, dt);
-
- // Since most kill boundaries in games are going to be out of the
- // display area just checking for body's center position
- // should be sufficient.
- if (
- space->use_kill_bounds &&
- !nv_collide_aabb_x_point(space->kill_bounds, body->position)
- )
- nvSpace_kill(space, body);
-}
-
-
-#ifdef NV_AVX
-
- void _nvSpace_integrate_accelerations_AVX(
- nvSpace *space,
- nv_float dt
- ) {
- /*
- Notes:
- ------
- It is very unlikely that damping coefficients will change so we can
- just use one pow operation. Or somehow vectorize it.
- Altough there isn't a pow intrinsic...
-
- Use fused multiply-add for integrations.
-
- Angular integration can be skipped if the torque is 0?
-
- TODO: Vectorize attractive forces as well.
- */
-
- #ifdef NV_USE_FLOAT
-
- __m256 vps_dt = NV_AVX_VECTOR_FROM_FLOAT((float)dt);
- __m256 vps_gravity_x = NV_AVX_VECTOR_FROM_FLOAT((float)(space->gravity.x));
- __m256 vps_gravity_y = NV_AVX_VECTOR_FROM_FLOAT((float)(space->gravity.y));
-
- size_t n = space->awake_bodies->size;
- size_t vector_n = n / 8 * 8;
-
- for (size_t i = 7; i < vector_n; i += 8) {
- nvBody *body0 = space->awake_bodies->data[i - 7];
- nvBody *body1 = space->awake_bodies->data[i - 6];
- nvBody *body2 = space->awake_bodies->data[i - 5];
- nvBody *body3 = space->awake_bodies->data[i - 4];
- nvBody *body4 = space->awake_bodies->data[i - 3];
- nvBody *body5 = space->awake_bodies->data[i - 2];
- nvBody *body6 = space->awake_bodies->data[i - 1];
- nvBody *body7 = space->awake_bodies->data[i];
-
- // Apply attractive forces
- for (size_t j = 0; j < space->attractors->size; j++) {
- nvBody *attractor = (nvBody *)space->attractors->data[j];
-
- if (body0 != attractor)
- nvBody_apply_attraction(body0, attractor, dt);
-
- if (body1 != attractor)
- nvBody_apply_attraction(body1, attractor, dt);
-
- if (body2 != attractor)
- nvBody_apply_attraction(body2, attractor, dt);
-
- if (body3 != attractor)
- nvBody_apply_attraction(body3, attractor, dt);
-
- if (body4 != attractor)
- nvBody_apply_attraction(body4, attractor, dt);
-
- if (body5 != attractor)
- nvBody_apply_attraction(body5, attractor, dt);
-
- if (body6 != attractor)
- nvBody_apply_attraction(body6, attractor, dt);
-
- if (body7 != attractor)
- nvBody_apply_attraction(body7, attractor, dt);
- }
-
- float kv = nv_pow(0.98, body7->linear_damping);
- float ka = nv_pow(0.98, body7->angular_damping);
- __m256 v_kv = NV_AVX_VECTOR_FROM_FLOAT(kv);
- __m256 v_ka = NV_AVX_VECTOR_FROM_FLOAT(ka);
-
- __m256 v_linear_velocity_x = _mm256_set_ps(
- body7->linear_velocity.x,
- body6->linear_velocity.x,
- body5->linear_velocity.x,
- body4->linear_velocity.x,
- body3->linear_velocity.x,
- body2->linear_velocity.x,
- body1->linear_velocity.x,
- body0->linear_velocity.x
- );
-
- __m256 v_linear_velocity_y = _mm256_set_ps(
- body7->linear_velocity.y,
- body6->linear_velocity.y,
- body5->linear_velocity.y,
- body4->linear_velocity.y,
- body3->linear_velocity.y,
- body2->linear_velocity.y,
- body1->linear_velocity.y,
- body0->linear_velocity.y
- );
-
- __m256 v_force_x = _mm256_set_ps(
- body7->force.x,
- body6->force.x,
- body5->force.x,
- body4->force.x,
- body3->force.x,
- body2->force.x,
- body1->force.x,
- body0->force.x
- );
-
- __m256 v_force_y = _mm256_set_ps(
- body7->force.y,
- body6->force.y,
- body5->force.y,
- body4->force.y,
- body3->force.y,
- body2->force.y,
- body1->force.y,
- body0->force.y
- );
-
- __m256 v_invmass = _mm256_set_ps(
- body7->invmass,
- body6->invmass,
- body5->invmass,
- body4->invmass,
- body3->invmass,
- body2->invmass,
- body1->invmass,
- body0->invmass
- );
-
- // Integrate linear acceleration
- v_linear_velocity_x = _mm256_add_ps(
- v_linear_velocity_x,
- _mm256_mul_ps(
- _mm256_add_ps(
- _mm256_mul_ps(v_force_x, v_invmass),
- vps_gravity_x
- ),
- vps_dt
- )
- );
- v_linear_velocity_y = _mm256_add_ps(
- v_linear_velocity_y,
- _mm256_mul_ps(
- _mm256_add_ps(
- _mm256_mul_ps(v_force_y, v_invmass),
- vps_gravity_y
- ),
- vps_dt
- )
- );
-
- // Apply damping
- v_linear_velocity_x = _mm256_mul_ps(v_linear_velocity_x, v_kv);
- v_linear_velocity_y = _mm256_mul_ps(v_linear_velocity_y, v_kv);
-
- NV_ALIGNED_AS(32) float final_linear_velocity_x[8];
- NV_ALIGNED_AS(32) float final_linear_velocity_y[8];
- _mm256_store_ps(final_linear_velocity_x, v_linear_velocity_x);
- _mm256_store_ps(final_linear_velocity_y, v_linear_velocity_y);
-
- body0->linear_velocity.x = final_linear_velocity_x[0];
- body1->linear_velocity.x = final_linear_velocity_x[1];
- body2->linear_velocity.x = final_linear_velocity_x[2];
- body3->linear_velocity.x = final_linear_velocity_x[3];
- body4->linear_velocity.x = final_linear_velocity_x[4];
- body5->linear_velocity.x = final_linear_velocity_x[5];
- body6->linear_velocity.x = final_linear_velocity_x[6];
- body7->linear_velocity.x = final_linear_velocity_x[7];
-
- body0->linear_velocity.y = final_linear_velocity_y[0];
- body1->linear_velocity.y = final_linear_velocity_y[1];
- body2->linear_velocity.y = final_linear_velocity_y[2];
- body3->linear_velocity.y = final_linear_velocity_y[3];
- body4->linear_velocity.y = final_linear_velocity_y[4];
- body5->linear_velocity.y = final_linear_velocity_y[5];
- body6->linear_velocity.y = final_linear_velocity_y[6];
- body7->linear_velocity.y = final_linear_velocity_y[7];
-
- __m256 v_angular_velocity = _mm256_set_ps(
- body7->angular_velocity,
- body6->angular_velocity,
- body5->angular_velocity,
- body4->angular_velocity,
- body3->angular_velocity,
- body2->angular_velocity,
- body1->angular_velocity,
- body0->angular_velocity
- );
-
- __m256 v_torque = _mm256_set_ps(
- body7->torque,
- body6->torque,
- body5->torque,
- body4->torque,
- body3->torque,
- body2->torque,
- body1->torque,
- body0->torque
- );
-
- __m256 v_invinertia = _mm256_set_ps(
- body7->invinertia,
- body6->invinertia,
- body5->invinertia,
- body4->invinertia,
- body3->invinertia,
- body2->invinertia,
- body1->invinertia,
- body0->invinertia
- );
-
- // Integrate angular acceleration
- v_angular_velocity = _mm256_add_ps(
- v_angular_velocity,
- _mm256_mul_ps(
- _mm256_mul_ps(v_torque, v_invinertia),
- vps_dt
- )
- );
-
- // Apply damping
- v_angular_velocity = _mm256_mul_ps(v_angular_velocity, v_ka);
-
- NV_ALIGNED_AS(32) float final_angular_velocity[8];
- _mm256_store_ps(final_angular_velocity, v_angular_velocity);
-
- body0->angular_velocity = final_angular_velocity[0];
- body1->angular_velocity = final_angular_velocity[1];
- body2->angular_velocity = final_angular_velocity[2];
- body3->angular_velocity = final_angular_velocity[3];
- body4->angular_velocity = final_angular_velocity[4];
- body5->angular_velocity = final_angular_velocity[5];
- body6->angular_velocity = final_angular_velocity[6];
- body7->angular_velocity = final_angular_velocity[7];
-
- // Cache AABBs and vertex transforms
-
- if (body0->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body0);
- }
- else {
- body0->_cache_aabb = false;
- body0->_cache_transform = false;
- }
-
- if (body1->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body1);
- }
- else {
- body1->_cache_aabb = false;
- body1->_cache_transform = false;
- }
-
- if (body2->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body2);
- }
- else {
- body2->_cache_aabb = false;
- body2->_cache_transform = false;
- }
-
- if (body3->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body3);
- }
- else {
- body3->_cache_aabb = false;
- body3->_cache_transform = false;
- }
-
- if (body4->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body4);
- }
- else {
- body4->_cache_aabb = false;
- body4->_cache_transform = false;
- }
-
- if (body5->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body5);
- }
- else {
- body5->_cache_aabb = false;
- body5->_cache_transform = false;
- }
-
- if (body6->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body6);
- }
- else {
- body6->_cache_aabb = false;
- body6->_cache_transform = false;
- }
-
- if (body7->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body7);
- }
- else {
- body7->_cache_aabb = false;
- body7->_cache_transform = false;
- }
- }
-
- #else
-
- __m256d vpd_dt = NV_AVX_VECTOR_FROM_DOUBLE(dt);
- __m256d vpd_gravity_x = NV_AVX_VECTOR_FROM_DOUBLE(space->gravity.x);
- __m256d vpd_gravity_y = NV_AVX_VECTOR_FROM_DOUBLE(space->gravity.y);
-
- size_t n = space->awake_bodies->size;
- size_t vector_n = n / 4 * 4;
-
- for (size_t i = 3; i < vector_n; i += 4) {
- nvBody *body0 = space->awake_bodies->data[i - 3];
- nvBody *body1 = space->awake_bodies->data[i - 2];
- nvBody *body2 = space->awake_bodies->data[i - 1];
- nvBody *body3 = space->awake_bodies->data[i];
-
- // Apply attractive forces
- for (size_t j = 0; j < space->attractors->size; j++) {
- nvBody *attractor = (nvBody *)space->attractors->data[j];
-
- if (body0 != attractor)
- nvBody_apply_attraction(body0, attractor, dt);
-
- if (body1 != attractor)
- nvBody_apply_attraction(body1, attractor, dt);
-
- if (body2 != attractor)
- nvBody_apply_attraction(body2, attractor, dt);
-
- if (body3 != attractor)
- nvBody_apply_attraction(body3, attractor, dt);
- }
-
- double kv = nv_pow(0.98, body3->linear_damping);
- double ka = nv_pow(0.98, body3->angular_damping);
- __m256d v_kv = NV_AVX_VECTOR_FROM_DOUBLE(kv);
- __m256d v_ka = NV_AVX_VECTOR_FROM_DOUBLE(ka);
-
- __m256d v_linear_velocity_x = _mm256_set_pd(
- body3->linear_velocity.x,
- body2->linear_velocity.x,
- body1->linear_velocity.x,
- body0->linear_velocity.x
- );
-
- __m256d v_linear_velocity_y = _mm256_set_pd(
- body3->linear_velocity.y,
- body2->linear_velocity.y,
- body1->linear_velocity.y,
- body0->linear_velocity.y
- );
-
- __m256d v_force_x = _mm256_set_pd(
- body3->force.x,
- body2->force.x,
- body1->force.x,
- body0->force.x
- );
-
- __m256d v_force_y = _mm256_set_pd(
- body3->force.y,
- body2->force.y,
- body1->force.y,
- body0->force.y
- );
-
- __m256d v_invmass = _mm256_set_pd(
- body3->invmass,
- body2->invmass,
- body1->invmass,
- body0->invmass
- );
-
- // Integrate linear acceleration
- v_linear_velocity_x = _mm256_add_pd(
- v_linear_velocity_x,
- _mm256_mul_pd(
- _mm256_add_pd(
- _mm256_mul_pd(v_force_x, v_invmass),
- vpd_gravity_x
- ),
- vpd_dt
- )
- );
- v_linear_velocity_y = _mm256_add_pd(
- v_linear_velocity_y,
- _mm256_mul_pd(
- _mm256_add_pd(
- _mm256_mul_pd(v_force_y, v_invmass),
- vpd_gravity_y
- ),
- vpd_dt
- )
- );
-
- // Apply damping
- v_linear_velocity_x = _mm256_mul_pd(v_linear_velocity_x, v_kv);
- v_linear_velocity_y = _mm256_mul_pd(v_linear_velocity_y, v_kv);
-
- NV_ALIGNED_AS(32) double final_linear_velocity_x[4];
- NV_ALIGNED_AS(32) double final_linear_velocity_y[4];
- _mm256_store_pd(final_linear_velocity_x, v_linear_velocity_x);
- _mm256_store_pd(final_linear_velocity_y, v_linear_velocity_y);
-
- body0->linear_velocity.x = final_linear_velocity_x[0];
- body1->linear_velocity.x = final_linear_velocity_x[1];
- body2->linear_velocity.x = final_linear_velocity_x[2];
- body3->linear_velocity.x = final_linear_velocity_x[3];
-
- body0->linear_velocity.y = final_linear_velocity_y[0];
- body1->linear_velocity.y = final_linear_velocity_y[1];
- body2->linear_velocity.y = final_linear_velocity_y[2];
- body3->linear_velocity.y = final_linear_velocity_y[3];
-
- __m256d v_angular_velocity = _mm256_set_pd(
- body3->angular_velocity,
- body2->angular_velocity,
- body1->angular_velocity,
- body0->angular_velocity
- );
-
- __m256d v_torque = _mm256_set_pd(
- body3->torque,
- body2->torque,
- body1->torque,
- body0->torque
- );
-
- __m256d v_invinertia = _mm256_set_pd(
- body3->invinertia,
- body2->invinertia,
- body1->invinertia,
- body0->invinertia
- );
-
- // Integrate angular acceleration
- v_angular_velocity = _mm256_add_pd(
- v_angular_velocity,
- _mm256_mul_pd(
- _mm256_mul_pd(v_torque, v_invinertia),
- vpd_dt
- )
- );
-
- // Apply damping
- v_angular_velocity = _mm256_mul_pd(v_angular_velocity, v_ka);
-
- NV_ALIGNED_AS(32) double final_angular_velocity[4];
- _mm256_store_pd(final_angular_velocity, v_angular_velocity);
-
- body0->angular_velocity = final_angular_velocity[0];
- body1->angular_velocity = final_angular_velocity[1];
- body2->angular_velocity = final_angular_velocity[2];
- body3->angular_velocity = final_angular_velocity[3];
-
- // Cache AABBs and vertex transforms
-
- if (body0->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body0);
- }
- else {
- body0->_cache_aabb = false;
- body0->_cache_transform = false;
- }
-
- if (body1->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body1);
- }
- else {
- body1->_cache_aabb = false;
- body1->_cache_transform = false;
- }
-
- if (body2->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body2);
- }
- else {
- body2->_cache_aabb = false;
- body2->_cache_transform = false;
- }
-
- if (body3->type == nvBodyType_STATIC) {
- nvBody_reset_velocities(body3);
- }
- else {
- body3->_cache_aabb = false;
- body3->_cache_transform = false;
- }
- }
-
- #endif
-
- // Integrate the rest of the bodies
- for (size_t i = vector_n; i < n; i++) {
- _nvSpace_integrate_accelerations(space, dt, i);
- }
- }
-
-
- void _nvSpace_integrate_velocities_AVX(
- nvSpace *space,
- nv_float dt
- ) {
- #ifdef NV_USE_FLOAT
-
- __m256 vps_dt = NV_AVX_VECTOR_FROM_FLOAT(dt);
-
- size_t n = space->awake_bodies->size;
- size_t vector_n = n / 8 * 8;
-
- for (size_t i = 7; i < vector_n; i += 8) {
- nvBody *body0 = space->awake_bodies->data[i - 7];
- nvBody *body1 = space->awake_bodies->data[i - 6];
- nvBody *body2 = space->awake_bodies->data[i - 5];
- nvBody *body3 = space->awake_bodies->data[i - 4];
- nvBody *body4 = space->awake_bodies->data[i - 3];
- nvBody *body5 = space->awake_bodies->data[i - 2];
- nvBody *body6 = space->awake_bodies->data[i - 1];
- nvBody *body7 = space->awake_bodies->data[i];
-
- __m256 v_position_x = _mm256_set_ps(
- body7->position.x,
- body6->position.x,
- body5->position.x,
- body4->position.x,
- body3->position.x,
- body2->position.x,
- body1->position.x,
- body0->position.x
- );
-
- __m256 v_position_y = _mm256_set_ps(
- body7->position.y,
- body6->position.y,
- body5->position.y,
- body4->position.y,
- body3->position.y,
- body2->position.y,
- body1->position.y,
- body0->position.y
- );
-
- __m256 v_linear_velocity_x = _mm256_set_ps(
- body7->linear_velocity.x,
- body6->linear_velocity.x,
- body5->linear_velocity.x,
- body4->linear_velocity.x,
- body3->linear_velocity.x,
- body2->linear_velocity.x,
- body1->linear_velocity.x,
- body0->linear_velocity.x
- );
-
- __m256 v_linear_velocity_y = _mm256_set_ps(
- body7->linear_velocity.y,
- body6->linear_velocity.y,
- body5->linear_velocity.y,
- body4->linear_velocity.y,
- body3->linear_velocity.y,
- body2->linear_velocity.y,
- body1->linear_velocity.y,
- body0->linear_velocity.y
- );
-
- v_position_x = _mm256_add_ps(v_position_x, _mm256_mul_ps(v_linear_velocity_x, vps_dt));
- v_position_y = _mm256_add_ps(v_position_y, _mm256_mul_ps(v_linear_velocity_y, vps_dt));
-
- NV_ALIGNED_AS(32) float final_position_x[8];
- NV_ALIGNED_AS(32) float final_position_y[8];
- _mm256_store_ps(final_position_x, v_position_x);
- _mm256_store_ps(final_position_y, v_position_y);
-
- body0->position.x = final_position_x[0];
- body1->position.x = final_position_x[1];
- body2->position.x = final_position_x[2];
- body3->position.x = final_position_x[3];
- body4->position.x = final_position_x[4];
- body5->position.x = final_position_x[5];
- body6->position.x = final_position_x[6];
- body7->position.x = final_position_x[7];
-
- body0->position.y = final_position_y[0];
- body1->position.y = final_position_y[1];
- body2->position.y = final_position_y[2];
- body3->position.y = final_position_y[3];
- body4->position.y = final_position_y[4];
- body5->position.y = final_position_y[5];
- body6->position.y = final_position_y[6];
- body7->position.y = final_position_y[7];
-
- __m256 v_angle = _mm256_set_ps(
- body7->angle,
- body6->angle,
- body5->angle,
- body4->angle,
- body3->angle,
- body2->angle,
- body1->angle,
- body0->angle
- );
-
- __m256 v_angular_velocity = _mm256_set_ps(
- body7->angular_velocity,
- body6->angular_velocity,
- body5->angular_velocity,
- body4->angular_velocity,
- body3->angular_velocity,
- body2->angular_velocity,
- body1->angular_velocity,
- body0->angular_velocity
- );
-
- v_angle = _mm256_add_ps(v_angle, _mm256_mul_ps(v_angular_velocity, vps_dt));
-
- NV_ALIGNED_AS(32) float final_angle[8];
- _mm256_store_ps(final_angle, v_angle);
-
- body0->angle = final_angle[0];
- body1->angle = final_angle[1];
- body2->angle = final_angle[2];
- body3->angle = final_angle[3];
- body4->angle = final_angle[4];
- body5->angle = final_angle[5];
- body6->angle = final_angle[6];
- body7->angle = final_angle[7];
-
- // Reset forces
- body0->force = nvVector2_zero;
- body1->force = nvVector2_zero;
- body2->force = nvVector2_zero;
- body3->force = nvVector2_zero;
- body4->force = nvVector2_zero;
- body5->force = nvVector2_zero;
- body6->force = nvVector2_zero;
- body7->force = nvVector2_zero;
- body0->torque = 0.0;
- body1->torque = 0.0;
- body2->torque = 0.0;
- body3->torque = 0.0;
- body4->torque = 0.0;
- body5->torque = 0.0;
- body6->torque = 0.0;
- body7->torque = 0.0;
-
- // Check out-of-bound bodies
-
- if (space->use_kill_bounds) {
- if (!nv_collide_aabb_x_point(space->kill_bounds, body0->position))
- nvSpace_kill(space, body0);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body1->position))
- nvSpace_kill(space, body1);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body2->position))
- nvSpace_kill(space, body2);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body3->position))
- nvSpace_kill(space, body3);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body4->position))
- nvSpace_kill(space, body4);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body5->position))
- nvSpace_kill(space, body5);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body6->position))
- nvSpace_kill(space, body6);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body7->position))
- nvSpace_kill(space, body7);
- }
-
- }
-
- #else
-
- __m256d vpd_dt = NV_AVX_VECTOR_FROM_DOUBLE(dt);
-
- size_t n = space->awake_bodies->size;
- size_t vector_n = n / 4 * 4;
-
- for (size_t i = 3; i < vector_n; i += 4) {
- nvBody *body0 = space->awake_bodies->data[i - 3];
- nvBody *body1 = space->awake_bodies->data[i - 2];
- nvBody *body2 = space->awake_bodies->data[i - 1];
- nvBody *body3 = space->awake_bodies->data[i];
-
- __m256d v_position_x = _mm256_set_pd(
- body3->position.x,
- body2->position.x,
- body1->position.x,
- body0->position.x
- );
-
- __m256d v_position_y = _mm256_set_pd(
- body3->position.y,
- body2->position.y,
- body1->position.y,
- body0->position.y
- );
-
- __m256d v_linear_velocity_x = _mm256_set_pd(
- body3->linear_velocity.x,
- body2->linear_velocity.x,
- body1->linear_velocity.x,
- body0->linear_velocity.x
- );
-
- __m256d v_linear_velocity_y = _mm256_set_pd(
- body3->linear_velocity.y,
- body2->linear_velocity.y,
- body1->linear_velocity.y,
- body0->linear_velocity.y
- );
-
- v_position_x = _mm256_add_pd(v_position_x, _mm256_mul_pd(v_linear_velocity_x, vpd_dt));
- v_position_y = _mm256_add_pd(v_position_y, _mm256_mul_pd(v_linear_velocity_y, vpd_dt));
-
- NV_ALIGNED_AS(32) double final_position_x[4];
- NV_ALIGNED_AS(32) double final_position_y[4];
- _mm256_store_pd(final_position_x, v_position_x);
- _mm256_store_pd(final_position_y, v_position_y);
-
- body0->position.x = final_position_x[0];
- body1->position.x = final_position_x[1];
- body2->position.x = final_position_x[2];
- body3->position.x = final_position_x[3];
-
- body0->position.y = final_position_y[0];
- body1->position.y = final_position_y[1];
- body2->position.y = final_position_y[2];
- body3->position.y = final_position_y[3];
-
- __m256d v_angle = _mm256_set_pd(
- body3->angle,
- body2->angle,
- body1->angle,
- body0->angle
- );
-
- __m256d v_angular_velocity = _mm256_set_pd(
- body3->angular_velocity,
- body2->angular_velocity,
- body1->angular_velocity,
- body0->angular_velocity
- );
-
- v_angle = _mm256_add_pd(v_angle, _mm256_mul_pd(v_angular_velocity, vpd_dt));
-
- NV_ALIGNED_AS(32) double final_angle[4];
- _mm256_store_pd(final_angle, v_angle);
-
- body0->angle = final_angle[0];
- body1->angle = final_angle[1];
- body2->angle = final_angle[2];
- body3->angle = final_angle[3];
-
- // Reset forces
- body0->force = nvVector2_zero;
- body1->force = nvVector2_zero;
- body2->force = nvVector2_zero;
- body3->force = nvVector2_zero;
- body0->torque = 0.0;
- body1->torque = 0.0;
- body2->torque = 0.0;
- body3->torque = 0.0;
-
- // Check out-of-bound bodies
-
- if (space->use_kill_bounds) {
- if (!nv_collide_aabb_x_point(space->kill_bounds, body0->position))
- nvSpace_kill(space, body0);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body1->position))
- nvSpace_kill(space, body1);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body2->position))
- nvSpace_kill(space, body2);
-
- if (!nv_collide_aabb_x_point(space->kill_bounds, body3->position))
- nvSpace_kill(space, body3);
- }
-
- }
-
- #endif
-
- // Integrate the rest of the bodies
- for (size_t i = vector_n; i < n; i++) {
- _nvSpace_integrate_velocities(space, dt, i);
- }
- }
-
-#endif
\ No newline at end of file
diff --git a/src/spring.c b/src/spring.c
deleted file mode 100644
index 1c01aa4..0000000
--- a/src/spring.c
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/spring.h"
-#include "novaphysics/space.h"
-
-
-/**
- * @file spring.c
- *
- * @brief Damped spring implementation.
- */
-
-
-nvConstraint *nvSpring_new(
- nvBody *a,
- nvBody *b,
- nvVector2 anchor_a,
- nvVector2 anchor_b,
- nv_float length,
- nv_float stiffness,
- nv_float damping
-) {
- nvConstraint *cons = NV_NEW(nvConstraint);
- if (!cons) return NULL;
-
- cons->a = a;
- cons->b = b;
- cons->type = nvConstraintType_SPRING;
-
- cons->def = (void *)NV_NEW(nvSpring);
- if (!cons->def) return NULL;
- nvSpring *spring = (nvSpring *)cons->def;
-
- spring->length = length;
- spring->stiffness = stiffness;
- spring->damping = damping;
-
- spring->anchor_a = anchor_a;
- spring->anchor_b = anchor_b;
- spring->ra = nvVector2_zero;
- spring->rb = nvVector2_zero;
- spring->normal = nvVector2_zero;
- spring->mass = 0.0;
- spring->jc = 0.0;
-
- return cons;
-}
-
-void nvSpring_presolve(
- nvSpace *space,
- nvConstraint *cons,
- nv_float inv_dt
-) {
- nvSpring *spring = (nvSpring *)cons->def;
- nvBody *a = cons->a;
- nvBody *b = cons->b;
-
- // Transform anchor points
- nvVector2 rpa, rpb;
- nv_float invmass_a, invmass_b, invinertia_a, invinertia_b;
-
- if (a == NULL) {
- spring->ra = nvVector2_zero;
- rpa = spring->anchor_a;
- invmass_a = invinertia_a = 0.0;
- } else {
- spring->ra = nvVector2_rotate(spring->anchor_a, a->angle);
- rpa = nvVector2_add(spring->ra, a->position);
- invmass_a = a->invmass;
- invinertia_a = a->invinertia;
- }
-
- if (b == NULL) {
- spring->rb = nvVector2_zero;
- rpb = spring->anchor_b;
- invmass_b = invinertia_b = 0.0;
- } else {
- spring->rb = nvVector2_rotate(spring->anchor_b, b->angle);
- rpb = nvVector2_add(spring->rb, b->position);
- invmass_b = b->invmass;
- invinertia_b = b->invinertia;
- }
-
- nvVector2 delta = nvVector2_sub(rpb, rpa);
- spring->normal = nvVector2_normalize(delta);
- nv_float dist = nvVector2_len(delta);
-
- // Constraint effective mass
- nv_float mass_k = nv_calc_mass_k(
- spring->normal,
- spring->ra, spring->rb,
- invmass_a, invmass_b,
- invinertia_a, invinertia_b
- );
- spring->mass = 1.0 / mass_k;
-
- spring->target_vel = 0.0;
- spring->damping_bias = 1.0 - nv_exp(-spring->damping / inv_dt * mass_k);
-
- // Apply spring force
- nv_float spring_force = (spring->length - dist) * spring->stiffness;
-
- spring->jc = spring_force / inv_dt;
- nvVector2 spring_impulse = nvVector2_mul(spring->normal, spring->jc);
-
- if (a) nvBody_apply_impulse(a, nvVector2_neg(spring_impulse), spring->ra);
- if (b) nvBody_apply_impulse(b, spring_impulse, spring->rb);
-}
-
-void nvSpring_solve(nvConstraint *cons) {
- nvSpring *spring = (nvSpring *)cons->def;
- nvBody *a = cons->a;
- nvBody *b = cons->b;
-
- nvVector2 linear_velocity_a, linear_velocity_b;
- nv_float angular_velocity_a, angular_velocity_b;
-
- if (a == NULL) {
- linear_velocity_a = nvVector2_zero;
- angular_velocity_a = 0.0;
- } else {
- linear_velocity_a = a->linear_velocity;
- angular_velocity_a = a->angular_velocity;
- }
-
- if (b == NULL) {
- linear_velocity_b = nvVector2_zero;
- angular_velocity_b = 0.0;
- } else {
- linear_velocity_b = b->linear_velocity;
- angular_velocity_b = b->angular_velocity;
- }
-
- // Relative velocity
- nvVector2 rv = nv_calc_relative_velocity(
- linear_velocity_a, angular_velocity_a, spring->ra,
- linear_velocity_b, angular_velocity_b, spring->rb
- );
-
- nv_float rn = nvVector2_dot(rv, spring->normal);
-
- // Velocity loss from drag
- nv_float damped = (spring->target_vel - rn) * spring->damping_bias;
- spring->target_vel = rn + damped;
-
- nv_float jc_damp = damped * spring->mass;
- spring->jc += jc_damp;
-
- nvVector2 impulse_damp = nvVector2_mul(spring->normal, jc_damp);
-
- if (a) nvBody_apply_impulse(a, nvVector2_neg(impulse_damp), spring->ra);
- if (b) nvBody_apply_impulse(b, impulse_damp, spring->rb);
-}
\ No newline at end of file
diff --git a/src/threading.c b/src/threading.c
deleted file mode 100644
index 7492799..0000000
--- a/src/threading.c
+++ /dev/null
@@ -1,570 +0,0 @@
-/*
-
- This file is a part of the Nova Physics Engine
- project and distributed under the MIT license.
-
- Copyright © Kadir Aksoy
- https://github.com/kadir014/nova-physics
-
-*/
-
-#include "novaphysics/threading.h"
-
-
-/**
- * @file threading.c
- *
- * @brief Cross-platform multi-threading API.
- */
-
-
-/*
- Notes
- -----
- Multi-threading in Nova Physics is highly experimental and all of the API
- is subject to change in later versions.
-
- On Windows, instead of condition variables I use events, which doesn't
- require a mutex to wait. So the nvCondition_wait function parameters
- and task executor functions gets inconsistent.
-
- I'm still not satisfied with how the task executor works in general.
- I will need to rewrite it before 1.0.0.
-*/
-
-
-#ifdef NV_WEB
-
- /* Do not expose any OS-threads for web. */
-
- nv_uint32 nv_get_cpu_count() {
- return 0;
- }
-
- nvMutex *nvMutex_new() {
- return NULL;
- }
-
- void nvMutex_free(nvMutex *mutex) {
- return;
- }
-
- bool nvMutex_lock(nvMutex *mutex) {
- return false;
- }
-
- bool nvMutex_unlock(nvMutex *mutex) {
- return false;
- }
-
-
- nvCondition *nvCondition_new() {
- return NULL;
- }
-
- void nvCondition_free(nvCondition *cond) {
- return;
- }
-
- void nvCondition_wait(nvCondition *cond, nvMutex *mutex) {
- return;
- }
-
- void nvCondition_signal(nvCondition *cond) {
- return;
- }
-
-
- nvThread *nvThread_create(nvThreadWorker func, void *data) {
- return NULL;
- }
-
- void nvThread_free(nvThread *thread) {
- return;
- }
-
- void nvThread_join(nvThread *thread) {
- return;
- }
-
- void nvThread_join_multiple(nvThread **threads, size_t length) {
- return;
- }
-
-#elif defined(NV_WINDOWS)
-
- /* Win32 implementation of the API. */
-
- #include
-
-
- nv_uint32 nv_get_cpu_count() {
- SYSTEM_INFO info;
- GetSystemInfo(&info);
- return (nv_uint32)info.dwNumberOfProcessors;
- }
-
-
- nvMutex *nvMutex_new() {
- nvMutex *mutex = NV_NEW(nvMutex);
- if (!mutex) return NULL;
-
- mutex->_handle = CreateMutex(
- NULL, // Default security attributes
- false, // Not owned by any thread by default
- NULL // Name of the mutex
- );
-
- if (!mutex->_handle) {
- free(mutex);
- return NULL;
- }
-
- return mutex;
- }
-
- void nvMutex_free(nvMutex *mutex) {
- CloseHandle(mutex->_handle);
- free(mutex);
- }
-
- bool nvMutex_lock(nvMutex *mutex) {
- NV_TRACY_ZONE_START;
-
- DWORD result = WaitForSingleObject(mutex->_handle, INFINITE);
-
- NV_TRACY_ZONE_END;
- return result != WAIT_ABANDONED && result != WAIT_FAILED;
- }
-
- bool nvMutex_unlock(nvMutex *mutex) {
- NV_TRACY_ZONE_START;
-
- bool result = ReleaseMutex(mutex->_handle);
-
- NV_TRACY_ZONE_END;
- return result;
- }
-
-
- nvCondition *nvCondition_new() {
- nvCondition *cond = NV_NEW(nvCondition);
- if (!cond) return NULL;
-
- cond->_handle = CreateEvent(
- NULL, // Default security attributes
- FALSE, // Manual reset or not
- FALSE, // Initial state of the signal
- NULL // Name of the event
- );
-
- if (!cond->_handle) {
- free(cond);
- return NULL;
- }
-
- return cond;
- }
-
- void nvCondition_free(nvCondition *cond) {
- CloseHandle(cond->_handle);
- free(cond);
- }
-
- void nvCondition_wait(nvCondition *cond, nvMutex *mutex) {
- WaitForSingleObject(cond->_handle, INFINITE);
- }
-
- void nvCondition_signal(nvCondition *cond) {
- SetEvent(cond->_handle);
- }
-
-
- nvThread *nvThread_create(nvThreadWorker func, void *data) {
- nvThread *thread = NV_NEW(nvThread);
- if (!thread) return NULL;
-
- thread->worker_data = NV_NEW(nvThreadWorkerData);
- if (!thread->worker_data) return NULL;
- thread->worker_data->data = data;
-
- // Thread ID pointer, this will be casted to DWORD pointer
- nv_uint64 *thread_id = &thread->id;
-
- HANDLE thread_handle = CreateThread(
- NULL, // Default security attributes
- 0, // 0 -> Use default stack size
- (LPTHREAD_START_ROUTINE)func, // Thread worker function
- thread->worker_data, // Data passed to thread function
- 0, // 0 -> Use default creation flags
- (DWORD *)thread_id // Pointer to thread identifier
- );
-
- if (!thread_handle) {
- free(thread);
- return NULL;
- }
-
- thread->worker_data->id = thread->id;
- thread->_handle = thread_handle;
-
- return thread;
- }
-
- void nvThread_free(nvThread *thread) {
- CloseHandle(thread->_handle);
- free(thread->worker_data);
- free(thread);
- }
-
- void nvThread_join(nvThread *thread) {
- WaitForSingleObject(thread->_handle, INFINITE);
- }
-
- void nvThread_join_multiple(nvThread **threads, size_t length) {
- #ifdef NV_COMPILER_MSVC
-
- // MSVC doesn't like VLAs, so malloc
- HANDLE *handles = malloc(sizeof(HANDLE) * length);
-
- #else
-
- HANDLE handles[length];
-
- #endif
-
- for (size_t i = 0; i < length; i++) {
- handles[i] = threads[i]->_handle;
- }
-
- WaitForMultipleObjects(length, handles, true, INFINITE);
-
- #ifdef NV_COMPILER_MSVC
-
- free(handles);
-
- #endif
- }
-
-#else
-
- /* Posix threads implementation of the API. */
-
- #include
- #include
-
-
- nv_uint32 nv_get_cpu_count() {
- long cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
- if (cpu_count == -1) return 1;
- return (nv_uint32)cpu_count;
- }
-
-
- nvMutex *nvMutex_new() {
- nvMutex *mutex = NV_NEW(nvMutex);
- if (!mutex) return NULL;
-
- mutex->_handle = NV_NEW(pthread_mutex_t);
- if (!mutex->_handle) {
- free(mutex);
- return NULL;
- }
-
- if (
- pthread_mutex_init(
- mutex->_handle, // Pointer to mutex
- NULL // Default creation attributes
- ) != 0
- ) {
- free(mutex->_handle);
- free(mutex);
- return NULL;
- }
-
- return mutex;
- }
-
- void nvMutex_free(nvMutex *mutex) {
- pthread_mutex_destroy(mutex->_handle);
- free(mutex->_handle);
- free(mutex);
- }
-
- bool nvMutex_lock(nvMutex *mutex) {
- return pthread_mutex_lock(mutex->_handle) != 0;
- }
-
- bool nvMutex_unlock(nvMutex *mutex) {
- return pthread_mutex_unlock(mutex->_handle) != 0;
- }
-
-
- nvCondition *nvCondition_new() {
- nvCondition *cond = NV_NEW(nvCondition);
- if (!cond) return NULL;
-
- cond->_handle = NV_NEW(pthread_cond_t);
- if (!cond->_handle) {
- free(cond);
- return NULL;
- }
-
- if (
- pthread_cond_init(
- cond->_handle, // Pointer to condition variable
- NULL // Default creation attributes
- ) != 0
- ) {
- free(cond->_handle);
- free(cond);
- return NULL;
- }
-
- return cond;
- }
-
- void nvCondition_free(nvCondition *cond) {
- pthread_cond_destroy(cond->_handle);
- free(cond->_handle);
- free(cond);
- }
-
- void nvCondition_wait(nvCondition *cond, nvMutex *mutex) {
- pthread_cond_wait(cond->_handle, mutex->_handle);
- }
-
- void nvCondition_signal(nvCondition *cond) {
- pthread_cond_signal(cond->_handle);
- }
-
-
- nvThread *nvThread_create(nvThreadWorker func, void *data) {
- nvThread *thread = NV_NEW(nvThread);
- if (!thread) return NULL;
-
- thread->worker_data = NV_NEW(nvThreadWorkerData);
- if (!thread->worker_data) return NULL;
- thread->worker_data->data = data;
-
- pthread_create(
- &thread->id, // Pointer to thread identifier
- NULL, // Default creation attributes
- (void * (*)(void *))func, // Thread worker function
- thread->worker_data // Data passed to worker function
- );
-
- thread->worker_data->id = thread->id;
-
- return thread;
- }
-
- void nvThread_free(nvThread *thread) {
- free(thread->worker_data);
- free(thread);
- }
-
- void nvThread_join(nvThread *thread) {
- }
-
- void nvThread_join_multiple(nvThread **threads, size_t length) {
- for (size_t i = 0; i < length; i++) {
- pthread_join(threads[i]->id, NULL);
- }
- }
-
-#endif
-
-
-static int nvTaskExecutor_main(nvThreadWorkerData *worker_data) {
- nvTaskExecutorData *data = worker_data->data;
- data->is_active = true;
-
- while (data->is_active) {
-
- #ifdef NV_WINDOWS
-
- nvCondition_wait(data->task_event, data->task_mutex);
- data->is_busy = true;
- data->task_arrived = true;
-
- if (data->task) {
- data->task->task_func(data->task->data);
- free(data->task);
- data->task = NULL;
- }
-
- data->is_busy = false;
- nvCondition_signal(data->done_event);
-
- #else
-
- nvMutex_lock(data->task_mutex);
- nvCondition_wait(data->task_event, data->task_mutex);
- data->is_busy = true;
- data->task_arrived = true;
- nvMutex_unlock(data->task_mutex);
-
- nvMutex_lock(data->task_mutex);
- if (data->task) {
- data->task->task_func(data->task->data);
- free(data->task);
- data->task = NULL;
- }
- nvMutex_unlock(data->task_mutex);
-
- nvMutex_lock(data->task_mutex);
- data->is_busy = false;
- nvCondition_signal(data->done_event);
- nvMutex_unlock(data->task_mutex);
-
- #endif
- }
-
- return 0;
-}
-
-nvTaskExecutor *nvTaskExecutor_new(size_t size) {
- nvTaskExecutor *task_executor = NV_NEW(nvTaskExecutor);
- if (!task_executor) return NULL;
-
- task_executor->threads = nvArray_new();
- task_executor->data = nvArray_new();
-
- for (size_t i = 0; i < size; i++) {
- nvTaskExecutorData *thread_data = NV_NEW(nvTaskExecutorData);
- if (!thread_data) return NULL;
-
- thread_data->is_active = true;
- thread_data->is_busy = false;
- thread_data->task_arrived = false;
- thread_data->task = NULL;
- thread_data->task_mutex = nvMutex_new();
- thread_data->task_event = nvCondition_new();
- thread_data->done_event = nvCondition_new();
- nvArray_add(task_executor->data, thread_data);
-
- nvThread *thread = nvThread_create(nvTaskExecutor_main, thread_data);
- nvArray_add(task_executor->threads, thread);
- }
-
- return task_executor;
-}
-
-void nvTaskExecutor_free(nvTaskExecutor *task_executor) {
- nvArray_free(task_executor->threads);
- for (size_t i = 0; i < task_executor->data->size; i++) {
- nvTaskExecutorData *data = task_executor->data->data[i];
- free(data->task);
- nvMutex_free(data->task_mutex);
- nvCondition_free(data->task_event);
- nvCondition_free(data->done_event);
- }
- nvArray_free_each(task_executor->data, free);
- nvArray_free(task_executor->data);
-}
-
-void nvTaskExecutor_close(nvTaskExecutor *task_executor) {
- for (size_t i = 0; i < task_executor->data->size; i++) {
- nvTaskExecutorData *data = task_executor->data->data[i];
-
- nvMutex_lock(data->task_mutex);
- data->is_active = false;
- data->task = NULL;
- nvCondition_signal(data->task_event);
- nvMutex_unlock(data->task_mutex);
-
- }
-
- nvThread_join_multiple(
- (nvThread **)task_executor->threads->data,
- task_executor->threads->size
- );
-}
-
-bool nvTaskExecutor_add_task(
- nvTaskExecutor *task_executor,
- nvTaskCallback task_func,
- void *task_data
-) {
- for (size_t i = 0; i < task_executor->threads->size; i++) {
- if (
- nvTaskExecutor_add_task_to(
- task_executor,
- task_func,
- task_data,
- i
- )
- )
- return true;
- }
-
- return false;
-}
-
-bool nvTaskExecutor_add_task_to(
- nvTaskExecutor *task_executor,
- nvTaskCallback task_func,
- void *task_data,
- size_t thread_no
-) {
- nvTaskExecutorData *data = task_executor->data->data[thread_no];
-
- if (!data->task) {
- nvTask *task = NV_NEW(nvTask);
- if (!task) return false;
-
- task->task_func = task_func;
- task->data = task_data;
-
- #ifdef NV_WINDOWS
-
- data->task = task;
- data->task_arrived = false;
-
- nvCondition_signal(data->task_event);
-
- #else
-
- nvMutex_lock(data->task_mutex);
-
- data->task = task;
- data->task_arrived = false;
-
- nvCondition_signal(data->task_event);
-
- nvMutex_unlock(data->task_mutex);
-
- #endif
-
- return true;
- }
-
- return false;
-}
-
-void nvTaskExecutor_wait_tasks(nvTaskExecutor *task_executor) {
- #ifdef NV_WINDOWS
-
- for (size_t i = 0; i < task_executor->threads->size; i++) {
- nvTaskExecutorData *data = task_executor->data->data[i];
- nvCondition_wait(data->done_event, data->task_mutex);
- }
-
- #else
-
- for (size_t i = 0; i < task_executor->threads->size; i++) {
- nvTaskExecutorData *data = task_executor->data->data[i];
-
- // Busy wait if the task hasn't arrived yet
- while (!data->task_arrived) {}
-
- while (data->is_busy) {
- nvMutex_lock(data->task_mutex);
- nvCondition_wait(data->done_event, data->task_mutex);
- nvMutex_unlock(data->task_mutex);
- }
- }
-
- #endif
-}
\ No newline at end of file
diff --git a/tests/tests.c b/tests/main.c
similarity index 67%
rename from tests/tests.c
rename to tests/main.c
index a426bbb..2d716c4 100644
--- a/tests/tests.c
+++ b/tests/main.c
@@ -11,6 +11,13 @@
#include "unittest.h"
+/**
+ * @file tests/main.c
+ *
+ * @brief Nova unit tests entry point.
+ */
+
+
/******************************************************************************
nvVector2 tests
@@ -18,93 +25,93 @@
******************************************************************************/
void TEST__nvVector2_eq(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(3.0, 2.0);
- nvVector2 b = NV_VEC2(3.0, 2.1);
+ nvVector2 a = NV_VECTOR2(3.0, 2.0);
+ nvVector2 b = NV_VECTOR2(3.0, 2.1);
expect_false(nvVector2_eq(a, b), test);
}
void TEST__nvVector2_add(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.0, 4.5);
- nvVector2 b = NV_VEC2(3.0, 2.1);
- expect_Vector2(nvVector2_add(a, b), NV_VEC2(2.0, 6.6), test);
+ nvVector2 a = NV_VECTOR2(-1.0, 4.5);
+ nvVector2 b = NV_VECTOR2(3.0, 2.1);
+ expect_Vector2(nvVector2_add(a, b), NV_VECTOR2(2.0, 6.6), test);
}
void TEST__nvVector2_sub(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.0, 4.5);
- nvVector2 b = NV_VEC2(3.0, 2.1);
- expect_Vector2(nvVector2_sub(a, b), NV_VEC2(-4.0, 2.4), test);
+ nvVector2 a = NV_VECTOR2(-1.0, 4.5);
+ nvVector2 b = NV_VECTOR2(3.0, 2.1);
+ expect_Vector2(nvVector2_sub(a, b), NV_VECTOR2(-4.0, 2.4), test);
}
void TEST__nvVector2_mul(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.0, 4.5);
+ nvVector2 a = NV_VECTOR2(-1.0, 4.5);
double b = 2.46;
- expect_Vector2(nvVector2_mul(a, b), NV_VEC2(-2.46, 11.07), test);
+ expect_Vector2(nvVector2_mul(a, b), NV_VECTOR2(-2.46, 11.07), test);
}
void TEST__nvVector2_div(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.0, 4.5);
+ nvVector2 a = NV_VECTOR2(-1.0, 4.5);
double b = 2.5;
- expect_Vector2(nvVector2_div(a, b), NV_VEC2(-0.4, 1.8), test);
+ expect_Vector2(nvVector2_div(a, b), NV_VECTOR2(-0.4, 1.8), test);
}
void TEST__nvVector2_neg(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.0, 4.5);
- expect_Vector2(nvVector2_neg(a), NV_VEC2(1.0, -4.5), test);
+ nvVector2 a = NV_VECTOR2(-1.0, 4.5);
+ expect_Vector2(nvVector2_neg(a), NV_VECTOR2(1.0, -4.5), test);
}
void TEST__nvVector2_rotate(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
double angle = NV_PI / 4.0;
- expect_Vector2(nvVector2_rotate(a, angle), NV_VEC2(-2.474874, 0.353553), test);
+ expect_Vector2(nvVector2_rotate(a, angle), NV_VECTOR2(-2.474874, 0.353553), test);
}
void TEST__nvVector2_perp(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
- expect_Vector2(nvVector2_perp(a), NV_VEC2(-2.0, -1.5), test);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
+ expect_Vector2(nvVector2_perp(a), NV_VECTOR2(-2.0, -1.5), test);
}
void TEST__nvVector2_perpr(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
- expect_Vector2(nvVector2_perpr(a), NV_VEC2(2.0, 1.5), test);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
+ expect_Vector2(nvVector2_perpr(a), NV_VECTOR2(2.0, 1.5), test);
}
void TEST__nvVector2_len2(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
expect_double(nvVector2_len2(a), 6.25, test);
}
void TEST__nvVector2_len(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
expect_double(nvVector2_len(a), 2.5, test);
}
void TEST__nvVector2_dot(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
- nvVector2 b = NV_VEC2(5.0, 8.5);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
+ nvVector2 b = NV_VECTOR2(5.0, 8.5);
expect_double(nvVector2_dot(a, b), 9.5, test);
}
void TEST__nvVector2_cross(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
- nvVector2 b = NV_VEC2(5.0, 8.5);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
+ nvVector2 b = NV_VECTOR2(5.0, 8.5);
expect_double(nvVector2_cross(a, b), -22.75, test);
}
void TEST__nvVector2_dist2(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
- nvVector2 b = NV_VEC2(5.3, 8.4);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
+ nvVector2 b = NV_VECTOR2(5.3, 8.4);
expect_double(nvVector2_dist2(a, b), 87.2, test);
}
void TEST__nvVector2_dist(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.5, 2.0);
- nvVector2 b = NV_VEC2(5.0, 8.5);
+ nvVector2 a = NV_VECTOR2(-1.5, 2.0);
+ nvVector2 b = NV_VECTOR2(5.0, 8.5);
expect_double(nvVector2_dist(a, b), 9.19239, test);
}
void TEST__nvVector2_normalize(UnitTestSuite *test) {
- nvVector2 a = NV_VEC2(-1.2, 4.5);
- expect_Vector2(nvVector2_normalize(a), NV_VEC2(-0.257663, 0.966235), test);
+ nvVector2 a = NV_VECTOR2(-1.2, 4.5);
+ expect_Vector2(nvVector2_normalize(a), NV_VECTOR2(-0.257663, 0.966235), test);
}
@@ -207,8 +214,10 @@ int main(int argc, char *argv[]) {
TEST(nvArray_pop)
TEST(nvArray_remove)
- printf("total: %d\n", test.total);
- printf("fails: %d\n", test.fails);
+ printf("\n");
+ printf("Total tests: %d\n", test.total);
+ printf("Failed: %d\n", test.fails);
+ printf("Passed: %d\n", test.total - test.fails);
return EXIT_SUCCESS;
}
\ No newline at end of file
diff --git a/tests/unittest.h b/tests/unittest.h
index c09f517..6c772a1 100644
--- a/tests/unittest.h
+++ b/tests/unittest.h
@@ -111,7 +111,7 @@ void expect_double(double value, double expect, UnitTestSuite *test) {
* @param value Value
* @param test Pointer to UnitTestSuite object
*/
-void expect_true(bool value, UnitTestSuite *test) {
+void expect_true(nv_bool value, UnitTestSuite *test) {
UPDATE_TOTAL;
if (value) {
@@ -129,7 +129,7 @@ void expect_true(bool value, UnitTestSuite *test) {
* @param value Value
* @param test Pointer to UnitTestSuite object
*/
-void expect_false(bool value, UnitTestSuite *test) {
+void expect_false(nv_bool value, UnitTestSuite *test) {
UPDATE_TOTAL;
if (!value) {