[
  {
    "path": ".NO_AI/README.md",
    "content": "\n[Use of AI is forbidden, see CONTRIBUTING.md for details.](../CONTRIBUTING.md)\n\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/1-stb_image-doesn-t-load-specific-image-correctly.md",
    "content": "---\nname: stb_image Doesn't Load Specific Image Correctly\nabout: if an image displays wrong in your program, and you've verified stb_image is\n  the problem\ntitle: ''\nlabels: 1 stb_image\nassignees: ''\n\n---\n\n1. **Confirm that, after loading the image with stbi_load, you've immediately written it out with stbi_write_png or similar, and that version of the image is also wrong.** If it is correct when written out, the problem is not in stb_image. If it displays wrong in a program you're writing, it's probably your display code. For example, people writing OpenGL programs frequently do not upload or display the image correctly and assume stb_image is at fault even though writing out the image demonstrates that it loads correctly.\n\n2. *Provide an image that does not load correctly using stb_image* so we can reproduce the problem.\n\n3. *Provide an image or description of what part of the image is incorrect and how* so we can be sure we've reproduced the problem correctly.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/2-bug_report.md",
    "content": "---\nname: Bug report\nabout: if you're having trouble using a library, try the support forum instead\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**DO NOT USE AI TO WRITE THE BUG REPORT FOR YOU**  \nSuch issues will be closed. See bottom for explanation.\n\n**Describe the bug**  \nA clear and concise description of what the bug is.\n\n**To Reproduce**  \nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**  \nA clear and concise description of what you expected to happen.\n\n**Screenshots**  \nIf applicable, add screenshots to help explain your problem.\n\n**AI BUG REPORTS**  \nUsing AI like LLMs just adds unnecessary additional verbiage that maintainers have to read and determine whether there is valuable and useful information. An AI by definition *cannot* add useful detail that was not in the original information you gathered. Just share the information you gathered. For example, it doesn't matter if your English isn't good.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/3-feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: 4 enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: support forum\n    url: https://github.com/nothings/stb/discussions/categories/q-a\n    about: having trouble using an stb library? don't create an issue, post in the forum\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "* Delete this list before clicking CREATE PULL REQUEST\n* Make sure you're using a special branch just for this pull request. (Sometimes people unknowingly use a default branch, then later update that branch, which updates the pull request with the other changes if it hasn't been merged yet.)\n* Do NOT update the version number in the file. (This just causes conflicts.)\n* Do add your name to the list of contributors. (Don't worry about the formatting.) I'll try to remember to add it if you don't, but I sometimes forget as it's an extra step.\n\nIf you get something above wrong, don't fret it, it's not the end of the world.\n"
  },
  {
    "path": ".github/workflows/ci-fuzz.yml",
    "content": "name: CIFuzz\non: [pull_request]\njobs:\n  Fuzzing:\n    runs-on: ubuntu-latest\n    steps:\n    - name: Build Fuzzers\n      uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master\n      with:\n        oss-fuzz-project-name: 'stb'\n        dry-run: false\n    - name: Run Fuzzers\n      uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master\n      with:\n        oss-fuzz-project-name: 'stb'\n        fuzz-seconds: 900\n        dry-run: false\n    - name: Upload Crash\n      uses: actions/upload-artifact@v1\n      if: failure()\n      with:\n        name: artifacts\n        path: ./out/artifacts\n"
  },
  {
    "path": ".gitignore",
    "content": "*.o\n*.obj\n*.exe\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: C\narch:\n  - AMD64\n  - ppc64le\ninstall: true\nscript:\n  - cd tests\n  - make all\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "AI AND LLM ARE FORBIDDEN\n========================\n\nThis project doesn't accept code or documentation generated\nby LLMs or any other forms of generative AI.\n\nPlease don't submit pull requests based on generative AI\noutput, and don't use AI auto completion when you write\npull requests.\n\nAdditionally, don't use LLMs to create pull requests or issues.\nWrite them yourself, in English, even if your English is bad.\n\n\nContributions Welcome\n=====================\n\nPull Requests and Issues are both welcome.\n\n\n### Responsiveness\n\nGeneral priority order is:\n\n* Crashes\n* Security issues in stb_image\n* Bugs\n* Security concerns in other libs\n* Warnings\n* Enhancements (new features, performance improvement, etc)\n\nPull requests get priority over Issues. Some pull requests I take\nas written; some I modify myself; some I will request changes before\naccepting them. Because I've ended up supporting a lot of libraries\n(20 as I write this, with more on the way), I am somewhat slow to\naddress things. Many issues have been around for a long time.\n\n\n### Pull requests\n\n* Make sure you're using a special branch just for this pull request. (Sometimes people unknowingly use a default branch, then later update that branch, which updates the pull request with the other changes if it hasn't been merged yet.)\n* Do NOT update the version number in the file. (This just causes conflicts.)\n* Do add your name to the list of contributors. (Don't worry about the formatting.) I'll try to remember to add it if you don't, but I sometimes forget as it's an extra step.\n* Your change needs to compile as both C and C++. Pre-C99 compilers should be supported (e.g. declare at start of block)\n\n\n### Specific libraries\n\nI generally do not want new file formats for stb_image because\nwe are trying to improve its security, so increasing its attack\nsurface is counter-productive.\n\n"
  },
  {
    "path": "LICENSE",
    "content": "This software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<!---   THIS FILE IS AUTOMATICALLY GENERATED, DO NOT CHANGE IT BY HAND   --->\n\nstb\n===\n\nsingle-file public domain (or MIT licensed) libraries for C/C++\n\n# This project discusses security-relevant bugs in public in Github Issues and Pull Requests, and it may take significant time for security fixes to be implemented or merged. If this poses an unreasonable risk to your project, do not use stb libraries.\n\nNoteworthy:\n\n* image loader: [stb_image.h](stb_image.h)\n* image writer: [stb_image_write.h](stb_image_write.h)\n* image resizer: [stb_image_resize2.h](stb_image_resize2.h)\n* font text rasterizer: [stb_truetype.h](stb_truetype.h)\n* typesafe containers: [stb_ds.h](stb_ds.h)\n\nMost libraries by stb, except: stb_dxt by Fabian \"ryg\" Giesen, original stb_image_resize\nby Jorge L. \"VinoBS\" Rodriguez, and stb_image_resize2 and stb_sprintf by Jeff Roberts.\n\n<a name=\"stb_libs\"></a>\n\nlibrary    | latest version | category | LoC | description\n--------------------- | ---- | -------- | --- | --------------------------------\n**[stb_vorbis.c](stb_vorbis.c)** | 1.22 | audio | 5584 | decode ogg vorbis files from file/memory to float/16-bit signed output\n**[stb_hexwave.h](stb_hexwave.h)** | 0.5 | audio | 680 | audio waveform synthesizer\n**[stb_image.h](stb_image.h)** | 2.30 | graphics | 7988 | image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC\n**[stb_truetype.h](stb_truetype.h)** | 1.26 | graphics | 5079 | parse, decode, and rasterize characters from truetype fonts\n**[stb_image_write.h](stb_image_write.h)** | 1.16 | graphics | 1724 | image writing to disk: PNG, TGA, BMP\n**[stb_image_resize2.h](stb_image_resize2.h)** | 2.18b | graphics | 10679 | resize images larger/smaller with good quality\n**[stb_rect_pack.h](stb_rect_pack.h)** | 1.01 | graphics | 623 | simple 2D rectangle packer with decent quality\n**[stb_perlin.h](stb_perlin.h)** | 0.5 | graphics | 428 | perlin's revised simplex noise w/ different seeds\n**[stb_ds.h](stb_ds.h)** | 0.67 | utility | 1895 | typesafe dynamic array and hash tables for C, will compile in C++\n**[stb_sprintf.h](stb_sprintf.h)** | 1.10 | utility | 1906 | fast sprintf, snprintf for C/C++\n**[stb_textedit.h](stb_textedit.h)** | 1.14 | user&nbsp;interface | 1429 | guts of a text editor for games etc implementing them from scratch\n**[stb_voxel_render.h](stb_voxel_render.h)** | 0.89 | 3D&nbsp;graphics | 3807 | Minecraft-esque voxel rendering \"engine\" with many more features\n**[stb_dxt.h](stb_dxt.h)** | 1.12 | 3D&nbsp;graphics | 719 | Fabian \"ryg\" Giesen's real-time DXT compressor\n**[stb_easy_font.h](stb_easy_font.h)** | 1.1 | 3D&nbsp;graphics | 305 | quick-and-dirty easy-to-deploy bitmap font for printing frame rate, etc\n**[stb_tilemap_editor.h](stb_tilemap_editor.h)** | 0.42 | game&nbsp;dev | 4187 | embeddable tilemap editor\n**[stb_herringbone_wa...](stb_herringbone_wang_tile.h)** | 0.7 | game&nbsp;dev | 1221 | herringbone Wang tile map generator\n**[stb_c_lexer.h](stb_c_lexer.h)** | 0.12 | parsing | 941 | simplify writing parsers for C-like languages\n**[stb_divide.h](stb_divide.h)** | 0.94 | math | 433 | more useful 32-bit modulus e.g. \"euclidean divide\"\n**[stb_connected_comp...](stb_connected_components.h)** | 0.96 | misc | 1049 | incrementally compute reachability on grids\n**[stb_leakcheck.h](stb_leakcheck.h)** | 0.6 | misc | 194 | quick-and-dirty malloc/free leak-checking\n**[stb_include.h](stb_include.h)** | 0.02 | misc | 295 | implement recursive #include support, particularly for GLSL\n\nTotal libraries: 21\nTotal lines of C code: 51166\n\n\nFAQ\n---\n\n#### What's the license?\n\nThese libraries are in the public domain. You can do anything you\nwant with them. You have no legal obligation\nto do anything else, although I appreciate attribution.\n\nThey are also licensed under the MIT open source license, if you have lawyers\nwho are unhappy with public domain. Every source file includes an explicit\ndual-license for you to choose from.\n\n#### How do I use these libraries?\n\nThe idea behind single-header file libraries is that they're easy to distribute and deploy\nbecause all the code is contained in a single file. By default, the .h files in here act as\ntheir own header files, i.e. they declare the functions contained in the file but don't\nactually result in any code getting compiled.\n\nSo in addition, you should select _exactly one_ C/C++ source file that actually instantiates\nthe code, preferably a file you're not editing frequently. This file should define a\nspecific macro (this is documented per-library) to actually enable the function definitions.\nFor example, to use stb_image, you should have exactly one C/C++ file that doesn't\ninclude stb_image.h regularly, but instead does\n\n    #define STB_IMAGE_IMPLEMENTATION\n    #include \"stb_image.h\"\n\nThe right macro to define is pointed out right at the top of each of these libraries.\n\n#### <a name=\"other_libs\"></a> Are there other single-file public-domain/open source libraries with minimal dependencies out there?\n\n[Yes.](https://github.com/nothings/single_file_libs)\n\n#### If I wrap an stb library in a new library, does the new library have to be public domain/MIT?\n\nNo, because it's public domain you can freely relicense it to whatever license your new\nlibrary wants to be.\n\n#### What's the deal with SSE support in GCC-based compilers?\n\nstb_image will either use SSE2 (if you compile with -msse2) or\nwill not use any SIMD at all, rather than trying to detect the\nprocessor at runtime and handle it correctly. As I understand it,\nthe approved path in GCC for runtime-detection require\nyou to use multiple source files, one for each CPU configuration.\nBecause stb_image is a header-file library that compiles in only\none source file, there's no approved way to build both an\nSSE-enabled and a non-SSE-enabled variation.\n\nWhile we've tried to work around it, we've had multiple issues over\nthe years due to specific versions of gcc breaking what we're doing,\nso we've given up on it. See https://github.com/nothings/stb/issues/280\nand https://github.com/nothings/stb/issues/410 for examples.\n\n#### Some of these libraries seem redundant to existing open source libraries. Are they better somehow?\n\nGenerally they're only better in that they're easier to integrate,\neasier to use, and easier to release (single file; good API; no\nattribution requirement). They may be less featureful, slower,\nand/or use more memory. If you're already using an equivalent\nlibrary, there's probably no good reason to switch.\n\n#### Can I link directly to the table of stb libraries?\n\nYou can use [this URL](https://github.com/nothings/stb#stb_libs) to link directly to that list.\n\n#### Why do you list \"lines of code\"? It's a terrible metric.\n\nJust to give you some idea of the internal complexity of the library,\nto help you manage your expectations, or to let you know what you're\ngetting into. While not all the libraries are written in the same\nstyle, they're certainly similar styles, and so comparisons between\nthe libraries are probably still meaningful.\n\nNote though that the lines do include both the implementation, the\npart that corresponds to a header file, and the documentation.\n\n#### Why single-file headers?\n\nWindows doesn't have standard directories where libraries\nlive. That makes deploying libraries in Windows a lot more\npainful than open source developers on Unix-derivates generally\nrealize. (It also makes library dependencies a lot worse in Windows.)\n\nThere's also a common problem in Windows where a library was built\nagainst a different version of the runtime library, which causes\nlink conflicts and confusion. Shipping the libs as headers means\nyou normally just compile them straight into your project without\nmaking libraries, thus sidestepping that problem.\n\nMaking them a single file makes it very easy to just\ndrop them into a project that needs them. (Of course you can\nstill put them in a proper shared library tree if you want.)\n\nWhy not two files, one a header and one an implementation?\nThe difference between 10 files and 9 files is not a big deal,\nbut the difference between 2 files and 1 file is a big deal.\nYou don't need to zip or tar the files up, you don't have to\nremember to attach *two* files, etc.\n\n#### Why \"stb\"? Is this something to do with Set-Top Boxes?\n\nNo, they are just the initials for my name, Sean T. Barrett.\nThis was not chosen out of egomania, but as a moderately sane\nway of namespacing the filenames and source function names.\n\n#### Will you add more image types to stb_image.h?\n\nNo. As stb_image use has grown, it has become more important\nfor us to focus on security of the codebase. Adding new image\nformats increases the amount of code we need to secure, so it\nis no longer worth adding new formats.\n\n#### Do you have any advice on how to create my own single-file library?\n\nYes. https://github.com/nothings/stb/blob/master/docs/stb_howto.txt\n\n#### Why public domain?\n\nI prefer it over GPL, LGPL, BSD, zlib, etc. for many reasons.\nSome of them are listed here:\nhttps://github.com/nothings/stb/blob/master/docs/why_public_domain.md\n\n#### Why C?\n\nPrimarily, because I use C, not C++. But it does also make it easier\nfor other people to use them from other languages.\n\n#### Why not C99? stdint.h, declare-anywhere, etc.\n\nI still use MSVC 6 (1998) as my IDE because it has better human factors\nfor me than later versions of MSVC.\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\nThis project discusses security-relevant bugs in public in Github Issues and Pull Requests, and it may take significant time for security fixes to be implemented or merged. If this poses an unreasonable risk to your project, do not use stb libraries.\n"
  },
  {
    "path": "data/herringbone/license.txt",
    "content": "All files in this directory are in the public domain. Where\na public domain declaration is not recognized, you are granted\na license to freely use, modify, and redistribute them in\nany way you choose."
  },
  {
    "path": "deprecated/rrsprintf.h",
    "content": "#ifndef RR_SPRINTF_H_INCLUDE\n#define RR_SPRINTF_H_INCLUDE\n\n/*\nSingle file sprintf replacement.\n\nOriginally written by Jeff Roberts at RAD Game Tools - 2015/10/20. \nHereby placed in public domain.\n\nThis is a full sprintf replacement that supports everything that\nthe C runtime sprintfs support, including float/double, 64-bit integers,\nhex floats, field parameters (%*.*d stuff), length reads backs, etc.\n\nWhy would you need this if sprintf already exists?  Well, first off,\nit's *much* faster (see below). It's also much smaller than the CRT\nversions code-space-wise. We've also added some simple improvements \nthat are super handy (commas in thousands, callbacks at buffer full,\nfor example). Finally, the format strings for MSVC and GCC differ \nfor 64-bit integers (among other small things), so this lets you use \nthe same format strings in cross platform code.\n\nIt uses the standard single file trick of being both the header file\nand the source itself. If you just include it normally, you just get \nthe header file function definitions. To get the code, you include\nit from a C or C++ file and define RR_SPRINTF_IMPLEMENTATION first.\n\nIt only uses va_args macros from the C runtime to do it's work. It\ndoes cast doubles to S64s and shifts and divides U64s, which does \ndrag in CRT code on most platforms.\n\nIt compiles to roughly 8K with float support, and 4K without.\nAs a comparison, when using MSVC static libs, calling sprintf drags\nin 16K.\n\nAPI:\n====\nint rrsprintf( char * buf, char const * fmt, ... )\nint rrsnprintf( char * buf, int count, char const * fmt, ... )\n  Convert an arg list into a buffer.  rrsnprintf always returns\n  a zero-terminated string (unlike regular snprintf).\n\nint rrvsprintf( char * buf, char const * fmt, va_list va )\nint rrvsnprintf( char * buf, int count, char const * fmt, va_list va )\n  Convert a va_list arg list into a buffer.  rrvsnprintf always returns\n  a zero-terminated string (unlike regular snprintf).\n\nint rrvsprintfcb( RRSPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )\n    typedef char * RRSPRINTFCB( char const * buf, void * user, int len );\n  Convert into a buffer, calling back every RR_SPRINTF_MIN chars.\n  Your callback can then copy the chars out, print them or whatever.\n  This function is actually the workhorse for everything else.\n  The buffer you pass in must hold at least RR_SPRINTF_MIN characters.\n    // you return the next buffer to use or 0 to stop converting\n\nvoid rrsetseparators( char comma, char period )\n  Set the comma and period characters to use.\n\nFLOATS/DOUBLES:\n===============\nThis code uses a internal float->ascii conversion method that uses\ndoubles with error correction (double-doubles, for ~105 bits of\nprecision).  This conversion is round-trip perfect - that is, an atof\nof the values output here will give you the bit-exact double back.\n\nOne difference is that our insignificant digits will be different than \nwith MSVC or GCC (but they don't match each other either).  We also \ndon't attempt to find the minimum length matching float (pre-MSVC15 \ndoesn't either).\n\nIf you don't need float or doubles at all, define RR_SPRINTF_NOFLOAT\nand you'll save 4K of code space.\n\n64-BIT INTS:\n============\nThis library also supports 64-bit integers and you can use MSVC style or\nGCC style indicators (%I64d or %lld).  It supports the C99 specifiers\nfor size_t and ptr_diff_t (%jd %zd) as well.\n\nEXTRAS:\n=======\nLike some GCCs, for integers and floats, you can use a ' (single quote)\nspecifier and commas will be inserted on the thousands: \"%'d\" on 12345 \nwould print 12,345.\n\nFor integers and floats, you can use a \"$\" specifier and the number \nwill be converted to float and then divided to get kilo, mega, giga or\ntera and then printed, so \"%$d\" 1024 is \"1.0 k\", \"%$.2d\" 2536000 is \n\"2.42 m\", etc.\n\nIn addition to octal and hexadecimal conversions, you can print \nintegers in binary: \"%b\" for 256 would print 100.\n\nPERFORMANCE vs MSVC 2008 32-/64-bit (GCC is even slower than MSVC):\n===================================================================\n\"%d\" across all 32-bit ints (4.8x/4.0x faster than 32-/64-bit MSVC)\n\"%24d\" across all 32-bit ints (4.5x/4.2x faster)\n\"%x\" across all 32-bit ints (4.5x/3.8x faster)\n\"%08x\" across all 32-bit ints (4.3x/3.8x faster)\n\"%f\" across e-10 to e+10 floats (7.3x/6.0x faster)\n\"%e\" across e-10 to e+10 floats (8.1x/6.0x faster)\n\"%g\" across e-10 to e+10 floats (10.0x/7.1x faster)\n\"%f\" for values near e-300 (7.9x/6.5x faster)\n\"%f\" for values near e+300 (10.0x/9.1x faster)\n\"%e\" for values near e-300 (10.1x/7.0x faster)\n\"%e\" for values near e+300 (9.2x/6.0x faster)\n\"%.320f\" for values near e-300 (12.6x/11.2x faster)\n\"%a\" for random values (8.6x/4.3x faster)\n\"%I64d\" for 64-bits with 32-bit values (4.8x/3.4x faster)\n\"%I64d\" for 64-bits > 32-bit values (4.9x/5.5x faster)\n\"%s%s%s\" for 64 char strings (7.1x/7.3x faster)\n\"...512 char string...\" ( 35.0x/32.5x faster!)\n*/\n\n#ifdef RR_SPRINTF_STATIC\n#define RRPUBLIC_DEC static\n#define RRPUBLIC_DEF static\n#else\n#ifdef __cplusplus\n#define RRPUBLIC_DEC extern \"C\"\n#define RRPUBLIC_DEF extern \"C\"\n#else\n#define RRPUBLIC_DEC extern \n#define RRPUBLIC_DEF\n#endif\n#endif\n\n#include <stdarg.h>  // for va_list()\n\n#ifndef RR_SPRINTF_MIN\n#define RR_SPRINTF_MIN 512 // how many characters per callback\n#endif\ntypedef char * RRSPRINTFCB( char * buf, void * user, int len );\n\n#ifndef RR_SPRINTF_DECORATE\n#define RR_SPRINTF_DECORATE(name) rr##name  // define this before including if you want to change the names\n#endif\n\n#ifndef RR_SPRINTF_IMPLEMENTATION\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintf )( char * buf, char const * fmt, va_list va );\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va );\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( sprintf ) ( char * buf, char const * fmt, ... );\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( snprintf )( char * buf, int count, char const * fmt, ... );\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintfcb )( RRSPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va );\nRRPUBLIC_DEF void RR_SPRINTF_DECORATE( setseparators )( char comma, char period );\n\n#else\n\n#include <stdlib.h>  // for va_arg()\n\n#define rU32 unsigned int\n#define rS32 signed int\n\n#ifdef _MSC_VER\n#define rU64 unsigned __int64\n#define rS64 signed __int64\n#else\n#define rU64 unsigned long long\n#define rS64 signed long long\n#endif\n#define rU16 unsigned short\n\n#ifndef rUINTa \n#if defined(__ppc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64)\n#define rUINTa rU64\n#else\n#define rUINTa rU32\n#endif\n#endif\n\n#ifndef RR_SPRINTF_MSVC_MODE  // used for MSVC2013 and earlier (MSVC2015 matches GCC)\n#if defined(_MSC_VER) && (_MSC_VER<1900)\n#define RR_SPRINTF_MSVC_MODE\n#endif\n#endif\n\n#ifdef RR_SPRINTF_NOUNALIGNED  // define this before inclusion to force rrsprint to always use aligned accesses\n#define RR_UNALIGNED(code)\n#else\n#define RR_UNALIGNED(code) code\n#endif\n\n#ifndef RR_SPRINTF_NOFLOAT\n// internal float utility functions\nstatic rS32 rrreal_to_str( char const * * start, rU32 * len, char *out, rS32 * decimal_pos, double value, rU32 frac_digits );\nstatic rS32 rrreal_to_parts( rS64 * bits, rS32 * expo, double value );\n#define RRSPECIAL 0x7000\n#endif\n\nstatic char RRperiod='.';\nstatic char RRcomma=',';\nstatic char rrdiglookup[201]=\"00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899\";\n\nRRPUBLIC_DEF void RR_SPRINTF_DECORATE( setseparators )( char pcomma, char pperiod )\n{\n  RRperiod=pperiod;\n  RRcomma=pcomma;\n}\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintfcb )( RRSPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )\n{\n  static char hex[]=\"0123456789abcdefxp\";\n  static char hexu[]=\"0123456789ABCDEFXP\";\n  char * bf;\n  char const * f;\n  int tlen = 0;\n\n  bf = buf;\n  f = fmt;\n  for(;;)\n  {\n    rS32 fw,pr,tz; rU32 fl;\n\n    #define LJ 1\n    #define LP 2\n    #define LS 4\n    #define LX 8\n    #define LZ 16\n    #define BI 32\n    #define CS 64\n    #define NG 128\n    #define KI 256\n    #define HW 512\n \n    // macros for the callback buffer stuff\n    #define chk_cb_bufL(bytes) { int len = (int)(bf-buf); if ((len+(bytes))>=RR_SPRINTF_MIN) { tlen+=len; if (0==(bf=buf=callback(buf,user,len))) goto done; } }\n    #define chk_cb_buf(bytes) { if ( callback ) { chk_cb_bufL(bytes); } }\n    #define flush_cb() { chk_cb_bufL(RR_SPRINTF_MIN-1); } //flush if there is even one byte in the buffer\n    #define cb_buf_clamp(cl,v) cl = v; if ( callback ) { int lg = RR_SPRINTF_MIN-(int)(bf-buf); if (cl>lg) cl=lg; }\n\n    // fast copy everything up to the next % (or end of string)\n    for(;;)\n    { \n      while (((rUINTa)f)&3)\n      {\n       schk1: if (f[0]=='%') goto scandd;\n       schk2: if (f[0]==0) goto endfmt;\n        chk_cb_buf(1); *bf++=f[0]; ++f;\n      } \n      for(;;)\n      { \n        rU32 v,c;\n        v=*(rU32*)f; c=(~v)&0x80808080;\n        if ((v-0x26262626)&c) goto schk1; \n        if ((v-0x01010101)&c) goto schk2; \n        if (callback) if ((RR_SPRINTF_MIN-(int)(bf-buf))<4) goto schk1;\n        *(rU32*)bf=v; bf+=4; f+=4;\n      }\n    } scandd:\n\n    ++f;\n\n    // ok, we have a percent, read the modifiers first\n    fw = 0; pr = -1; fl = 0; tz = 0;\n    \n    // flags\n    for(;;)\n    {\n      switch(f[0])\n      {\n        // if we have left just\n        case '-': fl|=LJ; ++f; continue;\n        // if we have leading plus\n        case '+': fl|=LP; ++f; continue; \n        // if we have leading space\n        case ' ': fl|=LS; ++f; continue; \n        // if we have leading 0x\n        case '#': fl|=LX; ++f; continue; \n        // if we have thousand commas\n        case '\\'': fl|=CS; ++f; continue; \n        // if we have kilo marker\n        case '$': fl|=KI; ++f; continue; \n        // if we have leading zero\n        case '0': fl|=LZ; ++f; goto flags_done; \n        default: goto flags_done;\n      }\n    }\n    flags_done:\n   \n    // get the field width\n    if ( f[0] == '*' ) {fw = va_arg(va,rU32); ++f;} else { while (( f[0] >= '0' ) && ( f[0] <= '9' )) { fw = fw * 10 + f[0] - '0'; f++; } }\n    // get the precision\n    if ( f[0]=='.' ) { ++f; if ( f[0] == '*' ) {pr = va_arg(va,rU32); ++f;} else { pr = 0; while (( f[0] >= '0' ) && ( f[0] <= '9' )) { pr = pr * 10 + f[0] - '0'; f++; } } } \n    \n    // handle integer size overrides\n    switch(f[0])\n    {\n      // are we halfwidth?\n      case 'h': fl|=HW; ++f; break;\n      // are we 64-bit (unix style)\n      case 'l': ++f; if ( f[0]=='l') { fl|=BI; ++f; } break;\n      // are we 64-bit on intmax? (c99)\n      case 'j': fl|=BI; ++f; break; \n      // are we 64-bit on size_t or ptrdiff_t? (c99)\n      case 'z': case 't': fl|=((sizeof(char*)==8)?BI:0); ++f; break; \n      // are we 64-bit (msft style)\n      case 'I': if ( ( f[1]=='6') && ( f[2]=='4') ) { fl|=BI; f+=3; } else if ( ( f[1]=='3') && ( f[2]=='2') ) { f+=3; } else { fl|=((sizeof(void*)==8)?BI:0); ++f; } break;\n      default: break;\n    }\n\n    // handle each replacement\n    switch( f[0] )\n    {\n      #define NUMSZ 512 // big enough for e308 (with commas) or e-307 \n      char num[NUMSZ]; \n      char lead[8]; \n      char tail[8]; \n      char *s;\n      char const *h;\n      rU32 l,n,cs;\n      rU64 n64;\n      #ifndef RR_SPRINTF_NOFLOAT      \n      double fv; \n      #endif\n      rS32 dp; char const * sn;\n\n      case 's':\n        // get the string\n        s = va_arg(va,char*); if (s==0) s = (char*)\"null\";\n        // get the length\n        sn = s;\n        for(;;)\n        { \n          if ((((rUINTa)sn)&3)==0) break;\n         lchk:\n          if (sn[0]==0) goto ld;\n          ++sn;\n        }\n        n = 0xffffffff;\n        if (pr>=0) { n=(rU32)(sn-s); if (n>=(rU32)pr) goto ld; n=((rU32)(pr-n))>>2; }\n        while(n) \n        { \n          rU32 v=*(rU32*)sn;\n          if ((v-0x01010101)&(~v)&0x80808080UL) goto lchk; \n          sn+=4; \n          --n;\n        }\n        goto lchk;\n       ld:\n\n        l = (rU32) ( sn - s );\n        // clamp to precision\n        if ( l > (rU32)pr ) l = pr;\n        lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;\n        // copy the string in\n        goto scopy;\n\n      case 'c': // char\n        // get the character\n        s = num + NUMSZ -1; *s = (char)va_arg(va,int);\n        l = 1;\n        lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;\n        goto scopy;\n\n      case 'n': // weird write-bytes specifier\n        { int * d = va_arg(va,int*);\n        *d = tlen + (int)( bf - buf ); }\n        break;\n\n#ifdef RR_SPRINTF_NOFLOAT\n      case 'A': // float\n      case 'a': // hex float\n      case 'G': // float\n      case 'g': // float\n      case 'E': // float\n      case 'e': // float\n      case 'f': // float\n        va_arg(va,double); // eat it\n        s = (char*)\"No float\";\n        l = 8;\n        lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;\n        goto scopy;\n#else\n      case 'A': // float\n        h=hexu;  \n        goto hexfloat;\n\n      case 'a': // hex float\n        h=hex;\n       hexfloat: \n        fv = va_arg(va,double);\n        if (pr==-1) pr=6; // default is 6\n        // read the double into a string\n        if ( rrreal_to_parts( (rS64*)&n64, &dp, fv ) )\n          fl |= NG;\n  \n        s = num+64;\n\n        // sign\n        lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };\n\n        if (dp==-1023) dp=(n64)?-1022:0; else n64|=(((rU64)1)<<52);\n        n64<<=(64-56);\n        if (pr<15) n64+=((((rU64)8)<<56)>>(pr*4));\n        // add leading chars\n        \n        #ifdef RR_SPRINTF_MSVC_MODE\n        *s++='0';*s++='x';\n        #else\n        lead[1+lead[0]]='0'; lead[2+lead[0]]='x'; lead[0]+=2;\n        #endif\n        *s++=h[(n64>>60)&15]; n64<<=4;\n        if ( pr ) *s++=RRperiod;\n        sn = s;\n\n        // print the bits\n        n = pr; if (n>13) n = 13; if (pr>(rS32)n) tz=pr-n; pr = 0;\n        while(n--) { *s++=h[(n64>>60)&15]; n64<<=4; }\n\n        // print the expo\n        tail[1]=h[17];\n        if (dp<0) { tail[2]='-'; dp=-dp;} else tail[2]='+';\n        n = (dp>=1000)?6:((dp>=100)?5:((dp>=10)?4:3));\n        tail[0]=(char)n;\n        for(;;) { tail[n]='0'+dp%10; if (n<=3) break; --n; dp/=10; }\n\n        dp = (int)(s-sn);\n        l = (int)(s-(num+64));\n        s = num+64;\n        cs = 1 + (3<<24);\n        goto scopy;\n\n      case 'G': // float\n        h=hexu;\n        goto dosmallfloat;\n\n      case 'g': // float\n        h=hex;\n       dosmallfloat:   \n        fv = va_arg(va,double);\n        if (pr==-1) pr=6; else if (pr==0) pr = 1; // default is 6\n        // read the double into a string\n        if ( rrreal_to_str( &sn, &l, num, &dp, fv, (pr-1)|0x80000000 ) )\n          fl |= NG;\n\n        // clamp the precision and delete extra zeros after clamp\n        n = pr;\n        if ( l > (rU32)pr ) l = pr; while ((l>1)&&(pr)&&(sn[l-1]=='0')) { --pr; --l; }\n\n        // should we use %e\n        if ((dp<=-4)||(dp>(rS32)n))\n        {\n          if ( pr > (rS32)l ) pr = l-1; else if ( pr ) --pr; // when using %e, there is one digit before the decimal\n          goto doexpfromg;\n        }\n        // this is the insane action to get the pr to match %g sematics for %f\n        if(dp>0) { pr=(dp<(rS32)l)?l-dp:0; } else { pr = -dp+((pr>(rS32)l)?l:pr); }\n        goto dofloatfromg;\n\n      case 'E': // float\n        h=hexu;  \n        goto doexp;\n\n      case 'e': // float\n        h=hex;\n       doexp:   \n        fv = va_arg(va,double);\n        if (pr==-1) pr=6; // default is 6\n        // read the double into a string\n        if ( rrreal_to_str( &sn, &l, num, &dp, fv, pr|0x80000000 ) )\n          fl |= NG;\n       doexpfromg: \n        tail[0]=0; \n        lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };\n        if ( dp == RRSPECIAL ) { s=(char*)sn; cs=0; pr=0; goto scopy; }\n        s=num+64; \n        // handle leading chars\n        *s++=sn[0];\n\n        if (pr) *s++=RRperiod;\n\n        // handle after decimal\n        if ((l-1)>(rU32)pr) l=pr+1;\n        for(n=1;n<l;n++) *s++=sn[n];\n        // trailing zeros\n        tz = pr-(l-1); pr=0;\n        // dump expo\n        tail[1]=h[0xe];\n        dp -= 1;\n        if (dp<0) { tail[2]='-'; dp=-dp;} else tail[2]='+';\n        #ifdef RR_SPRINTF_MSVC_MODE\n        n = 5;\n        #else\n        n = (dp>=100)?5:4;\n        #endif\n        tail[0]=(char)n;\n        for(;;) { tail[n]='0'+dp%10; if (n<=3) break; --n; dp/=10; }\n        cs = 1 + (3<<24); // how many tens\n        goto flt_lead;   \n\n      case 'f': // float\n        fv = va_arg(va,double);\n       doafloat: \n        // do kilos\n        if (fl&KI) {while(fl<0x4000000) { if ((fv<1024.0) && (fv>-1024.0)) break; fv/=1024.0; fl+=0x1000000; }} \n        if (pr==-1) pr=6; // default is 6\n        // read the double into a string\n        if ( rrreal_to_str( &sn, &l, num, &dp, fv, pr ) )\n          fl |= NG;\n        dofloatfromg:\n        tail[0]=0;\n        // sign\n        lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };\n        if ( dp == RRSPECIAL ) { s=(char*)sn; cs=0; pr=0; goto scopy; }\n        s=num+64; \n\n        // handle the three decimal varieties\n        if (dp<=0) \n        { \n          rS32 i;\n          // handle 0.000*000xxxx\n          *s++='0'; if (pr) *s++=RRperiod; \n          n=-dp; if((rS32)n>pr) n=pr; i=n; while(i) { if ((((rUINTa)s)&3)==0) break; *s++='0'; --i; } while(i>=4) { *(rU32*)s=0x30303030; s+=4; i-=4; } while(i) { *s++='0'; --i; }\n          if ((rS32)(l+n)>pr) l=pr-n; i=l; while(i) { *s++=*sn++; --i; }\n          tz = pr-(n+l);\n          cs = 1 + (3<<24); // how many tens did we write (for commas below)\n        }\n        else\n        {\n          cs = (fl&CS)?((600-(rU32)dp)%3):0;\n          if ((rU32)dp>=l)\n          {\n            // handle xxxx000*000.0\n            n=0; for(;;) { if ((fl&CS) && (++cs==4)) { cs = 0; *s++=RRcomma; } else { *s++=sn[n]; ++n; if (n>=l) break; } }\n            if (n<(rU32)dp)\n            {\n              n = dp - n;\n              if ((fl&CS)==0) { while(n) { if ((((rUINTa)s)&3)==0) break; *s++='0'; --n; }  while(n>=4) { *(rU32*)s=0x30303030; s+=4; n-=4; } }\n              while(n) { if ((fl&CS) && (++cs==4)) { cs = 0; *s++=RRcomma; } else { *s++='0'; --n; } }\n            }\n            cs = (int)(s-(num+64)) + (3<<24); // cs is how many tens\n            if (pr) { *s++=RRperiod; tz=pr;}\n          }\n          else\n          {\n            // handle xxxxx.xxxx000*000\n            n=0; for(;;) { if ((fl&CS) && (++cs==4)) { cs = 0; *s++=RRcomma; } else { *s++=sn[n]; ++n; if (n>=(rU32)dp) break; } }\n            cs = (int)(s-(num+64)) + (3<<24); // cs is how many tens\n            if (pr) *s++=RRperiod;\n            if ((l-dp)>(rU32)pr) l=pr+dp;\n            while(n<l) { *s++=sn[n]; ++n; }\n            tz = pr-(l-dp);\n          }\n        }\n        pr = 0;\n        \n        // handle k,m,g,t\n        if (fl&KI) { tail[0]=1; tail[1]=' '; { if (fl>>24) { tail[2]=\"_kmgt\"[fl>>24]; tail[0]=2; } } };\n\n        flt_lead:\n        // get the length that we copied\n        l = (rU32) ( s-(num+64) );\n        s=num+64; \n        goto scopy;\n#endif\n\n      case 'B': // upper binary\n        h = hexu;\n        goto binary;\n\n      case 'b': // lower binary\n        h = hex;\n        binary:\n        lead[0]=0;\n        if (fl&LX) { lead[0]=2;lead[1]='0';lead[2]=h[0xb]; }\n        l=(8<<4)|(1<<8);\n        goto radixnum;\n\n      case 'o': // octal\n        h = hexu;\n        lead[0]=0;\n        if (fl&LX) { lead[0]=1;lead[1]='0'; }\n        l=(3<<4)|(3<<8);\n        goto radixnum;\n\n      case 'p': // pointer\n        fl |= (sizeof(void*)==8)?BI:0;\n        pr = sizeof(void*)*2;\n        fl &= ~LZ; // 'p' only prints the pointer with zeros\n        // drop through to X\n      \n      case 'X': // upper binary\n        h = hexu;\n        goto dohexb;\n\n      case 'x': // lower binary\n        h = hex; dohexb:\n        l=(4<<4)|(4<<8);\n        lead[0]=0;\n        if (fl&LX) { lead[0]=2;lead[1]='0';lead[2]=h[16]; }\n       radixnum: \n        // get the number\n        if ( fl&BI )\n          n64 = va_arg(va,rU64);\n        else\n          n64 = va_arg(va,rU32);\n\n        s = num + NUMSZ; dp = 0;\n        // clear tail, and clear leading if value is zero\n        tail[0]=0; if (n64==0) { lead[0]=0; if (pr==0) { l=0; cs = ( ((l>>4)&15)) << 24; goto scopy; } }\n        // convert to string\n        for(;;) { *--s = h[n64&((1<<(l>>8))-1)]; n64>>=(l>>8); if ( ! ( (n64) || ((rS32) ( (num+NUMSZ) - s ) < pr ) ) ) break; if ( fl&CS) { ++l; if ((l&15)==((l>>4)&15)) { l&=~15; *--s=RRcomma; } } };\n        // get the tens and the comma pos\n        cs = (rU32) ( (num+NUMSZ) - s ) + ( ( ((l>>4)&15)) << 24 );\n        // get the length that we copied\n        l = (rU32) ( (num+NUMSZ) - s );\n        // copy it\n        goto scopy;\n\n      case 'u': // unsigned\n      case 'i':\n      case 'd': // integer\n        // get the integer and abs it\n        if ( fl&BI )\n        {\n          rS64 i64 = va_arg(va,rS64); n64 = (rU64)i64; if ((f[0]!='u') && (i64<0)) { n64=(rU64)-i64; fl|=NG; }\n        }\n        else\n        {\n          rS32 i = va_arg(va,rS32); n64 = (rU32)i; if ((f[0]!='u') && (i<0)) { n64=(rU32)-i; fl|=NG; }\n        }\n\n        #ifndef RR_SPRINTF_NOFLOAT\n        if (fl&KI) { if (n64<1024) pr=0; else if (pr==-1) pr=1; fv=(double)(rS64)n64; goto doafloat; } \n        #endif\n\n        // convert to string\n        s = num+NUMSZ; l=0; \n        \n        for(;;)\n        {\n          // do in 32-bit chunks (avoid lots of 64-bit divides even with constant denominators)\n          char * o=s-8;\n          if (n64>=100000000) { n = (rU32)( n64 % 100000000);  n64 /= 100000000; } else {n = (rU32)n64; n64 = 0; }\n          if((fl&CS)==0) { while(n) { s-=2; *(rU16*)s=*(rU16*)&rrdiglookup[(n%100)*2]; n/=100; } }\n          while (n) { if ( ( fl&CS) && (l++==3) ) { l=0; *--s=RRcomma; --o; } else { *--s=(char)(n%10)+'0'; n/=10; } }\n          if (n64==0) { if ((s[0]=='0') && (s!=(num+NUMSZ))) ++s; break; }\n          while (s!=o) if ( ( fl&CS) && (l++==3) ) { l=0; *--s=RRcomma; --o; } else { *--s='0'; }\n        }\n\n        tail[0]=0;\n        // sign\n        lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };\n\n        // get the length that we copied\n        l = (rU32) ( (num+NUMSZ) - s ); if ( l == 0 ) { *--s='0'; l = 1; }\n        cs = l + (3<<24);\n        if (pr<0) pr = 0;\n\n       scopy: \n        // get fw=leading/trailing space, pr=leading zeros\n        if (pr<(rS32)l) pr = l;\n        n = pr + lead[0] + tail[0] + tz;\n        if (fw<(rS32)n) fw = n;\n        fw -= n;\n        pr -= l;\n\n        // handle right justify and leading zeros\n        if ( (fl&LJ)==0 )\n        {\n          if (fl&LZ) // if leading zeros, everything is in pr\n          { \n            pr = (fw>pr)?fw:pr;\n            fw = 0;\n          }\n          else\n          {\n            fl &= ~CS; // if no leading zeros, then no commas\n          }\n        }\n\n        // copy the spaces and/or zeros\n        if (fw+pr)\n        {\n          rS32 i; rU32 c; \n\n          // copy leading spaces (or when doing %8.4d stuff)\n          if ( (fl&LJ)==0 ) while(fw>0) { cb_buf_clamp(i,fw); fw -= i; while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++=' '; --i; } while(i>=4) { *(rU32*)bf=0x20202020; bf+=4; i-=4; } while (i) {*bf++=' '; --i;} chk_cb_buf(1); }\n        \n          // copy leader\n          sn=lead+1; while(lead[0]) { cb_buf_clamp(i,lead[0]); lead[0] -= (char)i; while (i) {*bf++=*sn++; --i;} chk_cb_buf(1); }\n          \n          // copy leading zeros\n          c = cs >> 24; cs &= 0xffffff;\n          cs = (fl&CS)?((rU32)(c-((pr+cs)%(c+1)))):0;\n          while(pr>0) { cb_buf_clamp(i,pr); pr -= i; if((fl&CS)==0) { while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++='0'; --i; } while(i>=4) { *(rU32*)bf=0x30303030; bf+=4; i-=4; } } while (i) { if((fl&CS) && (cs++==c)) { cs = 0; *bf++=RRcomma; } else *bf++='0'; --i; } chk_cb_buf(1); }\n        }\n\n        // copy leader if there is still one\n        sn=lead+1; while(lead[0]) { rS32 i; cb_buf_clamp(i,lead[0]); lead[0] -= (char)i; while (i) {*bf++=*sn++; --i;} chk_cb_buf(1); }\n\n        // copy the string\n        n = l; while (n) { rS32 i; cb_buf_clamp(i,n); n-=i; RR_UNALIGNED( while(i>=4) { *(rU32*)bf=*(rU32*)s; bf+=4; s+=4; i-=4; } ) while (i) {*bf++=*s++; --i;} chk_cb_buf(1); }\n\n        // copy trailing zeros\n        while(tz) { rS32 i; cb_buf_clamp(i,tz); tz -= i; while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++='0'; --i; } while(i>=4) { *(rU32*)bf=0x30303030; bf+=4; i-=4; } while (i) {*bf++='0'; --i;} chk_cb_buf(1); }\n\n        // copy tail if there is one\n        sn=tail+1; while(tail[0]) { rS32 i; cb_buf_clamp(i,tail[0]); tail[0] -= (char)i; while (i) {*bf++=*sn++; --i;} chk_cb_buf(1); }\n\n        // handle the left justify\n        if (fl&LJ) if (fw>0) { while (fw) { rS32 i; cb_buf_clamp(i,fw); fw-=i; while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++=' '; --i; } while(i>=4) { *(rU32*)bf=0x20202020; bf+=4; i-=4; } while (i--) *bf++=' '; chk_cb_buf(1); } }\n        break;\n\n      default: // unknown, just copy code\n        s = num + NUMSZ -1; *s = f[0];\n        l = 1;\n        fw=pr=fl=0;\n        lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;\n        goto scopy;\n    }\n    ++f;\n  }\n endfmt:\n\n  if (!callback) \n    *bf = 0;\n  else\n    flush_cb();\n \n done:\n  return tlen + (int)(bf-buf);\n}\n\n// cleanup\n#undef LJ\n#undef LP\n#undef LS\n#undef LX\n#undef LZ\n#undef BI\n#undef CS\n#undef NG\n#undef KI\n#undef NUMSZ\n#undef chk_cb_bufL\n#undef chk_cb_buf\n#undef flush_cb\n#undef cb_buf_clamp\n\n// ============================================================================\n//   wrapper functions\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( sprintf )( char * buf, char const * fmt, ... )\n{\n  va_list va;\n  va_start( va, fmt );\n  return RR_SPRINTF_DECORATE( vsprintfcb )( 0, 0, buf, fmt, va );\n}\n\ntypedef struct RRCCS\n{\n  char * buf;\n  int count;\n  char tmp[ RR_SPRINTF_MIN ];\n} RRCCS;\n\nstatic char * rrclampcallback( char * buf, void * user, int len )\n{\n  RRCCS * c = (RRCCS*)user;\n\n  if ( len > c->count ) len = c->count;\n\n  if (len)\n  {\n    if ( buf != c->buf )\n    {\n      char * s, * d, * se;\n      d = c->buf; s = buf; se = buf+len;\n      do{ *d++ = *s++; } while (s<se);\n    }\n    c->buf += len;\n    c->count -= len;\n  }\n  \n  if ( c->count <= 0 ) return 0;\n  return ( c->count >= RR_SPRINTF_MIN ) ? c->buf : c->tmp; // go direct into buffer if you can\n}\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va )\n{\n  RRCCS c;\n  int l;\n\n  if ( count == 0 )\n    return 0;\n\n  c.buf = buf;\n  c.count = count;\n\n  RR_SPRINTF_DECORATE( vsprintfcb )( rrclampcallback, &c, rrclampcallback(0,&c,0), fmt, va );\n  \n  // zero-terminate\n  l = (int)( c.buf - buf );\n  if ( l >= count ) // should never be greater, only equal (or less) than count\n    l = count - 1;\n  buf[l] = 0;\n\n  return l;\n}\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( snprintf )( char * buf, int count, char const * fmt, ... )\n{\n  va_list va;\n  va_start( va, fmt );\n\n  return RR_SPRINTF_DECORATE( vsnprintf )( buf, count, fmt, va );\n}\n\nRRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintf )( char * buf, char const * fmt, va_list va )\n{\n  return RR_SPRINTF_DECORATE( vsprintfcb )( 0, 0, buf, fmt, va );\n}\n\n// =======================================================================\n//   low level float utility functions\n\n#ifndef RR_SPRINTF_NOFLOAT\n\n // copies d to bits w/ strict aliasing (this compiles to nothing on /Ox)\n #define RRCOPYFP(dest,src) { int cn; for(cn=0;cn<8;cn++) ((char*)&dest)[cn]=((char*)&src)[cn]; }\n \n// get float info\nstatic rS32 rrreal_to_parts( rS64 * bits, rS32 * expo, double value )\n{\n  double d;\n  rS64 b = 0;\n\n  // load value and round at the frac_digits\n  d = value;\n\n  RRCOPYFP( b, d );\n\n  *bits = b & ((((rU64)1)<<52)-1);\n  *expo = ((b >> 52) & 2047)-1023;\n    \n  return (rS32)(b >> 63);\n}\n\nstatic double const rrbot[23]={1e+000,1e+001,1e+002,1e+003,1e+004,1e+005,1e+006,1e+007,1e+008,1e+009,1e+010,1e+011,1e+012,1e+013,1e+014,1e+015,1e+016,1e+017,1e+018,1e+019,1e+020,1e+021,1e+022};\nstatic double const rrnegbot[22]={1e-001,1e-002,1e-003,1e-004,1e-005,1e-006,1e-007,1e-008,1e-009,1e-010,1e-011,1e-012,1e-013,1e-014,1e-015,1e-016,1e-017,1e-018,1e-019,1e-020,1e-021,1e-022};\nstatic double const rrnegboterr[22]={-5.551115123125783e-018,-2.0816681711721684e-019,-2.0816681711721686e-020,-4.7921736023859299e-021,-8.1803053914031305e-022,4.5251888174113741e-023,4.5251888174113739e-024,-2.0922560830128471e-025,-6.2281591457779853e-026,-3.6432197315497743e-027,6.0503030718060191e-028,2.0113352370744385e-029,-3.0373745563400371e-030,1.1806906454401013e-032,-7.7705399876661076e-032,2.0902213275965398e-033,-7.1542424054621921e-034,-7.1542424054621926e-035,2.4754073164739869e-036,5.4846728545790429e-037,9.2462547772103625e-038,-4.8596774326570872e-039};\nstatic double const rrtop[13]={1e+023,1e+046,1e+069,1e+092,1e+115,1e+138,1e+161,1e+184,1e+207,1e+230,1e+253,1e+276,1e+299};\nstatic double const rrnegtop[13]={1e-023,1e-046,1e-069,1e-092,1e-115,1e-138,1e-161,1e-184,1e-207,1e-230,1e-253,1e-276,1e-299};\nstatic double const rrtoperr[13]={8388608,6.8601809640529717e+028,-7.253143638152921e+052,-4.3377296974619174e+075,-1.5559416129466825e+098,-3.2841562489204913e+121,-3.7745893248228135e+144,-1.7356668416969134e+167,-3.8893577551088374e+190,-9.9566444326005119e+213,6.3641293062232429e+236,-5.2069140800249813e+259,-5.2504760255204387e+282};\nstatic double const rrnegtoperr[13]={3.9565301985100693e-040,-2.299904345391321e-063,3.6506201437945798e-086,1.1875228833981544e-109,-5.0644902316928607e-132,-6.7156837247865426e-155,-2.812077463003139e-178,-5.7778912386589953e-201,7.4997100559334532e-224,-4.6439668915134491e-247,-6.3691100762962136e-270,-9.436808465446358e-293,8.0970921678014997e-317};\n\n#if defined(_MSC_VER) && (_MSC_VER<=1200)                                                                                                                                                                                       \nstatic rU64 const rrpot[20]={1,10,100,1000, 10000,100000,1000000,10000000, 100000000,1000000000,10000000000,100000000000,  1000000000000,10000000000000,100000000000000,1000000000000000,  10000000000000000,100000000000000000,1000000000000000000,10000000000000000000U };\n#define rrtento19th ((rU64)1000000000000000000)\n#else\nstatic rU64 const rrpot[20]={1,10,100,1000, 10000,100000,1000000,10000000, 100000000,1000000000,10000000000ULL,100000000000ULL,  1000000000000ULL,10000000000000ULL,100000000000000ULL,1000000000000000ULL,  10000000000000000ULL,100000000000000000ULL,1000000000000000000ULL,10000000000000000000ULL };\n#define rrtento19th (1000000000000000000ULL)\n#endif\n\n#define rrddmulthi(oh,ol,xh,yh) \\\n{ \\\n  double ahi=0,alo,bhi=0,blo; \\\n  rS64 bt; \\\n  oh = xh * yh; \\\n  RRCOPYFP(bt,xh); bt&=((~(rU64)0)<<27); RRCOPYFP(ahi,bt); alo = xh-ahi; \\\n  RRCOPYFP(bt,yh); bt&=((~(rU64)0)<<27); RRCOPYFP(bhi,bt); blo = yh-bhi; \\\n  ol = ((ahi*bhi-oh)+ahi*blo+alo*bhi)+alo*blo; \\\n}\n\n#define rrddtoS64(ob,xh,xl) \\\n{ \\\n  double ahi=0,alo,vh,t;\\\n  ob = (rS64)ph;\\\n  vh=(double)ob;\\\n  ahi = ( xh - vh );\\\n  t = ( ahi - xh );\\\n  alo = (xh-(ahi-t))-(vh+t);\\\n  ob += (rS64)(ahi+alo+xl);\\\n}\n\n\n#define rrddrenorm(oh,ol) { double s; s=oh+ol; ol=ol-(s-oh); oh=s; }\n\n#define rrddmultlo(oh,ol,xh,xl,yh,yl) \\\n  ol = ol + ( xh*yl + xl*yh ); \\\n\n#define rrddmultlos(oh,ol,xh,yl) \\\n  ol = ol + ( xh*yl ); \\\n\nstatic void rrraise_to_power10( double *ohi, double *olo, double d, rS32 power )  // power can be -323 to +350\n{\n  double ph, pl;\n  if ((power>=0) && (power<=22))\n  {\n    rrddmulthi(ph,pl,d,rrbot[power]);\n  }\n  else\n  {\n    rS32 e,et,eb;\n    double p2h,p2l;\n\n    e=power; if (power<0) e=-e; \n    et = (e*0x2c9)>>14;/* %23 */ if (et>13) et=13; eb = e-(et*23);\n\n    ph = d; pl = 0.0;\n    if (power<0)\n    {\n      if (eb) { --eb; rrddmulthi(ph,pl,d,rrnegbot[eb]); rrddmultlos(ph,pl,d,rrnegboterr[eb]); }\n      if (et)\n      { \n        rrddrenorm(ph,pl);\n        --et; rrddmulthi(p2h,p2l,ph,rrnegtop[et]); rrddmultlo(p2h,p2l,ph,pl,rrnegtop[et],rrnegtoperr[et]); ph=p2h;pl=p2l;\n      }\n    }\n    else\n    {\n      if (eb) \n      { \n        e = eb; if (eb>22) eb=22; e -= eb;\n        rrddmulthi(ph,pl,d,rrbot[eb]); \n        if ( e ) { rrddrenorm(ph,pl); rrddmulthi(p2h,p2l,ph,rrbot[e]); rrddmultlos(p2h,p2l,rrbot[e],pl); ph=p2h;pl=p2l; }\n      }\n      if (et)\n      {\n        rrddrenorm(ph,pl);\n        --et; rrddmulthi(p2h,p2l,ph,rrtop[et]); rrddmultlo(p2h,p2l,ph,pl,rrtop[et],rrtoperr[et]); ph=p2h;pl=p2l;\n      }\n    }\n  }\n  rrddrenorm(ph,pl);\n  *ohi = ph; *olo = pl;\n}\n\n// given a float value, returns the significant bits in bits, and the position of the\n//   decimal point in decimal_pos.  +/-INF and NAN are specified by special values\n//   returned in the decimal_pos parameter.\n// frac_digits is absolute normally, but if you want from first significant digits (got %g and %e), or in 0x80000000\nstatic rS32 rrreal_to_str( char const * * start, rU32 * len, char *out, rS32 * decimal_pos, double value, rU32 frac_digits )\n{\n  double d;\n  rS64 bits = 0;\n  rS32 expo, e, ng, tens;\n\n  d = value;\n  RRCOPYFP(bits,d);\n  expo = (bits >> 52) & 2047;\n  ng = (rS32)(bits >> 63);\n  if (ng) d=-d;\n\n  if ( expo == 2047 ) // is nan or inf?\n  {\n    *start = (bits&((((rU64)1)<<52)-1)) ? \"NaN\" : \"Inf\";\n    *decimal_pos =  RRSPECIAL;\n    *len = 3;\n    return ng;\n  } \n\n  if ( expo == 0 ) // is zero or denormal\n  {\n    if ((bits<<1)==0) // do zero\n    {\n      *decimal_pos = 1; \n      *start = out;\n      out[0] = '0'; *len = 1;\n      return ng;\n    }\n    // find the right expo for denormals\n    {\n      rS64 v = ((rU64)1)<<51;\n      while ((bits&v)==0) { --expo; v >>= 1; }\n    }\n  }\n\n  // find the decimal exponent as well as the decimal bits of the value\n  {\n    double ph,pl;\n\n    // log10 estimate - very specifically tweaked to hit or undershoot by no more than 1 of log10 of all expos 1..2046\n    tens=expo-1023; tens = (tens<0)?((tens*617)/2048):(((tens*1233)/4096)+1);\n\n    // move the significant bits into position and stick them into an int \n    rrraise_to_power10( &ph, &pl, d, 18-tens );\n\n    // get full as much precision from double-double as possible\n    rrddtoS64( bits, ph,pl );\n\n    // check if we undershot\n    if ( ((rU64)bits) >= rrtento19th ) ++tens; \n  }\n\n  // now do the rounding in integer land\n  frac_digits = ( frac_digits & 0x80000000 ) ? ( (frac_digits&0x7ffffff) + 1 ) : ( tens + frac_digits );\n  if ( ( frac_digits < 24 ) )\n  {\n    rU32 dg = 1; if ((rU64)bits >= rrpot[9] ) dg=10; while( (rU64)bits >= rrpot[dg] ) { ++dg; if (dg==20) goto noround; }\n    if ( frac_digits < dg )\n    {\n      rU64 r;\n      // add 0.5 at the right position and round\n      e = dg - frac_digits;\n      if ( (rU32)e >= 24 ) goto noround;\n      r = rrpot[e];\n      bits = bits + (r/2);\n      if ( (rU64)bits >= rrpot[dg] ) ++tens;\n      bits /= r;\n    } \n    noround:;\n  }\n\n  // kill long trailing runs of zeros\n  if ( bits )\n  {\n    rU32 n; for(;;) { if ( bits<=0xffffffff ) break; if (bits%1000) goto donez; bits/=1000; } n = (rU32)bits; while ((n%1000)==0) n/=1000; bits=n; donez:;\n  }\n\n  // convert to string\n  out += 64;\n  e = 0; \n  for(;;)\n  {\n    rU32 n;\n    char * o = out-8;\n    // do the conversion in chunks of U32s (avoid most 64-bit divides, worth it, constant denomiators be damned)\n    if (bits>=100000000) { n = (rU32)( bits % 100000000);  bits /= 100000000; } else {n = (rU32)bits; bits = 0; }\n    while(n) { out-=2; *(rU16*)out=*(rU16*)&rrdiglookup[(n%100)*2]; n/=100; e+=2; }\n    if (bits==0) { if ((e) && (out[0]=='0')) { ++out; --e; } break; }\n    while( out!=o ) { *--out ='0'; ++e; }\n  }\n  \n  *decimal_pos = tens;\n  *start = out;\n  *len = e;\n  return ng;\n}\n\n#undef rrddmulthi\n#undef rrddrenorm\n#undef rrddmultlo\n#undef rrddmultlos\n#undef RRSPECIAL \n#undef RRCOPYFP\n \n#endif\n\n// clean up\n#undef rU16\n#undef rU32 \n#undef rS32 \n#undef rU64\n#undef rS64\n#undef RRPUBLIC_DEC\n#undef RRPUBLIC_DEF\n#undef RR_SPRINTF_DECORATE\n#undef RR_UNALIGNED\n\n#endif\n\n#endif\n"
  },
  {
    "path": "deprecated/stb.h",
    "content": "/* stb.h - v2.37 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h\n          no warranty is offered or implied; use this code at your own risk\n\n   This is a single header file with a bunch of useful utilities\n   for getting stuff done in C/C++.\n\n   Documentation: http://nothings.org/stb/stb_h.html\n   Unit tests:    http://nothings.org/stb/stb.c\n\n ============================================================================\n   You MUST\n\n      #define STB_DEFINE\n\n   in EXACTLY _one_ C or C++ file that includes this header, BEFORE the\n   include, like this:\n\n      #define STB_DEFINE\n      #include \"stb.h\"\n\n   All other files should just #include \"stb.h\" without the #define.\n ============================================================================\n\nVersion History\n\n   2.36   various fixes\n   2.35   fix clang-cl issues with swprintf\n   2.34   fix warnings\n   2.33   more fixes to random numbers\n   2.32   stb_intcmprev, stb_uidict, fix random numbers on Linux\n   2.31   stb_ucharcmp\n   2.30   MinGW fix\n   2.29   attempt to fix use of swprintf()\n   2.28   various new functionality\n   2.27   test _WIN32 not WIN32 in STB_THREADS\n   2.26   various warning & bugfixes\n   2.25   various warning & bugfixes\n   2.24   various warning & bugfixes\n   2.23   fix 2.22\n   2.22   64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name\n   2.21   utf-8 decoder rejects \"overlong\" encodings; attempted 64-bit improvements\n   2.20   fix to hash \"copy\" function--reported by someone with handle \"!=\"\n   2.19   ???\n   2.18   stb_readdir_subdirs_mask\n   2.17   stb_cfg_dir\n   2.16   fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper\n   2.15   upgraded hash table template to allow:\n            - aggregate keys (explicit comparison func for EMPTY and DEL keys)\n            - \"static\" implementations (so they can be culled if unused)\n   2.14   stb_mprintf\n   2.13   reduce identifiable strings in STB_NO_STB_STRINGS\n   2.12   fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in\n   2.11   fix bug in stb_dirtree_get() which caused \"c://path\" sorts of stuff\n   2.10   STB_F(), STB_I() inline constants (also KI,KU,KF,KD)\n   2.09   stb_box_face_vertex_axis_side\n   2.08   bugfix stb_trimwhite()\n   2.07   colored printing in windows (why are we in 1985?)\n   2.06   comparison functions are now functions-that-return-functions and\n          accept a struct-offset as a parameter (not thread-safe)\n   2.05   compile and pass tests under Linux (but no threads); thread cleanup\n   2.04   stb_cubic_bezier_1d, smoothstep, avoid dependency on registry\n   2.03   ?\n   2.02   remove integrated documentation\n   2.01   integrate various fixes; stb_force_uniprocessor\n   2.00   revised stb_dupe to use multiple hashes\n   1.99   stb_charcmp\n   1.98   stb_arr_deleten, stb_arr_insertn\n   1.97   fix stb_newell_normal()\n   1.96   stb_hash_number()\n   1.95   hack stb__rec_max; clean up recursion code to use new functions\n   1.94   stb_dirtree; rename stb_extra to stb_ptrmap\n   1.93   stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra')\n   1.92   stb_threadqueue--multi reader/writer queue, fixed size or resizeable\n   1.91   stb_bgio_* for reading disk asynchronously\n   1.90   stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread\n          joining; workqueue supports stb_sync instead of stb_semaphore\n   1.89   support ';' in constant-string wildcards; stb_mutex wrapper (can\n          implement with EnterCriticalRegion eventually)\n   1.88   portable threading API (only for win32 so far); worker thread queue\n   1.87   fix wildcard handling in stb_readdir_recursive\n   1.86   support ';' in wildcards\n   1.85   make stb_regex work with non-constant strings;\n               beginnings of stb_introspect()\n   1.84   (forgot to make notes)\n   1.83   whoops, stb_keep_if_different wasn't deleting the temp file\n   1.82   bring back stb_compress from stb_file.h for cmirror\n   1.81   various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release\n   1.80   stb_readdir returns utf8; write own utf8-utf16 because lib was wrong\n   1.79   stb_write\n   1.78   calloc() support for malloc wrapper, STB_FASTMALLOC\n   1.77   STB_FASTMALLOC\n   1.76   STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear)\n   1.75   alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs;\n          hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst\n   1.74   stb_replaceinplace; use stdlib C function to convert utf8 to UTF-16\n   1.73   fix performance bug & leak in stb_ischar (C++ port lost a 'static')\n   1.72   remove stb_block, stb_block_manager, stb_decompress (to stb_file.h)\n   1.71   stb_trimwhite, stb_tokens_nested, etc.\n   1.70   back out 1.69 because it might problemize mixed builds; stb_filec()\n   1.69   (stb_file returns 'char *' in C++)\n   1.68   add a special 'tree root' data type for stb_bst; stb_arr_end\n   1.67   full C++ port. (stb_block_manager)\n   1.66   stb_newell_normal\n   1.65   stb_lex_item_wild -- allow wildcard items which MUST match entirely\n   1.64   stb_data\n   1.63   stb_log_name\n   1.62   stb_define_sort; C++ cleanup\n   1.61   stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?)\n   1.60   stb_delete_directory_recursive\n   1.59   stb_readdir_recursive\n   1.58   stb_bst variant with parent pointer for O(1) iteration, not O(log N)\n   1.57   replace LCG random with Mersenne Twister (found a public domain one)\n   1.56   stb_perfect_hash, stb_ischar, stb_regex\n   1.55   new stb_bst API allows multiple BSTs per node (e.g. secondary keys)\n   1.54   bugfix: stb_define_hash, stb_wildmatch, regexp\n   1.53   stb_define_hash; recoded stb_extra, stb_sdict use it\n   1.52   stb_rand_define, stb_bst, stb_reverse\n   1.51   fix 'stb_arr_setlen(NULL, 0)'\n   1.50   stb_wordwrap\n   1.49   minor improvements to enable the scripting language\n   1.48   better approach for stb_arr using stb_malloc; more invasive, clearer\n   1.47   stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex)\n   1.46   stb_wrapper_*, STB_MALLOC_WRAPPER\n   1.45   lightly tested DFA acceleration of regexp searching\n   1.44   wildcard matching & searching; regexp matching & searching\n   1.43   stb_temp\n   1.42   allow stb_arr to use stb_malloc/realloc; note this is global\n   1.41   make it compile in C++; (disable stb_arr in C++)\n   1.40   stb_dupe tweak; stb_swap; stb_substr\n   1.39   stb_dupe; improve stb_file_max to be less stupid\n   1.38   stb_sha1_file: generate sha1 for file, even > 4GB\n   1.37   stb_file_max; partial support for utf8 filenames in Windows\n   1.36   remove STB__NO_PREFIX - poor interaction with IDE, not worth it\n          streamline stb_arr to make it separately publishable\n   1.35   bugfixes for stb_sdict, stb_malloc(0), stristr\n   1.34   (streaming interfaces for stb_compress)\n   1.33   stb_alloc; bug in stb_getopt; remove stb_overflow\n   1.32   (stb_compress returns, smaller&faster; encode window & 64-bit len)\n   1.31   stb_prefix_count\n   1.30   (STB__NO_PREFIX - remove stb_ prefixes for personal projects)\n   1.29   stb_fput_varlen64, etc.\n   1.28   stb_sha1\n   1.27   ?\n   1.26   stb_extra\n   1.25   ?\n   1.24   stb_copyfile\n   1.23   stb_readdir\n   1.22   ?\n   1.21   ?\n   1.20   ?\n   1.19   ?\n   1.18   ?\n   1.17   ?\n   1.16   ?\n   1.15   stb_fixpath, stb_splitpath, stb_strchr2\n   1.14   stb_arr\n   1.13   ?stb, stb_log, stb_fatal\n   1.12   ?stb_hash2\n   1.11   miniML\n   1.10   stb_crc32, stb_adler32\n   1.09   stb_sdict\n   1.08   stb_bitreverse, stb_ispow2, stb_big32\n          stb_fopen, stb_fput_varlen, stb_fput_ranged\n          stb_fcmp, stb_feq\n   1.07   (stb_encompress)\n   1.06   stb_compress\n   1.05   stb_tokens, (stb_hheap)\n   1.04   stb_rand\n   1.03   ?(s-strings)\n   1.02   ?stb_filelen, stb_tokens\n   1.01   stb_tolower\n   1.00   stb_hash, stb_intcmp\n          stb_file, stb_stringfile, stb_fgets\n          stb_prefix, stb_strlower, stb_strtok\n          stb_image\n          (stb_array), (stb_arena)\n\nParenthesized items have since been removed.\n\nLICENSE\n\n See end of file for license information.\n\nCREDITS\n\n Written by Sean Barrett.\n\n Fixes:\n  Philipp Wiesemann\n  Robert Nix\n  r-lyeh\n  blackpawn\n  github:Mojofreem\n  Ryan Whitworth\n  Vincent Isambart\n  Mike Sartain\n  Eugene Opalev\n  Tim Sjostrand\n  github:infatum\n  Dave Butler (Croepha)\n  Ethan Lee (flibitijibibo)\n  Brian Collins\n  Kyle Langley\n*/\n\n#include <stdarg.h>\n\n#ifndef STB__INCLUDE_STB_H\n#define STB__INCLUDE_STB_H\n\n#define STB_VERSION  1\n\n#ifdef STB_INTROSPECT\n   #define STB_DEFINE\n#endif\n\n#ifdef STB_DEFINE_THREADS\n   #ifndef STB_DEFINE\n   #define STB_DEFINE\n   #endif\n   #ifndef STB_THREADS\n   #define STB_THREADS\n   #endif\n#endif\n\n#if defined(_WIN32) && !defined(__MINGW32__)\n   #ifndef _CRT_SECURE_NO_WARNINGS\n   #define _CRT_SECURE_NO_WARNINGS\n   #endif\n   #ifndef _CRT_NONSTDC_NO_DEPRECATE\n   #define _CRT_NONSTDC_NO_DEPRECATE\n   #endif\n   #ifndef _CRT_NON_CONFORMING_SWPRINTFS\n   #define _CRT_NON_CONFORMING_SWPRINTFS\n   #endif\n   #if !defined(_MSC_VER) || _MSC_VER > 1700\n   #include <intrin.h> // _BitScanReverse\n   #endif\n#endif\n\n#include <stdlib.h>     // stdlib could have min/max\n#include <stdio.h>      // need FILE\n#include <string.h>     // stb_define_hash needs memcpy/memset\n#include <time.h>       // stb_dirtree\n#ifdef __MINGW32__\n   #include <fcntl.h>   // O_RDWR\n#endif\n\n#ifdef STB_PERSONAL\n   typedef int Bool;\n   #define False 0\n   #define True 1\n#endif\n\n#ifdef STB_MALLOC_WRAPPER_PAGED\n   #define STB_MALLOC_WRAPPER_DEBUG\n#endif\n#ifdef STB_MALLOC_WRAPPER_DEBUG\n   #define STB_MALLOC_WRAPPER\n#endif\n#ifdef STB_MALLOC_WRAPPER_FASTMALLOC\n   #define STB_FASTMALLOC\n   #define STB_MALLOC_WRAPPER\n#endif\n\n#ifdef STB_FASTMALLOC\n   #ifndef _WIN32\n      #undef STB_FASTMALLOC\n   #endif\n#endif\n\n#ifdef STB_DEFINE\n   #include <assert.h>\n   #include <stdarg.h>\n   #include <stddef.h>\n   #include <ctype.h>\n   #include <math.h>\n   #ifndef _WIN32\n   #include <unistd.h>\n   #else\n   #include <io.h>      // _mktemp\n   #include <direct.h>  // _rmdir\n   #endif\n   #include <sys/types.h> // stat()/_stat()\n   #include <sys/stat.h>  // stat()/_stat()\n#endif\n\n#define stb_min(a,b)   ((a) < (b) ? (a) : (b))\n#define stb_max(a,b)   ((a) > (b) ? (a) : (b))\n\n#ifndef STB_ONLY\n   #if !defined(__cplusplus) && !defined(min) && !defined(max)\n     #define min(x,y) stb_min(x,y)\n     #define max(x,y) stb_max(x,y)\n   #endif\n\n   #ifndef M_PI\n     #define M_PI  3.14159265358979323846f\n   #endif\n\n   #ifndef TRUE\n     #define TRUE  1\n     #define FALSE 0\n   #endif\n\n   #ifndef deg2rad\n   #define deg2rad(a)  ((a)*(M_PI/180))\n   #endif\n   #ifndef rad2deg\n   #define rad2deg(a)  ((a)*(180/M_PI))\n   #endif\n\n   #ifndef swap\n   #ifndef __cplusplus\n   #define swap(TYPE,a,b)  \\\n               do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0)\n   #endif\n   #endif\n\n   typedef unsigned char  uint8 ;\n   typedef   signed char   int8 ;\n   typedef unsigned short uint16;\n   typedef   signed short  int16;\n  #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)\n   typedef unsigned long  uint32;\n   typedef   signed long   int32;\n  #else\n   typedef unsigned int   uint32;\n   typedef   signed int    int32;\n  #endif\n\n   typedef unsigned char  uchar ;\n   typedef unsigned short ushort;\n   typedef unsigned int   uint  ;\n   typedef unsigned long  ulong ;\n\n   // produce compile errors if the sizes aren't right\n   typedef char stb__testsize16[sizeof(int16)==2];\n   typedef char stb__testsize32[sizeof(int32)==4];\n#endif\n\n#ifndef STB_TRUE\n  #define STB_TRUE 1\n  #define STB_FALSE 0\n#endif\n\n// if we're STB_ONLY, can't rely on uint32 or even uint, so all the\n// variables we'll use herein need typenames prefixed with 'stb':\ntypedef unsigned char stb_uchar;\ntypedef unsigned char stb_uint8;\ntypedef unsigned int  stb_uint;\ntypedef unsigned short stb_uint16;\ntypedef          short stb_int16;\ntypedef   signed char  stb_int8;\n#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)\n  typedef unsigned long  stb_uint32;\n  typedef          long  stb_int32;\n#else\n  typedef unsigned int   stb_uint32;\n  typedef          int   stb_int32;\n#endif\ntypedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];\ntypedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];\n\n#ifdef _MSC_VER\n  typedef unsigned __int64 stb_uint64;\n  typedef          __int64 stb_int64;\n  #define STB_IMM_UINT64(literalui64) (literalui64##ui64)\n  #define STB_IMM_INT64(literali64) (literali64##i64)\n#else\n  // ??\n  typedef unsigned long long stb_uint64;\n  typedef          long long stb_int64;\n  #define STB_IMM_UINT64(literalui64) (literalui64##ULL)\n  #define STB_IMM_INT64(literali64) (literali64##LL)\n#endif\ntypedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];\n\n// add platform-specific ways of checking for sizeof(char*) == 8,\n// and make those define STB_PTR64\n#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)\n  #define STB_PTR64\n#endif\n\n#ifdef STB_PTR64\ntypedef char stb__testsize2_ptr[sizeof(char *) == 8];\ntypedef stb_uint64 stb_uinta;\ntypedef stb_int64  stb_inta;\n#else\ntypedef char stb__testsize2_ptr[sizeof(char *) == 4];\ntypedef stb_uint32 stb_uinta;\ntypedef stb_int32  stb_inta;\n#endif\ntypedef char stb__testsize2_uinta[sizeof(stb_uinta)==sizeof(char*) ? 1 : -1];\n\n// if so, we should define an int type that is the pointer size. until then,\n// we'll have to make do with this (which is not the same at all!)\n\ntypedef union\n{\n   unsigned int i;\n   void * p;\n} stb_uintptr;\n\n\n#ifdef __cplusplus\n   #define STB_EXTERN   extern \"C\"\n#else\n   #define STB_EXTERN   extern\n#endif\n\n// check for well-known debug defines\n#if defined(DEBUG) || defined(_DEBUG) || defined(DBG)\n   #ifndef NDEBUG\n      #define STB_DEBUG\n   #endif\n#endif\n\n#ifdef STB_DEBUG\n   #include <assert.h>\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         C library function platform handling\n//\n\n#ifdef STB_DEFINE\n\n#if defined(_WIN32) &&  defined(__STDC_WANT_SECURE_LIB__)\nstatic FILE * stb_p_fopen(const char *filename, const char *mode)\n{\n   FILE *f;\n   if (0 == fopen_s(&f, filename, mode))\n      return f;\n   else\n      return NULL;\n}\nstatic FILE * stb_p_wfopen(const wchar_t *filename, const wchar_t *mode)\n{\n   FILE *f;\n   if (0 == _wfopen_s(&f, filename, mode))\n      return f;\n   else\n      return NULL;\n}\nstatic char *stb_p_strcpy_s(char *a, size_t size, const char *b)\n{\n   strcpy_s(a,size,b);\n   return a;\n}\nstatic char *stb_p_strncpy_s(char *a, size_t size, const char *b, size_t count)\n{\n   strncpy_s(a,size,b,count);\n   return a;\n}\n#define stb_p_mktemp(s)  (_mktemp_s(s, strlen(s)+1) == 0)\n#define stb_p_sprintf    sprintf_s\n#define stb_p_size(x)    ,(x)\n#else\n#define stb_p_fopen      fopen\n#define stb_p_wfopen     _wfopen\n#define stb_p_strcpy_s(a,s,b)     strcpy(a,b)\n#define stb_p_strncpy_s(a,s,b,c)  strncpy(a,b,c)\n#define stb_p_mktemp(s)  (mktemp(s) != NULL)\n\n#define stb_p_sprintf    sprintf\n#define stb_p_size(x)\n#endif\n\n#if defined(_WIN32)\n#define stb_p_vsnprintf  _vsnprintf\n#else\n#define stb_p_vsnprintf  vsnprintf\n#endif\n#endif // STB_DEFINE\n\n#if defined(_WIN32) && (_MSC_VER >= 1300)\n#define stb_p_stricmp    _stricmp\n#define stb_p_strnicmp   _strnicmp\n#define stb_p_strdup     _strdup\n#else\n#define stb_p_strdup     strdup\n#define stb_p_stricmp    stricmp\n#define stb_p_strnicmp   strnicmp\n#endif\n\nSTB_EXTERN void stb_wrapper_malloc(void *newp, size_t sz, char *file, int line);\nSTB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line);\nSTB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, size_t sz, char *file, int line);\nSTB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line);\nSTB_EXTERN void stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line));\nSTB_EXTERN void stb_wrapper_dump(char *filename);\nSTB_EXTERN size_t stb_wrapper_allocsize(void *oldp);\nSTB_EXTERN void stb_wrapper_check(void *oldp);\n\n#ifdef STB_DEFINE\n// this is a special function used inside malloc wrapper\n// to do allocations that aren't tracked (to avoid\n// reentrancy). Of course if someone _else_ wraps realloc,\n// this breaks, but if they're doing that AND the malloc\n// wrapper they need to explicitly check for reentrancy.\n//\n// only define realloc_raw() and we do realloc(NULL,sz)\n// for malloc() and realloc(p,0) for free().\nstatic void * stb__realloc_raw(void *p, int sz)\n{\n   if (p == NULL) return malloc(sz);\n   if (sz == 0)   { free(p); return NULL; }\n   return realloc(p,sz);\n}\n#endif\n\n#ifdef _WIN32\nSTB_EXTERN void * stb_smalloc(size_t sz);\nSTB_EXTERN void   stb_sfree(void *p);\nSTB_EXTERN void * stb_srealloc(void *p, size_t sz);\nSTB_EXTERN void * stb_scalloc(size_t n, size_t sz);\nSTB_EXTERN char * stb_sstrdup(char *s);\n#endif\n\n#ifdef STB_FASTMALLOC\n#define malloc  stb_smalloc\n#define free    stb_sfree\n#define realloc stb_srealloc\n#define strdup  stb_sstrdup\n#define calloc  stb_scalloc\n#endif\n\n#ifndef STB_MALLOC_ALLCHECK\n   #define stb__check(p)  1\n#else\n   #ifndef STB_MALLOC_WRAPPER\n      #error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER\n   #else\n      #define stb__check(p) stb_mcheck(p)\n   #endif\n#endif\n\n#ifdef STB_MALLOC_WRAPPER\n   STB_EXTERN void * stb__malloc(size_t, char *, int);\n   STB_EXTERN void * stb__realloc(void *, size_t, char *, int);\n   STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int);\n   STB_EXTERN void   stb__free(void *, char *file, int);\n   STB_EXTERN char * stb__strdup(char *s, char *file, int);\n   STB_EXTERN void   stb_malloc_checkall(void);\n   STB_EXTERN void   stb_malloc_check_counter(int init_delay, int rep_delay);\n   #ifndef STB_MALLOC_WRAPPER_DEBUG\n      #define stb_mcheck(p) 1\n   #else\n      STB_EXTERN int   stb_mcheck(void *);\n   #endif\n\n\n   #ifdef STB_DEFINE\n\n   #ifdef STB_MALLOC_WRAPPER_DEBUG\n      #define STB__PAD   32\n      #define STB__BIAS  16\n      #define STB__SIG   0x51b01234\n      #define STB__FIXSIZE(sz)  (((sz+3) & ~3) + STB__PAD)\n      #define STB__ptr(x,y)   ((char *) (x) + (y))\n   #else\n      #define STB__ptr(x,y)   (x)\n      #define STB__FIXSIZE(sz)  (sz)\n   #endif\n\n   #ifdef STB_MALLOC_WRAPPER_DEBUG\n   int stb_mcheck(void *p)\n   {\n      unsigned int sz;\n      if (p == NULL) return 1;\n      p = ((char *) p) - STB__BIAS;\n      sz = * (unsigned int *) p;\n      assert(* (unsigned int *) STB__ptr(p,4) == STB__SIG);\n      assert(* (unsigned int *) STB__ptr(p,8) == STB__SIG);\n      assert(* (unsigned int *) STB__ptr(p,12) == STB__SIG);\n      assert(* (unsigned int *) STB__ptr(p,sz-4) == STB__SIG+1);\n      assert(* (unsigned int *) STB__ptr(p,sz-8) == STB__SIG+1);\n      assert(* (unsigned int *) STB__ptr(p,sz-12) == STB__SIG+1);\n      assert(* (unsigned int *) STB__ptr(p,sz-16) == STB__SIG+1);\n      stb_wrapper_check(STB__ptr(p, STB__BIAS));\n      return 1;\n   }\n\n   static void stb__check2(void *p, size_t sz, char *file, int line)\n   {\n      stb_mcheck(p);\n   }\n\n   void stb_malloc_checkall(void)\n   {\n      stb_wrapper_listall(stb__check2);\n   }\n   #else\n   void stb_malloc_checkall(void) { }\n   #endif\n\n   static int stb__malloc_wait=(1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter;\n   void stb_malloc_check_counter(int init_delay, int rep_delay)\n   {\n      stb__malloc_wait = init_delay;\n      stb__malloc_next_wait = rep_delay;\n   }\n\n   void stb_mcheck_all(void)\n   {\n      #ifdef STB_MALLOC_WRAPPER_DEBUG\n      ++stb__malloc_iter;\n      if (--stb__malloc_wait <= 0) {\n         stb_malloc_checkall();\n         stb__malloc_wait = stb__malloc_next_wait;\n      }\n      #endif\n   }\n\n   #ifdef STB_MALLOC_WRAPPER_PAGED\n   #define STB__WINDOWS_PAGE (1 << 12)\n   #ifndef _WINDOWS_\n   STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);\n   STB_EXTERN __declspec(dllimport) int   __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);\n   #endif\n   #endif\n\n   static void *stb__malloc_final(size_t sz)\n   {\n      #ifdef STB_MALLOC_WRAPPER_PAGED\n      size_t aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE-1);\n      char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE\n      if (p == NULL) return p;\n      VirtualAlloc(p, aligned,   0x1000, 0x04); // COMMIT, READWRITE\n      return p;\n      #else\n      return malloc(sz);\n      #endif\n   }\n\n   static void stb__free_final(void *p)\n   {\n      #ifdef STB_MALLOC_WRAPPER_PAGED\n      VirtualFree(p, 0, 0x8000); // RELEASE\n      #else\n      free(p);\n      #endif\n   }\n\n   int stb__malloc_failure;\n   #ifdef STB_MALLOC_WRAPPER_PAGED\n   static void *stb__realloc_final(void *p, size_t sz, size_t old_sz)\n   {\n      void *q = stb__malloc_final(sz);\n      if (q == NULL)\n          return ++stb__malloc_failure, q;\n      // @TODO: deal with p being smaller!\n      memcpy(q, p, sz < old_sz ? sz : old_sz);\n      stb__free_final(p);\n      return q;\n   }\n   #endif\n\n   void stb__free(void *p, char *file, int line)\n   {\n      stb_mcheck_all();\n      if (!p) return;\n      #ifdef STB_MALLOC_WRAPPER_DEBUG\n      stb_mcheck(p);\n      #endif\n      stb_wrapper_free(p,file,line);\n      #ifdef STB_MALLOC_WRAPPER_DEBUG\n         p = STB__ptr(p,-STB__BIAS);\n         * (unsigned int *) STB__ptr(p,0) = 0xdeadbeef;\n         * (unsigned int *) STB__ptr(p,4) = 0xdeadbeef;\n         * (unsigned int *) STB__ptr(p,8) = 0xdeadbeef;\n         * (unsigned int *) STB__ptr(p,12) = 0xdeadbeef;\n      #endif\n      stb__free_final(p);\n   }\n\n   void * stb__malloc(size_t sz, char *file, int line)\n   {\n      void *p;\n      stb_mcheck_all();\n      if (sz == 0) return NULL;\n      p = stb__malloc_final(STB__FIXSIZE(sz));\n      if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));\n      if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));\n      if (p == NULL) {\n         ++stb__malloc_failure;\n         #ifdef STB_MALLOC_WRAPPER_DEBUG\n         stb_malloc_checkall();\n         #endif\n         return p;\n      }\n      #ifdef STB_MALLOC_WRAPPER_DEBUG\n      * (int *) STB__ptr(p,0) = STB__FIXSIZE(sz);\n      * (unsigned int *) STB__ptr(p,4) = STB__SIG;\n      * (unsigned int *) STB__ptr(p,8) = STB__SIG;\n      * (unsigned int *) STB__ptr(p,12) = STB__SIG;\n      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-4) = STB__SIG+1;\n      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-8) = STB__SIG+1;\n      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-12) = STB__SIG+1;\n      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-16) = STB__SIG+1;\n      p = STB__ptr(p, STB__BIAS);\n      #endif\n      stb_wrapper_malloc(p,sz,file,line);\n      return p;\n   }\n\n   void * stb__realloc(void *p, size_t sz, char *file, int line)\n   {\n      void *q;\n\n      stb_mcheck_all();\n      if (p == NULL) return stb__malloc(sz,file,line);\n      if (sz == 0  ) { stb__free(p,file,line); return NULL; }\n\n      #ifdef STB_MALLOC_WRAPPER_DEBUG\n         stb_mcheck(p);\n         p = STB__ptr(p,-STB__BIAS);\n      #endif\n      #ifdef STB_MALLOC_WRAPPER_PAGED\n      {\n         size_t n = stb_wrapper_allocsize(STB__ptr(p,STB__BIAS));\n         if (!n)\n            stb_wrapper_check(STB__ptr(p,STB__BIAS));\n         q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n));\n      }\n      #else\n      q = realloc(p, STB__FIXSIZE(sz));\n      #endif\n      if (q == NULL)\n         return ++stb__malloc_failure, q;\n      #ifdef STB_MALLOC_WRAPPER_DEBUG\n      * (int *) STB__ptr(q,0) = STB__FIXSIZE(sz);\n      * (unsigned int *) STB__ptr(q,4) = STB__SIG;\n      * (unsigned int *) STB__ptr(q,8) = STB__SIG;\n      * (unsigned int *) STB__ptr(q,12) = STB__SIG;\n      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-4) = STB__SIG+1;\n      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-8) = STB__SIG+1;\n      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-12) = STB__SIG+1;\n      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-16) = STB__SIG+1;\n\n      q = STB__ptr(q, STB__BIAS);\n      p = STB__ptr(p, STB__BIAS);\n      #endif\n      stb_wrapper_realloc(p,q,sz,file,line);\n      return q;\n   }\n\n   STB_EXTERN int stb_log2_ceil(size_t);\n   static void *stb__calloc(size_t n, size_t sz, char *file, int line)\n   {\n      void *q;\n      stb_mcheck_all();\n      if (n == 0 || sz == 0) return NULL;\n      if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL;\n      q = stb__malloc(n*sz, file, line);\n      if (q) memset(q, 0, n*sz);\n      return q;\n   }\n\n   char * stb__strdup(char *s, char *file, int line)\n   {\n      char *p;\n      stb_mcheck_all();\n      p = stb__malloc(strlen(s)+1, file, line);\n      if (!p) return p;\n      stb_p_strcpy_s(p, strlen(s)+1, s);\n      return p;\n   }\n   #endif // STB_DEFINE\n\n   #ifdef STB_FASTMALLOC\n   #undef malloc\n   #undef realloc\n   #undef free\n   #undef strdup\n   #undef calloc\n   #endif\n\n   // include everything that might define these, BEFORE making macros\n   #include <stdlib.h>\n   #include <string.h>\n   #include <malloc.h>\n\n   #define malloc(s)      stb__malloc (  s, __FILE__, __LINE__)\n   #define realloc(p,s)   stb__realloc(p,s, __FILE__, __LINE__)\n   #define calloc(n,s)    stb__calloc (n,s, __FILE__, __LINE__)\n   #define free(p)        stb__free   (p,   __FILE__, __LINE__)\n   #define strdup(p)      stb__strdup (p,   __FILE__, __LINE__)\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Windows pretty display\n//\n\nSTB_EXTERN void stbprint(const char *fmt, ...);\nSTB_EXTERN char *stb_sprintf(const char *fmt, ...);\nSTB_EXTERN char *stb_mprintf(const char *fmt, ...);\nSTB_EXTERN int  stb_snprintf(char *s, size_t n, const char *fmt, ...);\nSTB_EXTERN int  stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);\n\n#ifdef STB_DEFINE\nint stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)\n{\n   int res;\n   #ifdef _WIN32\n      #ifdef __STDC_WANT_SECURE_LIB__\n      res = _vsnprintf_s(s, n, _TRUNCATE, fmt, v);\n      #else\n      res = stb_p_vsnprintf(s,n,fmt,v);\n      #endif\n   #else\n   res = vsnprintf(s,n,fmt,v);\n   #endif\n   if (n) s[n-1] = 0;\n   // Unix returns length output would require, Windows returns negative when truncated.\n   return (res >= (int) n || res < 0) ? -1 : res;\n}\n\nint stb_snprintf(char *s, size_t n, const char *fmt, ...)\n{\n   int res;\n   va_list v;\n   va_start(v,fmt);\n   res = stb_vsnprintf(s, n, fmt, v);\n   va_end(v);\n   return res;\n}\n\nchar *stb_sprintf(const char *fmt, ...)\n{\n   static char buffer[1024];\n   va_list v;\n   va_start(v,fmt);\n   stb_vsnprintf(buffer,1024,fmt,v);\n   va_end(v);\n   return buffer;\n}\n\nchar *stb_mprintf(const char *fmt, ...)\n{\n   static char buffer[1024];\n   va_list v;\n   va_start(v,fmt);\n   stb_vsnprintf(buffer,1024,fmt,v);\n   va_end(v);\n   return stb_p_strdup(buffer);\n}\n\n#ifdef _WIN32\n\n#ifndef _WINDOWS_\nSTB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *);\nSTB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int);\nSTB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short);\n#endif\n\nstatic void stb__print_one(void *handle, char *s, ptrdiff_t  len)\n{\n   if (len)\n      if (0==WriteConsoleA(handle, s, (unsigned) len, NULL,NULL))\n         // if it fails, maybe redirected, so output normally...\n         // but it's supriously reporting failure now on Win7 and later\n         {}//fwrite(s, 1, (unsigned) len, stdout);\n}\n\nstatic void stb__print(char *s)\n{\n   void *handle = GetStdHandle((unsigned int) -11); // STD_OUTPUT_HANDLE\n   int pad=0; // number of padding characters to add\n\n   char *t = s;\n   while (*s) {\n      int lpad;\n      while (*s && *s != '{') {\n         if (pad) {\n            if (*s == '\\r' || *s == '\\n')\n               pad = 0;\n            else if (s[0] == ' ' && s[1] == ' ') {\n               stb__print_one(handle, t, s-t);\n               t = s;\n               while (pad) {\n                  stb__print_one(handle, t, 1);\n                  --pad;\n               }\n            }\n         }\n         ++s;\n      }\n      if (!*s) break;\n      stb__print_one(handle, t, s-t);\n      if (s[1] == '{') {\n         ++s;\n         continue;\n      }\n\n      if (s[1] == '#') {\n         t = s+3;\n         if (isxdigit(s[2]))\n            if (isdigit(s[2]))\n               SetConsoleTextAttribute(handle, s[2] - '0');\n            else\n               SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10);\n         else {\n            SetConsoleTextAttribute(handle, 0x0f);\n            t=s+2;\n         }\n      } else if (s[1] == '!') {\n         SetConsoleTextAttribute(handle, 0x0c);\n         t = s+2;\n      } else if (s[1] == '@') {\n         SetConsoleTextAttribute(handle, 0x09);\n         t = s+2;\n      } else if (s[1] == '$') {\n         SetConsoleTextAttribute(handle, 0x0a);\n         t = s+2;\n      } else {\n         SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey\n         t = s+1;\n      }\n\n      lpad = (int) (t-s);\n      s = t;\n      while (*s && *s != '}') ++s;\n      if (!*s) break;\n      stb__print_one(handle, t, s-t);\n      if (s[1] == '}') {\n         t = s+2;\n      } else {\n         pad += 1+lpad;\n         t = s+1;\n      }\n      s=t;\n      SetConsoleTextAttribute(handle, 0x07);\n   }\n   stb__print_one(handle, t, s-t);\n   SetConsoleTextAttribute(handle, 0x07);\n}\n\nvoid stbprint(const char *fmt, ...)\n{\n   int res;\n   char buffer[1024];\n   char *tbuf = buffer;\n   va_list v;\n\n   va_start(v,fmt);\n   res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v);\n   va_end(v);\n\n   if (res < 0) {\n      tbuf = (char *) malloc(16384);\n      va_start(v,fmt);\n      res = stb_vsnprintf(tbuf,16384, fmt, v);\n      va_end(v);\n      tbuf[16383] = 0;\n   }\n\n   stb__print(tbuf);\n\n   if (tbuf != buffer)\n      free(tbuf);\n}\n\n#else  // _WIN32\nvoid stbprint(const char *fmt, ...)\n{\n   va_list v;\n   va_start(v,fmt);\n   vprintf(fmt,v);\n   va_end(v);\n}\n#endif // _WIN32\n#endif // STB_DEFINE\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Windows UTF8 filename handling\n//\n// Windows stupidly treats 8-bit filenames as some dopey code page,\n// rather than utf-8. If we want to use utf8 filenames, we have to\n// convert them to WCHAR explicitly and call WCHAR versions of the\n// file functions. So, ok, we do.\n\n\n#ifdef _WIN32\n   #define stb__fopen(x,y)    stb_p_wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))\n   #define stb__windows(x,y)  x\n#else\n   #define stb__fopen(x,y)    stb_p_fopen(x,y)\n   #define stb__windows(x,y)  y\n#endif\n\n\ntypedef unsigned short stb__wchar;\n\nSTB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *str, int n);\nSTB_EXTERN char       * stb_to_utf8  (char *buffer, const stb__wchar *str, int n);\n\nSTB_EXTERN stb__wchar *stb__from_utf8(const char *str);\nSTB_EXTERN stb__wchar *stb__from_utf8_alt(const char *str);\nSTB_EXTERN char *stb__to_utf8(const stb__wchar *str);\n\n\n#ifdef STB_DEFINE\nstb__wchar * stb_from_utf8(stb__wchar *buffer, const char *ostr, int n)\n{\n   unsigned char *str = (unsigned char *) ostr;\n   stb_uint32 c;\n   int i=0;\n   --n;\n   while (*str) {\n      if (i >= n)\n         return NULL;\n      if (!(*str & 0x80))\n         buffer[i++] = *str++;\n      else if ((*str & 0xe0) == 0xc0) {\n         if (*str < 0xc2) return NULL;\n         c = (*str++ & 0x1f) << 6;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         buffer[i++] = c + (*str++ & 0x3f);\n      } else if ((*str & 0xf0) == 0xe0) {\n         if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;\n         if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below\n         c = (*str++ & 0x0f) << 12;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f) << 6;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         buffer[i++] = c + (*str++ & 0x3f);\n      } else if ((*str & 0xf8) == 0xf0) {\n         if (*str > 0xf4) return NULL;\n         if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;\n         if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below\n         c = (*str++ & 0x07) << 18;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f) << 12;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f) << 6;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f);\n         // utf-8 encodings of values used in surrogate pairs are invalid\n         if ((c & 0xFFFFF800) == 0xD800) return NULL;\n         if (c >= 0x10000) {\n            c -= 0x10000;\n            if (i + 2 > n) return NULL;\n            buffer[i++] = 0xD800 | (0x3ff & (c >> 10));\n            buffer[i++] = 0xDC00 | (0x3ff & (c      ));\n         }\n      } else\n         return NULL;\n   }\n   buffer[i] = 0;\n   return buffer;\n}\n\nchar * stb_to_utf8(char *buffer, const stb__wchar *str, int n)\n{\n   int i=0;\n   --n;\n   while (*str) {\n      if (*str < 0x80) {\n         if (i+1 > n) return NULL;\n         buffer[i++] = (char) *str++;\n      } else if (*str < 0x800) {\n         if (i+2 > n) return NULL;\n         buffer[i++] = 0xc0 + (*str >> 6);\n         buffer[i++] = 0x80 + (*str & 0x3f);\n         str += 1;\n      } else if (*str >= 0xd800 && *str < 0xdc00) {\n         stb_uint32 c;\n         if (i+4 > n) return NULL;\n         c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;\n         buffer[i++] = 0xf0 + (c >> 18);\n         buffer[i++] = 0x80 + ((c >> 12) & 0x3f);\n         buffer[i++] = 0x80 + ((c >>  6) & 0x3f);\n         buffer[i++] = 0x80 + ((c      ) & 0x3f);\n         str += 2;\n      } else if (*str >= 0xdc00 && *str < 0xe000) {\n         return NULL;\n      } else {\n         if (i+3 > n) return NULL;\n         buffer[i++] = 0xe0 + (*str >> 12);\n         buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);\n         buffer[i++] = 0x80 + ((*str     ) & 0x3f);\n         str += 1;\n      }\n   }\n   buffer[i] = 0;\n   return buffer;\n}\n\nstb__wchar *stb__from_utf8(const char *str)\n{\n   static stb__wchar buffer[4096];\n   return stb_from_utf8(buffer, str, 4096);\n}\n\nstb__wchar *stb__from_utf8_alt(const char *str)\n{\n   static stb__wchar buffer[4096];\n   return stb_from_utf8(buffer, str, 4096);\n}\n\nchar *stb__to_utf8(const stb__wchar *str)\n{\n   static char buffer[4096];\n   return stb_to_utf8(buffer, str, 4096);\n}\n\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Miscellany\n//\n\nSTB_EXTERN void stb_fatal(const char *fmt, ...);\nSTB_EXTERN void stb_(char *fmt, ...);\nSTB_EXTERN void stb_append_to_file(char *file, char *fmt, ...);\nSTB_EXTERN void stb_log(int active);\nSTB_EXTERN void stb_log_fileline(int active);\nSTB_EXTERN void stb_log_name(char *filename);\n\nSTB_EXTERN void stb_swap(void *p, void *q, size_t sz);\nSTB_EXTERN void *stb_copy(void *p, size_t sz);\nSTB_EXTERN void stb_pointer_array_free(void *p, int len);\nSTB_EXTERN void **stb_array_block_alloc(int count, int blocksize);\n\n#define stb_arrcount(x)   (sizeof(x)/sizeof((x)[0]))\n\n\nSTB_EXTERN int  stb__record_fileline(const char *f, int n);\n\n#ifdef STB_DEFINE\n\nstatic char *stb__file;\nstatic int   stb__line;\n\nint  stb__record_fileline(const char *f, int n)\n{\n   stb__file = (char*) f;\n   stb__line = n;\n   return 0;\n}\n\nvoid stb_fatal(const char *s, ...)\n{\n   va_list a;\n   if (stb__file)\n      fprintf(stderr, \"[%s:%d] \", stb__file, stb__line);\n   va_start(a,s);\n   fputs(\"Fatal error: \", stderr);\n   vfprintf(stderr, s, a);\n   va_end(a);\n   fputs(\"\\n\", stderr);\n   #ifdef STB_DEBUG\n   #ifdef _MSC_VER\n   #ifndef STB_PTR64\n   __asm int 3;   // trap to debugger!\n   #else\n   __debugbreak();\n   #endif\n   #else\n   __builtin_trap();\n   #endif\n   #endif\n   exit(1);\n}\n\nstatic int stb__log_active=1, stb__log_fileline=1;\n\nvoid stb_log(int active)\n{\n   stb__log_active = active;\n}\n\nvoid stb_log_fileline(int active)\n{\n   stb__log_fileline = active;\n}\n\n#ifdef STB_NO_STB_STRINGS\nconst char *stb__log_filename = \"temp.log\";\n#else\nconst char *stb__log_filename = \"stb.log\";\n#endif\n\nvoid stb_log_name(char *s)\n{\n   stb__log_filename = s;\n}\n\nvoid stb_(char *s, ...)\n{\n   if (stb__log_active) {\n      FILE *f = stb_p_fopen(stb__log_filename, \"a\");\n      if (f) {\n         va_list a;\n         if (stb__log_fileline && stb__file)\n            fprintf(f, \"[%s:%4d] \", stb__file, stb__line);\n         va_start(a,s);\n         vfprintf(f, s, a);\n         va_end(a);\n         fputs(\"\\n\", f);\n         fclose(f);\n      }\n   }\n}\n\nvoid stb_append_to_file(char *filename, char *s, ...)\n{\n   FILE *f = stb_p_fopen(filename, \"a\");\n   if (f) {\n      va_list a;\n      va_start(a,s);\n      vfprintf(f, s, a);\n      va_end(a);\n      fputs(\"\\n\", f);\n      fclose(f);\n   }\n}\n\n\ntypedef struct { char d[4]; } stb__4;\ntypedef struct { char d[8]; } stb__8;\n\n// optimize the small cases, though you shouldn't be calling this for those!\nvoid stb_swap(void *p, void *q, size_t sz)\n{\n   char buffer[256];\n   if (p == q) return;\n   if (sz == 4) {\n      stb__4 temp    = * ( stb__4 *) p;\n      * (stb__4 *) p = * ( stb__4 *) q;\n      * (stb__4 *) q = temp;\n      return;\n   } else if (sz == 8) {\n      stb__8 temp    = * ( stb__8 *) p;\n      * (stb__8 *) p = * ( stb__8 *) q;\n      * (stb__8 *) q = temp;\n      return;\n   }\n\n   while (sz > sizeof(buffer)) {\n      stb_swap(p, q, sizeof(buffer));\n      p = (char *) p + sizeof(buffer);\n      q = (char *) q + sizeof(buffer);\n      sz -= sizeof(buffer);\n   }\n\n   memcpy(buffer, p     , sz);\n   memcpy(p     , q     , sz);\n   memcpy(q     , buffer, sz);\n}\n\nvoid *stb_copy(void *p, size_t sz)\n{\n   void *q = malloc(sz);\n   memcpy(q, p, sz);\n   return q;\n}\n\nvoid stb_pointer_array_free(void *q, int len)\n{\n   void **p = (void **) q;\n   int i;\n   for (i=0; i < len; ++i)\n      free(p[i]);\n}\n\nvoid **stb_array_block_alloc(int count, int blocksize)\n{\n   int i;\n   char *p = (char *) malloc(sizeof(void *) * count + count * blocksize);\n   void **q;\n   if (p == NULL) return NULL;\n   q = (void **) p;\n   p += sizeof(void *) * count;\n   for (i=0; i < count; ++i)\n      q[i] = p + i * blocksize;\n   return q;\n}\n#endif\n\n#ifdef STB_DEBUG\n   // tricky hack to allow recording FILE,LINE even in varargs functions\n   #define STB__RECORD_FILE(x)  (stb__record_fileline(__FILE__, __LINE__),(x))\n   #define stb_log              STB__RECORD_FILE(stb_log)\n   #define stb_                 STB__RECORD_FILE(stb_)\n   #ifndef STB_FATAL_CLEAN\n   #define stb_fatal            STB__RECORD_FILE(stb_fatal)\n   #endif\n   #define STB__DEBUG(x)        x\n#else\n   #define STB__DEBUG(x)\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         stb_temp\n//\n\n#define stb_temp(block, sz)     stb__temp(block, sizeof(block), (sz))\n\nSTB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz);\nSTB_EXTERN void   stb_tempfree(void *block, void *ptr);\n\n#ifdef STB_DEFINE\n\nvoid * stb__temp(void *b, int b_sz, int want_sz)\n{\n   if (b_sz >= want_sz)\n      return b;\n   else\n      return malloc(want_sz);\n}\n\nvoid   stb_tempfree(void *b, void *p)\n{\n   if (p != b)\n      free(p);\n}\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                      math/sampling operations\n//\n\n\n#define stb_lerp(t,a,b)               ( (a) + (t) * (float) ((b)-(a)) )\n#define stb_unlerp(t,a,b)             ( ((t) - (a)) / (float) ((b) - (a)) )\n\n#define stb_clamp(x,xmin,xmax)  ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x))\n\nSTB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize);\nSTB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis);\nSTB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt);\n\nSTB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps);\nSTB_EXTERN int stb_is_prime(unsigned int m);\nSTB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n);\n\nSTB_EXTERN float stb_smoothstep(float t);\nSTB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3);\n\nSTB_EXTERN double stb_linear_remap(double x, double a, double b,\n                                             double c, double d);\n\n#ifdef STB_DEFINE\nfloat stb_smoothstep(float t)\n{\n   return (3 - 2*t)*(t*t);\n}\n\nfloat stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3)\n{\n   float it = 1-t;\n   return it*it*it*p0 + 3*it*it*t*p1 + 3*it*t*t*p2 + t*t*t*p3;\n}\n\nvoid stb_newell_normal(float *normal, int num_vert, float **vert, int normalize)\n{\n   int i,j;\n   float p;\n   normal[0] = normal[1] = normal[2] = 0;\n   for (i=num_vert-1,j=0; j < num_vert; i=j++) {\n      float *u = vert[i];\n      float *v = vert[j];\n      normal[0] += (u[1] - v[1]) * (u[2] + v[2]);\n      normal[1] += (u[2] - v[2]) * (u[0] + v[0]);\n      normal[2] += (u[0] - v[0]) * (u[1] + v[1]);\n   }\n   if (normalize) {\n      p = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2];\n      p = (float) (1.0 / sqrt(p));\n      normal[0] *= p;\n      normal[1] *= p;\n      normal[2] *= p;\n   }\n}\n\nint stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis)\n{\n   static int box_vertices[6][4][3] =\n   {\n      { { 1,1,1 }, { 1,0,1 }, { 1,0,0 }, { 1,1,0 } },\n      { { 0,0,0 }, { 0,0,1 }, { 0,1,1 }, { 0,1,0 } },\n      { { 0,0,0 }, { 0,1,0 }, { 1,1,0 }, { 1,0,0 } },\n      { { 0,0,0 }, { 1,0,0 }, { 1,0,1 }, { 0,0,1 } },\n      { { 1,1,1 }, { 0,1,1 }, { 0,0,1 }, { 1,0,1 } },\n      { { 1,1,1 }, { 1,1,0 }, { 0,1,0 }, { 0,1,1 } },\n   };\n   assert(face_number >= 0 && face_number < 6);\n   assert(vertex_number >= 0 && vertex_number < 4);\n   assert(axis >= 0 && axis < 3);\n   return box_vertices[face_number][vertex_number][axis];\n}\n\nvoid stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt)\n{\n   float sign = 1, p, cp = *curpos;\n   if (cp == target_pos) return;\n   if (target_pos < cp) {\n      target_pos = -target_pos;\n      cp = -cp;\n      sign = -1;\n   }\n   // first decelerate\n   if (cp < 0) {\n      p = cp + deacc * dt;\n      if (p > 0) {\n         p = 0;\n         dt = dt - cp / deacc;\n         if (dt < 0) dt = 0;\n      } else {\n         dt = 0;\n      }\n      cp = p;\n   }\n   // now accelerate\n   p = cp + acc*dt;\n   if (p > target_pos) p = target_pos;\n   *curpos = p * sign;\n   // @TODO: testing\n}\n\nfloat stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel)\n{\n   return 0; // @TODO\n}\n\nint stb_float_eq(float x, float y, float delta, int max_ulps)\n{\n   if (fabs(x-y) <= delta) return 1;\n   if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1;\n   return 0;\n}\n\nint stb_is_prime(unsigned int m)\n{\n   unsigned int i,j;\n   if (m < 2) return 0;\n   if (m == 2) return 1;\n   if (!(m & 1)) return 0;\n   if (m % 3 == 0) return (m == 3);\n   for (i=5; (j=i*i), j <= m && j > i; i += 6) {\n      if (m %   i   == 0) return 0;\n      if (m % (i+2) == 0) return 0;\n   }\n   return 1;\n}\n\nunsigned int stb_power_of_two_nearest_prime(int n)\n{\n   static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1,\n                                   0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 };\n   if (!tab[0]) {\n      int i;\n      for (i=0; i < 32; ++i)\n         tab[i] = (1 << i) + 2*tab[i] - 1;\n      tab[1] = 2;\n      tab[0] = 1;\n   }\n   if (n >= 32) return 0xfffffffb;\n   return tab[n];\n}\n\ndouble stb_linear_remap(double x, double x_min, double x_max,\n                                  double out_min, double out_max)\n{\n   return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);\n}\n#endif\n\n// create a macro so it's faster, but you can get at the function pointer\n#define stb_linear_remap(t,a,b,c,d)   stb_lerp(stb_unlerp(t,a,b),c,d)\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         bit operations\n//\n\n#define stb_big32(c)    (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])\n#define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0])\n#define stb_big16(c)    ((c)[0]*256 + (c)[1])\n#define stb_little16(c) ((c)[1]*256 + (c)[0])\n\nSTB_EXTERN          int stb_bitcount(unsigned int a);\nSTB_EXTERN unsigned int stb_bitreverse8(unsigned char n);\nSTB_EXTERN unsigned int stb_bitreverse(unsigned int n);\n\nSTB_EXTERN          int stb_is_pow2(size_t);\nSTB_EXTERN          int stb_log2_ceil(size_t);\nSTB_EXTERN          int stb_log2_floor(size_t);\n\nSTB_EXTERN          int stb_lowbit8(unsigned int n);\nSTB_EXTERN          int stb_highbit8(unsigned int n);\n\n#ifdef STB_DEFINE\nint stb_bitcount(unsigned int a)\n{\n   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2\n   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4\n   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits\n   a = (a + (a >> 8)); // max 16 per 8 bits\n   a = (a + (a >> 16)); // max 32 per 8 bits\n   return a & 0xff;\n}\n\nunsigned int stb_bitreverse8(unsigned char n)\n{\n   n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1);\n   n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2);\n   return (unsigned char) ((n >> 4) + (n << 4));\n}\n\nunsigned int stb_bitreverse(unsigned int n)\n{\n  n = ((n & 0xAAAAAAAA) >>  1) | ((n & 0x55555555) << 1);\n  n = ((n & 0xCCCCCCCC) >>  2) | ((n & 0x33333333) << 2);\n  n = ((n & 0xF0F0F0F0) >>  4) | ((n & 0x0F0F0F0F) << 4);\n  n = ((n & 0xFF00FF00) >>  8) | ((n & 0x00FF00FF) << 8);\n  return (n >> 16) | (n << 16);\n}\n\nint stb_is_pow2(size_t n)\n{\n   return (n & (n-1)) == 0;\n}\n\n// tricky use of 4-bit table to identify 5 bit positions (note the '-1')\n// 3-bit table would require another tree level; 5-bit table wouldn't save one\n#if defined(_WIN32) && !defined(__MINGW32__)\n#pragma warning(push)\n#pragma warning(disable: 4035)  // disable warning about no return value\nint stb_log2_floor(size_t n)\n{\n   #if _MSC_VER > 1700\n   unsigned long i;\n   #ifdef STB_PTR64\n   _BitScanReverse64(&i, n);\n   #else\n   _BitScanReverse(&i, n);\n   #endif\n   return i != 0 ? i : -1;\n   #else\n   __asm {\n      bsr eax,n\n      jnz done\n      mov eax,-1\n   }\n   done:;\n   #endif\n}\n#pragma warning(pop)\n#else\nint stb_log2_floor(size_t n)\n{\n   static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 };\n\n#ifdef STB_PTR64\n   if (n >= ((size_t) 1u << 32))\n        return stb_log2_floor(n >> 32);\n#endif\n\n   // 2 compares if n < 16, 3 compares otherwise\n   if (n < (1U << 14))\n        if (n < (1U <<  4))        return     0 + log2_4[n      ];\n        else if (n < (1U <<  9))      return  5 + log2_4[n >>  5];\n             else                     return 10 + log2_4[n >> 10];\n   else if (n < (1U << 24))\n             if (n < (1U << 19))      return 15 + log2_4[n >> 15];\n             else                     return 20 + log2_4[n >> 20];\n        else if (n < (1U << 29))      return 25 + log2_4[n >> 25];\n             else                     return 30 + log2_4[n >> 30];\n}\n#endif\n\n// define ceil from floor\nint stb_log2_ceil(size_t n)\n{\n   if (stb_is_pow2(n))  return     stb_log2_floor(n);\n   else                 return 1 + stb_log2_floor(n);\n}\n\nint stb_highbit8(unsigned int n)\n{\n   return stb_log2_ceil(n&255);\n}\n\nint stb_lowbit8(unsigned int n)\n{\n   static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 };\n   int k = lowbit4[n & 15];\n   if (k >= 0) return k;\n   k = lowbit4[(n >> 4) & 15];\n   if (k >= 0) return k+4;\n   return k;\n}\n#endif\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                            qsort Compare Routines\n//\n\n#ifdef _WIN32\n   #define stb_stricmp(a,b) stb_p_stricmp(a,b)\n   #define stb_strnicmp(a,b,n) stb_p_strnicmp(a,b,n)\n#else\n   #define stb_stricmp(a,b) strcasecmp(a,b)\n   #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)\n#endif\n\n\nSTB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_intcmprev(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);\n\n#ifdef STB_DEFINE\nstatic int stb__intcmpoffset, stb__ucharcmpoffset, stb__strcmpoffset;\nstatic int stb__floatcmpoffset, stb__doublecmpoffset;\nstatic int stb__memcmpoffset, stb__memcmpsize;\n\nint stb__intcmp(const void *a, const void *b)\n{\n   const int p = *(const int *) ((const char *) a + stb__intcmpoffset);\n   const int q = *(const int *) ((const char *) b + stb__intcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__intcmprev(const void *a, const void *b)\n{\n   const int p = *(const int *) ((const char *) a + stb__intcmpoffset);\n   const int q = *(const int *) ((const char *) b + stb__intcmpoffset);\n   return q < p ? -1 : q > p;\n}\n\nint stb__ucharcmp(const void *a, const void *b)\n{\n   const int p = *(const unsigned char *) ((const char *) a + stb__ucharcmpoffset);\n   const int q = *(const unsigned char *) ((const char *) b + stb__ucharcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__floatcmp(const void *a, const void *b)\n{\n   const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);\n   const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__doublecmp(const void *a, const void *b)\n{\n   const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);\n   const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__qsort_strcmp(const void *a, const void *b)\n{\n   const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);\n   const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);\n   return strcmp(p,q);\n}\n\nint stb__qsort_stricmp(const void *a, const void *b)\n{\n   const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);\n   const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);\n   return stb_stricmp(p,q);\n}\n\nint stb__memcmp(const void *a, const void *b)\n{\n   return memcmp((char *) a + stb__memcmpoffset, (char *) b + stb__memcmpoffset, stb__memcmpsize);\n}\n\nint (*stb_intcmp(int offset))(const void *, const void *)\n{\n   stb__intcmpoffset = offset;\n   return &stb__intcmp;\n}\n\nint (*stb_intcmprev(int offset))(const void *, const void *)\n{\n   stb__intcmpoffset = offset;\n   return &stb__intcmprev;\n}\n\nint (*stb_ucharcmp(int offset))(const void *, const void *)\n{\n   stb__ucharcmpoffset = offset;\n   return &stb__ucharcmp;\n}\n\nint (*stb_qsort_strcmp(int offset))(const void *, const void *)\n{\n   stb__strcmpoffset = offset;\n   return &stb__qsort_strcmp;\n}\n\nint (*stb_qsort_stricmp(int offset))(const void *, const void *)\n{\n   stb__strcmpoffset = offset;\n   return &stb__qsort_stricmp;\n}\n\nint (*stb_floatcmp(int offset))(const void *, const void *)\n{\n   stb__floatcmpoffset = offset;\n   return &stb__floatcmp;\n}\n\nint (*stb_doublecmp(int offset))(const void *, const void *)\n{\n   stb__doublecmpoffset = offset;\n   return &stb__doublecmp;\n}\n\nint (*stb_memcmp(int offset, int size))(const void *, const void *)\n{\n   stb__memcmpoffset = offset;\n   stb__memcmpsize = size;\n   return &stb__memcmp;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                           Binary Search Toolkit\n//\n\ntypedef struct\n{\n   int minval, maxval, guess;\n   int mode, step;\n} stb_search;\n\nSTB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest);\nSTB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest);\nSTB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done\n\n#ifdef STB_DEFINE\nenum\n{\n   STB_probe_binary_smallest,\n   STB_probe_binary_largest,\n   STB_probe_open_smallest,\n   STB_probe_open_largest,\n};\n\nstatic int stb_probe_guess(stb_search *s, int *result)\n{\n   switch(s->mode) {\n      case STB_probe_binary_largest:\n         if (s->minval == s->maxval) {\n            *result = s->minval;\n            return 0;\n         }\n         assert(s->minval < s->maxval);\n         // if a < b, then a < p <= b\n         s->guess = s->minval + (((unsigned) s->maxval - s->minval + 1) >> 1);\n         break;\n\n      case STB_probe_binary_smallest:\n         if (s->minval == s->maxval) {\n            *result = s->minval;\n            return 0;\n         }\n         assert(s->minval < s->maxval);\n         // if a < b, then a <= p < b\n         s->guess = s->minval + (((unsigned) s->maxval - s->minval) >> 1);\n         break;\n      case STB_probe_open_smallest:\n      case STB_probe_open_largest:\n         s->guess = s->maxval;  // guess the current maxval\n         break;\n   }\n   *result = s->guess;\n   return 1;\n}\n\nint stb_probe(stb_search *s, int compare, int *result)\n{\n   switch(s->mode) {\n      case STB_probe_open_smallest:\n      case STB_probe_open_largest: {\n         if (compare <= 0) {\n            // then it lies within minval & maxval\n            if (s->mode == STB_probe_open_smallest)\n               s->mode = STB_probe_binary_smallest;\n            else\n               s->mode = STB_probe_binary_largest;\n         } else {\n            // otherwise, we need to probe larger\n            s->minval  = s->maxval + 1;\n            s->maxval  = s->minval + s->step;\n            s->step   += s->step;\n         }\n         break;\n      }\n      case STB_probe_binary_smallest: {\n         // if compare < 0, then s->minval <= a <  p\n         // if compare = 0, then s->minval <= a <= p\n         // if compare > 0, then         p <  a <= s->maxval\n         if (compare <= 0)\n            s->maxval = s->guess;\n         else\n            s->minval = s->guess+1;\n         break;\n      }\n      case STB_probe_binary_largest: {\n         // if compare < 0, then s->minval <= a < p\n         // if compare = 0, then         p <= a <= s->maxval\n         // if compare > 0, then         p <  a <= s->maxval\n         if (compare < 0)\n            s->maxval = s->guess-1;\n         else\n            s->minval = s->guess;\n         break;\n      }\n   }\n   return stb_probe_guess(s, result);\n}\n\nint stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest)\n{\n   int r;\n   if (maxv < minv) return minv-1;\n   s->minval = minv;\n   s->maxval = maxv;\n   s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest;\n   stb_probe_guess(s, &r);\n   return r;\n}\n\nint stb_search_open(stb_search *s, int minv, int find_smallest)\n{\n   int r;\n   s->step   = 4;\n   s->minval = minv;\n   s->maxval = minv+s->step;\n   s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest;\n   stb_probe_guess(s, &r);\n   return r;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                           String Processing\n//\n\n#define stb_prefixi(s,t)  (0==stb_strnicmp((s),(t),strlen(t)))\n\nenum stb_splitpath_flag\n{\n   STB_PATH = 1,\n   STB_FILE = 2,\n   STB_EXT  = 4,\n   STB_PATH_FILE = STB_PATH + STB_FILE,\n   STB_FILE_EXT  = STB_FILE + STB_EXT,\n   STB_EXT_NO_PERIOD = 8,\n};\n\nSTB_EXTERN char * stb_skipwhite(char *s);\nSTB_EXTERN char * stb_trimwhite(char *s);\nSTB_EXTERN char * stb_skipnewline(char *s);\nSTB_EXTERN char * stb_strncpy(char *s, char *t, int n);\nSTB_EXTERN char * stb_substr(char *t, int n);\nSTB_EXTERN char * stb_duplower(char *s);\nSTB_EXTERN void   stb_tolower (char *s);\nSTB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);\nSTB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);\nSTB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);\nSTB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);\nSTB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);\nSTB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);\nSTB_EXTERN void   stb_replaceinplace(char *s, char *find, char *replace);\nSTB_EXTERN char * stb_splitpath(char *output, char *src, int flag);\nSTB_EXTERN char * stb_splitpathdup(char *src, int flag);\nSTB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);\nSTB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);\nSTB_EXTERN void   stb_fixpath(char *path);\nSTB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);\nSTB_EXTERN int    stb_suffix (char *s, char *t);\nSTB_EXTERN int    stb_suffixi(char *s, char *t);\nSTB_EXTERN int    stb_prefix (char *s, char *t);\nSTB_EXTERN char * stb_strichr(char *s, char t);\nSTB_EXTERN char * stb_stristr(char *s, char *t);\nSTB_EXTERN int    stb_prefix_count(char *s, char *t);\nSTB_EXTERN const char * stb_plural(int n);  // \"s\" or \"\"\nSTB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);\n\nSTB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);\nSTB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);\nSTB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);\n// with 'quoted', allow delimiters to appear inside quotation marks, and don't\n// strip whitespace inside them (and we delete the quotation marks unless they\n// appear back to back, in which case they're considered escaped)\n\n#ifdef STB_DEFINE\n\nsize_t stb_strscpy(char *d, const char *s, size_t n)\n{\n   size_t len = strlen(s);\n   if (len >= n) {\n      if (n) d[0] = 0;\n      return 0;\n   }\n   stb_p_strcpy_s(d,n,s);\n   return len;\n}\n\nconst char *stb_plural(int n)\n{\n   return n == 1 ? \"\" : \"s\";\n}\n\nint stb_prefix(char *s, char *t)\n{\n   while (*t)\n      if (*s++ != *t++)\n         return STB_FALSE;\n   return STB_TRUE;\n}\n\nint stb_prefix_count(char *s, char *t)\n{\n   int c=0;\n   while (*t) {\n      if (*s++ != *t++)\n         break;\n      ++c;\n   }\n   return c;\n}\n\nint stb_suffix(char *s, char *t)\n{\n   size_t n = strlen(s);\n   size_t m = strlen(t);\n   if (m <= n)\n      return 0 == strcmp(s+n-m, t);\n   else\n      return 0;\n}\n\nint stb_suffixi(char *s, char *t)\n{\n   size_t n = strlen(s);\n   size_t m = strlen(t);\n   if (m <= n)\n      return 0 == stb_stricmp(s+n-m, t);\n   else\n      return 0;\n}\n\n// originally I was using this table so that I could create known sentinel\n// values--e.g. change whitetable[0] to be true if I was scanning for whitespace,\n// and false if I was scanning for nonwhite. I don't appear to be using that\n// functionality anymore (I do for tokentable, though), so just replace it\n// with isspace()\nchar *stb_skipwhite(char *s)\n{\n   while (isspace((unsigned char) *s)) ++s;\n   return s;\n}\n\nchar *stb_skipnewline(char *s)\n{\n   if (s[0] == '\\r' || s[0] == '\\n') {\n      if (s[0]+s[1] == '\\r' + '\\n') ++s;\n      ++s;\n   }\n   return s;\n}\n\nchar *stb_trimwhite(char *s)\n{\n   int i,n;\n   s = stb_skipwhite(s);\n   n = (int) strlen(s);\n   for (i=n-1; i >= 0; --i)\n      if (!isspace(s[i]))\n         break;\n   s[i+1] = 0;\n   return s;\n}\n\nchar *stb_strncpy(char *s, char *t, int n)\n{\n   stb_p_strncpy_s(s,n+1,t,n);\n   s[n] = 0;\n   return s;\n}\n\nchar *stb_substr(char *t, int n)\n{\n   char *a;\n   int z = (int) strlen(t);\n   if (z < n) n = z;\n   a = (char *) malloc(n+1);\n   stb_p_strncpy_s(a,n+1,t,n);\n   a[n] = 0;\n   return a;\n}\n\nchar *stb_duplower(char *s)\n{\n   char *p = stb_p_strdup(s), *q = p;\n   while (*q) {\n      *q = tolower(*q);\n      ++q;\n   }\n   return p;\n}\n\nvoid stb_tolower(char *s)\n{\n   while (*s) {\n      *s = tolower(*s);\n      ++s;\n   }\n}\n\nchar *stb_strchr2(char *s, char x, char y)\n{\n   for(; *s; ++s)\n      if (*s == x || *s == y)\n         return s;\n   return NULL;\n}\n\nchar *stb_strrchr2(char *s, char x, char y)\n{\n   char *r = NULL;\n   for(; *s; ++s)\n      if (*s == x || *s == y)\n         r = s;\n   return r;\n}\n\nchar *stb_strichr(char *s, char t)\n{\n   if (tolower(t) == toupper(t))\n      return strchr(s,t);\n   return stb_strchr2(s, (char) tolower(t), (char) toupper(t));\n}\n\nchar *stb_stristr(char *s, char *t)\n{\n   size_t n = strlen(t);\n   char *z;\n   if (n==0) return s;\n   while ((z = stb_strichr(s, *t)) != NULL) {\n      if (0==stb_strnicmp(z, t, n))\n         return z;\n      s = z+1;\n   }\n   return NULL;\n}\n\nstatic char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert)\n{\n   if (invert) {\n      while (*src && strchr(delimit, *src) != NULL) {\n         *output++ = *src++;\n      }\n   } else {\n      while (*src && strchr(delimit, *src) == NULL) {\n         *output++ = *src++;\n      }\n   }\n   *output = 0;\n   if (keep)\n      return src;\n   else\n      return *src ? src+1 : src;\n}\n\nchar *stb_strtok(char *output, char *src, char *delimit)\n{\n   return stb_strtok_raw(output, src, delimit, 0, 0);\n}\n\nchar *stb_strtok_keep(char *output, char *src, char *delimit)\n{\n   return stb_strtok_raw(output, src, delimit, 1, 0);\n}\n\nchar *stb_strtok_invert(char *output, char *src, char *delimit)\n{\n   return stb_strtok_raw(output, src, delimit, 1,1);\n}\n\nstatic char **stb_tokens_raw(char *src_, char *delimit, int *count,\n                             int stripwhite, int allow_empty, char *start, char *end)\n{\n   int nested = 0;\n   unsigned char *src = (unsigned char *) src_;\n   static char stb_tokentable[256]; // rely on static initializion to 0\n   static char stable[256],etable[256];\n   char *out;\n   char **result;\n   int num=0;\n   unsigned char *s;\n\n   s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 1;\n   if (start) {\n      s = (unsigned char *) start;         while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) etable[*s++] = 1;\n   }\n   stable[0] = 1;\n\n   // two passes through: the first time, counting how many\n   s = (unsigned char *) src;\n   while (*s) {\n      // state: just found delimiter\n      // skip further delimiters\n      if (!allow_empty) {\n         stb_tokentable[0] = 0;\n         while (stb_tokentable[*s])\n            ++s;\n         if (!*s) break;\n      }\n      ++num;\n      // skip further non-delimiters\n      stb_tokentable[0] = 1;\n      if (stripwhite == 2) { // quoted strings\n         while (!stb_tokentable[*s]) {\n            if (*s != '\"')\n               ++s;\n            else {\n               ++s;\n               if (*s == '\"')\n                  ++s;   // \"\" -> \", not start a string\n               else {\n                  // begin a string\n                  while (*s) {\n                     if (s[0] == '\"') {\n                        if (s[1] == '\"') s += 2; // \"\" -> \"\n                        else { ++s; break; } // terminating \"\n                     } else\n                        ++s;\n                  }\n               }\n            }\n         }\n      } else\n         while (nested || !stb_tokentable[*s]) {\n            if (stable[*s]) {\n               if (!*s) break;\n               if (end ? etable[*s] : nested)\n                  --nested;\n               else\n                  ++nested;\n            }\n            ++s;\n         }\n      if (allow_empty) {\n         if (*s) ++s;\n      }\n   }\n   // now num has the actual count... malloc our output structure\n   // need space for all the strings: strings won't be any longer than\n   // original input, since for every '\\0' there's at least one delimiter\n   result = (char **) malloc(sizeof(*result) * (num+1) + (s-src+1));\n   if (result == NULL) return result;\n   out = (char *) (result + (num+1));\n   // second pass: copy out the data\n   s = (unsigned char *) src;\n   num = 0;\n   nested = 0;\n   while (*s) {\n      char *last_nonwhite;\n      // state: just found delimiter\n      // skip further delimiters\n      if (!allow_empty) {\n         stb_tokentable[0] = 0;\n         if (stripwhite)\n            while (stb_tokentable[*s] || isspace(*s))\n               ++s;\n         else\n            while (stb_tokentable[*s])\n               ++s;\n      } else if (stripwhite) {\n         while (isspace(*s)) ++s;\n      }\n      if (!*s) break;\n      // we're past any leading delimiters and whitespace\n      result[num] = out;\n      ++num;\n      // copy non-delimiters\n      stb_tokentable[0] = 1;\n      last_nonwhite = out-1;\n      if (stripwhite == 2) {\n         while (!stb_tokentable[*s]) {\n            if (*s != '\"') {\n               if (!isspace(*s)) last_nonwhite = out;\n               *out++ = *s++;\n            } else {\n               ++s;\n               if (*s == '\"') {\n                  if (!isspace(*s)) last_nonwhite = out;\n                  *out++ = *s++; // \"\" -> \", not start string\n               } else {\n                  // begin a quoted string\n                  while (*s) {\n                     if (s[0] == '\"') {\n                        if (s[1] == '\"') { *out++ = *s; s += 2; }\n                        else { ++s; break; } // terminating \"\n                     } else\n                        *out++ = *s++;\n                  }\n                  last_nonwhite = out-1; // all in quotes counts as non-white\n               }\n            }\n         }\n      } else {\n         while (nested || !stb_tokentable[*s]) {\n            if (!isspace(*s)) last_nonwhite = out;\n            if (stable[*s]) {\n               if (!*s) break;\n               if (end ? etable[*s] : nested)\n                  --nested;\n               else\n                  ++nested;\n            }\n            *out++ = *s++;\n         }\n      }\n\n      if (stripwhite) // rewind to last non-whitespace char\n         out = last_nonwhite+1;\n      *out++ = '\\0';\n\n      if (*s) ++s; // skip delimiter\n   }\n   s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 0;\n   if (start) {\n      s = (unsigned char *) start;         while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) etable[*s++] = 1;\n   }\n   if (count != NULL) *count = num;\n   result[num] = 0;\n   return result;\n}\n\nchar **stb_tokens(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,0,0,0,0);\n}\n\nchar **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out)\n{\n   return stb_tokens_raw(src,delimit,count,0,0,nest_in,nest_out);\n}\n\nchar **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out)\n{\n   return stb_tokens_raw(src,delimit,count,0,1,nest_in,nest_out);\n}\n\nchar **stb_tokens_allowempty(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,0,1,0,0);\n}\n\nchar **stb_tokens_stripwhite(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,1,1,0,0);\n}\n\nchar **stb_tokens_quoted(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,2,1,0,0);\n}\n\nchar *stb_dupreplace(char *src, char *find, char *replace)\n{\n   size_t len_find = strlen(find);\n   size_t len_replace = strlen(replace);\n   int count = 0;\n\n   char *s,*p,*q;\n\n   s = strstr(src, find);\n   if (s == NULL) return stb_p_strdup(src);\n   do {\n      ++count;\n      s = strstr(s + len_find, find);\n   } while (s != NULL);\n\n   p = (char *)  malloc(strlen(src) + count * (len_replace - len_find) + 1);\n   if (p == NULL) return p;\n   q = p;\n   s = src;\n   for (;;) {\n      char *t = strstr(s, find);\n      if (t == NULL) {\n         stb_p_strcpy_s(q,strlen(src)+count*(len_replace-len_find)+1,s);\n         assert(strlen(p) == strlen(src) + count*(len_replace-len_find));\n         return p;\n      }\n      memcpy(q, s, t-s);\n      q += t-s;\n      memcpy(q, replace, len_replace);\n      q += len_replace;\n      s = t + len_find;\n   }\n}\n\nvoid stb_replaceinplace(char *src, char *find, char *replace)\n{\n   size_t len_find = strlen(find);\n   size_t len_replace = strlen(replace);\n   int delta;\n\n   char *s,*p,*q;\n\n   delta = (int) (len_replace - len_find);\n   assert(delta <= 0);\n   if (delta > 0) return;\n\n   p = strstr(src, find);\n   if (p == NULL) return;\n\n   s = q = p;\n   while (*s) {\n      memcpy(q, replace, len_replace);\n      p += len_find;\n      q += len_replace;\n      s = strstr(p, find);\n      if (s == NULL) s = p + strlen(p);\n      memmove(q, p, s-p);\n      q += s-p;\n      p = s;\n   }\n   *q = 0;\n}\n\nvoid stb_fixpath(char *path)\n{\n   for(; *path; ++path)\n      if (*path == '\\\\')\n         *path = '/';\n}\n\nvoid stb__add_section(char *buffer, char *data, ptrdiff_t curlen, ptrdiff_t newlen)\n{\n   if (newlen < curlen) {\n      ptrdiff_t z1 = newlen >> 1, z2 = newlen-z1;\n      memcpy(buffer, data, z1-1);\n      buffer[z1-1] = '.';\n      buffer[z1-0] = '.';\n      memcpy(buffer+z1+1, data+curlen-z2+1, z2-1);\n   } else\n      memcpy(buffer, data, curlen);\n}\n\nchar * stb_shorten_path_readable(char *path, int len)\n{\n   static char buffer[1024];\n   ptrdiff_t n = strlen(path),n1,n2,r1,r2;\n   char *s;\n   if (n <= len) return path;\n   if (len > 1024) return path;\n   s = stb_strrchr2(path, '/', '\\\\');\n   if (s) {\n      n1 = s - path + 1;\n      n2 = n - n1;\n      ++s;\n   } else {\n      n1 = 0;\n      n2 = n;\n      s = path;\n   }\n   // now we need to reduce r1 and r2 so that they fit in len\n   if (n1 < len>>1) {\n      r1 = n1;\n      r2 = len - r1;\n   } else if (n2 < len >> 1) {\n      r2 = n2;\n      r1 = len - r2;\n   } else {\n      r1 = n1 * len / n;\n      r2 = n2 * len / n;\n      if (r1 < len>>2) r1 = len>>2, r2 = len-r1;\n      if (r2 < len>>2) r2 = len>>2, r1 = len-r2;\n   }\n   assert(r1 <= n1 && r2 <= n2);\n   if (n1)\n      stb__add_section(buffer, path, n1, r1);\n   stb__add_section(buffer+r1, s, n2, r2);\n   buffer[len] = 0;\n   return buffer;\n}\n\nstatic char *stb__splitpath_raw(char *buffer, char *path, int flag)\n{\n   ptrdiff_t len=0,x,y, n = (int) strlen(path), f1,f2;\n   char *s = stb_strrchr2(path, '/', '\\\\');\n   char *t = strrchr(path, '.');\n   if (s && t && t < s) t = NULL;\n\n   if (!s) {\n      // check for drive\n      if (isalpha(path[0]) && path[1] == ':')\n         s = &path[1];\n   }\n   if (s) ++s;\n\n   if (flag == STB_EXT_NO_PERIOD)\n      flag |= STB_EXT;\n\n   if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL;\n\n   f1 = s == NULL ? 0 : s-path; // start of filename\n   f2 = t == NULL ? n : t-path; // just past end of filename\n\n   if (flag & STB_PATH) {\n      x = 0; if (f1 == 0 && flag == STB_PATH) len=2;\n   } else if (flag & STB_FILE) {\n      x = f1;\n   } else {\n      x = f2;\n      if (flag & STB_EXT_NO_PERIOD)\n         if (path[x] == '.')\n            ++x;\n   }\n\n   if (flag & STB_EXT)\n      y = n;\n   else if (flag & STB_FILE)\n      y = f2;\n   else\n      y = f1;\n\n   if (buffer == NULL) {\n      buffer = (char *) malloc(y-x + len + 1);\n      if (!buffer) return NULL;\n   }\n\n   if (len) { stb_p_strcpy_s(buffer, 3, \"./\"); return buffer; }\n   stb_strncpy(buffer, path+(int)x, (int)(y-x));\n   return buffer;\n}\n\nchar *stb_splitpath(char *output, char *src, int flag)\n{\n   return stb__splitpath_raw(output, src, flag);\n}\n\nchar *stb_splitpathdup(char *src, int flag)\n{\n   return stb__splitpath_raw(NULL, src, flag);\n}\n\nchar *stb_replacedir(char *output, char *src, char *dir)\n{\n   char buffer[4096];\n   stb_splitpath(buffer, src, STB_FILE | STB_EXT);\n   if (dir)\n      stb_p_sprintf(output stb_p_size(9999), \"%s/%s\", dir, buffer);\n   else\n      stb_p_strcpy_s(output, sizeof(buffer),  buffer); // @UNSAFE\n   return output;\n}\n\nchar *stb_replaceext(char *output, char *src, char *ext)\n{\n   char buffer[4096];\n   stb_splitpath(buffer, src, STB_PATH | STB_FILE);\n   if (ext)\n      stb_p_sprintf(output stb_p_size(9999), \"%s.%s\", buffer, ext[0] == '.' ? ext+1 : ext);\n   else\n      stb_p_strcpy_s(output, sizeof(buffer), buffer); // @UNSAFE\n   return output;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                   stb_alloc - hierarchical allocator\n//\n//                                     inspired by http://swapped.cc/halloc\n//\n//\n// When you alloc a given block through stb_alloc, you have these choices:\n//\n//       1. does it have a parent?\n//       2. can it have children?\n//       3. can it be freed directly?\n//       4. is it transferrable?\n//       5. what is its alignment?\n//\n// Here are interesting combinations of those:\n//\n//                              children   free    transfer     alignment\n//  arena                          Y         Y         N           n/a\n//  no-overhead, chunked           N         N         N         normal\n//  string pool alloc              N         N         N            1\n//  parent-ptr, chunked            Y         N         N         normal\n//  low-overhead, unchunked        N         Y         Y         normal\n//  general purpose alloc          Y         Y         Y         normal\n//\n// Unchunked allocations will probably return 16-aligned pointers. If\n// we 16-align the results, we have room for 4 pointers. For smaller\n// allocations that allow finer alignment, we can reduce the pointers.\n//\n// The strategy is that given a pointer, assuming it has a header (only\n// the no-overhead allocations have no header), we can determine the\n// type of the header fields, and the number of them, by stepping backwards\n// through memory and looking at the tags in the bottom bits.\n//\n// Implementation strategy:\n//     chunked allocations come from the middle of chunks, and can't\n//     be freed. thefore they do not need to be on a sibling chain.\n//     they may need child pointers if they have children.\n//\n// chunked, with-children\n//     void *parent;\n//\n// unchunked, no-children -- reduced storage\n//     void *next_sibling;\n//     void *prev_sibling_nextp;\n//\n// unchunked, general\n//     void *first_child;\n//     void *next_sibling;\n//     void *prev_sibling_nextp;\n//     void *chunks;\n//\n// so, if we code each of these fields with different bit patterns\n// (actually same one for next/prev/child), then we can identify which\n// each one is from the last field.\n\nSTB_EXTERN void  stb_free(void *p);\nSTB_EXTERN void *stb_malloc_global(size_t size);\nSTB_EXTERN void *stb_malloc(void *context, size_t size);\nSTB_EXTERN void *stb_malloc_nofree(void *context, size_t size);\nSTB_EXTERN void *stb_malloc_leaf(void *context, size_t size);\nSTB_EXTERN void *stb_malloc_raw(void *context, size_t size);\nSTB_EXTERN void *stb_realloc(void *ptr, size_t newsize);\n\nSTB_EXTERN void stb_reassign(void *new_context, void *ptr);\nSTB_EXTERN void stb_malloc_validate(void *p, void *parent);\n\nextern int stb_alloc_chunk_size ;\nextern int stb_alloc_count_free ;\nextern int stb_alloc_count_alloc;\nextern int stb_alloc_alignment  ;\n\n#ifdef STB_DEFINE\n\nint stb_alloc_chunk_size  = 65536;\nint stb_alloc_count_free  = 0;\nint stb_alloc_count_alloc = 0;\nint stb_alloc_alignment   = -16;\n\ntypedef struct stb__chunk\n{\n   struct stb__chunk *next;\n   int                data_left;\n   int                alloc;\n} stb__chunk;\n\ntypedef struct\n{\n   void *  next;\n   void ** prevn;\n} stb__nochildren;\n\ntypedef struct\n{\n   void ** prevn;\n   void *  child;\n   void *  next;\n   stb__chunk *chunks;\n} stb__alloc;\n\ntypedef struct\n{\n   stb__alloc *parent;\n} stb__chunked;\n\n#define STB__PARENT          1\n#define STB__CHUNKS          2\n\ntypedef enum\n{\n   STB__nochildren = 0,\n   STB__chunked    = STB__PARENT,\n   STB__alloc      = STB__CHUNKS,\n\n   STB__chunk_raw  = 4,\n} stb__alloc_type;\n\n// these functions set the bottom bits of a pointer efficiently\n#define STB__DECODE(x,v)  ((void *) ((char *) (x) - (v)))\n#define STB__ENCODE(x,v)  ((void *) ((char *) (x) + (v)))\n\n#define stb__parent(z)       (stb__alloc *) STB__DECODE((z)->parent, STB__PARENT)\n#define stb__chunks(z)       (stb__chunk *) STB__DECODE((z)->chunks, STB__CHUNKS)\n\n#define stb__setparent(z,p)  (z)->parent = (stb__alloc *) STB__ENCODE((p), STB__PARENT)\n#define stb__setchunks(z,c)  (z)->chunks = (stb__chunk *) STB__ENCODE((c), STB__CHUNKS)\n\nstatic stb__alloc stb__alloc_global =\n{\n   NULL,\n   NULL,\n   NULL,\n   (stb__chunk *) STB__ENCODE(NULL, STB__CHUNKS)\n};\n\nstatic stb__alloc_type stb__identify(void *p)\n{\n   void **q = (void **) p;\n   return (stb__alloc_type) ((stb_uinta) q[-1] & 3);\n}\n\nstatic void *** stb__prevn(void *p)\n{\n   if (stb__identify(p) == STB__alloc) {\n      stb__alloc      *s = (stb__alloc *) p - 1;\n      return &s->prevn;\n   } else {\n      stb__nochildren *s = (stb__nochildren *) p - 1;\n      return &s->prevn;\n   }\n}\n\nvoid stb_free(void *p)\n{\n   if (p == NULL) return;\n\n   // count frees so that unit tests can see what's happening\n   ++stb_alloc_count_free;\n\n   switch(stb__identify(p)) {\n      case STB__chunked:\n         // freeing a chunked-block with children does nothing;\n         // they only get freed when the parent does\n         // surely this is wrong, and it should free them immediately?\n         // otherwise how are they getting put on the right chain?\n         return;\n      case STB__nochildren: {\n         stb__nochildren *s = (stb__nochildren *) p - 1;\n         // unlink from sibling chain\n         *(s->prevn) = s->next;\n         if (s->next)\n            *stb__prevn(s->next) = s->prevn;\n         free(s);\n         return;\n      }\n      case STB__alloc: {\n         stb__alloc *s = (stb__alloc *) p - 1;\n         stb__chunk *c, *n;\n         void *q;\n\n         // unlink from sibling chain, if any\n         *(s->prevn) = s->next;\n         if (s->next)\n            *stb__prevn(s->next) = s->prevn;\n\n         // first free chunks\n         c = (stb__chunk *) stb__chunks(s);\n         while (c != NULL) {\n            n = c->next;\n            stb_alloc_count_free += c->alloc;\n            free(c);\n            c = n;\n         }\n\n         // validating\n         stb__setchunks(s,NULL);\n         s->prevn = NULL;\n         s->next = NULL;\n\n         // now free children\n         while ((q = s->child) != NULL) {\n            stb_free(q);\n         }\n\n         // now free self\n         free(s);\n         return;\n      }\n      default:\n         assert(0); /* NOTREACHED */\n   }\n}\n\nvoid stb_malloc_validate(void *p, void *parent)\n{\n   if (p == NULL) return;\n\n   switch(stb__identify(p)) {\n      case STB__chunked:\n         return;\n      case STB__nochildren: {\n         stb__nochildren *n = (stb__nochildren *) p - 1;\n         if (n->prevn)\n            assert(*n->prevn == p);\n         if (n->next) {\n            assert(*stb__prevn(n->next) == &n->next);\n            stb_malloc_validate(n, parent);\n         }\n         return;\n      }\n      case STB__alloc: {\n         stb__alloc *s = (stb__alloc *) p - 1;\n\n         if (s->prevn)\n            assert(*s->prevn == p);\n\n         if (s->child) {\n            assert(*stb__prevn(s->child) == &s->child);\n            stb_malloc_validate(s->child, p);\n         }\n\n         if (s->next) {\n            assert(*stb__prevn(s->next) == &s->next);\n            stb_malloc_validate(s->next, parent);\n         }\n         return;\n      }\n      default:\n         assert(0); /* NOTREACHED */\n   }\n}\n\nstatic void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align)\n{\n   char *memblock = (char *) (c+1), *q;\n   stb_inta iq;\n   int start_offset;\n\n   // we going to allocate at the end of the chunk, not the start. confusing,\n   // but it means we don't need both a 'limit' and a 'cur', just a 'cur'.\n   // the block ends at: p + c->data_left\n   //   then we move back by size\n   start_offset = c->data_left - size;\n\n   // now we need to check the alignment of that\n   q = memblock + start_offset;\n   iq = (stb_inta) q;\n   assert(sizeof(q) == sizeof(iq));\n\n   // suppose align = 2\n   // then we need to retreat iq far enough that (iq & (2-1)) == 0\n   // to get (iq & (align-1)) = 0 requires subtracting (iq & (align-1))\n\n   start_offset -= iq & (align-1);\n   assert(((stb_uinta) (memblock+start_offset) & (align-1)) == 0);\n\n   // now, if that + pre_align works, go for it!\n   start_offset -= pre_align;\n\n   if (start_offset >= 0) {\n      c->data_left = start_offset;\n      return memblock + start_offset;\n   }\n\n   return NULL;\n}\n\nstatic void stb__sort_chunks(stb__alloc *src)\n{\n   // of the first two chunks, put the chunk with more data left in it first\n   stb__chunk *c = stb__chunks(src), *d;\n   if (c == NULL) return;\n   d = c->next;\n   if (d == NULL) return;\n   if (c->data_left > d->data_left) return;\n\n   c->next = d->next;\n   d->next = c;\n   stb__setchunks(src, d);\n}\n\nstatic void * stb__alloc_chunk(stb__alloc *src, int size, int align, int pre_align)\n{\n   void *p;\n   stb__chunk *c = stb__chunks(src);\n\n   if (c && size <= stb_alloc_chunk_size) {\n\n      p = stb__try_chunk(c, size, align, pre_align);\n      if (p) { ++c->alloc; return p; }\n\n      // try a second chunk to reduce wastage\n      if (c->next) {\n         p = stb__try_chunk(c->next, size, align, pre_align);\n         if (p) { ++c->alloc; return p; }\n\n         // put the bigger chunk first, since the second will get buried\n         // the upshot of this is that, until it gets allocated from, chunk #2\n         // is always the largest remaining chunk. (could formalize\n         // this with a heap!)\n         stb__sort_chunks(src);\n         c = stb__chunks(src);\n      }\n   }\n\n   // allocate a new chunk\n   {\n      stb__chunk *n;\n\n      int chunk_size = stb_alloc_chunk_size;\n      // we're going to allocate a new chunk to put this in\n      if (size > chunk_size)\n         chunk_size = size;\n\n      assert(sizeof(*n) + pre_align <= 16);\n\n      // loop trying to allocate a large enough chunk\n      // the loop is because the alignment may cause problems if it's big...\n      // and we don't know what our chunk alignment is going to be\n      while (1) {\n         n = (stb__chunk *) malloc(16 + chunk_size);\n         if (n == NULL) return NULL;\n\n         n->data_left = chunk_size - sizeof(*n);\n\n         p = stb__try_chunk(n, size, align, pre_align);\n         if (p != NULL) {\n            n->next = c;\n            stb__setchunks(src, n);\n\n            // if we just used up the whole block immediately,\n            // move the following chunk up\n            n->alloc = 1;\n            if (size == chunk_size)\n               stb__sort_chunks(src);\n\n            return p;\n         }\n\n         free(n);\n         chunk_size += 16+align;\n      }\n   }\n}\n\nstatic stb__alloc * stb__get_context(void *context)\n{\n   if (context == NULL) {\n      return &stb__alloc_global;\n   } else {\n      int u = stb__identify(context);\n      // if context is chunked, grab parent\n      if (u == STB__chunked) {\n         stb__chunked *s = (stb__chunked *) context - 1;\n         return stb__parent(s);\n      } else {\n         return (stb__alloc *) context - 1;\n      }\n   }\n}\n\nstatic void stb__insert_alloc(stb__alloc *src, stb__alloc *s)\n{\n   s->prevn = &src->child;\n   s->next  = src->child;\n   src->child = s+1;\n   if (s->next)\n      *stb__prevn(s->next) = &s->next;\n}\n\nstatic void stb__insert_nochild(stb__alloc *src, stb__nochildren *s)\n{\n   s->prevn = &src->child;\n   s->next  = src->child;\n   src->child = s+1;\n   if (s->next)\n      *stb__prevn(s->next) = &s->next;\n}\n\nstatic void * malloc_base(void *context, size_t size, stb__alloc_type t, int align)\n{\n   void *p;\n\n   stb__alloc *src = stb__get_context(context);\n\n   if (align <= 0) {\n      // compute worst-case C packed alignment\n      // e.g. a 24-byte struct is 8-aligned\n      int align_proposed = 1 << stb_lowbit8((unsigned int) size);\n\n      if (align_proposed < 0)\n         align_proposed = 4;\n\n      if (align_proposed == 0) {\n         if (size == 0)\n            align_proposed = 1;\n         else\n            align_proposed = 256;\n      }\n\n      // a negative alignment means 'don't align any larger\n      // than this'; so -16 means we align 1,2,4,8, or 16\n\n      if (align < 0) {\n         if (align_proposed > -align)\n            align_proposed = -align;\n      }\n\n      align = align_proposed;\n   }\n\n   assert(stb_is_pow2(align));\n\n   // don't cause misalignment when allocating nochildren\n   if (t == STB__nochildren && align > 8)\n      t = STB__alloc;\n\n   switch (t) {\n      case STB__alloc: {\n         stb__alloc *s = (stb__alloc *) malloc(size + sizeof(*s));\n         if (s == NULL) return NULL;\n         p = s+1;\n         s->child = NULL;\n         stb__insert_alloc(src, s);\n\n         stb__setchunks(s,NULL);\n         break;\n      }\n\n      case STB__nochildren: {\n         stb__nochildren *s = (stb__nochildren *) malloc(size + sizeof(*s));\n         if (s == NULL) return NULL;\n         p = s+1;\n         stb__insert_nochild(src, s);\n         break;\n      }\n\n      case STB__chunk_raw: {\n         p = stb__alloc_chunk(src, (int) size, align, 0);\n         if (p == NULL) return NULL;\n         break;\n      }\n\n      case STB__chunked: {\n         stb__chunked *s;\n         if (align < sizeof(stb_uintptr)) align = sizeof(stb_uintptr);\n         s = (stb__chunked *) stb__alloc_chunk(src, (int) size, align, sizeof(*s));\n         if (s == NULL) return NULL;\n         stb__setparent(s, src);\n         p = s+1;\n         break;\n      }\n\n      default: p = NULL; assert(0); /* NOTREACHED */\n   }\n\n   ++stb_alloc_count_alloc;\n   return p;\n}\n\nvoid *stb_malloc_global(size_t size)\n{\n   return malloc_base(NULL, size, STB__alloc, stb_alloc_alignment);\n}\n\nvoid *stb_malloc(void *context, size_t size)\n{\n   return malloc_base(context, size, STB__alloc, stb_alloc_alignment);\n}\n\nvoid *stb_malloc_nofree(void *context, size_t size)\n{\n   return malloc_base(context, size, STB__chunked, stb_alloc_alignment);\n}\n\nvoid *stb_malloc_leaf(void *context, size_t size)\n{\n   return malloc_base(context, size, STB__nochildren, stb_alloc_alignment);\n}\n\nvoid *stb_malloc_raw(void *context, size_t size)\n{\n   return malloc_base(context, size, STB__chunk_raw, stb_alloc_alignment);\n}\n\nchar *stb_malloc_string(void *context, size_t size)\n{\n   return (char *) malloc_base(context, size, STB__chunk_raw, 1);\n}\n\nvoid *stb_realloc(void *ptr, size_t newsize)\n{\n   stb__alloc_type t;\n\n   if (ptr == NULL) return stb_malloc(NULL, newsize);\n   if (newsize == 0) { stb_free(ptr); return NULL; }\n\n   t = stb__identify(ptr);\n   assert(t == STB__alloc || t == STB__nochildren);\n\n   if (t == STB__alloc) {\n      stb__alloc *s = (stb__alloc *) ptr - 1;\n\n      s = (stb__alloc *) realloc(s, newsize + sizeof(*s));\n      if (s == NULL) return NULL;\n\n      ptr = s+1;\n\n      // update pointers\n      (*s->prevn) = ptr;\n      if (s->next)\n         *stb__prevn(s->next) = &s->next;\n\n      if (s->child)\n         *stb__prevn(s->child) = &s->child;\n\n      return ptr;\n   } else {\n      stb__nochildren *s = (stb__nochildren *) ptr - 1;\n\n      s = (stb__nochildren *) realloc(ptr, newsize + sizeof(s));\n      if (s == NULL) return NULL;\n\n      // update pointers\n      (*s->prevn) = s+1;\n      if (s->next)\n         *stb__prevn(s->next) = &s->next;\n\n      return s+1;\n   }\n}\n\nvoid *stb_realloc_c(void *context, void *ptr, size_t newsize)\n{\n   if (ptr == NULL) return stb_malloc(context, newsize);\n   if (newsize == 0) { stb_free(ptr); return NULL; }\n   // @TODO: verify you haven't changed contexts\n   return stb_realloc(ptr, newsize);\n}\n\nvoid stb_reassign(void *new_context, void *ptr)\n{\n   stb__alloc *src = stb__get_context(new_context);\n\n   stb__alloc_type t = stb__identify(ptr);\n   assert(t == STB__alloc || t == STB__nochildren);\n\n   if (t == STB__alloc) {\n      stb__alloc *s = (stb__alloc *) ptr - 1;\n\n      // unlink from old\n      *(s->prevn) = s->next;\n      if (s->next)\n         *stb__prevn(s->next) = s->prevn;\n\n      stb__insert_alloc(src, s);\n   } else {\n      stb__nochildren *s = (stb__nochildren *) ptr - 1;\n\n      // unlink from old\n      *(s->prevn) = s->next;\n      if (s->next)\n         *stb__prevn(s->next) = s->prevn;\n\n      stb__insert_nochild(src, s);\n   }\n}\n\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                                stb_arr\n//\n//  An stb_arr is directly useable as a pointer (use the actual type in your\n//  definition), but when it resizes, it returns a new pointer and you can't\n//  use the old one, so you have to be careful to copy-in-out as necessary.\n//\n//  Use a NULL pointer as a 0-length array.\n//\n//     float *my_array = NULL, *temp;\n//\n//     // add elements on the end one at a time\n//     stb_arr_push(my_array, 0.0f);\n//     stb_arr_push(my_array, 1.0f);\n//     stb_arr_push(my_array, 2.0f);\n//\n//     assert(my_array[1] == 2.0f);\n//\n//     // add an uninitialized element at the end, then assign it\n//     *stb_arr_add(my_array) = 3.0f;\n//\n//     // add three uninitialized elements at the end\n//     temp = stb_arr_addn(my_array,3);\n//     temp[0] = 4.0f;\n//     temp[1] = 5.0f;\n//     temp[2] = 6.0f;\n//\n//     assert(my_array[5] == 5.0f);\n//\n//     // remove the last one\n//     stb_arr_pop(my_array);\n//\n//     assert(stb_arr_len(my_array) == 6);\n\n\n#ifdef STB_MALLOC_WRAPPER\n  #define STB__PARAMS    , char *file, int line\n  #define STB__ARGS      ,       file,     line\n#else\n  #define STB__PARAMS\n  #define STB__ARGS\n#endif\n\n// calling this function allocates an empty stb_arr attached to p\n// (whereas NULL isn't attached to anything)\nSTB_EXTERN void stb_arr_malloc(void **target, void *context);\n\n// call this function with a non-NULL value to have all successive\n// stbs that are created be attached to the associated parent. Note\n// that once a given stb_arr is non-empty, it stays attached to its\n// current parent, even if you call this function again.\n// it turns the previous value, so you can restore it\nSTB_EXTERN void* stb_arr_malloc_parent(void *p);\n\n// simple functions written on top of other functions\n#define stb_arr_empty(a)       (  stb_arr_len(a) == 0 )\n#define stb_arr_add(a)         (  stb_arr_addn((a),1) )\n#define stb_arr_push(a,v)      ( *stb_arr_add(a)=(v)  )\n\ntypedef struct\n{\n   int len, limit;\n   int stb_malloc;\n   unsigned int signature;\n} stb__arr;\n\n#define stb_arr_signature      0x51bada7b  // ends with 0123 in decimal\n\n// access the header block stored before the data\n#define stb_arrhead(a)         /*lint --e(826)*/ (((stb__arr *) (a)) - 1)\n#define stb_arrhead2(a)        /*lint --e(826)*/ (((stb__arr *) (a)) - 1)\n\n#ifdef STB_DEBUG\n#define stb_arr_check(a)       assert(!a || stb_arrhead(a)->signature == stb_arr_signature)\n#define stb_arr_check2(a)      assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)\n#else\n#define stb_arr_check(a)       ((void) 0)\n#define stb_arr_check2(a)      ((void) 0)\n#endif\n\n// ARRAY LENGTH\n\n// get the array length; special case if pointer is NULL\n#define stb_arr_len(a)         (a ? stb_arrhead(a)->len : 0)\n#define stb_arr_len2(a)        ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0)\n#define stb_arr_lastn(a)       (stb_arr_len(a)-1)\n\n// check whether a given index is valid -- tests 0 <= i < stb_arr_len(a)\n#define stb_arr_valid(a,i)     (a ? (int) (i) < stb_arrhead(a)->len : 0)\n\n// change the array length so is is exactly N entries long, creating\n// uninitialized entries as needed\n#define stb_arr_setlen(a,n)  \\\n            (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n)))\n\n// change the array length so that N is a valid index (that is, so\n// it is at least N entries long), creating uninitialized entries as needed\n#define stb_arr_makevalid(a,n)  \\\n            (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a))\n\n// remove the last element of the array, returning it\n#define stb_arr_pop(a)         ((stb_arr_check(a), (a))[--stb_arrhead(a)->len])\n\n// access the last element in the array\n#define stb_arr_last(a)        ((stb_arr_check(a), (a))[stb_arr_len(a)-1])\n\n// is iterator at end of list?\n#define stb_arr_end(a,i)       ((i) >= &(a)[stb_arr_len(a)])\n\n// (internal) change the allocated length of the array\n#define stb_arr__grow(a,n)     (stb_arr_check(a), stb_arrhead(a)->len += (n))\n\n// add N new uninitialized elements to the end of the array\n#define stb_arr__addn(a,n)     /*lint --e(826)*/ \\\n                               ((stb_arr_len(a)+(n) > stb_arrcurmax(a))      \\\n                                 ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \\\n                                 : ((stb_arr__grow(a,n), 0)))\n\n// add N new uninitialized elements to the end of the array, and return\n// a pointer to the first new one\n#define stb_arr_addn(a,n)      (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n))\n\n// add N new uninitialized elements starting at index 'i'\n#define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), (i), (n)))\n\n// insert an element at i\n#define stb_arr_insert(a,i,v)  (stb__arr_insertn((void **) &(a), sizeof(*a), (i), (1)), ((a)[i] = v))\n\n// delete N elements from the middle starting at index 'i'\n#define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), (i), (n)))\n\n// delete the i'th element\n#define stb_arr_delete(a,i)   stb_arr_deleten(a,i,1)\n\n// delete the i'th element, swapping down from the end\n#define stb_arr_fastdelete(a,i)  \\\n   (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a))\n\n\n// ARRAY STORAGE\n\n// get the array maximum storage; special case if NULL\n#define stb_arrcurmax(a)       (a ? stb_arrhead(a)->limit : 0)\n#define stb_arrcurmax2(a)      (a ? stb_arrhead2(a)->limit : 0)\n\n// set the maxlength of the array to n in anticipation of further growth\n#define stb_arr_setsize(a,n)   (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n))\n\n// make sure maxlength is large enough for at least N new allocations\n#define stb_arr_atleast(a,n)   (stb_arr_len(a)+(n) > stb_arrcurmax(a)      \\\n                                 ? stb_arr_setsize((a), (n)) : 0)\n\n// make a copy of a given array (copies contents via 'memcpy'!)\n#define stb_arr_copy(a)        stb__arr_copy(a, sizeof((a)[0]))\n\n// compute the storage needed to store all the elements of the array\n#define stb_arr_storage(a)     (stb_arr_len(a) * sizeof((a)[0]))\n\n#define stb_arr_for(v,arr)     for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v))\n\n// IMPLEMENTATION\n\nSTB_EXTERN void stb_arr_free_(void **p);\nSTB_EXTERN void *stb__arr_copy_(void *p, int elem_size);\nSTB_EXTERN void stb__arr_setsize_(void **p, int size, int limit  STB__PARAMS);\nSTB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen  STB__PARAMS);\nSTB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen  STB__PARAMS);\nSTB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n  STB__PARAMS);\nSTB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n  STB__PARAMS);\n\n#define stb_arr_free(p)            stb_arr_free_((void **) &(p))\n#define stb__arr_copy              stb__arr_copy_\n\n#ifndef STB_MALLOC_WRAPPER\n  #define stb__arr_setsize         stb__arr_setsize_\n  #define stb__arr_setlen          stb__arr_setlen_\n  #define stb__arr_addlen          stb__arr_addlen_\n  #define stb__arr_deleten         stb__arr_deleten_\n  #define stb__arr_insertn         stb__arr_insertn_\n#else\n  #define stb__arr_addlen(p,s,n)    stb__arr_addlen_(p,s,n,__FILE__,__LINE__)\n  #define stb__arr_setlen(p,s,n)    stb__arr_setlen_(p,s,n,__FILE__,__LINE__)\n  #define stb__arr_setsize(p,s,n)   stb__arr_setsize_(p,s,n,__FILE__,__LINE__)\n  #define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__)\n  #define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__)\n#endif\n\n#ifdef STB_DEFINE\nstatic void *stb__arr_context;\n\nvoid *stb_arr_malloc_parent(void *p)\n{\n   void *q = stb__arr_context;\n   stb__arr_context = p;\n   return q;\n}\n\nvoid stb_arr_malloc(void **target, void *context)\n{\n   stb__arr *q = (stb__arr *) stb_malloc(context, sizeof(*q));\n   q->len = q->limit = 0;\n   q->stb_malloc = 1;\n   q->signature = stb_arr_signature;\n   *target = (void *) (q+1);\n}\n\nstatic void * stb__arr_malloc(int size)\n{\n   if (stb__arr_context)\n      return stb_malloc(stb__arr_context, size);\n   return malloc(size);\n}\n\nvoid * stb__arr_copy_(void *p, int elem_size)\n{\n   stb__arr *q;\n   if (p == NULL) return p;\n   q = (stb__arr *) stb__arr_malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit);\n   stb_arr_check2(p);\n   memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len);\n   q->stb_malloc = !!stb__arr_context;\n   return q+1;\n}\n\nvoid stb_arr_free_(void **pp)\n{\n   void *p = *pp;\n   stb_arr_check2(p);\n   if (p) {\n      stb__arr *q = stb_arrhead2(p);\n      if (q->stb_malloc)\n         stb_free(q);\n      else\n         free(q);\n   }\n   *pp = NULL;\n}\n\nstatic void stb__arrsize_(void **pp, int size, int limit, int len  STB__PARAMS)\n{\n   void *p = *pp;\n   stb__arr *a;\n   stb_arr_check2(p);\n   if (p == NULL) {\n      if (len == 0 && size == 0) return;\n      a = (stb__arr *) stb__arr_malloc(sizeof(*a) + size*limit);\n      a->limit = limit;\n      a->len   = len;\n      a->stb_malloc = !!stb__arr_context;\n      a->signature = stb_arr_signature;\n   } else {\n      a = stb_arrhead2(p);\n      a->len = len;\n      if (a->limit < limit) {\n         void *p;\n         if (a->limit >= 4 && limit < a->limit * 2)\n            limit = a->limit * 2;\n         if (a->stb_malloc)\n            p = stb_realloc(a, sizeof(*a) + limit*size);\n         else\n            #ifdef STB_MALLOC_WRAPPER\n            p = stb__realloc(a, sizeof(*a) + limit*size, file, line);\n            #else\n            p = realloc(a, sizeof(*a) + limit*size);\n            #endif\n         if (p) {\n            a = (stb__arr *) p;\n            a->limit = limit;\n         } else {\n            // throw an error!\n         }\n      }\n   }\n   a->len   = stb_min(a->len, a->limit);\n   *pp = a+1;\n}\n\nvoid stb__arr_setsize_(void **pp, int size, int limit  STB__PARAMS)\n{\n   void *p = *pp;\n   stb_arr_check2(p);\n   stb__arrsize_(pp, size, limit, stb_arr_len2(p)  STB__ARGS);\n}\n\nvoid stb__arr_setlen_(void **pp, int size, int newlen  STB__PARAMS)\n{\n   void *p = *pp;\n   stb_arr_check2(p);\n   if (stb_arrcurmax2(p) < newlen || p == NULL) {\n      stb__arrsize_(pp, size, newlen, newlen  STB__ARGS);\n   } else {\n      stb_arrhead2(p)->len = newlen;\n   }\n}\n\nvoid stb__arr_addlen_(void **p, int size, int addlen  STB__PARAMS)\n{\n   stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen  STB__ARGS);\n}\n\nvoid stb__arr_insertn_(void **pp, int size, int i, int n  STB__PARAMS)\n{\n   void *p = *pp;\n   if (n) {\n      int z;\n\n      if (p == NULL) {\n         stb__arr_addlen_(pp, size, n  STB__ARGS);\n         return;\n      }\n\n      z = stb_arr_len2(p);\n      stb__arr_addlen_(&p, size, n  STB__ARGS);\n      memmove((char *) p + (i+n)*size, (char *) p + i*size, size * (z-i));\n   }\n   *pp = p;\n}\n\nvoid stb__arr_deleten_(void **pp, int size, int i, int n  STB__PARAMS)\n{\n   void *p = *pp;\n   if (n) {\n      memmove((char *) p + i*size, (char *) p + (i+n)*size, size * (stb_arr_len2(p)-(i+n)));\n      stb_arrhead2(p)->len -= n;\n   }\n   *pp = p;\n}\n\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                               Hashing\n//\n//      typical use for this is to make a power-of-two hash table.\n//\n//      let N = size of table (2^n)\n//      let H = stb_hash(str)\n//      let S = stb_rehash(H) | 1\n//\n//      then hash probe sequence P(i) for i=0..N-1\n//         P(i) = (H + S*i) & (N-1)\n//\n//      the idea is that H has 32 bits of hash information, but the\n//      table has only, say, 2^20 entries so only uses 20 of the bits.\n//      then by rehashing the original H we get 2^12 different probe\n//      sequences for a given initial probe location. (So it's optimal\n//      for 64K tables and its optimality decreases past that.)\n//\n//      ok, so I've added something that generates _two separate_\n//      32-bit hashes simultaneously which should scale better to\n//      very large tables.\n\n\nSTB_EXTERN unsigned int stb_hash(char *str);\nSTB_EXTERN unsigned int stb_hashptr(void *p);\nSTB_EXTERN unsigned int stb_hashlen(char *str, int len);\nSTB_EXTERN unsigned int stb_rehash_improved(unsigned int v);\nSTB_EXTERN unsigned int stb_hash_fast(void *p, int len);\nSTB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr);\nSTB_EXTERN unsigned int stb_hash_number(unsigned int hash);\n\n#define stb_rehash(x)  ((x) + ((x) >> 6) + ((x) >> 19))\n\n#ifdef STB_DEFINE\nunsigned int stb_hash(char *str)\n{\n   unsigned int hash = 0;\n   while (*str)\n      hash = (hash << 7) + (hash >> 25) + *str++;\n   return hash + (hash >> 16);\n}\n\nunsigned int stb_hashlen(char *str, int len)\n{\n   unsigned int hash = 0;\n   while (len-- > 0 && *str)\n      hash = (hash << 7) + (hash >> 25) + *str++;\n   return hash + (hash >> 16);\n}\n\nunsigned int stb_hashptr(void *p)\n{\n    unsigned int x = (unsigned int)(size_t) p;\n\n   // typically lacking in low bits and high bits\n   x = stb_rehash(x);\n   x += x << 16;\n\n   // pearson's shuffle\n   x ^= x << 3;\n   x += x >> 5;\n   x ^= x << 2;\n   x += x >> 15;\n   x ^= x << 10;\n   return stb_rehash(x);\n}\n\nunsigned int stb_rehash_improved(unsigned int v)\n{\n   return stb_hashptr((void *)(size_t) v);\n}\n\nunsigned int stb_hash2(char *str, unsigned int *hash2_ptr)\n{\n   unsigned int hash1 = 0x3141592c;\n   unsigned int hash2 = 0x77f044ed;\n   while (*str) {\n      hash1 = (hash1 << 7) + (hash1 >> 25) + *str;\n      hash2 = (hash2 << 11) + (hash2 >> 21) + *str;\n      ++str;\n   }\n   *hash2_ptr = hash2 + (hash1 >> 16);\n   return       hash1 + (hash2 >> 16);\n}\n\n// Paul Hsieh hash\n#define stb__get16(p) ((p)[0] | ((p)[1] << 8))\n\nunsigned int stb_hash_fast(void *p, int len)\n{\n   unsigned char *q = (unsigned char *) p;\n   unsigned int hash = len;\n\n   if (len <= 0 || q == NULL) return 0;\n\n   /* Main loop */\n   for (;len > 3; len -= 4) {\n      unsigned int val;\n      hash +=  stb__get16(q);\n      val   = (stb__get16(q+2) << 11);\n      hash  = (hash << 16) ^ hash ^ val;\n      q    += 4;\n      hash += hash >> 11;\n   }\n\n   /* Handle end cases */\n   switch (len) {\n      case 3: hash += stb__get16(q);\n              hash ^= hash << 16;\n              hash ^= q[2] << 18;\n              hash += hash >> 11;\n              break;\n      case 2: hash += stb__get16(q);\n              hash ^= hash << 11;\n              hash += hash >> 17;\n              break;\n      case 1: hash += q[0];\n              hash ^= hash << 10;\n              hash += hash >> 1;\n              break;\n      case 0: break;\n   }\n\n   /* Force \"avalanching\" of final 127 bits */\n   hash ^= hash << 3;\n   hash += hash >> 5;\n   hash ^= hash << 4;\n   hash += hash >> 17;\n   hash ^= hash << 25;\n   hash += hash >> 6;\n\n   return hash;\n}\n\nunsigned int stb_hash_number(unsigned int hash)\n{\n   hash ^= hash << 3;\n   hash += hash >> 5;\n   hash ^= hash << 4;\n   hash += hash >> 17;\n   hash ^= hash << 25;\n   hash += hash >> 6;\n   return hash;\n}\n\n#endif\n\n#ifdef STB_PERFECT_HASH\n//////////////////////////////////////////////////////////////////////////////\n//\n//                     Perfect hashing for ints/pointers\n//\n//   This is mainly useful for making faster pointer-indexed tables\n//   that don't change frequently. E.g. for stb_ischar().\n//\n\ntypedef struct\n{\n   stb_uint32  addend;\n   stb_uint    multiplicand;\n   stb_uint    b_mask;\n   stb_uint8   small_bmap[16];\n   stb_uint16  *large_bmap;\n\n   stb_uint table_mask;\n   stb_uint32 *table;\n} stb_perfect;\n\nSTB_EXTERN int stb_perfect_create(stb_perfect *,unsigned int*,int n);\nSTB_EXTERN void stb_perfect_destroy(stb_perfect *);\nSTB_EXTERN int stb_perfect_hash(stb_perfect *, unsigned int x);\nextern int stb_perfect_hash_max_failures;\n\n#ifdef STB_DEFINE\n\nint stb_perfect_hash_max_failures;\n\nint stb_perfect_hash(stb_perfect *p, unsigned int x)\n{\n   stb_uint m = x * p->multiplicand;\n   stb_uint y = x >> 16;\n   stb_uint bv = (m >> 24) + y;\n   stb_uint av = (m + y) >> 12;\n   if (p->table == NULL) return -1;  // uninitialized table fails\n   bv &= p->b_mask;\n   av &= p->table_mask;\n   if (p->large_bmap)\n      av ^= p->large_bmap[bv];\n   else\n      av ^= p->small_bmap[bv];\n   return p->table[av] == x ? av : -1;\n}\n\nstatic void stb__perfect_prehash(stb_perfect *p, stb_uint x, stb_uint16 *a, stb_uint16 *b)\n{\n   stb_uint m = x * p->multiplicand;\n   stb_uint y = x >> 16;\n   stb_uint bv = (m >> 24) + y;\n   stb_uint av = (m + y) >> 12;\n   bv &= p->b_mask;\n   av &= p->table_mask;\n   *b = bv;\n   *a = av;\n}\n\nstatic unsigned long stb__perfect_rand(void)\n{\n   static unsigned long stb__rand;\n   stb__rand = stb__rand * 2147001325 + 715136305;\n   return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));\n}\n\ntypedef struct {\n   unsigned short count;\n   unsigned short b;\n   unsigned short map;\n   unsigned short *entries;\n} stb__slot;\n\nstatic int stb__slot_compare(const void *p, const void *q)\n{\n   stb__slot *a = (stb__slot *) p;\n   stb__slot *b = (stb__slot *) q;\n   return a->count > b->count ? -1 : a->count < b->count;  // sort large to small\n}\n\nint stb_perfect_create(stb_perfect *p, unsigned int *v, int n)\n{\n   unsigned int buffer1[64], buffer2[64], buffer3[64], buffer4[64], buffer5[32];\n   unsigned short *as = (unsigned short *) stb_temp(buffer1, sizeof(*v)*n);\n   unsigned short *bs = (unsigned short *) stb_temp(buffer2, sizeof(*v)*n);\n   unsigned short *entries = (unsigned short *) stb_temp(buffer4, sizeof(*entries) * n);\n   int size = 1 << stb_log2_ceil(n), bsize=8;\n   int failure = 0,i,j,k;\n\n   assert(n <= 32768);\n   p->large_bmap = NULL;\n\n   for(;;) {\n      stb__slot *bcount = (stb__slot *) stb_temp(buffer3, sizeof(*bcount) * bsize);\n      unsigned short *bloc = (unsigned short *) stb_temp(buffer5, sizeof(*bloc) * bsize);\n      unsigned short *e;\n      int bad=0;\n\n      p->addend = stb__perfect_rand();\n      p->multiplicand = stb__perfect_rand() | 1;\n      p->table_mask = size-1;\n      p->b_mask = bsize-1;\n      p->table = (stb_uint32 *) malloc(size * sizeof(*p->table));\n\n      for (i=0; i < bsize; ++i) {\n         bcount[i].b     = i;\n         bcount[i].count = 0;\n         bcount[i].map   = 0;\n      }\n      for (i=0; i < n; ++i) {\n         stb__perfect_prehash(p, v[i], as+i, bs+i);\n         ++bcount[bs[i]].count;\n      }\n      qsort(bcount, bsize, sizeof(*bcount), stb__slot_compare);\n      e = entries; // now setup up their entries index\n      for (i=0; i < bsize; ++i) {\n         bcount[i].entries = e;\n         e += bcount[i].count;\n         bcount[i].count = 0;\n         bloc[bcount[i].b] = i;\n      }\n      // now fill them out\n      for (i=0; i < n; ++i) {\n         int b = bs[i];\n         int w = bloc[b];\n         bcount[w].entries[bcount[w].count++] = i;\n      }\n      stb_tempfree(buffer5,bloc);\n      // verify\n      for (i=0; i < bsize; ++i)\n         for (j=0; j < bcount[i].count; ++j)\n            assert(bs[bcount[i].entries[j]] == bcount[i].b);\n      memset(p->table, 0, size*sizeof(*p->table));\n\n      // check if any b has duplicate a\n      for (i=0; i < bsize; ++i) {\n         if (bcount[i].count > 1) {\n            for (j=0; j < bcount[i].count; ++j) {\n               if (p->table[as[bcount[i].entries[j]]])\n                  bad = 1;\n               p->table[as[bcount[i].entries[j]]] = 1;\n            }\n            for (j=0; j < bcount[i].count; ++j) {\n               p->table[as[bcount[i].entries[j]]] = 0;\n            }\n            if (bad) break;\n         }\n      }\n\n      if (!bad) {\n         // go through the bs and populate the table, first fit\n         for (i=0; i < bsize; ++i) {\n            if (bcount[i].count) {\n               // go through the candidate table[b] values\n               for (j=0; j < size; ++j) {\n                  // go through the a values and see if they fit\n                  for (k=0; k < bcount[i].count; ++k) {\n                     int a = as[bcount[i].entries[k]];\n                     if (p->table[(a^j)&p->table_mask]) {\n                        break; // fails\n                     }\n                  }\n                  // if succeeded, accept\n                  if (k == bcount[i].count) {\n                     bcount[i].map = j;\n                     for (k=0; k < bcount[i].count; ++k) {\n                        int a = as[bcount[i].entries[k]];\n                        p->table[(a^j)&p->table_mask] = 1;\n                     }\n                     break;\n                  }\n               }\n               if (j == size)\n                  break; // no match for i'th entry, so break out in failure\n            }\n         }\n         if (i == bsize) {\n            // success... fill out map\n            if (bsize <= 16 && size <= 256) {\n               p->large_bmap = NULL;\n               for (i=0; i < bsize; ++i)\n                  p->small_bmap[bcount[i].b] = (stb_uint8) bcount[i].map;\n            } else {\n               p->large_bmap = (unsigned short *) malloc(sizeof(*p->large_bmap) * bsize);\n               for (i=0; i < bsize; ++i)\n                  p->large_bmap[bcount[i].b] = bcount[i].map;\n            }\n\n            // initialize table to v[0], so empty slots will fail\n            for (i=0; i < size; ++i)\n               p->table[i] = v[0];\n\n            for (i=0; i < n; ++i)\n               if (p->large_bmap)\n                  p->table[as[i] ^ p->large_bmap[bs[i]]] = v[i];\n               else\n                  p->table[as[i] ^ p->small_bmap[bs[i]]] = v[i];\n\n            // and now validate that none of them collided\n            for (i=0; i < n; ++i)\n               assert(stb_perfect_hash(p, v[i]) >= 0);\n\n            stb_tempfree(buffer3, bcount);\n            break;\n         }\n      }\n      free(p->table);\n      p->table = NULL;\n      stb_tempfree(buffer3, bcount);\n\n      ++failure;\n      if (failure >= 4 && bsize < size) bsize *= 2;\n      if (failure >= 8 && (failure & 3) == 0 && size < 4*n) {\n         size *= 2;\n         bsize *= 2;\n      }\n      if (failure == 6) {\n         // make sure the input data is unique, so we don't infinite loop\n         unsigned int *data = (unsigned int *) stb_temp(buffer3, n * sizeof(*data));\n         memcpy(data, v, sizeof(*data) * n);\n         qsort(data, n, sizeof(*data), stb_intcmp(0));\n         for (i=1; i < n; ++i) {\n            if (data[i] == data[i-1])\n               size = 0; // size is return value, so 0 it\n         }\n         stb_tempfree(buffer3, data);\n         if (!size) break;\n      }\n   }\n\n   if (failure > stb_perfect_hash_max_failures)\n      stb_perfect_hash_max_failures = failure;\n\n   stb_tempfree(buffer1, as);\n   stb_tempfree(buffer2, bs);\n   stb_tempfree(buffer4, entries);\n\n   return size;\n}\n\nvoid stb_perfect_destroy(stb_perfect *p)\n{\n   if (p->large_bmap) free(p->large_bmap);\n   if (p->table     ) free(p->table);\n   p->large_bmap = NULL;\n   p->table      = NULL;\n   p->b_mask     = 0;\n   p->table_mask = 0;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                     Perfect hash clients\n\nSTB_EXTERN int    stb_ischar(char s, char *set);\n\n#ifdef STB_DEFINE\n\nint stb_ischar(char c, char *set)\n{\n   static unsigned char bit[8] = { 1,2,4,8,16,32,64,128 };\n   static stb_perfect p;\n   static unsigned char (*tables)[256];\n   static char ** sets = NULL;\n\n   int z = stb_perfect_hash(&p, (int)(size_t) set);\n   if (z < 0) {\n      int i,k,n,j,f;\n      // special code that means free all existing data\n      if (set == NULL) {\n         stb_arr_free(sets);\n         free(tables);\n         tables = NULL;\n         stb_perfect_destroy(&p);\n         return 0;\n      }\n      stb_arr_push(sets, set);\n      stb_perfect_destroy(&p);\n      n = stb_perfect_create(&p, (unsigned int *) (char **) sets, stb_arr_len(sets));\n      assert(n != 0);\n      k = (n+7) >> 3;\n      tables = (unsigned char (*)[256]) realloc(tables, sizeof(*tables) * k);\n      memset(tables, 0, sizeof(*tables) * k);\n      for (i=0; i < stb_arr_len(sets); ++i) {\n          k = stb_perfect_hash(&p, (int)(size_t) sets[i]);\n         assert(k >= 0);\n         n = k >> 3;\n         f = bit[k&7];\n         for (j=0; !j || sets[i][j]; ++j) {\n            tables[n][(unsigned char) sets[i][j]] |= f;\n         }\n      }\n      z = stb_perfect_hash(&p, (int)(size_t) set);\n   }\n   return tables[z >> 3][(unsigned char) c] & bit[z & 7];\n}\n\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                     Instantiated data structures\n//\n// This is an attempt to implement a templated data structure.\n//\n// Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE)\n//     TYPE     -- will define a structure type containing the hash table\n//     N        -- the name, will prefix functions named:\n//                        N create\n//                        N destroy\n//                        N get\n//                        N set, N add, N update,\n//                        N remove\n//     KEY      -- the type of the key. 'x == y' must be valid\n//       K1,K2  -- keys never used by the app, used as flags in the hashtable\n//       HASH   -- a piece of code ending with 'return' that hashes key 'k'\n//     VALUE    -- the type of the value. 'x = y' must be valid\n//\n//  Note that stb_define_hash_base can be used to define more sophisticated\n//  hash tables, e.g. those that make copies of the key or use special\n//  comparisons (e.g. strcmp).\n\n#define STB_(prefix,name)     stb__##prefix##name\n#define STB__(prefix,name)    prefix##name\n#define STB__use(x)           x\n#define STB__skip(x)\n\n#define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \\\n   typedef struct stb__st_##TYPE TYPE;\\\n   PREFIX int STB__(N, init)(TYPE *h, int count);\\\n   PREFIX int STB__(N, memory_usage)(TYPE *h);\\\n   PREFIX TYPE * STB__(N, create)(void);\\\n   PREFIX TYPE * STB__(N, copy)(TYPE *h);\\\n   PREFIX void STB__(N, destroy)(TYPE *h);\\\n   PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\\\n   PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\\\n   PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\\\n   PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\\\n   PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\\\n   PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v);\n\n#define STB_nocopy(x)        (x)\n#define STB_nodelete(x)      0\n#define STB_nofields\n#define STB_nonullvalue(x)\n#define STB_nullvalue(x)     x\n#define STB_safecompare(x)   x\n#define STB_nosafe(x)\n#define STB_noprefix\n\n#ifdef __GNUC__\n#define STB__nogcc(x)\n#else\n#define STB__nogcc(x)  x\n#endif\n\n#define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR,             \\\n                             KEY,EMPTY,DEL,COPY,DISPOSE,SAFE,                 \\\n                             VCOMPARE,CCOMPARE,HASH,                          \\\n                             VALUE,HASVNULL,VNULL)                            \\\n                                                                              \\\ntypedef struct                                                                \\\n{                                                                             \\\n   KEY   k;                                                                   \\\n   VALUE v;                                                                   \\\n} STB_(N,_hashpair);                                                          \\\n                                                                              \\\nSTB__nogcc( typedef struct stb__st_##TYPE TYPE;  )                            \\\nstruct stb__st_##TYPE {                                                       \\\n   FIELDS                                                                     \\\n   STB_(N,_hashpair) *table;                                                  \\\n   unsigned int mask;                                                         \\\n   int count, limit;                                                          \\\n   int deleted;                                                               \\\n                                                                              \\\n   int delete_threshhold;                                                     \\\n   int grow_threshhold;                                                       \\\n   int shrink_threshhold;                                                     \\\n   unsigned char alloced, has_empty, has_del;                                 \\\n   VALUE ev; VALUE dv;                                                        \\\n};                                                                            \\\n                                                                              \\\nstatic unsigned int STB_(N, hash)(KEY k)                                      \\\n{                                                                             \\\n   HASH                                                                       \\\n}                                                                             \\\n                                                                              \\\nPREFIX int STB__(N, init)(TYPE *h, int count)                                        \\\n{                                                                             \\\n   int i;                                                                     \\\n   if (count < 4) count = 4;                                                  \\\n   h->limit = count;                                                          \\\n   h->count = 0;                                                              \\\n   h->mask  = count-1;                                                        \\\n   h->deleted = 0;                                                            \\\n   h->grow_threshhold = (int) (count * LOAD_FACTOR);                          \\\n   h->has_empty = h->has_del = 0;                                             \\\n   h->alloced = 0;                                                            \\\n   if (count <= 64)                                                           \\\n      h->shrink_threshhold = 0;                                               \\\n   else                                                                       \\\n      h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25));              \\\n   h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2);                  \\\n   h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count);       \\\n   if (h->table == NULL) return 0;                                            \\\n   /* ideally this gets turned into a memset32 automatically */               \\\n   for (i=0; i < count; ++i)                                                  \\\n      h->table[i].k = EMPTY;                                                  \\\n   return 1;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX int STB__(N, memory_usage)(TYPE *h)                                           \\\n{                                                                             \\\n   return sizeof(*h) + h->limit * sizeof(h->table[0]);                        \\\n}                                                                             \\\n                                                                              \\\nPREFIX TYPE * STB__(N, create)(void)                                                 \\\n{                                                                             \\\n   TYPE *h = (TYPE *) malloc(sizeof(*h));                                     \\\n   if (h) {                                                                   \\\n      if (STB__(N, init)(h, 16))                                              \\\n         h->alloced = 1;                                                      \\\n      else { free(h); h=NULL; }                                               \\\n   }                                                                          \\\n   return h;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX void STB__(N, destroy)(TYPE *a)                                               \\\n{                                                                             \\\n   int i;                                                                     \\\n   for (i=0; i < a->limit; ++i)                                               \\\n      if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL))    \\\n         DISPOSE(a->table[i].k);                                              \\\n   free(a->table);                                                            \\\n   if (a->alloced)                                                            \\\n      free(a);                                                                \\\n}                                                                             \\\n                                                                              \\\nstatic void STB_(N, rehash)(TYPE *a, int count);                              \\\n                                                                              \\\nPREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v)                               \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask, s;                                           \\\n   if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\\\n   if (CCOMPARE(k,DEL)) { if (a->has_del  ) *v = a->dv; return a->has_del;   }\\\n   if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \\\n   SAFE(if (!CCOMPARE(a->table[n].k,DEL)))                                    \\\n   if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; }            \\\n   s = stb_rehash(h) | 1;                                                     \\\n   for(;;) {                                                                  \\\n      n = (n + s) & a->mask;                                                  \\\n      if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                            \\\n      SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;)                        \\\n      if (VCOMPARE(a->table[n].k,k))                                           \\\n         { *v = a->table[n].v; return 1; }                                    \\\n   }                                                                          \\\n}                                                                             \\\n                                                                              \\\nHASVNULL(                                                                     \\\n   PREFIX VALUE STB__(N,get)(TYPE *a, KEY k)                                         \\\n   {                                                                          \\\n      VALUE v;                                                                \\\n      if (STB__(N,get_flag)(a,k,&v)) return v;                                \\\n      else                           return VNULL;                            \\\n   }                                                                          \\\n)                                                                             \\\n                                                                              \\\nPREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout)                                \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask, s;                                           \\\n   if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0;                          \\\n   if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \\\n   SAFE(if (!CCOMPARE(a->table[n].k,DEL)))                                    \\\n   if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; }         \\\n   s = stb_rehash(h) | 1;                                                     \\\n   for(;;) {                                                                  \\\n      n = (n + s) & a->mask;                                                  \\\n      if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                            \\\n      SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;)                        \\\n      if (VCOMPARE(a->table[n].k,k))                                          \\\n         { *kout = a->table[n].k; return 1; }                                 \\\n   }                                                                          \\\n}                                                                             \\\n                                                                              \\\nstatic int STB_(N,addset)(TYPE *a, KEY k, VALUE v,                            \\\n                             int allow_new, int allow_old, int copy)          \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask;                                              \\\n   int b = -1;                                                                \\\n   if (CCOMPARE(k,EMPTY)) {                                                   \\\n      if (a->has_empty ? allow_old : allow_new) {                             \\\n          n=a->has_empty; a->ev = v; a->has_empty = 1; return !n;             \\\n      } else return 0;                                                        \\\n   }                                                                          \\\n   if (CCOMPARE(k,DEL)) {                                                     \\\n      if (a->has_del ? allow_old : allow_new) {                               \\\n          n=a->has_del; a->dv = v; a->has_del = 1; return !n;                 \\\n      } else return 0;                                                        \\\n   }                                                                          \\\n   if (!CCOMPARE(a->table[n].k, EMPTY)) {                                     \\\n      unsigned int s;                                                         \\\n      if (CCOMPARE(a->table[n].k, DEL))                                       \\\n         b = n;                                                               \\\n      else if (VCOMPARE(a->table[n].k,k)) {                                   \\\n         if (allow_old)                                                       \\\n            a->table[n].v = v;                                                \\\n         return !allow_new;                                                   \\\n      }                                                                       \\\n      s = stb_rehash(h) | 1;                                                  \\\n      for(;;) {                                                               \\\n         n = (n + s) & a->mask;                                               \\\n         if (CCOMPARE(a->table[n].k, EMPTY)) break;                           \\\n         if (CCOMPARE(a->table[n].k, DEL)) {                                  \\\n            if (b < 0) b = n;                                                 \\\n         } else if (VCOMPARE(a->table[n].k,k)) {                              \\\n            if (allow_old)                                                    \\\n               a->table[n].v = v;                                             \\\n            return !allow_new;                                                \\\n         }                                                                    \\\n      }                                                                       \\\n   }                                                                          \\\n   if (!allow_new) return 0;                                                  \\\n   if (b < 0) b = n; else --a->deleted;                                       \\\n   a->table[b].k = copy ? COPY(k) : k;                                        \\\n   a->table[b].v = v;                                                         \\\n   ++a->count;                                                                \\\n   if (a->count > a->grow_threshhold)                                         \\\n      STB_(N,rehash)(a, a->limit*2);                                          \\\n   return 1;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\\\nPREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\\\nPREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\\\n                                                                              \\\nPREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v)                                \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask, s;                                           \\\n   if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \\\n   if (CCOMPARE(k,DEL))   { if (a->has_del  ) { if(v)*v = a->dv; a->has_del  =0; return 1; } return 0; } \\\n   if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \\\n   if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) {     \\\n      s = stb_rehash(h) | 1;                                                  \\\n      for(;;) {                                                               \\\n         n = (n + s) & a->mask;                                               \\\n         if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                         \\\n         SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;)                    \\\n         if (VCOMPARE(a->table[n].k,k)) break;                                 \\\n      }                                                                       \\\n   }                                                                          \\\n   DISPOSE(a->table[n].k);                                                    \\\n   a->table[n].k = DEL;                                                       \\\n   --a->count;                                                                \\\n   ++a->deleted;                                                              \\\n   if (v != NULL)                                                             \\\n      *v = a->table[n].v;                                                     \\\n   if (a->count < a->shrink_threshhold)                                       \\\n      STB_(N, rehash)(a, a->limit >> 1);                                      \\\n   else if (a->deleted > a->delete_threshhold)                                \\\n      STB_(N, rehash)(a, a->limit);                                           \\\n   return 1;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX TYPE * STB__(NC, copy)(TYPE *a)                                        \\\n{                                                                             \\\n   int i;                                                                     \\\n   TYPE *h = (TYPE *) malloc(sizeof(*h));                                     \\\n   if (!h) return NULL;                                                       \\\n   if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; }                \\\n   h->count = a->count;                                                       \\\n   h->deleted = a->deleted;                                                   \\\n   h->alloced = 1;                                                            \\\n   h->ev = a->ev; h->dv = a->dv;                                              \\\n   h->has_empty = a->has_empty; h->has_del = a->has_del;                      \\\n   memcpy(h->table, a->table, h->limit * sizeof(h->table[0]));                \\\n   for (i=0; i < a->limit; ++i)                                               \\\n      if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL))     \\\n         h->table[i].k = COPY(h->table[i].k);                                 \\\n   return h;                                                                  \\\n}                                                                             \\\n                                                                              \\\nstatic void STB_(N, rehash)(TYPE *a, int count)                               \\\n{                                                                             \\\n   int i;                                                                     \\\n   TYPE b;                                                                    \\\n   STB__(N, init)(&b, count);                                                 \\\n   for (i=0; i < a->limit; ++i)                                               \\\n      if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL))     \\\n         STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0);              \\\n   free(a->table);                                                            \\\n   a->table = b.table;                                                        \\\n   a->mask = b.mask;                                                          \\\n   a->count = b.count;                                                        \\\n   a->limit = b.limit;                                                        \\\n   a->deleted = b.deleted;                                                    \\\n   a->delete_threshhold = b.delete_threshhold;                                \\\n   a->grow_threshhold = b.grow_threshhold;                                    \\\n   a->shrink_threshhold = b.shrink_threshhold;                                \\\n}\n\n#define STB_equal(a,b)  ((a) == (b))\n\n#define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE)                      \\\n   stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f,           \\\n              KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe,               \\\n              STB_equal,STB_equal,HASH,                                       \\\n              VALUE,STB_nonullvalue,0)\n\n#define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL)          \\\n   stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f,           \\\n              KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe,               \\\n              STB_equal,STB_equal,HASH,                                       \\\n              VALUE,STB_nullvalue,VNULL)\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                        stb_ptrmap\n//\n// An stb_ptrmap data structure is an O(1) hash table between pointers. One\n// application is to let you store \"extra\" data associated with pointers,\n// which is why it was originally called stb_extra.\n\nstb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *)\nstb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32)\nstb_declare_hash(STB_EXTERN, stb_uidict, stbi_uidict_, stb_uint32, stb_uint32)\n\nSTB_EXTERN void        stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *));\nSTB_EXTERN stb_ptrmap *stb_ptrmap_new(void);\n\nSTB_EXTERN stb_idict * stb_idict_new_size(int size);\nSTB_EXTERN void        stb_idict_remove_all(stb_idict *e);\nSTB_EXTERN void        stb_uidict_reset(stb_uidict *e);\n\n#ifdef STB_DEFINE\n\n#define STB_EMPTY ((void *) 2)\n#define STB_EDEL  ((void *) 6)\n\nstb_define_hash_base(STB_noprefix,stb_ptrmap, STB_nofields, stb_ptrmap_,stb_ptrmap_,0.85f,\n              void *,STB_EMPTY,STB_EDEL,STB_nocopy,STB_nodelete,STB_nosafe,\n              STB_equal,STB_equal,return stb_hashptr(k);,\n              void *,STB_nullvalue,NULL)\n\nstb_ptrmap *stb_ptrmap_new(void)\n{\n   return stb_ptrmap_create();\n}\n\nvoid stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *))\n{\n   int i;\n   if (free_func)\n      for (i=0; i < e->limit; ++i)\n         if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) {\n            if (free_func == free)\n               free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate\n            else\n               free_func(e->table[i].v);\n         }\n   stb_ptrmap_destroy(e);\n}\n\n// extra fields needed for stua_dict\n#define STB_IEMPTY  ((int) 1)\n#define STB_IDEL    ((int) 3)\nstb_define_hash_base(STB_noprefix, stb_idict, short type; short gc; STB_nofields, stb_idict_,stb_idict_,0.95f,\n              stb_int32,STB_IEMPTY,STB_IDEL,STB_nocopy,STB_nodelete,STB_nosafe,\n              STB_equal,STB_equal,\n              return stb_rehash_improved(k);,stb_int32,STB_nonullvalue,0)\n\nstb_idict * stb_idict_new_size(int size)\n{\n   stb_idict *e = (stb_idict *) malloc(sizeof(*e));\n   if (e) {\n      if (!stb_is_pow2(size))\n         size = 1 << stb_log2_ceil(size);\n      stb_idict_init(e, size);\n      e->alloced = 1;\n   }\n   return e;\n}\n\nvoid stb_idict_remove_all(stb_idict *e)\n{\n   int n;\n   for (n=0; n < e->limit; ++n)\n      e->table[n].k = STB_IEMPTY;\n   e->has_empty = e->has_del = 0;\n   e->count = 0;\n   e->deleted = 0;\n}\n\nstb_define_hash_base(STB_noprefix, stb_uidict, STB_nofields, stb_uidict_,stb_uidict_,0.85f,\n              stb_int32,0xffffffff,0xfffffffe,STB_nocopy,STB_nodelete,STB_nosafe,\n              STB_equal,STB_equal,\n              return stb_rehash_improved(k);,stb_uint32,STB_nonullvalue,0)\n\nvoid stb_uidict_reset(stb_uidict *e)\n{\n   int n;\n   for (n=0; n < e->limit; ++n)\n      e->table[n].k = 0xffffffff;\n   e->has_empty = e->has_del = 0;\n   e->count = 0;\n   e->deleted = 0;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                        stb_sparse_ptr_matrix\n//\n// An stb_ptrmap data structure is an O(1) hash table storing an arbitrary\n// block of data for a given pair of pointers.\n//\n// If create=0, returns\n\ntypedef struct stb__st_stb_spmatrix stb_spmatrix;\n\nSTB_EXTERN stb_spmatrix * stb_sparse_ptr_matrix_new(int val_size);\nSTB_EXTERN void           stb_sparse_ptr_matrix_free(stb_spmatrix *z);\nSTB_EXTERN void         * stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create);\n\n#ifdef STB_DEFINE\ntypedef struct\n{\n   void *a;\n   void *b;\n} stb__ptrpair;\n\nstatic stb__ptrpair stb__ptrpair_empty = { (void *) 1, (void *) 1 };\nstatic stb__ptrpair stb__ptrpair_del   = { (void *) 2, (void *) 2 };\n\n#define STB__equal_ptrpair(x,y) ((x).a == (y).a && (x).b == (y).b)\n\nstb_define_hash_base(STB_noprefix, stb_spmatrix, int val_size; void *arena;, stb__spmatrix_,stb__spmatrix_, 0.85,\n     stb__ptrpair, stb__ptrpair_empty, stb__ptrpair_del,\n     STB_nocopy, STB_nodelete, STB_nosafe,\n     STB__equal_ptrpair, STB__equal_ptrpair, return stb_rehash(stb_hashptr(k.a))+stb_hashptr(k.b);,\n     void *, STB_nullvalue, 0)\n\nstb_spmatrix *stb_sparse_ptr_matrix_new(int val_size)\n{\n   stb_spmatrix *m = stb__spmatrix_create();\n   if (m) m->val_size = val_size;\n   if (m) m->arena = stb_malloc_global(1);\n   return m;\n}\n\nvoid stb_sparse_ptr_matrix_free(stb_spmatrix *z)\n{\n   if (z->arena) stb_free(z->arena);\n   stb__spmatrix_destroy(z);\n}\n\nvoid *stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create)\n{\n   stb__ptrpair t = { a,b };\n   void *data = stb__spmatrix_get(z, t);\n   if (!data && create) {\n      data = stb_malloc_raw(z->arena, z->val_size);\n      if (!data) return NULL;\n      memset(data, 0, z->val_size);\n      stb__spmatrix_add(z, t, data);\n   }\n   return data;\n}\n#endif\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                  SDICT: Hash Table for Strings (symbol table)\n//\n//           if \"use_arena=1\", then strings will be copied\n//           into blocks and never freed until the sdict is freed;\n//           otherwise they're malloc()ed and free()d on the fly.\n//           (specify use_arena=1 if you never stb_sdict_remove)\n\nstb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *)\n\nSTB_EXTERN stb_sdict * stb_sdict_new(int use_arena);\nSTB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*);\nSTB_EXTERN void        stb_sdict_delete(stb_sdict *);\nSTB_EXTERN void *      stb_sdict_change(stb_sdict *, char *str, void *p);\nSTB_EXTERN int         stb_sdict_count(stb_sdict *d);\n\nSTB_EXTERN int         stb_sdict_internal_limit(stb_sdict *d);\nSTB_EXTERN char *      stb_sdict_internal_key(stb_sdict *d, int n);\nSTB_EXTERN void *      stb_sdict_internal_value(stb_sdict *d, int n);\n\n#define stb_sdict_for(d,i,q,z)                                          \\\n   for(i=0; i < stb_sdict_internal_limit(d) ? (q=stb_sdict_internal_key(d,i),z=stb_sdict_internal_value(d,i),1) : 0; ++i)    \\\n      if (q==NULL||q==(void *) 1);else   // reversed makes macro friendly\n\n#ifdef STB_DEFINE\n\n// if in same translation unit, for speed, don't call accessors\n#undef stb_sdict_for\n#define stb_sdict_for(d,i,q,z)                                          \\\n   for(i=0; i < (d)->limit ? (q=(d)->table[i].k,z=(d)->table[i].v,1) : 0; ++i)    \\\n      if (q==NULL||q==(void *) 1);else   // reversed makes macro friendly\n\n#define STB_DEL ((void *) 1)\n#define STB_SDEL  ((char *) 1)\n\n#define stb_sdict__copy(x)                                             \\\n   stb_p_strcpy_s(a->arena ? stb_malloc_string(a->arena, strlen(x)+1)    \\\n                         : (char *) malloc(strlen(x)+1), strlen(x)+1, x)\n\n#define stb_sdict__dispose(x)  if (!a->arena) free(x)\n\nstb_define_hash_base(STB_noprefix, stb_sdict, void*arena;, stb_sdict_,stb_sdictinternal_, 0.85f,\n        char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose,\n                        STB_safecompare, !strcmp, STB_equal, return stb_hash(k);,\n        void *, STB_nullvalue, NULL)\n\nint stb_sdict_count(stb_sdict *a)\n{\n   return a->count;\n}\n\nint stb_sdict_internal_limit(stb_sdict *a)\n{\n   return a->limit;\n}\nchar* stb_sdict_internal_key(stb_sdict *a, int n)\n{\n   return a->table[n].k;\n}\nvoid* stb_sdict_internal_value(stb_sdict *a, int n)\n{\n   return a->table[n].v;\n}\n\nstb_sdict * stb_sdict_new(int use_arena)\n{\n   stb_sdict *d = stb_sdict_create();\n   if (d == NULL) return NULL;\n   d->arena = use_arena ? stb_malloc_global(1) : NULL;\n   return d;\n}\n\nstb_sdict* stb_sdict_copy(stb_sdict *old)\n{\n   stb_sdict *n;\n   void *old_arena = old->arena;\n   void *new_arena = old_arena ? stb_malloc_global(1) : NULL;\n   old->arena = new_arena;\n   n = stb_sdictinternal_copy(old);\n   old->arena = old_arena;\n   if (n)\n      n->arena = new_arena;\n   else if (new_arena)\n      stb_free(new_arena);\n   return n;\n}\n\n\nvoid stb_sdict_delete(stb_sdict *d)\n{\n   if (d->arena)\n      stb_free(d->arena);\n   stb_sdict_destroy(d);\n}\n\nvoid * stb_sdict_change(stb_sdict *d, char *str, void *p)\n{\n   void *q = stb_sdict_get(d, str);\n   stb_sdict_set(d, str, p);\n   return q;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                     Instantiated data structures\n//\n// This is an attempt to implement a templated data structure.\n// What you do is define a struct foo, and then include several\n// pointer fields to struct foo in your struct. Then you call\n// the instantiator, which creates the functions that implement\n// the data structure. This requires massive undebuggable #defines,\n// so we limit the cases where we do this.\n//\n// AA tree is an encoding of a 2-3 tree whereas RB trees encode a 2-3-4 tree;\n// much simpler code due to fewer cases.\n\n#define stb__bst_parent(x)    x\n#define stb__bst_noparent(x)\n\n#define stb_bst_fields(N)                                   \\\n    *STB_(N,left), *STB_(N,right);                          \\\n    unsigned char STB_(N,level)\n\n#define stb_bst_fields_parent(N)                            \\\n    *STB_(N,left), *STB_(N,right),  *STB_(N,parent);        \\\n    unsigned char STB_(N,level)\n\n#define STB__level(N,x)         ((x) ? (x)->STB_(N,level) : 0)\n\n#define stb_bst_base(TYPE, N, TREE, M, compare, PAR)                         \\\n                                                                             \\\nstatic int STB_(N,_compare)(TYPE *p, TYPE *q)                                \\\n{                                                                            \\\n   compare                                                                   \\\n}                                                                            \\\n                                                                             \\\nstatic void STB_(N,setleft)(TYPE *q, TYPE *v)                                \\\n{                                                                            \\\n   q->STB_(N,left) = v;                                                      \\\n   PAR(if (v) v->STB_(N,parent) = q;)                                        \\\n}                                                                            \\\n                                                                             \\\nstatic void STB_(N,setright)(TYPE *q, TYPE *v)                               \\\n{                                                                            \\\n   q->STB_(N,right) = v;                                                     \\\n   PAR(if (v) v->STB_(N,parent) = q;)                                        \\\n}                                                                            \\\n                                                                             \\\nstatic TYPE *STB_(N,skew)(TYPE *q)                                           \\\n{                                                                            \\\n   if (q == NULL) return q;                                                  \\\n   if (q->STB_(N,left)                                                       \\\n        && q->STB_(N,left)->STB_(N,level) == q->STB_(N,level)) {             \\\n      TYPE *p       = q->STB_(N,left);                                       \\\n      STB_(N,setleft)(q, p->STB_(N,right));                                  \\\n      STB_(N,setright)(p, q);                                                \\\n      return p;                                                              \\\n   }                                                                         \\\n   return q;                                                                 \\\n}                                                                            \\\n                                                                             \\\nstatic TYPE *STB_(N,split)(TYPE *p)                                          \\\n{                                                                            \\\n   TYPE *q = p->STB_(N,right);                                               \\\n   if (q && q->STB_(N,right)                                                 \\\n         && q->STB_(N,right)->STB_(N,level) == p->STB_(N,level)) {           \\\n      STB_(N,setright)(p, q->STB_(N,left));                                  \\\n      STB_(N,setleft)(q,p);                                                  \\\n      ++q->STB_(N,level);                                                    \\\n      return q;                                                              \\\n   }                                                                         \\\n   return p;                                                                 \\\n}                                                                            \\\n                                                                             \\\nTYPE *STB__(N,insert)(TYPE *tree, TYPE *item)                                \\\n{                                                                            \\\n   int c;                                                                    \\\n   if (tree == NULL) {                                                       \\\n      item->STB_(N,left) = NULL;                                             \\\n      item->STB_(N,right) = NULL;                                            \\\n      item->STB_(N,level) = 1;                                               \\\n      PAR(item->STB_(N,parent) = NULL;)                                      \\\n      return item;                                                           \\\n   }                                                                         \\\n   c = STB_(N,_compare)(item,tree);                                          \\\n   if (c == 0) {                                                             \\\n      if (item != tree) {                                                    \\\n         STB_(N,setleft)(item, tree->STB_(N,left));                          \\\n         STB_(N,setright)(item, tree->STB_(N,right));                        \\\n         item->STB_(N,level) = tree->STB_(N,level);                          \\\n         PAR(item->STB_(N,parent) = NULL;)                                   \\\n      }                                                                      \\\n      return item;                                                           \\\n   }                                                                         \\\n   if (c < 0)                                                                \\\n      STB_(N,setleft )(tree, STB__(N,insert)(tree->STB_(N,left), item));     \\\n   else                                                                      \\\n      STB_(N,setright)(tree, STB__(N,insert)(tree->STB_(N,right), item));    \\\n   tree = STB_(N,skew)(tree);                                                \\\n   tree = STB_(N,split)(tree);                                               \\\n   PAR(tree->STB_(N,parent) = NULL;)                                         \\\n   return tree;                                                              \\\n}                                                                            \\\n                                                                             \\\nTYPE *STB__(N,remove)(TYPE *tree, TYPE *item)                                \\\n{                                                                            \\\n   static TYPE *delnode, *leaf, *restore;                                    \\\n   if (tree == NULL) return NULL;                                            \\\n   leaf = tree;                                                              \\\n   if (STB_(N,_compare)(item, tree) < 0) {                                   \\\n      STB_(N,setleft)(tree, STB__(N,remove)(tree->STB_(N,left), item));      \\\n   } else {                                                                  \\\n      TYPE *r;                                                               \\\n      delnode = tree;                                                        \\\n      r = STB__(N,remove)(tree->STB_(N,right), item);                        \\\n      /* maybe move 'leaf' up to this location */                            \\\n      if (restore == tree) { tree = leaf; leaf = restore = NULL;  }          \\\n      STB_(N,setright)(tree,r);                                              \\\n      assert(tree->STB_(N,right) != tree);                                   \\\n   }                                                                         \\\n   if (tree == leaf) {                                                       \\\n      if (delnode == item) {                                                 \\\n         tree = tree->STB_(N,right);                                         \\\n         assert(leaf->STB_(N,left) == NULL);                                 \\\n         /* move leaf (the right sibling) up to delnode */                   \\\n         STB_(N,setleft )(leaf, item->STB_(N,left ));                        \\\n         STB_(N,setright)(leaf, item->STB_(N,right));                        \\\n         leaf->STB_(N,level) = item->STB_(N,level);                          \\\n         if (leaf != item)                                                   \\\n            restore = delnode;                                               \\\n      }                                                                      \\\n      delnode = NULL;                                                        \\\n   } else {                                                                  \\\n      if (STB__level(N,tree->STB_(N,left) ) < tree->STB_(N,level)-1 ||       \\\n          STB__level(N,tree->STB_(N,right)) < tree->STB_(N,level)-1) {       \\\n         --tree->STB_(N,level);                                              \\\n         if (STB__level(N,tree->STB_(N,right)) > tree->STB_(N,level))        \\\n            tree->STB_(N,right)->STB_(N,level) = tree->STB_(N,level);        \\\n         tree = STB_(N,skew)(tree);                                          \\\n         STB_(N,setright)(tree, STB_(N,skew)(tree->STB_(N,right)));          \\\n         if (tree->STB_(N,right))                                            \\\n            STB_(N,setright)(tree->STB_(N,right),                            \\\n                  STB_(N,skew)(tree->STB_(N,right)->STB_(N,right)));         \\\n         tree = STB_(N,split)(tree);                                         \\\n         if (tree->STB_(N,right))                                            \\\n            STB_(N,setright)(tree,  STB_(N,split)(tree->STB_(N,right)));     \\\n      }                                                                      \\\n   }                                                                         \\\n   PAR(if (tree) tree->STB_(N,parent) = NULL;)                               \\\n   return tree;                                                              \\\n}                                                                            \\\n                                                                             \\\nTYPE *STB__(N,last)(TYPE *tree)                                              \\\n{                                                                            \\\n   if (tree)                                                                 \\\n      while (tree->STB_(N,right)) tree = tree->STB_(N,right);                \\\n   return tree;                                                              \\\n}                                                                            \\\n                                                                             \\\nTYPE *STB__(N,first)(TYPE *tree)                                             \\\n{                                                                            \\\n   if (tree)                                                                 \\\n      while (tree->STB_(N,left)) tree = tree->STB_(N,left);                  \\\n   return tree;                                                              \\\n}                                                                            \\\n                                                                             \\\nTYPE *STB__(N,next)(TYPE *tree, TYPE *item)                                  \\\n{                                                                            \\\n   TYPE *next = NULL;                                                        \\\n   if (item->STB_(N,right))                                                  \\\n      return STB__(N,first)(item->STB_(N,right));                            \\\n   PAR(                                                                      \\\n      while(item->STB_(N,parent)) {                                          \\\n         TYPE *up = item->STB_(N,parent);                                    \\\n         if (up->STB_(N,left) == item) return up;                            \\\n         item = up;                                                          \\\n      }                                                                      \\\n      return NULL;                                                           \\\n   )                                                                         \\\n   while (tree != item) {                                                    \\\n      if (STB_(N,_compare)(item, tree) < 0) {                                \\\n         next = tree;                                                        \\\n         tree = tree->STB_(N,left);                                          \\\n      } else {                                                               \\\n         tree = tree->STB_(N,right);                                         \\\n      }                                                                      \\\n   }                                                                         \\\n   return next;                                                              \\\n}                                                                            \\\n                                                                             \\\nTYPE *STB__(N,prev)(TYPE *tree, TYPE *item)                                  \\\n{                                                                            \\\n   TYPE *next = NULL;                                                        \\\n   if (item->STB_(N,left))                                                   \\\n      return STB__(N,last)(item->STB_(N,left));                              \\\n   PAR(                                                                      \\\n      while(item->STB_(N,parent)) {                                          \\\n         TYPE *up = item->STB_(N,parent);                                    \\\n         if (up->STB_(N,right) == item) return up;                           \\\n         item = up;                                                          \\\n      }                                                                      \\\n      return NULL;                                                           \\\n   )                                                                         \\\n   while (tree != item) {                                                    \\\n      if (STB_(N,_compare)(item, tree) < 0) {                                \\\n         tree = tree->STB_(N,left);                                          \\\n      } else {                                                               \\\n         next = tree;                                                        \\\n         tree = tree->STB_(N,right);                                         \\\n      }                                                                      \\\n   }                                                                         \\\n   return next;                                                              \\\n}                                                                            \\\n                                                                             \\\nSTB__DEBUG(                                                                  \\\n   void STB__(N,_validate)(TYPE *tree, int root)                             \\\n   {                                                                         \\\n      if (tree == NULL) return;                                              \\\n      PAR(if(root) assert(tree->STB_(N,parent) == NULL);)                    \\\n      assert(STB__level(N,tree->STB_(N,left) ) == tree->STB_(N,level)-1);    \\\n      assert(STB__level(N,tree->STB_(N,right)) <= tree->STB_(N,level));      \\\n      assert(STB__level(N,tree->STB_(N,right)) >= tree->STB_(N,level)-1);    \\\n      if (tree->STB_(N,right)) {                                             \\\n        assert(STB__level(N,tree->STB_(N,right)->STB_(N,right))              \\\n                                               !=    tree->STB_(N,level));   \\\n        PAR(assert(tree->STB_(N,right)->STB_(N,parent) == tree);)            \\\n      }                                                                      \\\n      PAR(if(tree->STB_(N,left)) assert(tree->STB_(N,left)->STB_(N,parent) == tree);) \\\n      STB__(N,_validate)(tree->STB_(N,left) ,0);                             \\\n      STB__(N,_validate)(tree->STB_(N,right),0);                             \\\n   }                                                                         \\\n)                                                                            \\\n                                                                             \\\ntypedef struct                                                               \\\n{                                                                            \\\n   TYPE *root;                                                               \\\n} TREE;                                                                      \\\n                                                                             \\\nvoid  STB__(M,Insert)(TREE *tree, TYPE *item)                                \\\n{ tree->root = STB__(N,insert)(tree->root, item); }                          \\\nvoid  STB__(M,Remove)(TREE *tree, TYPE *item)                                \\\n{ tree->root = STB__(N,remove)(tree->root, item); }                          \\\nTYPE *STB__(M,Next)(TREE *tree, TYPE *item)                                  \\\n{ return STB__(N,next)(tree->root, item); }                                  \\\nTYPE *STB__(M,Prev)(TREE *tree, TYPE *item)                                  \\\n{ return STB__(N,prev)(tree->root, item); }                                  \\\nTYPE *STB__(M,First)(TREE *tree) { return STB__(N,first)(tree->root); }      \\\nTYPE *STB__(M,Last) (TREE *tree) { return STB__(N,last) (tree->root); }      \\\nvoid STB__(M,Init)(TREE *tree) { tree->root = NULL; }\n\n\n#define stb_bst_find(N,tree,fcompare)                                        \\\n{                                                                            \\\n   int c;                                                                    \\\n   while (tree != NULL) {                                                    \\\n      fcompare                                                               \\\n      if (c == 0) return tree;                                               \\\n      if (c < 0)  tree = tree->STB_(N,left);                                 \\\n      else        tree = tree->STB_(N,right);                                \\\n   }                                                                         \\\n   return NULL;                                                              \\\n}\n\n#define stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,PAR)                  \\\n   stb_bst_base(TYPE,N,TREE,M,                                               \\\n         VTYPE a = p->vfield; VTYPE b = q->vfield; return (compare);, PAR )  \\\n                                                                             \\\nTYPE *STB__(N,find)(TYPE *tree, VTYPE a)                                     \\\n   stb_bst_find(N,tree,VTYPE b = tree->vfield; c = (compare);)               \\\nTYPE *STB__(M,Find)(TREE *tree, VTYPE a)                                     \\\n{ return STB__(N,find)(tree->root, a); }\n\n#define stb_bst(TYPE,N,TREE,M,vfield,VTYPE,compare) \\\n   stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_noparent)\n#define stb_bst_parent(TYPE,N,TREE,M,vfield,VTYPE,compare) \\\n   stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_parent)\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                             Pointer Nulling\n//\n//  This lets you automatically NULL dangling pointers to \"registered\"\n//  objects. Note that you have to make sure you call the appropriate\n//  functions when you free or realloc blocks of memory that contain\n//  pointers or pointer targets. stb.h can automatically do this for\n//  stb_arr, or for all frees/reallocs if it's wrapping them.\n//\n\n#ifdef STB_NPTR\n\nSTB_EXTERN void stb_nptr_set(void *address_of_pointer, void *value_to_write);\nSTB_EXTERN void stb_nptr_didset(void *address_of_pointer);\n\nSTB_EXTERN void stb_nptr_didfree(void *address_being_freed, int len);\nSTB_EXTERN void stb_nptr_free(void *address_being_freed, int len);\n\nSTB_EXTERN void stb_nptr_didrealloc(void *new_address, void *old_address, int len);\nSTB_EXTERN void stb_nptr_recache(void); // recache all known pointers\n                                       // do this after pointer sets outside your control, slow\n\n#ifdef STB_DEFINE\n// for fast updating on free/realloc, we need to be able to find\n// all the objects (pointers and targets) within a given block;\n// this precludes hashing\n\n// we use a three-level hierarchy of memory to minimize storage:\n//   level 1: 65536 pointers to stb__memory_node (always uses 256 KB)\n//   level 2: each stb__memory_node represents a 64K block of memory\n//            with 256 stb__memory_leafs (worst case 64MB)\n//   level 3: each stb__memory_leaf represents 256 bytes of memory\n//            using a list of target locations and a list of pointers\n//            (which are hopefully fairly short normally!)\n\n// this approach won't work in 64-bit, which has a much larger address\n// space. need to redesign\n\n#define STB__NPTR_ROOT_LOG2   16\n#define STB__NPTR_ROOT_NUM    (1 << STB__NPTR_ROOT_LOG2)\n#define STB__NPTR_ROOT_SHIFT  (32 - STB__NPTR_ROOT_LOG2)\n\n#define STB__NPTR_NODE_LOG2   5\n#define STB__NPTR_NODE_NUM    (1 << STB__NPTR_NODE_LOG2)\n#define STB__NPTR_NODE_MASK   (STB__NPTR_NODE_NUM-1)\n#define STB__NPTR_NODE_SHIFT  (STB__NPTR_ROOT_SHIFT - STB__NPTR_NODE_LOG2)\n#define STB__NPTR_NODE_OFFSET(x)   (((x) >> STB__NPTR_NODE_SHIFT) & STB__NPTR_NODE_MASK)\n\ntypedef struct stb__st_nptr\n{\n   void *ptr;   // address of actual pointer\n   struct stb__st_nptr *next;   // next pointer with same target\n   struct stb__st_nptr **prev;  // prev pointer with same target, address of 'next' field (or first)\n   struct stb__st_nptr *next_in_block;\n} stb__nptr;\n\ntypedef struct stb__st_nptr_target\n{\n   void *ptr;   // address of target\n   stb__nptr *first; // address of first nptr pointing to this\n   struct stb__st_nptr_target *next_in_block;\n} stb__nptr_target;\n\ntypedef struct\n{\n   stb__nptr *pointers;\n   stb__nptr_target *targets;\n} stb__memory_leaf;\n\ntypedef struct\n{\n   stb__memory_leaf *children[STB__NPTR_NODE_NUM];\n} stb__memory_node;\n\nstb__memory_node *stb__memtab_root[STB__NPTR_ROOT_NUM];\n\nstatic stb__memory_leaf *stb__nptr_find_leaf(void *mem)\n{\n   stb_uint32 address = (stb_uint32) mem;\n   stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];\n   if (z)\n      return z->children[STB__NPTR_NODE_OFFSET(address)];\n   else\n      return NULL;\n}\n\nstatic void * stb__nptr_alloc(int size)\n{\n   return stb__realloc_raw(0,size);\n}\n\nstatic void stb__nptr_free(void *p)\n{\n   stb__realloc_raw(p,0);\n}\n\nstatic stb__memory_leaf *stb__nptr_make_leaf(void *mem)\n{\n   stb_uint32 address = (stb_uint32) mem;\n   stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];\n   stb__memory_leaf *f;\n   if (!z) {\n      int i;\n      z = (stb__memory_node *) stb__nptr_alloc(sizeof(*stb__memtab_root[0]));\n      stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT] = z;\n      for (i=0; i < 256; ++i)\n         z->children[i] = 0;\n   }\n   f = (stb__memory_leaf *) stb__nptr_alloc(sizeof(*f));\n   z->children[STB__NPTR_NODE_OFFSET(address)] = f;\n   f->pointers = NULL;\n   f->targets = NULL;\n   return f;\n}\n\nstatic stb__nptr_target *stb__nptr_find_target(void *target, int force)\n{\n   stb__memory_leaf *p = stb__nptr_find_leaf(target);\n   if (p) {\n      stb__nptr_target *t = p->targets;\n      while (t) {\n         if (t->ptr == target)\n            return t;\n         t = t->next_in_block;\n      }\n   }\n   if (force) {\n      stb__nptr_target *t = (stb__nptr_target*) stb__nptr_alloc(sizeof(*t));\n      if (!p) p = stb__nptr_make_leaf(target);\n      t->ptr = target;\n      t->first = NULL;\n      t->next_in_block = p->targets;\n      p->targets = t;\n      return t;\n   } else\n      return NULL;\n}\n\nstatic stb__nptr *stb__nptr_find_pointer(void *ptr, int force)\n{\n   stb__memory_leaf *p = stb__nptr_find_leaf(ptr);\n   if (p) {\n      stb__nptr *t = p->pointers;\n      while (t) {\n         if (t->ptr == ptr)\n            return t;\n         t = t->next_in_block;\n      }\n   }\n   if (force) {\n      stb__nptr *t = (stb__nptr *) stb__nptr_alloc(sizeof(*t));\n      if (!p) p = stb__nptr_make_leaf(ptr);\n      t->ptr = ptr;\n      t->next = NULL;\n      t->prev = NULL;\n      t->next_in_block = p->pointers;\n      p->pointers = t;\n      return t;\n   } else\n      return NULL;\n}\n\nvoid stb_nptr_set(void *address_of_pointer, void *value_to_write)\n{\n   if (*(void **)address_of_pointer != value_to_write) {\n      *(void **) address_of_pointer = value_to_write;\n      stb_nptr_didset(address_of_pointer);\n   }\n}\n\nvoid stb_nptr_didset(void *address_of_pointer)\n{\n   // first unlink from old chain\n   void *new_address;\n   stb__nptr *p = stb__nptr_find_pointer(address_of_pointer, 1); // force building if doesn't exist\n   if (p->prev) { // if p->prev is NULL, we just built it, or it was NULL\n      *(p->prev) = p->next;\n      if (p->next) p->next->prev = p->prev;\n   }\n   // now add to new chain\n   new_address = *(void **)address_of_pointer;\n   if (new_address != NULL) {\n      stb__nptr_target *t = stb__nptr_find_target(new_address, 1);\n      p->next = t->first;\n      if (p->next) p->next->prev = &p->next;\n      p->prev = &t->first;\n      t->first = p;\n   } else {\n      p->prev = NULL;\n      p->next = NULL;\n   }\n}\n\nvoid stb__nptr_block(void *address, int len, void (*function)(stb__memory_leaf *f, int datum, void *start, void *end), int datum)\n{\n   void *end_address = (void *) ((char *) address + len - 1);\n   stb__memory_node *n;\n   stb_uint32 start = (stb_uint32) address;\n   stb_uint32 end   = start + len - 1;\n\n   int b0 = start >> STB__NPTR_ROOT_SHIFT;\n   int b1 = end >> STB__NPTR_ROOT_SHIFT;\n   int b=b0,i,e0,e1;\n\n   e0 = STB__NPTR_NODE_OFFSET(start);\n\n   if (datum <= 0) {\n      // first block\n      n = stb__memtab_root[b0];\n      if (n) {\n         if (b0 != b1)\n            e1 = STB__NPTR_NODE_NUM-1;\n         else\n            e1 = STB__NPTR_NODE_OFFSET(end);\n         for (i=e0; i <= e1; ++i)\n            if (n->children[i])\n               function(n->children[i], datum, address, end_address);\n      }\n      if (b1 > b0) {\n         // blocks other than the first and last block\n         for (b=b0+1; b < b1; ++b) {\n            n = stb__memtab_root[b];\n            if (n)\n               for (i=0; i <= STB__NPTR_NODE_NUM-1; ++i)\n                  if (n->children[i])\n                     function(n->children[i], datum, address, end_address);\n         }\n         // last block\n         n = stb__memtab_root[b1];\n         if (n) {\n            e1 = STB__NPTR_NODE_OFFSET(end);\n            for (i=0; i <= e1; ++i)\n               if (n->children[i])\n                  function(n->children[i], datum, address, end_address);\n         }\n      }\n   } else {\n      if (b1 > b0) {\n         // last block\n         n = stb__memtab_root[b1];\n         if (n) {\n            e1 = STB__NPTR_NODE_OFFSET(end);\n            for (i=e1; i >= 0; --i)\n               if (n->children[i])\n                  function(n->children[i], datum, address, end_address);\n         }\n         // blocks other than the first and last block\n         for (b=b1-1; b > b0; --b) {\n            n = stb__memtab_root[b];\n            if (n)\n               for (i=STB__NPTR_NODE_NUM-1; i >= 0; --i)\n                  if (n->children[i])\n                     function(n->children[i], datum, address, end_address);\n         }\n      }\n      // first block\n      n = stb__memtab_root[b0];\n      if (n) {\n         if (b0 != b1)\n            e1 = STB__NPTR_NODE_NUM-1;\n         else\n            e1 = STB__NPTR_NODE_OFFSET(end);\n         for (i=e1; i >= e0; --i)\n            if (n->children[i])\n               function(n->children[i], datum, address, end_address);\n      }\n   }\n}\n\nstatic void stb__nptr_delete_pointers(stb__memory_leaf *f, int offset, void *start, void *end)\n{\n   stb__nptr **p = &f->pointers;\n   while (*p) {\n      stb__nptr *n = *p;\n      if (n->ptr >= start && n->ptr <= end) {\n         // unlink\n         if (n->prev) {\n            *(n->prev) = n->next;\n            if (n->next) n->next->prev = n->prev;\n         }\n         *p = n->next_in_block;\n         stb__nptr_free(n);\n      } else\n         p = &(n->next_in_block);\n   }\n}\n\nstatic void stb__nptr_delete_targets(stb__memory_leaf *f, int offset, void *start, void *end)\n{\n   stb__nptr_target **p = &f->targets;\n   while (*p) {\n      stb__nptr_target *n = *p;\n      if (n->ptr >= start && n->ptr <= end) {\n         // null pointers\n         stb__nptr *z = n->first;\n         while (z) {\n            stb__nptr *y = z->next;\n            z->prev = NULL;\n            z->next = NULL;\n            *(void **) z->ptr = NULL;\n            z = y;\n         }\n         // unlink this target\n         *p = n->next_in_block;\n         stb__nptr_free(n);\n      } else\n         p = &(n->next_in_block);\n   }\n}\n\nvoid stb_nptr_didfree(void *address_being_freed, int len)\n{\n   // step one: delete all pointers in this block\n   stb__nptr_block(address_being_freed, len, stb__nptr_delete_pointers, 0);\n   // step two: NULL all pointers to this block; do this second to avoid NULLing deleted pointers\n   stb__nptr_block(address_being_freed, len, stb__nptr_delete_targets, 0);\n}\n\nvoid stb_nptr_free(void *address_being_freed, int len)\n{\n   free(address_being_freed);\n   stb_nptr_didfree(address_being_freed, len);\n}\n\nstatic void stb__nptr_move_targets(stb__memory_leaf *f, int offset, void *start, void *end)\n{\n   stb__nptr_target **t = &f->targets;\n   while (*t) {\n      stb__nptr_target *n = *t;\n      if (n->ptr >= start && n->ptr <= end) {\n         stb__nptr *z;\n         stb__memory_leaf *f;\n         // unlink n\n         *t = n->next_in_block;\n         // update n to new address\n         n->ptr = (void *) ((char *) n->ptr + offset);\n         f = stb__nptr_find_leaf(n->ptr);\n         if (!f) f = stb__nptr_make_leaf(n->ptr);\n         n->next_in_block = f->targets;\n         f->targets = n;\n         // now go through all pointers and make them point here\n         z = n->first;\n         while (z) {\n            *(void**) z->ptr = n->ptr;\n            z = z->next;\n         }\n      } else\n         t = &(n->next_in_block);\n   }\n}\n\nstatic void stb__nptr_move_pointers(stb__memory_leaf *f, int offset, void *start, void *end)\n{\n   stb__nptr **p = &f->pointers;\n   while (*p) {\n      stb__nptr *n = *p;\n      if (n->ptr >= start && n->ptr <= end) {\n         // unlink\n         *p = n->next_in_block;\n         n->ptr = (void *) ((int) n->ptr + offset);\n         // move to new block\n         f = stb__nptr_find_leaf(n->ptr);\n         if (!f) f = stb__nptr_make_leaf(n->ptr);\n         n->next_in_block = f->pointers;\n         f->pointers = n;\n      } else\n         p = &(n->next_in_block);\n   }\n}\n\nvoid stb_nptr_realloc(void *new_address, void *old_address, int len)\n{\n   if (new_address == old_address) return;\n\n   // have to move the pointers first, because moving the targets\n   //      requires writing to the pointers-to-the-targets, and if some of those moved too,\n   //      we need to make sure we don't write to the old memory\n\n   // step one: move all pointers within the block\n   stb__nptr_block(old_address, len, stb__nptr_move_pointers, (char *) new_address - (char *) old_address);\n   // step two: move all targets within the block\n   stb__nptr_block(old_address, len, stb__nptr_move_targets, (char *) new_address - (char *) old_address);\n}\n\nvoid stb_nptr_move(void *new_address, void *old_address)\n{\n   stb_nptr_realloc(new_address, old_address, 1);\n}\n\nvoid stb_nptr_recache(void)\n{\n   int i,j;\n   for (i=0; i < STB__NPTR_ROOT_NUM; ++i)\n      if (stb__memtab_root[i])\n         for (j=0; j < STB__NPTR_NODE_NUM; ++j)\n            if (stb__memtab_root[i]->children[j]) {\n               stb__nptr *p = stb__memtab_root[i]->children[j]->pointers;\n               while (p) {\n                  stb_nptr_didset(p->ptr);\n                  p = p->next_in_block;\n               }\n            }\n}\n\n#endif // STB_DEFINE\n#endif // STB_NPTR\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                             File Processing\n//\n\n\n#ifdef _WIN32\n  #define stb_rename(x,y)   _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))\n#else\n  #define stb_rename   rename\n#endif\n\nSTB_EXTERN void     stb_fput_varlen64(FILE *f, stb_uint64 v);\nSTB_EXTERN stb_uint64  stb_fget_varlen64(FILE *f);\nSTB_EXTERN int      stb_size_varlen64(stb_uint64 v);\n\n\n#define stb_filec    (char *) stb_file\n#define stb_fileu    (unsigned char *) stb_file\nSTB_EXTERN void *  stb_file(char *filename, size_t *length);\nSTB_EXTERN void *  stb_file_max(char *filename, size_t *length);\nSTB_EXTERN size_t  stb_filelen(FILE *f);\nSTB_EXTERN int     stb_filewrite(char *filename, void *data, size_t length);\nSTB_EXTERN int     stb_filewritestr(char *filename, char *data);\nSTB_EXTERN char ** stb_stringfile(char *filename, int *len);\nSTB_EXTERN char ** stb_stringfile_trimmed(char *name, int *len, char comm);\nSTB_EXTERN char *  stb_fgets(char *buffer, int buflen, FILE *f);\nSTB_EXTERN char *  stb_fgets_malloc(FILE *f);\nSTB_EXTERN int     stb_fexists(char *filename);\nSTB_EXTERN int     stb_fcmp(char *s1, char *s2);\nSTB_EXTERN int     stb_feq(char *s1, char *s2);\nSTB_EXTERN time_t  stb_ftimestamp(char *filename);\n\nSTB_EXTERN int     stb_fullpath(char *abs, int abs_size, char *rel);\nSTB_EXTERN FILE *  stb_fopen(char *filename, const char *mode);\nSTB_EXTERN int     stb_fclose(FILE *f, int keep);\n\nenum\n{\n   stb_keep_no = 0,\n   stb_keep_yes = 1,\n   stb_keep_if_different = 2,\n};\n\nSTB_EXTERN int     stb_copyfile(char *src, char *dest);\n\nSTB_EXTERN void     stb_fput_varlen64(FILE *f, stb_uint64 v);\nSTB_EXTERN stb_uint64  stb_fget_varlen64(FILE *f);\nSTB_EXTERN int      stb_size_varlen64(stb_uint64 v);\n\nSTB_EXTERN void    stb_fwrite32(FILE *f, stb_uint32 datum);\nSTB_EXTERN void    stb_fput_varlen (FILE *f, int v);\nSTB_EXTERN void    stb_fput_varlenu(FILE *f, unsigned int v);\nSTB_EXTERN int     stb_fget_varlen (FILE *f);\nSTB_EXTERN stb_uint stb_fget_varlenu(FILE *f);\nSTB_EXTERN void    stb_fput_ranged (FILE *f, int v, int b, stb_uint n);\nSTB_EXTERN int     stb_fget_ranged (FILE *f, int b, stb_uint n);\nSTB_EXTERN int     stb_size_varlen (int v);\nSTB_EXTERN int     stb_size_varlenu(unsigned int v);\nSTB_EXTERN int     stb_size_ranged (int b, stb_uint n);\n\nSTB_EXTERN int     stb_fread(void *data, size_t len, size_t count, void *f);\nSTB_EXTERN int     stb_fwrite(void *data, size_t len, size_t count, void *f);\n\n#if 0\ntypedef struct\n{\n   FILE  *base_file;\n   char  *buffer;\n   int    buffer_size;\n   int    buffer_off;\n   int    buffer_left;\n} STBF;\n\nSTB_EXTERN STBF *stb_tfopen(char *filename, char *mode);\nSTB_EXTERN int stb_tfread(void *data, size_t len, size_t count, STBF *f);\nSTB_EXTERN int stb_tfwrite(void *data, size_t len, size_t count, STBF *f);\n#endif\n\n#ifdef STB_DEFINE\n\n#if 0\nSTBF *stb_tfopen(char *filename, char *mode)\n{\n   STBF *z;\n   FILE *f = stb_p_fopen(filename, mode);\n   if (!f) return NULL;\n   z = (STBF *) malloc(sizeof(*z));\n   if (!z) { fclose(f); return NULL; }\n   z->base_file = f;\n   if (!strcmp(mode, \"rb\") || !strcmp(mode, \"wb\")) {\n      z->buffer_size = 4096;\n      z->buffer_off = z->buffer_size;\n      z->buffer_left = 0;\n      z->buffer = malloc(z->buffer_size);\n      if (!z->buffer) { free(z); fclose(f); return NULL; }\n   } else {\n      z->buffer = 0;\n      z->buffer_size = 0;\n      z->buffer_left = 0;\n   }\n   return z;\n}\n\nint stb_tfread(void *data, size_t len, size_t count, STBF *f)\n{\n   int total = len*count, done=0;\n   if (!total) return 0;\n   if (total <= z->buffer_left) {\n      memcpy(data, z->buffer + z->buffer_off, total);\n      z->buffer_off += total;\n      z->buffer_left -= total;\n      return count;\n   } else {\n      char *out = (char *) data;\n\n      // consume all buffered data\n      memcpy(data, z->buffer + z->buffer_off, z->buffer_left);\n      done = z->buffer_left;\n      out += z->buffer_left;\n      z->buffer_left=0;\n\n      if (total-done > (z->buffer_size >> 1)) {\n         done += fread(out\n      }\n   }\n}\n#endif\n\nvoid stb_fwrite32(FILE *f, stb_uint32 x)\n{\n   fwrite(&x, 4, 1, f);\n}\n\n#if defined(_WIN32)\n   #define stb__stat   _stat\n#else\n   #define stb__stat   stat\n#endif\n\nint stb_fexists(char *filename)\n{\n   struct stb__stat buf;\n   return stb__windows(\n             _wstat((const wchar_t *)stb__from_utf8(filename), &buf),\n               stat(filename,&buf)\n          ) == 0;\n}\n\ntime_t stb_ftimestamp(char *filename)\n{\n   struct stb__stat buf;\n   if (stb__windows(\n             _wstat((const wchar_t *)stb__from_utf8(filename), &buf),\n               stat(filename,&buf)\n          ) == 0)\n   {\n      return buf.st_mtime;\n   } else {\n      return 0;\n   }\n}\n\nsize_t  stb_filelen(FILE *f)\n{\n   long len, pos;\n   pos = ftell(f);\n   fseek(f, 0, SEEK_END);\n   len = ftell(f);\n   fseek(f, pos, SEEK_SET);\n   return (size_t) len;\n}\n\nvoid *stb_file(char *filename, size_t *length)\n{\n   FILE *f = stb__fopen(filename, \"rb\");\n   char *buffer;\n   size_t len, len2;\n   if (!f) return NULL;\n   len = stb_filelen(f);\n   buffer = (char *) malloc(len+2); // nul + extra\n   len2 = fread(buffer, 1, len, f);\n   if (len2 == len) {\n      if (length) *length = len;\n      buffer[len] = 0;\n   } else {\n      free(buffer);\n      buffer = NULL;\n   }\n   fclose(f);\n   return buffer;\n}\n\nint stb_filewrite(char *filename, void *data, size_t length)\n{\n   FILE *f = stb_fopen(filename, \"wb\");\n   if (f) {\n      unsigned char *data_ptr = (unsigned char *) data;\n      size_t remaining = length;\n      while (remaining > 0) {\n         size_t len2 = remaining > 65536 ? 65536 : remaining;\n         size_t len3 = fwrite(data_ptr, 1, len2, f);\n         if (len2 != len3) {\n            fprintf(stderr, \"Failed while writing %s\\n\", filename);\n            break;\n         }\n         remaining -= len2;\n         data_ptr += len2;\n      }\n      stb_fclose(f, stb_keep_if_different);\n   }\n   return f != NULL;\n}\n\nint stb_filewritestr(char *filename, char *data)\n{\n   return stb_filewrite(filename, data, strlen(data));\n}\n\nvoid *  stb_file_max(char *filename, size_t *length)\n{\n   FILE *f = stb__fopen(filename, \"rb\");\n   char *buffer;\n   size_t len, maxlen;\n   if (!f) return NULL;\n   maxlen = *length;\n   buffer = (char *) malloc(maxlen+1);\n   len = fread(buffer, 1, maxlen, f);\n   buffer[len] = 0;\n   fclose(f);\n   *length = len;\n   return buffer;\n}\n\nchar ** stb_stringfile(char *filename, int *plen)\n{\n   FILE *f = stb__fopen(filename, \"rb\");\n   char *buffer, **list=NULL, *s;\n   size_t len, count, i;\n\n   if (!f) return NULL;\n   len = stb_filelen(f);\n   buffer = (char *) malloc(len+1);\n   len = fread(buffer, 1, len, f);\n   buffer[len] = 0;\n   fclose(f);\n\n   // two passes through: first time count lines, second time set them\n   for (i=0; i < 2; ++i) {\n      s = buffer;\n      if (i == 1)\n         list[0] = s;\n      count = 1;\n      while (*s) {\n         if (*s == '\\n' || *s == '\\r') {\n            // detect if both cr & lf are together\n            int crlf = (s[0] + s[1]) == ('\\n' + '\\r');\n            if (i == 1) *s = 0;\n            if (crlf) ++s;\n            if (s[1]) {  // it's not over yet\n               if (i == 1) list[count] = s+1;\n               ++count;\n            }\n         }\n         ++s;\n      }\n      if (i == 0) {\n         list = (char **) malloc(sizeof(*list) * (count+1) + len+1);\n         if (!list) return NULL;\n         list[count] = 0;\n         // recopy the file so there's just a single allocation to free\n         memcpy(&list[count+1], buffer, len+1);\n         free(buffer);\n         buffer = (char *) &list[count+1];\n         if (plen) *plen = (int) count;\n      }\n   }\n   return list;\n}\n\nchar ** stb_stringfile_trimmed(char *name, int *len, char comment)\n{\n   int i,n,o=0;\n   char **s = stb_stringfile(name, &n);\n   if (s == NULL) return NULL;\n   for (i=0; i < n; ++i) {\n      char *p = stb_skipwhite(s[i]);\n      if (*p && *p != comment)\n         s[o++] = p;\n   }\n   s[o] = NULL;\n   if (len) *len = o;\n   return s;\n}\n\nchar * stb_fgets(char *buffer, int buflen, FILE *f)\n{\n   char *p;\n   buffer[0] = 0;\n   p = fgets(buffer, buflen, f);\n   if (p) {\n      int n = (int) (strlen(p)-1);\n      if (n >= 0)\n         if (p[n] == '\\n')\n            p[n] = 0;\n   }\n   return p;\n}\n\nchar * stb_fgets_malloc(FILE *f)\n{\n   // avoid reallocing for small strings\n   char quick_buffer[800];\n   quick_buffer[sizeof(quick_buffer)-2] = 0;\n   if (!fgets(quick_buffer, sizeof(quick_buffer), f))\n      return NULL;\n\n   if (quick_buffer[sizeof(quick_buffer)-2] == 0) {\n      size_t n = strlen(quick_buffer);\n      if (n > 0 && quick_buffer[n-1] == '\\n')\n         quick_buffer[n-1] = 0;\n      return stb_p_strdup(quick_buffer);\n   } else {\n      char *p;\n      char *a = stb_p_strdup(quick_buffer);\n      size_t len = sizeof(quick_buffer)-1;\n\n      while (!feof(f)) {\n         if (a[len-1] == '\\n') break;\n         a = (char *) realloc(a, len*2);\n         p = &a[len];\n         p[len-2] = 0;\n         if (!fgets(p, (int) len, f))\n            break;\n         if (p[len-2] == 0) {\n            len += strlen(p);\n            break;\n         }\n         len = len + (len-1);\n      }\n      if (a[len-1] == '\\n')\n         a[len-1] = 0;\n      return a;\n   }\n}\n\nint stb_fullpath(char *abs, int abs_size, char *rel)\n{\n   #ifdef _WIN32\n   return _fullpath(abs, rel, abs_size) != NULL;\n   #else\n   if (rel[0] == '/' || rel[0] == '~') {\n      if ((int) strlen(rel) >= abs_size)\n         return 0;\n      stb_p_strcpy_s(abs,65536,rel);\n      return STB_TRUE;\n   } else {\n      int n;\n      getcwd(abs, abs_size);\n      n = strlen(abs);\n      if (n+(int) strlen(rel)+2 <= abs_size) {\n         abs[n] = '/';\n         stb_p_strcpy_s(abs+n+1, 65536,rel);\n         return STB_TRUE;\n      } else {\n         return STB_FALSE;\n      }\n   }\n   #endif\n}\n\nstatic int stb_fcmp_core(FILE *f, FILE *g)\n{\n   char buf1[1024],buf2[1024];\n   int n1,n2, res=0;\n\n   while (1) {\n      n1 = (int) fread(buf1, 1, sizeof(buf1), f);\n      n2 = (int) fread(buf2, 1, sizeof(buf2), g);\n      res = memcmp(buf1,buf2,stb_min(n1,n2));\n      if (res)\n         break;\n      if (n1 != n2) {\n         res = n1 < n2 ? -1 : 1;\n         break;\n      }\n      if (n1 == 0)\n         break;\n   }\n\n   fclose(f);\n   fclose(g);\n   return res;\n}\n\nint stb_fcmp(char *s1, char *s2)\n{\n   FILE *f = stb__fopen(s1, \"rb\");\n   FILE *g = stb__fopen(s2, \"rb\");\n\n   if (f == NULL || g == NULL) {\n      if (f) fclose(f);\n      if (g) {\n         fclose(g);\n         return STB_TRUE;\n      }\n      return f != NULL;\n   }\n\n   return stb_fcmp_core(f,g);\n}\n\nint stb_feq(char *s1, char *s2)\n{\n   FILE *f = stb__fopen(s1, \"rb\");\n   FILE *g = stb__fopen(s2, \"rb\");\n\n   if (f == NULL || g == NULL) {\n      if (f) fclose(f);\n      if (g) fclose(g);\n      return f == g;\n   }\n\n   // feq is faster because it shortcuts if they're different length\n   if (stb_filelen(f) != stb_filelen(g)) {\n      fclose(f);\n      fclose(g);\n      return 0;\n   }\n\n   return !stb_fcmp_core(f,g);\n}\n\nstatic stb_ptrmap *stb__files;\n\ntypedef struct\n{\n   char *temp_name;\n   char *name;\n   int   errors;\n} stb__file_data;\n\nstatic FILE *stb__open_temp_file(char *temp_name, char *src_name, const char *mode)\n{\n   size_t p;\n#ifdef _MSC_VER\n   int j;\n#endif\n   FILE *f;\n   // try to generate a temporary file in the same directory\n   p = strlen(src_name)-1;\n   while (p > 0 && src_name[p] != '/' && src_name[p] != '\\\\'\n                && src_name[p] != ':' && src_name[p] != '~')\n      --p;\n   ++p;\n\n   memcpy(temp_name, src_name, p);\n\n   #ifdef _MSC_VER\n   // try multiple times to make a temp file... just in\n   // case some other process makes the name first\n   for (j=0; j < 32; ++j) {\n      stb_p_strcpy_s(temp_name+p, 65536, \"stmpXXXXXX\");\n      if (!stb_p_mktemp(temp_name))\n         return 0;\n\n      f = stb_p_fopen(temp_name, mode);\n      if (f != NULL)\n         break;\n   }\n   #else\n   {\n      stb_p_strcpy_s(temp_name+p, 65536, \"stmpXXXXXX\");\n      #ifdef __MINGW32__\n         int fd = open(stb_p_mktemp(temp_name), O_RDWR);\n      #else\n         int fd = mkstemp(temp_name);\n      #endif\n      if (fd == -1) return NULL;\n      f = fdopen(fd, mode);\n      if (f == NULL) {\n         unlink(temp_name);\n         close(fd);\n         return NULL;\n      }\n   }\n   #endif\n   return f;\n}\n\n\nFILE *  stb_fopen(char *filename, const char *mode)\n{\n   FILE *f;\n   char name_full[4096];\n   char temp_full[sizeof(name_full) + 12];\n\n   // @TODO: if the file doesn't exist, we can also use the fastpath here\n   if (mode[0] != 'w' && !strchr(mode, '+'))\n      return stb__fopen(filename, mode);\n\n   // save away the full path to the file so if the program\n   // changes the cwd everything still works right! unix has\n   // better ways to do this, but we have to work in windows\n   name_full[0] = '\\0'; // stb_fullpath reads name_full[0]\n   if (stb_fullpath(name_full, sizeof(name_full), filename)==0)\n      return 0;\n\n   f = stb__open_temp_file(temp_full, name_full, mode);\n   if (f != NULL) {\n      stb__file_data *d = (stb__file_data *) malloc(sizeof(*d));\n      if (!d) { assert(0);  /* NOTREACHED */fclose(f); return NULL; }\n      if (stb__files == NULL) stb__files = stb_ptrmap_create();\n      d->temp_name = stb_p_strdup(temp_full);\n      d->name      = stb_p_strdup(name_full);\n      d->errors    = 0;\n      stb_ptrmap_add(stb__files, f, d);\n      return f;\n   }\n\n   return NULL;\n}\n\nint     stb_fclose(FILE *f, int keep)\n{\n   stb__file_data *d;\n\n   int ok = STB_FALSE;\n   if (f == NULL) return 0;\n\n   if (ferror(f))\n      keep = stb_keep_no;\n\n   fclose(f);\n\n   if (stb__files && stb_ptrmap_remove(stb__files, f, (void **) &d)) {\n      if (stb__files->count == 0) {\n         stb_ptrmap_destroy(stb__files);\n         stb__files = NULL;\n      }\n   } else\n      return STB_TRUE; // not special\n\n   if (keep == stb_keep_if_different) {\n      // check if the files are identical\n      if (stb_feq(d->name, d->temp_name)) {\n         keep = stb_keep_no;\n         ok = STB_TRUE;  // report success if no change\n      }\n   }\n\n   if (keep == stb_keep_no) {\n      remove(d->temp_name);\n   } else {\n      if (!stb_fexists(d->name)) {\n         // old file doesn't exist, so just move the new file over it\n         stb_rename(d->temp_name, d->name);\n      } else {\n         // don't delete the old file yet in case there are troubles! First rename it!\n         char preserved_old_file[4096];\n\n         // generate a temp filename in the same directory (also creates it, which we don't need)\n         FILE *dummy = stb__open_temp_file(preserved_old_file, d->name, \"wb\");\n         if (dummy != NULL) {\n            // we don't actually want the open file\n            fclose(dummy);\n\n            // discard what we just created\n            remove(preserved_old_file);  // if this fails, there's nothing we can do, and following logic handles it as best as possible anyway\n\n            // move the existing file to the preserved name\n            if (0 != stb_rename(d->name, preserved_old_file)) {  // 0 on success\n               // failed, state is:\n               //    filename  -> old file\n               //    tempname  -> new file\n               // keep tempname around so we don't lose data\n            } else {\n               //  state is:\n               //    preserved -> old file\n               //    tempname  -> new file\n               // move the new file to the old name\n               if (0 == stb_rename(d->temp_name, d->name)) {\n                  //  state is:\n                  //    preserved -> old file\n                  //    filename  -> new file\n                  ok = STB_TRUE;\n\n                  // 'filename -> new file' has always been the goal, so clean up\n                  remove(preserved_old_file); // nothing to be done if it fails\n               } else {\n                  // couldn't rename, so try renaming preserved file back\n\n                  //  state is:\n                  //    preserved -> old file\n                  //    tempname  -> new file\n                  stb_rename(preserved_old_file, d->name);\n                  // if the rename failed, there's nothing more we can do\n               }\n            }\n         } else {\n            // we couldn't get a temp filename. do this the naive way; the worst case failure here\n            // leaves the filename pointing to nothing and the new file as a tempfile\n            remove(d->name);\n            stb_rename(d->temp_name, d->name);\n         }\n      }\n   }\n\n   free(d->temp_name);\n   free(d->name);\n   free(d);\n\n   return ok;\n}\n\nint stb_copyfile(char *src, char *dest)\n{\n   char raw_buffer[1024];\n   char *buffer;\n   int buf_size = 65536;\n\n   FILE *f, *g;\n\n   // if file already exists at destination, do nothing\n   if (stb_feq(src, dest)) return STB_TRUE;\n\n   // open file\n   f = stb__fopen(src, \"rb\");\n   if (f == NULL) return STB_FALSE;\n\n   // open file for writing\n   g = stb__fopen(dest, \"wb\");\n   if (g == NULL) {\n      fclose(f);\n      return STB_FALSE;\n   }\n\n   buffer = (char *) malloc(buf_size);\n   if (buffer == NULL) {\n      buffer = raw_buffer;\n      buf_size = sizeof(raw_buffer);\n   }\n\n   while (!feof(f)) {\n      size_t n = fread(buffer, 1, buf_size, f);\n      if (n != 0)\n         fwrite(buffer, 1, n, g);\n   }\n\n   fclose(f);\n   if (buffer != raw_buffer)\n      free(buffer);\n\n   fclose(g);\n   return STB_TRUE;\n}\n\n// varlen:\n//    v' = (v >> 31) + (v < 0 ? ~v : v)<<1;  // small abs(v) => small v'\n// output v as big endian v'+k for v' <= k:\n//   1 byte :  v' <= 0x00000080          (  -64 <= v <   64)   7 bits\n//   2 bytes:  v' <= 0x00004000          (-8192 <= v < 8192)  14 bits\n//   3 bytes:  v' <= 0x00200000                               21 bits\n//   4 bytes:  v' <= 0x10000000                               28 bits\n// the number of most significant 1-bits in the first byte\n// equals the number of bytes after the first\n\n#define stb__varlen_xform(v)     (v<0 ? (~v << 1)+1 : (v << 1))\n\nint stb_size_varlen(int v) { return stb_size_varlenu(stb__varlen_xform(v)); }\nint stb_size_varlenu(unsigned int v)\n{\n   if (v < 0x00000080) return 1;\n   if (v < 0x00004000) return 2;\n   if (v < 0x00200000) return 3;\n   if (v < 0x10000000) return 4;\n   return 5;\n}\n\nvoid    stb_fput_varlen(FILE *f, int v) { stb_fput_varlenu(f, stb__varlen_xform(v)); }\n\nvoid    stb_fput_varlenu(FILE *f, unsigned int z)\n{\n   if (z >= 0x10000000) fputc(0xF0,f);\n   if (z >= 0x00200000) fputc((z < 0x10000000 ? 0xE0 : 0)+(z>>24),f);\n   if (z >= 0x00004000) fputc((z < 0x00200000 ? 0xC0 : 0)+(z>>16),f);\n   if (z >= 0x00000080) fputc((z < 0x00004000 ? 0x80 : 0)+(z>> 8),f);\n   fputc(z,f);\n}\n\n#define stb_fgetc(f)    ((unsigned char) fgetc(f))\n\nint     stb_fget_varlen(FILE *f)\n{\n   unsigned int z = stb_fget_varlenu(f);\n   return (z & 1) ? ~(z>>1) : (z>>1);\n}\n\nunsigned int stb_fget_varlenu(FILE *f)\n{\n   unsigned int z;\n   unsigned char d;\n   d = stb_fgetc(f);\n\n   if (d >= 0x80) {\n      if (d >= 0xc0) {\n         if (d >= 0xe0) {\n            if (d == 0xf0) z = stb_fgetc(f) << 24;\n            else           z = (d - 0xe0) << 24;\n            z += stb_fgetc(f) << 16;\n         }\n         else\n            z = (d - 0xc0) << 16;\n         z += stb_fgetc(f) << 8;\n      } else\n         z = (d - 0x80) <<  8;\n      z += stb_fgetc(f);\n   } else\n      z = d;\n   return z;\n}\n\nstb_uint64   stb_fget_varlen64(FILE *f)\n{\n   stb_uint64 z;\n   unsigned char d;\n   d = stb_fgetc(f);\n\n   if (d >= 0x80) {\n      if (d >= 0xc0) {\n         if (d >= 0xe0) {\n            if (d >= 0xf0) {\n               if (d >= 0xf8) {\n                  if (d >= 0xfc) {\n                     if (d >= 0xfe) {\n                        if (d >= 0xff)\n                           z = (stb_uint64) stb_fgetc(f) << 56;\n                        else\n                           z = (stb_uint64) (d - 0xfe) << 56;\n                        z |= (stb_uint64) stb_fgetc(f) << 48;\n                     } else z = (stb_uint64) (d - 0xfc) << 48;\n                     z |= (stb_uint64) stb_fgetc(f) << 40;\n                  } else z = (stb_uint64) (d - 0xf8) << 40;\n                  z |= (stb_uint64) stb_fgetc(f) << 32;\n               } else z = (stb_uint64) (d - 0xf0) << 32;\n               z |= (stb_uint) stb_fgetc(f) << 24;\n            } else z = (stb_uint) (d - 0xe0) << 24;\n            z |= (stb_uint) stb_fgetc(f) << 16;\n         } else z = (stb_uint) (d - 0xc0) << 16;\n         z |= (stb_uint) stb_fgetc(f) << 8;\n      } else z = (stb_uint) (d - 0x80) << 8;\n      z |= stb_fgetc(f);\n   } else\n      z = d;\n\n   return (z & 1) ? ~(z >> 1) : (z >> 1);\n}\n\nint stb_size_varlen64(stb_uint64 v)\n{\n   if (v < 0x00000080) return 1;\n   if (v < 0x00004000) return 2;\n   if (v < 0x00200000) return 3;\n   if (v < 0x10000000) return 4;\n   if (v < STB_IMM_UINT64(0x0000000800000000)) return 5;\n   if (v < STB_IMM_UINT64(0x0000040000000000)) return 6;\n   if (v < STB_IMM_UINT64(0x0002000000000000)) return 7;\n   if (v < STB_IMM_UINT64(0x0100000000000000)) return 8;\n   return 9;\n}\n\nvoid    stb_fput_varlen64(FILE *f, stb_uint64 v)\n{\n   stb_uint64 z = stb__varlen_xform(v);\n   int first=1;\n   if (z >= STB_IMM_UINT64(0x100000000000000)) {\n      fputc(0xff,f);\n      first=0;\n   }\n   if (z >= STB_IMM_UINT64(0x02000000000000)) fputc((first ? 0xFE : 0)+(char)(z>>56),f), first=0;\n   if (z >= STB_IMM_UINT64(0x00040000000000)) fputc((first ? 0xFC : 0)+(char)(z>>48),f), first=0;\n   if (z >= STB_IMM_UINT64(0x00000800000000)) fputc((first ? 0xF8 : 0)+(char)(z>>40),f), first=0;\n   if (z >= STB_IMM_UINT64(0x00000010000000)) fputc((first ? 0xF0 : 0)+(char)(z>>32),f), first=0;\n   if (z >= STB_IMM_UINT64(0x00000000200000)) fputc((first ? 0xE0 : 0)+(char)(z>>24),f), first=0;\n   if (z >= STB_IMM_UINT64(0x00000000004000)) fputc((first ? 0xC0 : 0)+(char)(z>>16),f), first=0;\n   if (z >= STB_IMM_UINT64(0x00000000000080)) fputc((first ? 0x80 : 0)+(char)(z>> 8),f), first=0;\n   fputc((char)z,f);\n}\n\nvoid    stb_fput_ranged(FILE *f, int v, int b, stb_uint n)\n{\n   v -= b;\n   if (n <= (1 << 31))\n      assert((stb_uint) v < n);\n   if (n > (1 << 24)) fputc(v >> 24, f);\n   if (n > (1 << 16)) fputc(v >> 16, f);\n   if (n > (1 <<  8)) fputc(v >>  8, f);\n   fputc(v,f);\n}\n\nint     stb_fget_ranged(FILE *f, int b, stb_uint n)\n{\n   unsigned int v=0;\n   if (n > (1 << 24)) v += stb_fgetc(f) << 24;\n   if (n > (1 << 16)) v += stb_fgetc(f) << 16;\n   if (n > (1 <<  8)) v += stb_fgetc(f) <<  8;\n   v += stb_fgetc(f);\n   return b+v;\n}\n\nint     stb_size_ranged(int b, stb_uint n)\n{\n   if (n > (1 << 24)) return 4;\n   if (n > (1 << 16)) return 3;\n   if (n > (1 <<  8)) return 2;\n   return 1;\n}\n\nvoid stb_fput_string(FILE *f, char *s)\n{\n   size_t len = strlen(s);\n   stb_fput_varlenu(f, (unsigned int) len);\n   fwrite(s, 1, len, f);\n}\n\n// inverse of the above algorithm\nchar *stb_fget_string(FILE *f, void *p)\n{\n   char *s;\n   int len = stb_fget_varlenu(f);\n   if (len > 4096) return NULL;\n   s = p ? stb_malloc_string(p, len+1) : (char *) malloc(len+1);\n   fread(s, 1, len, f);\n   s[len] = 0;\n   return s;\n}\n\nchar *stb_strdup(char *str, void *pool)\n{\n   size_t len = strlen(str);\n   char *p = stb_malloc_string(pool, len+1);\n   stb_p_strcpy_s(p, len+1, str);\n   return p;\n}\n\n// strip the trailing '/' or '\\\\' from a directory so we can refer to it\n// as a file for _stat()\nchar *stb_strip_final_slash(char *t)\n{\n   if (t[0]) {\n      char *z = t + strlen(t) - 1;\n      // *z is the last character\n      if (*z == '\\\\' || *z == '/')\n         if (z != t+2 || t[1] != ':') // but don't strip it if it's e.g. \"c:/\"\n            *z = 0;\n      if (*z == '\\\\')\n         *z = '/'; // canonicalize to make sure it matches db\n   }\n   return t;\n}\n\nchar *stb_strip_final_slash_regardless(char *t)\n{\n   if (t[0]) {\n      char *z = t + strlen(t) - 1;\n      // *z is the last character\n      if (*z == '\\\\' || *z == '/')\n         *z = 0;\n      if (*z == '\\\\')\n         *z = '/'; // canonicalize to make sure it matches db\n   }\n   return t;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                 Options parsing\n//\n\nSTB_EXTERN char **stb_getopt_param(int *argc, char **argv, char *param);\nSTB_EXTERN char **stb_getopt(int *argc, char **argv);\nSTB_EXTERN void   stb_getopt_free(char **opts);\n\n#ifdef STB_DEFINE\n\nvoid   stb_getopt_free(char **opts)\n{\n   int i;\n   char ** o2 = opts;\n   for (i=0; i < stb_arr_len(o2); ++i)\n      free(o2[i]);\n   stb_arr_free(o2);\n}\n\nchar **stb_getopt(int *argc, char **argv)\n{\n   return stb_getopt_param(argc, argv, (char*) \"\");\n}\n\nchar **stb_getopt_param(int *argc, char **argv, char *param)\n{\n   char ** opts=NULL;\n   int i,j=1;\n   for (i=1; i < *argc; ++i) {\n      if (argv[i][0] != '-') {\n         argv[j++] = argv[i];\n      } else {\n         if (argv[i][1] == 0) { // plain - == don't parse further options\n            ++i;\n            while (i < *argc)\n               argv[j++] = argv[i++];\n            break;\n         } else if (argv[i][1] == '-') {\n            // copy argument through including initial '-' for clarity\n            stb_arr_push(opts, stb_p_strdup(argv[i]));\n         } else {\n            int k;\n            char *q = argv[i];  // traverse options list\n            for (k=1; q[k]; ++k) {\n               char *s;\n               if (strchr(param, q[k])) {  // does it take a parameter?\n                  char *t = &q[k+1], z = q[k];\n                  size_t len=0;\n                  if (*t == 0) {\n                     if (i == *argc-1) { // takes a parameter, but none found\n                        *argc = 0;\n                        stb_getopt_free(opts);\n                        return NULL;\n                     }\n                     t = argv[++i];\n                  } else\n                     k += (int) strlen(t);\n                  len = strlen(t);\n                  s = (char *) malloc(len+2);\n                  if (!s) return NULL;\n                  s[0] = z;\n                  stb_p_strcpy_s(s+1, len+2, t);\n               } else {\n                  // no parameter\n                  s = (char *) malloc(2);\n                  if (!s) return NULL;\n                  s[0] = q[k];\n                  s[1] = 0;\n               }\n               stb_arr_push(opts, s);\n            }\n         }\n      }\n   }\n   stb_arr_push(opts, NULL);\n   *argc = j;\n   return opts;\n}\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                 Portable directory reading\n//\n\nSTB_EXTERN char **stb_readdir_files  (char *dir);\nSTB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild);\nSTB_EXTERN char **stb_readdir_subdirs(char *dir);\nSTB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild);\nSTB_EXTERN void   stb_readdir_free   (char **files);\nSTB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec);\nSTB_EXTERN void stb_delete_directory_recursive(char *dir);\n\n#ifdef STB_DEFINE\n\n#ifdef _MSC_VER\n#include <io.h>\n#else\n#include <unistd.h>\n#include <dirent.h>\n#endif\n\nvoid stb_readdir_free(char **files)\n{\n   char **f2 = files;\n   int i;\n   for (i=0; i < stb_arr_len(f2); ++i)\n      free(f2[i]);\n   stb_arr_free(f2);\n}\n\nstatic int isdotdirname(char *name)\n{\n   if (name[0] == '.')\n      return (name[1] == '.') ? !name[2] : !name[1];\n   return 0;\n}\n\nSTB_EXTERN int stb_wildmatchi(char *expr, char *candidate);\nstatic char **readdir_raw(char *dir, int return_subdirs, char *mask)\n{\n   char **results = NULL;\n   char buffer[4096], with_slash[4096];\n   size_t n;\n\n   #ifdef WIN32\n      stb__wchar *ws;\n      struct _wfinddata_t data;\n   #ifdef _WIN64\n      const intptr_t none = -1;\n      intptr_t z;\n   #else\n      const long none = -1;\n      long z;\n   #endif\n   #else // !WIN32\n      const DIR *none = NULL;\n      DIR *z;\n   #endif\n\n   n = stb_strscpy(buffer,dir,sizeof(buffer));\n   if (!n || n >= sizeof(buffer))\n      return NULL;\n   stb_fixpath(buffer);\n\n   if (n > 0 && (buffer[n-1] != '/')) {\n      buffer[n++] = '/';\n   }\n   buffer[n] = 0;\n   if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))\n      return NULL;\n\n   #ifdef WIN32\n      if (!stb_strscpy(buffer+n,\"*.*\",sizeof(buffer)-n))\n         return NULL;\n      ws = stb__from_utf8(buffer);\n      z = _wfindfirst((wchar_t *)ws, &data);\n   #else\n      z = opendir(dir);\n   #endif\n\n   if (z != none) {\n      int nonempty = STB_TRUE;\n      #ifndef WIN32\n      struct dirent *data = readdir(z);\n      nonempty = (data != NULL);\n      #endif\n\n      if (nonempty) {\n\n         do {\n            int is_subdir;\n            #ifdef WIN32\n            char *name = stb__to_utf8((stb__wchar *)data.name);\n            if (name == NULL) {\n               fprintf(stderr, \"%s to convert '%S' to %s!\\n\", \"Unable\", data.name, \"utf8\");\n               continue;\n            }\n            is_subdir = !!(data.attrib & _A_SUBDIR);\n            #else\n            char *name = data->d_name;\n            if (!stb_strscpy(buffer+n,name,sizeof(buffer)-n))\n               break;\n            // Could follow DT_LNK, but would need to check for recursive links.\n            is_subdir = !!(data->d_type & DT_DIR);\n            #endif\n\n            if (is_subdir == return_subdirs) {\n               if (!is_subdir || !isdotdirname(name)) {\n                  if (!mask || stb_wildmatchi(mask, name)) {\n                     char buffer[4096],*p=buffer;\n                     if ( stb_snprintf(buffer, sizeof(buffer), \"%s%s\", with_slash, name) < 0 )\n                        break;\n                     if (buffer[0] == '.' && buffer[1] == '/')\n                        p = buffer+2;\n                     stb_arr_push(results, stb_p_strdup(p));\n                  }\n               }\n            }\n         }\n         #ifdef WIN32\n         while (0 == _wfindnext(z, &data));\n         #else\n         while ((data = readdir(z)) != NULL);\n         #endif\n      }\n      #ifdef WIN32\n         _findclose(z);\n      #else\n         closedir(z);\n      #endif\n   }\n   return results;\n}\n\nchar **stb_readdir_files  (char *dir) { return readdir_raw(dir, 0, NULL); }\nchar **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); }\nchar **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); }\nchar **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); }\n\nint stb__rec_max=0x7fffffff;\nstatic char **stb_readdir_rec(char **sofar, char *dir, char *filespec)\n{\n   char **files;\n   char ** dirs;\n   char **p;\n\n   if (stb_arr_len(sofar) >= stb__rec_max) return sofar;\n\n   files = stb_readdir_files_mask(dir, filespec);\n   stb_arr_for(p, files) {\n      stb_arr_push(sofar, stb_p_strdup(*p));\n      if (stb_arr_len(sofar) >= stb__rec_max) break;\n   }\n   stb_readdir_free(files);\n   if (stb_arr_len(sofar) >= stb__rec_max) return sofar;\n\n   dirs = stb_readdir_subdirs(dir);\n   stb_arr_for(p, dirs)\n      sofar = stb_readdir_rec(sofar, *p, filespec);\n   stb_readdir_free(dirs);\n   return sofar;\n}\n\nchar **stb_readdir_recursive(char *dir, char *filespec)\n{\n   return stb_readdir_rec(NULL, dir, filespec);\n}\n\nvoid stb_delete_directory_recursive(char *dir)\n{\n   char **list = stb_readdir_subdirs(dir);\n   int i;\n   for (i=0; i < stb_arr_len(list); ++i)\n      stb_delete_directory_recursive(list[i]);\n   stb_arr_free(list);\n   list = stb_readdir_files(dir);\n   for (i=0; i < stb_arr_len(list); ++i)\n      if (!remove(list[i])) {\n         // on windows, try again after making it writeable; don't ALWAYS\n         // do this first since that would be slow in the normal case\n         #ifdef _MSC_VER\n         _chmod(list[i], _S_IWRITE);\n         remove(list[i]);\n         #endif\n      }\n   stb_arr_free(list);\n   stb__windows(_rmdir,rmdir)(dir);\n}\n\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//   construct trees from filenames; useful for cmirror summaries\n\ntypedef struct stb_dirtree2 stb_dirtree2;\n\nstruct stb_dirtree2\n{\n   stb_dirtree2 **subdirs;\n\n   // make convenient for stb_summarize_tree\n   int num_subdir;\n   float weight;\n\n   // actual data\n   char *fullpath;\n   char *relpath;\n   char **files;\n};\n\nSTB_EXTERN stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count);\nSTB_EXTERN stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count);\nSTB_EXTERN int stb_dir_is_prefix(char *dir, int dirlen, char *file);\n\n#ifdef STB_DEFINE\n\nint stb_dir_is_prefix(char *dir, int dirlen, char *file)\n{\n   if (dirlen == 0) return STB_TRUE;\n   if (stb_strnicmp(dir, file, dirlen)) return STB_FALSE;\n   if (file[dirlen] == '/' || file[dirlen] == '\\\\') return STB_TRUE;\n   return STB_FALSE;\n}\n\nstb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count)\n{\n   char buffer1[1024];\n   int i;\n   int dlen = (int) strlen(src), elen;\n   stb_dirtree2 *d;\n   char ** descendents = NULL;\n   char ** files = NULL;\n   char *s;\n   if (!count) return NULL;\n   // first find all the ones that belong here... note this is will take O(NM) with N files and M subdirs\n   for (i=0; i < count; ++i) {\n      if (stb_dir_is_prefix(src, dlen, filelist[i])) {\n         stb_arr_push(descendents, filelist[i]);\n      }\n   }\n   if (descendents == NULL)\n      return NULL;\n   elen = dlen;\n   // skip a leading slash\n   if (elen == 0 && (descendents[0][0] == '/' || descendents[0][0] == '\\\\'))\n      ++elen;\n   else if (elen)\n      ++elen;\n   // now extract all the ones that have their root here\n   for (i=0; i < stb_arr_len(descendents);) {\n      if (!stb_strchr2(descendents[i]+elen, '/', '\\\\')) {\n         stb_arr_push(files, descendents[i]);\n         descendents[i] = descendents[stb_arr_len(descendents)-1];\n         stb_arr_pop(descendents);\n      } else\n         ++i;\n   }\n   // now create a record\n   d = (stb_dirtree2 *) malloc(sizeof(*d));\n   d->files = files;\n   d->subdirs = NULL;\n   d->fullpath = stb_p_strdup(src);\n   s = stb_strrchr2(d->fullpath, '/', '\\\\');\n   if (s)\n      ++s;\n   else\n      s = d->fullpath;\n   d->relpath = s;\n   // now create the children\n   qsort(descendents, stb_arr_len(descendents), sizeof(char *), stb_qsort_stricmp(0));\n   buffer1[0] = 0;\n   for (i=0; i < stb_arr_len(descendents); ++i) {\n      char buffer2[1024];\n      char *s = descendents[i] + elen, *t;\n      t = stb_strchr2(s, '/', '\\\\');\n      assert(t);\n      stb_strncpy(buffer2, descendents[i], (int) (t-descendents[i]+1));\n      if (stb_stricmp(buffer1, buffer2)) {\n         stb_dirtree2 *t = stb_dirtree2_from_files_relative(buffer2, descendents, stb_arr_len(descendents));\n         assert(t != NULL);\n         stb_p_strcpy_s(buffer1, sizeof(buffer1), buffer2);\n         stb_arr_push(d->subdirs, t);\n      }\n   }\n   d->num_subdir = stb_arr_len(d->subdirs);\n   d->weight = 0;\n   return d;\n}\n\nstb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count)\n{\n   return stb_dirtree2_from_files_relative((char*) \"\", filelist, count);\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                 Checksums: CRC-32, ADLER32, SHA-1\n//\n//    CRC-32 and ADLER32 allow streaming blocks\n//    SHA-1 requires either a complete buffer, max size 2^32 - 73\n//          or it can checksum directly from a file, max 2^61\n\n#define STB_ADLER32_SEED   1\n#define STB_CRC32_SEED     0    // note that we logical NOT this in the code\n\nSTB_EXTERN stb_uint\n  stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen);\nSTB_EXTERN stb_uint\n  stb_crc32_block(stb_uint crc32, stb_uchar *buffer, stb_uint len);\nSTB_EXTERN stb_uint stb_crc32(unsigned char *buffer, stb_uint len);\n\nSTB_EXTERN void stb_sha1(\n  unsigned char output[20], unsigned char *buffer, unsigned int len);\nSTB_EXTERN int stb_sha1_file(unsigned char output[20], char *file);\n\nSTB_EXTERN void stb_sha1_readable(char display[27], unsigned char sha[20]);\n\n#ifdef STB_DEFINE\nstb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len)\n{\n   static stb_uint crc_table[256];\n   stb_uint i,j,s;\n   crc = ~crc;\n\n   if (crc_table[1] == 0)\n      for(i=0; i < 256; i++) {\n         for (s=i, j=0; j < 8; ++j)\n            s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0);\n         crc_table[i] = s;\n      }\n   for (i=0; i < len; ++i)\n      crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];\n   return ~crc;\n}\n\nstb_uint stb_crc32(unsigned char *buffer, stb_uint len)\n{\n   return stb_crc32_block(0, buffer, len);\n}\n\nstb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)\n{\n   const unsigned long ADLER_MOD = 65521;\n   unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;\n   unsigned long blocklen, i;\n\n   blocklen = buflen % 5552;\n   while (buflen) {\n      for (i=0; i + 7 < blocklen; i += 8) {\n         s1 += buffer[0], s2 += s1;\n         s1 += buffer[1], s2 += s1;\n         s1 += buffer[2], s2 += s1;\n         s1 += buffer[3], s2 += s1;\n         s1 += buffer[4], s2 += s1;\n         s1 += buffer[5], s2 += s1;\n         s1 += buffer[6], s2 += s1;\n         s1 += buffer[7], s2 += s1;\n\n         buffer += 8;\n      }\n\n      for (; i < blocklen; ++i)\n         s1 += *buffer++, s2 += s1;\n\n      s1 %= ADLER_MOD, s2 %= ADLER_MOD;\n      buflen -= blocklen;\n      blocklen = 5552;\n   }\n   return (s2 << 16) + s1;\n}\n\nstatic void stb__sha1(stb_uchar *chunk, stb_uint h[5])\n{\n   int i;\n   stb_uint a,b,c,d,e;\n   stb_uint w[80];\n\n   for (i=0; i < 16; ++i)\n      w[i] = stb_big32(&chunk[i*4]);\n   for (i=16; i < 80; ++i) {\n      stb_uint t;\n      t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];\n      w[i] = (t + t) | (t >> 31);\n   }\n\n   a = h[0];\n   b = h[1];\n   c = h[2];\n   d = h[3];\n   e = h[4];\n\n   #define STB__SHA1(k,f)                                            \\\n   {                                                                 \\\n      stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i];  \\\n      e = d;                                                       \\\n      d = c;                                                     \\\n      c = (b << 30) + (b >> 2);                               \\\n      b = a;                                              \\\n      a = temp;                                    \\\n   }\n\n   i=0;\n   for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d))       );\n   for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d               );\n   for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );\n   for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d               );\n\n   #undef STB__SHA1\n\n   h[0] += a;\n   h[1] += b;\n   h[2] += c;\n   h[3] += d;\n   h[4] += e;\n}\n\nvoid stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len)\n{\n   unsigned char final_block[128];\n   stb_uint end_start, final_len, j;\n   int i;\n\n   stb_uint h[5];\n\n   h[0] = 0x67452301;\n   h[1] = 0xefcdab89;\n   h[2] = 0x98badcfe;\n   h[3] = 0x10325476;\n   h[4] = 0xc3d2e1f0;\n\n   // we need to write padding to the last one or two\n   // blocks, so build those first into 'final_block'\n\n   // we have to write one special byte, plus the 8-byte length\n\n   // compute the block where the data runs out\n   end_start = len & ~63;\n\n   // compute the earliest we can encode the length\n   if (((len+9) & ~63) == end_start) {\n      // it all fits in one block, so fill a second-to-last block\n      end_start -= 64;\n   }\n\n   final_len = end_start + 128;\n\n   // now we need to copy the data in\n   assert(end_start + 128 >= len+9);\n   assert(end_start < len || len < 64-9);\n\n   j = 0;\n   if (end_start > len)\n      j = (stb_uint) - (int) end_start;\n\n   for (; end_start + j < len; ++j)\n      final_block[j] = buffer[end_start + j];\n   final_block[j++] = 0x80;\n   while (j < 128-5) // 5 byte length, so write 4 extra padding bytes\n      final_block[j++] = 0;\n   // big-endian size\n   final_block[j++] = len >> 29;\n   final_block[j++] = len >> 21;\n   final_block[j++] = len >> 13;\n   final_block[j++] = len >>  5;\n   final_block[j++] = len <<  3;\n   assert(j == 128 && end_start + j == final_len);\n\n   for (j=0; j < final_len; j += 64) { // 512-bit chunks\n      if (j+64 >= end_start+64)\n         stb__sha1(&final_block[j - end_start], h);\n      else\n         stb__sha1(&buffer[j], h);\n   }\n\n   for (i=0; i < 5; ++i) {\n      output[i*4 + 0] = h[i] >> 24;\n      output[i*4 + 1] = h[i] >> 16;\n      output[i*4 + 2] = h[i] >>  8;\n      output[i*4 + 3] = h[i] >>  0;\n   }\n}\n\n#ifdef _MSC_VER\nint stb_sha1_file(stb_uchar output[20], char *file)\n{\n   int i;\n   stb_uint64 length=0;\n   unsigned char buffer[128];\n\n   FILE *f = stb__fopen(file, \"rb\");\n   stb_uint h[5];\n\n   if (f == NULL) return 0; // file not found\n\n   h[0] = 0x67452301;\n   h[1] = 0xefcdab89;\n   h[2] = 0x98badcfe;\n   h[3] = 0x10325476;\n   h[4] = 0xc3d2e1f0;\n\n   for(;;) {\n      size_t n = fread(buffer, 1, 64, f);\n      if (n == 64) {\n         stb__sha1(buffer, h);\n         length += n;\n      } else {\n         int block = 64;\n\n         length += n;\n\n         buffer[n++] = 0x80;\n\n         // if there isn't enough room for the length, double the block\n         if (n + 8 > 64)\n            block = 128;\n\n         // pad to end\n         memset(buffer+n, 0, block-8-n);\n\n         i = block - 8;\n         buffer[i++] = (stb_uchar) (length >> 53);\n         buffer[i++] = (stb_uchar) (length >> 45);\n         buffer[i++] = (stb_uchar) (length >> 37);\n         buffer[i++] = (stb_uchar) (length >> 29);\n         buffer[i++] = (stb_uchar) (length >> 21);\n         buffer[i++] = (stb_uchar) (length >> 13);\n         buffer[i++] = (stb_uchar) (length >>  5);\n         buffer[i++] = (stb_uchar) (length <<  3);\n         assert(i == block);\n         stb__sha1(buffer, h);\n         if (block == 128)\n            stb__sha1(buffer+64, h);\n         else\n            assert(block == 64);\n         break;\n      }\n   }\n   fclose(f);\n\n   for (i=0; i < 5; ++i) {\n      output[i*4 + 0] = h[i] >> 24;\n      output[i*4 + 1] = h[i] >> 16;\n      output[i*4 + 2] = h[i] >>  8;\n      output[i*4 + 3] = h[i] >>  0;\n   }\n\n   return 1;\n}\n#endif // _MSC_VER\n\n// client can truncate this wherever they like\nvoid stb_sha1_readable(char display[27], unsigned char sha[20])\n{\n   char encoding[65] = \"0123456789abcdefghijklmnopqrstuv\"\n                       \"wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%$\";\n   int num_bits = 0, acc=0;\n   int i=0,o=0;\n   while (o < 26) {\n      int v;\n      // expand the accumulator\n      if (num_bits < 6) {\n         assert(i != 20);\n         acc += sha[i++] << num_bits;\n         num_bits += 8;\n      }\n      v = acc & ((1 << 6) - 1);\n      display[o++] = encoding[v];\n      acc >>= 6;\n      num_bits -= 6;\n   }\n   assert(num_bits == 20*8 - 26*6);\n   display[o++] = encoding[acc];\n}\n\n#endif // STB_DEFINE\n\n///////////////////////////////////////////////////////////\n//\n// simplified WINDOWS registry interface... hopefully\n// we'll never actually use this?\n\n#if defined(_WIN32)\n\nSTB_EXTERN void * stb_reg_open(const char *mode, const char *where); // mode: \"rHKLM\" or \"rHKCU\" or \"w..\"\nSTB_EXTERN void   stb_reg_close(void *reg);\nSTB_EXTERN int    stb_reg_read(void *zreg, const char *str, void *data, unsigned long len);\nSTB_EXTERN int    stb_reg_read_string(void *zreg, const char *str, char *data, int len);\nSTB_EXTERN void   stb_reg_write(void *zreg, const char *str, const void *data, unsigned long len);\nSTB_EXTERN void   stb_reg_write_string(void *zreg, const char *str, const char *data);\n\n#if defined(STB_DEFINE) && !defined(STB_NO_REGISTRY)\n\n#define STB_HAS_REGISTRY\n\n#ifndef _WINDOWS_\n\n#define HKEY void *\n\nSTB_EXTERN __declspec(dllimport) long __stdcall RegCloseKey ( HKEY hKey );\nSTB_EXTERN __declspec(dllimport) long __stdcall RegCreateKeyExA ( HKEY hKey, const char * lpSubKey,\n    int  Reserved, char * lpClass, int  dwOptions,\n    int samDesired, void *lpSecurityAttributes,     HKEY * phkResult,     int * lpdwDisposition );\nSTB_EXTERN __declspec(dllimport) long __stdcall RegDeleteKeyA ( HKEY hKey, const char * lpSubKey );\nSTB_EXTERN __declspec(dllimport) long __stdcall RegQueryValueExA ( HKEY hKey, const char * lpValueName,\n    int * lpReserved, unsigned long * lpType, unsigned char * lpData, unsigned long * lpcbData );\nSTB_EXTERN __declspec(dllimport) long __stdcall RegSetValueExA ( HKEY hKey, const char * lpValueName,\n    int  Reserved, int  dwType, const unsigned char* lpData, int  cbData );\nSTB_EXTERN __declspec(dllimport) long __stdcall  RegOpenKeyExA ( HKEY hKey, const char * lpSubKey,\n    int ulOptions, int samDesired, HKEY * phkResult );\n\n#endif // _WINDOWS_\n\n#define STB__REG_OPTION_NON_VOLATILE  0\n#define STB__REG_KEY_ALL_ACCESS       0x000f003f\n#define STB__REG_KEY_READ             0x00020019\n\n#ifdef _M_AMD64\n#define STB__HKEY_CURRENT_USER        0x80000001ull\n#define STB__HKEY_LOCAL_MACHINE       0x80000002ull\n#else\n#define STB__HKEY_CURRENT_USER        0x80000001\n#define STB__HKEY_LOCAL_MACHINE       0x80000002\n#endif\n\nvoid *stb_reg_open(const char *mode, const char *where)\n{\n   long res;\n   HKEY base;\n   HKEY zreg;\n   if (!stb_stricmp(mode+1, \"cu\") || !stb_stricmp(mode+1, \"hkcu\"))\n      base = (HKEY) STB__HKEY_CURRENT_USER;\n   else if (!stb_stricmp(mode+1, \"lm\") || !stb_stricmp(mode+1, \"hklm\"))\n      base = (HKEY) STB__HKEY_LOCAL_MACHINE;\n   else\n      return NULL;\n\n   if (mode[0] == 'r')\n      res = RegOpenKeyExA(base, where, 0, STB__REG_KEY_READ, &zreg);\n   else if (mode[0] == 'w')\n      res = RegCreateKeyExA(base, where,  0, NULL, STB__REG_OPTION_NON_VOLATILE, STB__REG_KEY_ALL_ACCESS, NULL, &zreg, NULL);\n   else\n      return NULL;\n\n   return res ? NULL : zreg;\n}\n\nvoid stb_reg_close(void *reg)\n{\n   RegCloseKey((HKEY) reg);\n}\n\n#define STB__REG_SZ         1\n#define STB__REG_BINARY     3\n#define STB__REG_DWORD      4\n\nint stb_reg_read(void *zreg, const char *str, void *data, unsigned long len)\n{\n   unsigned long type;\n   unsigned long alen = len;\n   if (0 == RegQueryValueExA((HKEY) zreg, str, 0, &type, (unsigned char *) data, &len))\n      if (type == STB__REG_BINARY || type == STB__REG_SZ || type == STB__REG_DWORD) {\n         if (len < alen)\n            *((char *) data + len) = 0;\n         return 1;\n      }\n   return 0;\n}\n\nvoid stb_reg_write(void *zreg, const char *str, const void *data, unsigned long len)\n{\n   if (zreg)\n      RegSetValueExA((HKEY) zreg, str, 0, STB__REG_BINARY, (const unsigned char *) data, len);\n}\n\nint stb_reg_read_string(void *zreg, const char *str, char *data, int len)\n{\n   if (!stb_reg_read(zreg, str, data, len)) return 0;\n   data[len-1] = 0; // force a 0 at the end of the string no matter what\n   return 1;\n}\n\nvoid stb_reg_write_string(void *zreg, const char *str, const char *data)\n{\n   if (zreg)\n      RegSetValueExA((HKEY) zreg, str, 0, STB__REG_SZ, (const unsigned char *)  data, (int) strlen(data)+1);\n}\n#endif  // STB_DEFINE\n#endif  // _WIN32\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//     stb_cfg - This is like the registry, but the config info\n//               is all stored in plain old files where we can\n//               backup and restore them easily. The LOCATION of\n//               the config files is gotten from... the registry!\n\n#ifndef STB_NO_STB_STRINGS\ntypedef struct stb_cfg_st stb_cfg;\n\nSTB_EXTERN stb_cfg * stb_cfg_open(char *config, const char *mode); // mode = \"r\", \"w\"\nSTB_EXTERN void      stb_cfg_close(stb_cfg *cfg);\nSTB_EXTERN int       stb_cfg_read(stb_cfg *cfg, char *key, void *value, int len);\nSTB_EXTERN void      stb_cfg_write(stb_cfg *cfg, char *key, void *value, int len);\nSTB_EXTERN int       stb_cfg_read_string(stb_cfg *cfg, char *key, char *value, int len);\nSTB_EXTERN void      stb_cfg_write_string(stb_cfg *cfg, char *key, char *value);\nSTB_EXTERN int       stb_cfg_delete(stb_cfg *cfg, char *key);\nSTB_EXTERN void      stb_cfg_set_directory(char *dir);\n\n#ifdef STB_DEFINE\n\ntypedef struct\n{\n   char *key;\n   void *value;\n   int value_len;\n} stb__cfg_item;\n\nstruct stb_cfg_st\n{\n   stb__cfg_item *data;\n   char *loaded_file;   // this needs to be freed\n   FILE *f; // write the data to this file on close\n};\n\nstatic const char *stb__cfg_sig = \"sTbCoNfIg!\\0\\0\";\nstatic char stb__cfg_dir[512];\nSTB_EXTERN void stb_cfg_set_directory(char *dir)\n{\n   stb_p_strcpy_s(stb__cfg_dir, sizeof(stb__cfg_dir), dir);\n}\n\nSTB_EXTERN stb_cfg * stb_cfg_open(char *config, const char *mode)\n{\n   size_t len;\n   stb_cfg *z;\n   char file[512];\n   if (mode[0] != 'r' && mode[0] != 'w') return NULL;\n\n   if (!stb__cfg_dir[0]) {\n      #ifdef _WIN32\n      stb_p_strcpy_s(stb__cfg_dir, sizeof(stb__cfg_dir), \"c:/stb\");\n      #else\n      strcpy(stb__cfg_dir, \"~/.stbconfig\");\n      #endif\n\n      #ifdef STB_HAS_REGISTRY\n      {\n         void *reg = stb_reg_open(\"rHKLM\", \"Software\\\\SilverSpaceship\\\\stb\");\n         if (reg) {\n            stb_reg_read_string(reg, \"config_dir\", stb__cfg_dir, sizeof(stb__cfg_dir));\n            stb_reg_close(reg);\n         }\n      }\n      #endif\n   }\n\n   stb_p_sprintf(file stb_p_size(sizeof(file)), \"%s/%s.cfg\", stb__cfg_dir, config);\n\n   z = (stb_cfg *) stb_malloc(0, sizeof(*z));\n   z->data = NULL;\n\n   z->loaded_file = stb_filec(file, &len);\n   if (z->loaded_file) {\n      char *s = z->loaded_file;\n      if (!memcmp(s, stb__cfg_sig, 12)) {\n         char *s = z->loaded_file + 12;\n         while (s < z->loaded_file + len) {\n            stb__cfg_item a;\n            int n = *(stb_int16 *) s;\n            a.key = s+2;\n            s = s+2 + n;\n            a.value_len = *(int *) s;\n            s += 4;\n            a.value = s;\n            s += a.value_len;\n            stb_arr_push(z->data, a);\n         }\n         assert(s == z->loaded_file + len);\n      }\n   }\n\n   if (mode[0] == 'w')\n      z->f = stb_p_fopen(file, \"wb\");\n   else\n      z->f = NULL;\n\n   return z;\n}\n\nvoid stb_cfg_close(stb_cfg *z)\n{\n   if (z->f) {\n      int i;\n      // write the file out\n      fwrite(stb__cfg_sig, 12, 1, z->f);\n      for (i=0; i < stb_arr_len(z->data); ++i) {\n         stb_int16 n = (stb_int16) strlen(z->data[i].key)+1;\n         fwrite(&n, 2, 1, z->f);\n         fwrite(z->data[i].key, n, 1, z->f);\n         fwrite(&z->data[i].value_len, 4, 1, z->f);\n         fwrite(z->data[i].value, z->data[i].value_len, 1, z->f);\n      }\n      fclose(z->f);\n   }\n   stb_arr_free(z->data);\n   stb_free(z);\n}\n\nint stb_cfg_read(stb_cfg *z, char *key, void *value, int len)\n{\n   int i;\n   for (i=0; i < stb_arr_len(z->data); ++i) {\n      if (!stb_stricmp(z->data[i].key, key)) {\n         int n = stb_min(len, z->data[i].value_len);\n         memcpy(value, z->data[i].value, n);\n         if (n < len)\n            *((char *) value + n) = 0;\n         return 1;\n      }\n   }\n   return 0;\n}\n\nvoid stb_cfg_write(stb_cfg *z, char *key, void *value, int len)\n{\n   int i;\n   for (i=0; i < stb_arr_len(z->data); ++i)\n      if (!stb_stricmp(z->data[i].key, key))\n         break;\n   if (i == stb_arr_len(z->data)) {\n      stb__cfg_item p;\n      p.key = stb_strdup(key, z);\n      p.value = NULL;\n      p.value_len = 0;\n      stb_arr_push(z->data, p);\n   }\n   z->data[i].value = stb_malloc(z, len);\n   z->data[i].value_len = len;\n   memcpy(z->data[i].value, value, len);\n}\n\nint stb_cfg_delete(stb_cfg *z, char *key)\n{\n   int i;\n   for (i=0; i < stb_arr_len(z->data); ++i)\n      if (!stb_stricmp(z->data[i].key, key)) {\n         stb_arr_fastdelete(z->data, i);\n         return 1;\n      }\n   return 0;\n}\n\nint stb_cfg_read_string(stb_cfg *z, char *key, char *value, int len)\n{\n   if (!stb_cfg_read(z, key, value, len)) return 0;\n   value[len-1] = 0;\n   return 1;\n}\n\nvoid stb_cfg_write_string(stb_cfg *z, char *key, char *value)\n{\n   stb_cfg_write(z, key, value, (int) strlen(value)+1);\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//     stb_dirtree  - load a description of a directory tree\n//                      uses a cache and stat()s the directories for changes\n//                      MUCH faster on NTFS, _wrong_ on FAT32, so should\n//                      ignore the db on FAT32\n\n#ifdef _WIN32\n\ntypedef struct\n{\n   char   * path;           // full path from passed-in root\n   time_t   last_modified;\n   int      num_files;\n   int      flag;\n} stb_dirtree_dir;\n\ntypedef struct\n{\n   char *name;              // name relative to path\n   int   dir;               // index into dirs[] array\n   stb_int64 size;      // size, max 4GB\n   time_t   last_modified;\n   int      flag;\n} stb_dirtree_file;\n\ntypedef struct\n{\n   stb_dirtree_dir  *dirs;\n   stb_dirtree_file *files;\n\n   // internal use\n   void             * string_pool;   // used to free data en masse\n} stb_dirtree;\n\nextern void         stb_dirtree_free          ( stb_dirtree *d );\nextern stb_dirtree *stb_dirtree_get           ( char *dir);\nextern stb_dirtree *stb_dirtree_get_dir       ( char *dir, char *cache_dir);\nextern stb_dirtree *stb_dirtree_get_with_file ( char *dir, char *cache_file);\n\n// get a list of all the files recursively underneath 'dir'\n//\n// cache_file is used to store a copy of the directory tree to speed up\n// later calls. It must be unique to 'dir' and the current working\n// directory! Otherwise who knows what will happen (a good solution\n// is to put it _in_ dir, but this API doesn't force that).\n//\n// Also, it might be possible to break this if you have two different processes\n// do a call to stb_dirtree_get() with the same cache file at about the same\n// time, but I _think_ it might just work.\n\n// i needed to build an identical data structure representing the state of\n// a mirrored copy WITHOUT bothering to rescan it (i.e. we're mirroring to\n// it WITHOUT scanning it, e.g. it's over the net), so this requires access\n// to all of the innards.\nextern void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last);\nextern void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last);\nextern void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir);\nextern void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir);\n\n#ifdef STB_DEFINE\nstatic void stb__dirtree_add_dir(char *path, time_t last, stb_dirtree *active)\n{\n   stb_dirtree_dir d;\n   d.last_modified = last;\n   d.num_files = 0;\n   d.path = stb_strdup(path, active->string_pool);\n   stb_arr_push(active->dirs, d);\n}\n\nstatic void stb__dirtree_add_file(char *name, int dir, stb_int64 size, time_t last, stb_dirtree *active)\n{\n   stb_dirtree_file f;\n   f.dir = dir;\n   f.size = size;\n   f.last_modified = last;\n   f.name = stb_strdup(name, active->string_pool);\n   ++active->dirs[dir].num_files;\n   stb_arr_push(active->files, f);\n}\n\n// version 02 supports > 4GB files\nstatic char stb__signature[12] = { 's', 'T', 'b', 'D', 'i', 'R', 't', 'R', 'e', 'E', '0', '2' };\n\nstatic void stb__dirtree_save_db(char *filename, stb_dirtree *data, char *root)\n{\n   int i, num_dirs_final=0, num_files_final;\n   char *info = root ? root : (char*)\"\";\n   int *remap;\n   FILE *f = stb_p_fopen(filename, \"wb\");\n   if (!f) return;\n\n   fwrite(stb__signature, sizeof(stb__signature), 1, f);\n   fwrite(info, strlen(info)+1, 1, f);\n   // need to be slightly tricky and not write out NULLed directories, nor the root\n\n   // build remapping table of all dirs we'll be writing out\n   remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(data->dirs));\n   for (i=0; i < stb_arr_len(data->dirs); ++i) {\n      if (data->dirs[i].path == NULL || (root && 0==stb_stricmp(data->dirs[i].path, root))) {\n         remap[i] = -1;\n      } else {\n         remap[i] = num_dirs_final++;\n      }\n   }\n\n   fwrite(&num_dirs_final, 4, 1, f);\n   for (i=0; i < stb_arr_len(data->dirs); ++i) {\n      if (remap[i] >= 0) {\n         fwrite(&data->dirs[i].last_modified, 4, 1, f);\n         stb_fput_string(f, data->dirs[i].path);\n      }\n   }\n\n   num_files_final = 0;\n   for (i=0; i < stb_arr_len(data->files); ++i)\n      if (remap[data->files[i].dir] >= 0 && data->files[i].name)\n         ++num_files_final;\n\n   fwrite(&num_files_final, 4, 1, f);\n   for (i=0; i < stb_arr_len(data->files); ++i) {\n      if (remap[data->files[i].dir] >= 0 && data->files[i].name) {\n         stb_fput_ranged(f, remap[data->files[i].dir], 0, num_dirs_final);\n         stb_fput_varlen64(f, data->files[i].size);\n         fwrite(&data->files[i].last_modified, 4, 1, f);\n         stb_fput_string(f, data->files[i].name);\n      }\n   }\n\n   fclose(f);\n}\n\n// note: stomps any existing data, rather than appending\nstatic void stb__dirtree_load_db(char *filename, stb_dirtree *data, char *dir)\n{\n   char sig[2048];\n   int i,n;\n   FILE *f = stb_p_fopen(filename, \"rb\");\n\n   if (!f) return;\n\n   data->string_pool = stb_malloc(0,1);\n\n   fread(sig, sizeof(stb__signature), 1, f);\n   if (memcmp(stb__signature, sig, sizeof(stb__signature))) { fclose(f); return; }\n   if (!fread(sig, strlen(dir)+1, 1, f))                    { fclose(f); return; }\n   if (stb_stricmp(sig,dir))                                { fclose(f); return; }\n\n   // we can just read them straight in, because they're guaranteed to be valid\n   fread(&n, 4, 1, f);\n   stb_arr_setlen(data->dirs, n);\n   for(i=0; i < stb_arr_len(data->dirs); ++i) {\n      fread(&data->dirs[i].last_modified, 4, 1, f);\n      data->dirs[i].path = stb_fget_string(f, data->string_pool);\n      if (data->dirs[i].path == NULL) goto bail;\n   }\n   fread(&n, 4, 1, f);\n   stb_arr_setlen(data->files, n);\n   for (i=0; i < stb_arr_len(data->files); ++i) {\n      data->files[i].dir  = stb_fget_ranged(f, 0, stb_arr_len(data->dirs));\n      data->files[i].size = stb_fget_varlen64(f);\n      fread(&data->files[i].last_modified, 4, 1, f);\n      data->files[i].name = stb_fget_string(f, data->string_pool);\n      if (data->files[i].name == NULL) goto bail;\n   }\n\n   if (0) {\n      bail:\n         stb_arr_free(data->dirs);\n         stb_arr_free(data->files);\n   }\n   fclose(f);\n}\n\nFILE *hlog;\n\nstatic int stb__dircount, stb__dircount_mask, stb__showfile;\nstatic void stb__dirtree_scandir(char *path, time_t last_time, stb_dirtree *active)\n{\n   // this is dumb depth first; theoretically it might be faster\n   // to fully traverse each directory before visiting its children,\n   // but it's complicated and didn't seem like a gain in the test app\n\n   int n;\n\n   struct _wfinddatai64_t c_file;\n   long hFile;\n   stb__wchar full_path[1024];\n   int has_slash;\n   if (stb__showfile) printf(\"<\");\n\n   has_slash = (path[0] && path[strlen(path)-1] == '/');\n\n   // @TODO: do this concatenation without using swprintf to avoid this mess:\n#if (defined(_MSC_VER) && _MSC_VER < 1400) // || (defined(__clang__))\n   // confusingly, Windows Kits\\10 needs to go down this path?!?\n   // except now it doesn't, I don't know what changed\n   if (has_slash)\n      swprintf(full_path, L\"%s*\", stb__from_utf8(path));\n   else\n      swprintf(full_path, L\"%s/*\", stb__from_utf8(path));\n#else\n   if (has_slash)\n      swprintf((wchar_t *) full_path, (size_t) 1024, L\"%s*\", (wchar_t *) stb__from_utf8(path));\n   else\n      swprintf((wchar_t *) full_path, (size_t) 1024, L\"%s/*\", (wchar_t *) stb__from_utf8(path));\n#endif\n\n   // it's possible this directory is already present: that means it was in the\n   // cache, but its parent wasn't... in that case, we're done with it\n   if (stb__showfile) printf(\"C[%d]\", stb_arr_len(active->dirs));\n   for (n=0; n < stb_arr_len(active->dirs); ++n)\n      if (0 == stb_stricmp(active->dirs[n].path, path)) {\n         if (stb__showfile) printf(\"D\");\n         return;\n      }\n   if (stb__showfile) printf(\"E\");\n\n   // otherwise, we need to add it\n   stb__dirtree_add_dir(path, last_time, active);\n   n = stb_arr_lastn(active->dirs);\n\n   if (stb__showfile) printf(\"[\");\n   if( (hFile = (long) _wfindfirsti64( (wchar_t *) full_path, &c_file )) != -1L ) {\n      do {\n         if (stb__showfile) printf(\")\");\n         if (c_file.attrib & _A_SUBDIR) {\n            // ignore subdirectories starting with '.', e.g. \".\" and \"..\"\n            if (c_file.name[0] != '.') {\n               char *new_path = (char *) full_path;\n               char *temp = stb__to_utf8((stb__wchar *) c_file.name);\n\n               if (has_slash)\n                  stb_p_sprintf(new_path stb_p_size(sizeof(full_path)), \"%s%s\", path, temp);\n               else\n                  stb_p_sprintf(new_path stb_p_size(sizeof(full_path)), \"%s/%s\", path, temp);\n\n               if (stb__dircount_mask) {\n                  ++stb__dircount;\n                  if (!(stb__dircount & stb__dircount_mask)) {\n                     char dummy_path[128], *pad;\n                     stb_strncpy(dummy_path, new_path, sizeof(dummy_path)-1);\n                     if (strlen(dummy_path) > 96) {\n                        stb_p_strcpy_s(dummy_path+96/2-1,128, \"...\");\n                        stb_p_strcpy_s(dummy_path+96/2+2,128, new_path + strlen(new_path)-96/2+2);\n                     }\n                     pad = dummy_path + strlen(dummy_path);\n                     while (pad < dummy_path+98)\n                        *pad++ = ' ';\n                     *pad = 0;\n                     printf(\"%s\\r\", dummy_path);\n                     #if 0\n                     if (hlog == 0) {\n                        hlog = stb_p_fopen(\"c:/x/temp.log\", \"w\");\n                        fprintf(hlog, \"%s\\n\", dummy_path);\n                     }\n                     #endif\n                  }\n               }\n\n               stb__dirtree_scandir(new_path, c_file.time_write, active);\n            }\n         } else {\n            char *temp = stb__to_utf8((stb__wchar *) c_file.name);\n            stb__dirtree_add_file(temp, n, c_file.size, c_file.time_write, active);\n         }\n         if (stb__showfile) printf(\"(\");\n      } while( _wfindnexti64( hFile, &c_file ) == 0 );\n      if (stb__showfile) printf(\"]\");\n      _findclose( hFile );\n   }\n   if (stb__showfile) printf(\">\\n\");\n}\n\n// scan the database and see if it's all valid\nstatic int stb__dirtree_update_db(stb_dirtree *db, stb_dirtree *active)\n{\n   int changes_detected = STB_FALSE;\n   int i;\n   int *remap;\n   int *rescan=NULL;\n   remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(db->dirs));\n   memset(remap, 0, sizeof(remap[0]) * stb_arr_len(db->dirs));\n   rescan = NULL;\n\n   for (i=0; i < stb_arr_len(db->dirs); ++i) {\n      struct _stat info;\n      if (stb__dircount_mask) {\n         ++stb__dircount;\n         if (!(stb__dircount & stb__dircount_mask)) {\n            printf(\".\");\n         }\n      }\n      if (0 == _stat(db->dirs[i].path, &info)) {\n         if (info.st_mode & _S_IFDIR) {\n            // it's still a directory, as expected\n            int n = abs((int) (info.st_mtime - db->dirs[i].last_modified));\n            if (n > 1 && n != 3600) {  // the 3600 is a hack because sometimes this jumps for no apparent reason, even when no time zone or DST issues are at play\n               // it's changed! force a rescan\n               // we don't want to scan it until we've stat()d its\n               // subdirs, though, so we queue it\n               if (stb__showfile) printf(\"Changed: %s - %08x:%08x\\n\", db->dirs[i].path, (unsigned int) db->dirs[i].last_modified, (unsigned int) info.st_mtime);\n               stb_arr_push(rescan, i);\n               // update the last_mod time\n               db->dirs[i].last_modified = info.st_mtime;\n               // ignore existing files in this dir\n               remap[i] = -1;\n               changes_detected = STB_TRUE;\n            } else {\n               // it hasn't changed, just copy it through unchanged\n               stb__dirtree_add_dir(db->dirs[i].path, db->dirs[i].last_modified, active);\n               remap[i] = stb_arr_lastn(active->dirs);\n            }\n         } else {\n            // this path used to refer to a directory, but now it's a file!\n            // assume that the parent directory is going to be forced to rescan anyway\n            goto delete_entry;\n         }\n      } else {\n        delete_entry:\n         // directory no longer exists, so don't copy it\n         // we don't free it because it's in the string pool now\n         db->dirs[i].path = NULL;\n         remap[i] = -1;\n         changes_detected = STB_TRUE;\n      }\n   }\n\n   // at this point, we have:\n   //\n   //   <rescan> holds a list of directory indices that need to be scanned due to being out of date\n   //   <remap> holds the directory index in <active> for each dir in <db>, if it exists; -1 if not\n   //           directories in <rescan> are not in <active> yet\n\n   // so we can go ahead and remap all the known files right now\n   for (i=0; i < stb_arr_len(db->files); ++i) {\n      int dir = db->files[i].dir;\n      if (remap[dir] >= 0) {\n         stb__dirtree_add_file(db->files[i].name, remap[dir], db->files[i].size, db->files[i].last_modified, active);\n      }\n   }\n\n   // at this point we're done with db->files, and done with remap\n   free(remap);\n\n   // now scan those directories using the standard scan\n   for (i=0; i < stb_arr_len(rescan); ++i) {\n      int z = rescan[i];\n      stb__dirtree_scandir(db->dirs[z].path, db->dirs[z].last_modified, active);\n   }\n   stb_arr_free(rescan);\n\n   return changes_detected;\n}\n\nstatic void stb__dirtree_free_raw(stb_dirtree *d)\n{\n   stb_free(d->string_pool);\n   stb_arr_free(d->dirs);\n   stb_arr_free(d->files);\n}\n\nstb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file)\n{\n   stb_dirtree *output = (stb_dirtree *) malloc(sizeof(*output));\n   stb_dirtree db,active;\n   int prev_dir_count, cache_mismatch;\n\n   char *stripped_dir; // store the directory name without a trailing '/' or '\\\\'\n\n   // load the database of last-known state on disk\n   db.string_pool = NULL;\n   db.files = NULL;\n   db.dirs = NULL;\n\n   stripped_dir = stb_strip_final_slash(stb_p_strdup(dir));\n\n   if (cache_file != NULL)\n      stb__dirtree_load_db(cache_file, &db, stripped_dir);\n   else if (stb__showfile)\n      printf(\"No cache file\\n\");\n\n   active.files = NULL;\n   active.dirs = NULL;\n   active.string_pool = stb_malloc(0,1); // @TODO: share string pools between both?\n\n   // check all the directories in the database; make note if\n   // anything we scanned had changed, and rescan those things\n   cache_mismatch = stb__dirtree_update_db(&db, &active);\n\n   // check the root tree\n   prev_dir_count = stb_arr_len(active.dirs);  // record how many directories we've seen\n\n   stb__dirtree_scandir(stripped_dir, 0, &active);  // no last_modified time available for root\n\n   if (stb__dircount_mask)\n      printf(\"                                                                              \\r\");\n\n   // done with the DB; write it back out if any changes, i.e. either\n   //      1. any inconsistency found between cached information and actual disk\n   //   or 2. if scanning the root found any new directories--which we detect because\n   //         more than one directory got added to the active db during that scan\n   if (cache_mismatch || stb_arr_len(active.dirs) > prev_dir_count+1)\n      stb__dirtree_save_db(cache_file, &active, stripped_dir);\n\n   free(stripped_dir);\n\n   stb__dirtree_free_raw(&db);\n\n   *output = active;\n   return output;\n}\n\nstb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir)\n{\n   int i;\n   stb_uint8 sha[20];\n   char dir_lower[1024];\n   char cache_file[1024],*s;\n   if (cache_dir == NULL)\n      return stb_dirtree_get_with_file(dir, NULL);\n   stb_p_strcpy_s(dir_lower, sizeof(dir_lower), dir);\n   stb_tolower(dir_lower);\n   stb_sha1(sha, (unsigned char *) dir_lower, (unsigned int) strlen(dir_lower));\n   stb_p_strcpy_s(cache_file, sizeof(cache_file), cache_dir);\n   s = cache_file + strlen(cache_file);\n   if (s[-1] != '/' && s[-1] != '\\\\') *s++ = '/';\n   stb_p_strcpy_s(s, sizeof(cache_file), \"dirtree_\");\n   s += strlen(s);\n   for (i=0; i < 8; ++i) {\n      char *hex = (char*)\"0123456789abcdef\";\n      stb_uint z = sha[i];\n      *s++ = hex[z >> 4];\n      *s++ = hex[z & 15];\n   }\n   stb_p_strcpy_s(s, sizeof(cache_file), \".bin\");\n   return stb_dirtree_get_with_file(dir, cache_file);\n}\n\nstb_dirtree *stb_dirtree_get(char *dir)\n{\n   char cache_dir[256];\n   stb_p_strcpy_s(cache_dir, sizeof(cache_dir), \"c:/bindata\");\n   #ifdef STB_HAS_REGISTRY\n   {\n      void *reg = stb_reg_open(\"rHKLM\", \"Software\\\\SilverSpaceship\\\\stb\");\n      if (reg) {\n         stb_reg_read(reg, \"dirtree\", cache_dir, sizeof(cache_dir));\n         stb_reg_close(reg);\n      }\n   }\n   #endif\n   return stb_dirtree_get_dir(dir, cache_dir);\n}\n\nvoid stb_dirtree_free(stb_dirtree *d)\n{\n   stb__dirtree_free_raw(d);\n   free(d);\n}\n\nvoid stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last)\n{\n   stb__dirtree_add_dir(path, last, active);\n}\n\nvoid stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last)\n{\n   stb__dirtree_add_file(name, dir, size, last, active);\n}\n\nvoid stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir)\n{\n   char *s = stb_strip_final_slash(stb_p_strdup(dir));\n   target->dirs = 0;\n   target->files = 0;\n   target->string_pool = 0;\n   stb__dirtree_load_db(filename, target, s);\n   free(s);\n}\n\nvoid stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir)\n{\n   stb__dirtree_save_db(filename, target, 0); // don't strip out any directories\n}\n\n#endif // STB_DEFINE\n\n#endif // _WIN32\n#endif // STB_NO_STB_STRINGS\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  STB_MALLOC_WRAPPER\n//\n//    you can use the wrapper functions with your own malloc wrapper,\n//    or define STB_MALLOC_WRAPPER project-wide to have\n//    malloc/free/realloc/strdup all get vectored to it\n\n// this has too many very specific error messages you could google for and find in stb.h,\n// so don't use it if they don't want any stb.h-identifiable strings\n#if defined(STB_DEFINE) && !defined(STB_NO_STB_STRINGS)\n\ntypedef struct\n{\n   void *p;\n   char *file;\n   int  line;\n   size_t size;\n} stb_malloc_record;\n\n#ifndef STB_MALLOC_HISTORY_COUNT\n#define STB_MALLOC_HISTORY_COUNT 50 // 800 bytes\n#endif\n\nstb_malloc_record *stb__allocations;\nstatic int stb__alloc_size, stb__alloc_limit, stb__alloc_mask;\nint stb__alloc_count;\n\nstb_malloc_record stb__alloc_history[STB_MALLOC_HISTORY_COUNT];\nint stb__history_pos;\n\nstatic int stb__hashfind(void *p)\n{\n   stb_uint32 h = stb_hashptr(p);\n   int s,n = h & stb__alloc_mask;\n   if (stb__allocations[n].p == p)\n      return n;\n   s = stb_rehash(h)|1;\n   for(;;) {\n      if (stb__allocations[n].p == NULL)\n         return -1;\n      n = (n+s) & stb__alloc_mask;\n      if (stb__allocations[n].p == p)\n         return n;\n   }\n}\n\nsize_t stb_wrapper_allocsize(void *p)\n{\n   int n = stb__hashfind(p);\n   if (n < 0) return 0;\n   return stb__allocations[n].size;\n}\n\nstatic int stb__historyfind(void *p)\n{\n   int n = stb__history_pos;\n   int i;\n   for (i=0; i < STB_MALLOC_HISTORY_COUNT; ++i) {\n      if (--n < 0) n = STB_MALLOC_HISTORY_COUNT-1;\n      if (stb__alloc_history[n].p == p)\n         return n;\n   }\n   return -1;\n}\n\nstatic void stb__add_alloc(void *p, size_t sz, char *file, int line);\nstatic void stb__grow_alloc(void)\n{\n   int i,old_num = stb__alloc_size;\n   stb_malloc_record *old = stb__allocations;\n   if (stb__alloc_size == 0)\n      stb__alloc_size = 64;\n   else\n      stb__alloc_size *= 2;\n\n   stb__allocations = (stb_malloc_record *) stb__realloc_raw(NULL, stb__alloc_size * sizeof(stb__allocations[0]));\n   if (stb__allocations == NULL)\n      stb_fatal(\"Internal error: couldn't grow malloc wrapper table\");\n   memset(stb__allocations, 0, stb__alloc_size * sizeof(stb__allocations[0]));\n   stb__alloc_limit = (stb__alloc_size*3)>>2;\n   stb__alloc_mask = stb__alloc_size-1;\n\n   stb__alloc_count = 0;\n\n   for (i=0; i < old_num; ++i)\n      if (old[i].p > STB_DEL) {\n         stb__add_alloc(old[i].p, old[i].size, old[i].file, old[i].line);\n         assert(stb__hashfind(old[i].p) >= 0);\n      }\n   for (i=0; i < old_num; ++i)\n      if (old[i].p > STB_DEL)\n         assert(stb__hashfind(old[i].p) >= 0);\n   stb__realloc_raw(old, 0);\n}\n\nstatic void stb__add_alloc(void *p, size_t sz, char *file, int line)\n{\n   stb_uint32 h;\n   int n;\n   if (stb__alloc_count >= stb__alloc_limit)\n      stb__grow_alloc();\n   h = stb_hashptr(p);\n   n = h & stb__alloc_mask;\n   if (stb__allocations[n].p > STB_DEL) {\n      int s = stb_rehash(h)|1;\n      do {\n         n = (n+s) & stb__alloc_mask;\n      } while (stb__allocations[n].p > STB_DEL);\n   }\n   assert(stb__allocations[n].p == NULL || stb__allocations[n].p == STB_DEL);\n   stb__allocations[n].p = p;\n   stb__allocations[n].size = sz;\n   stb__allocations[n].line = line;\n   stb__allocations[n].file = file;\n   ++stb__alloc_count;\n}\n\nstatic void stb__remove_alloc(int n, char *file, int line)\n{\n   stb__alloc_history[stb__history_pos] = stb__allocations[n];\n   stb__alloc_history[stb__history_pos].file = file;\n   stb__alloc_history[stb__history_pos].line = line;\n   if (++stb__history_pos == STB_MALLOC_HISTORY_COUNT)\n      stb__history_pos = 0;\n   stb__allocations[n].p = STB_DEL;\n   --stb__alloc_count;\n}\n\nvoid stb_wrapper_malloc(void *p, size_t sz, char *file, int line)\n{\n   if (!p) return;\n   stb__add_alloc(p,sz,file,line);\n}\n\nvoid stb_wrapper_free(void *p, char *file, int line)\n{\n   int n;\n\n   if (p == NULL) return;\n\n   n = stb__hashfind(p);\n\n   if (n >= 0)\n      stb__remove_alloc(n, file, line);\n   else {\n      // tried to free something we hadn't allocated!\n      n = stb__historyfind(p);\n      assert(0); /* NOTREACHED */\n      if (n >= 0)\n         stb_fatal(\"Attempted to free %d-byte block %p at %s:%d previously freed/realloced at %s:%d\",\n                       stb__alloc_history[n].size, p,\n                       file, line,\n                       stb__alloc_history[n].file, stb__alloc_history[n].line);\n      else\n         stb_fatal(\"Attempted to free unknown block %p at %s:%d\", p, file,line);\n   }\n}\n\nvoid stb_wrapper_check(void *p)\n{\n   int n;\n\n   if (p == NULL) return;\n\n   n = stb__hashfind(p);\n\n   if (n >= 0) return;\n\n   for (n=0; n < stb__alloc_size; ++n)\n      if (stb__allocations[n].p == p)\n         stb_fatal(\"Internal error: pointer %p was allocated, but hash search failed\", p);\n\n   // tried to free something that wasn't allocated!\n   n = stb__historyfind(p);\n   if (n >= 0)\n      stb_fatal(\"Checked %d-byte block %p previously freed/realloced at %s:%d\",\n                    stb__alloc_history[n].size, p,\n                    stb__alloc_history[n].file, stb__alloc_history[n].line);\n   stb_fatal(\"Checked unknown block %p\");\n}\n\nvoid stb_wrapper_realloc(void *p, void *q, size_t sz, char *file, int line)\n{\n   int n;\n   if (p == NULL) { stb_wrapper_malloc(q, sz, file, line); return; }\n   if (q == NULL) return; // nothing happened\n\n   n = stb__hashfind(p);\n   if (n == -1) {\n      // tried to free something we hadn't allocated!\n      // this is weird, though, because we got past the realloc!\n      n = stb__historyfind(p);\n      assert(0); /* NOTREACHED */\n      if (n >= 0)\n         stb_fatal(\"Attempted to realloc %d-byte block %p at %s:%d previously freed/realloced at %s:%d\",\n                       stb__alloc_history[n].size, p,\n                       file, line,\n                       stb__alloc_history[n].file, stb__alloc_history[n].line);\n      else\n         stb_fatal(\"Attempted to realloc unknown block %p at %s:%d\", p, file,line);\n   } else {\n      if (q == p) {\n         stb__allocations[n].size = sz;\n         stb__allocations[n].file = file;\n         stb__allocations[n].line = line;\n      } else {\n         stb__remove_alloc(n, file, line);\n         stb__add_alloc(q,sz,file,line);\n      }\n   }\n}\n\nvoid stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line))\n{\n   int i;\n   for (i=0; i < stb__alloc_size; ++i)\n      if (stb__allocations[i].p > STB_DEL)\n         func(stb__allocations[i].p   , stb__allocations[i].size,\n              stb__allocations[i].file, stb__allocations[i].line);\n}\n\nvoid stb_wrapper_dump(char *filename)\n{\n   int i;\n   FILE *f = stb_p_fopen(filename, \"w\");\n   if (!f) return;\n   for (i=0; i < stb__alloc_size; ++i)\n      if (stb__allocations[i].p > STB_DEL)\n         fprintf(f, \"%p %7d - %4d %s\\n\",\n            stb__allocations[i].p   , (int) stb__allocations[i].size,\n            stb__allocations[i].line, stb__allocations[i].file);\n}\n#endif // STB_DEFINE\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                  stb_pointer_set\n//\n//\n// For data structures that support querying by key, data structure\n// classes always hand-wave away the issue of what to do if two entries\n// have the same key: basically, store a linked list of all the nodes\n// which have the same key (a LISP-style list).\n//\n// The thing is, it's not that trivial. If you have an O(log n)\n// lookup data structure, but then n/4 items have the same value,\n// you don't want to spend O(n) time scanning that list when\n// deleting an item if you already have a pointer to the item.\n// (You have to spend O(n) time enumerating all the items with\n// a given key, sure, and you can't accelerate deleting a particular\n// item if you only have the key, not a pointer to the item.)\n//\n// I'm going to call this data structure, whatever it turns out to\n// be, a \"pointer set\", because we don't store any associated data for\n// items in this data structure, we just answer the question of\n// whether an item is in it or not (it's effectively one bit per pointer).\n// Technically they don't have to be pointers; you could cast ints\n// to (void *) if you want, but you can't store 0 or 1 because of the\n// hash table.\n//\n// Since the fastest data structure we might want to add support for\n// identical-keys to is a hash table with O(1)-ish lookup time,\n// that means that the conceptual \"linked list of all items with\n// the same indexed value\" that we build needs to have the same\n// performance; that way when we index a table we think is arbitrary\n// ints, but in fact half of them are 0, we don't get screwed.\n//\n// Therefore, it needs to be a hash table, at least when it gets\n// large. On the other hand, when the data has totally arbitrary ints\n// or floats, there won't be many collisions, and we'll have tons of\n// 1-item bitmaps. That will be grossly inefficient as hash tables;\n// trade-off; the hash table is reasonably efficient per-item when\n// it's large, but not when it's small. So we need to do something\n// Judy-like and use different strategies depending on the size.\n//\n// Like Judy, we'll use the bottom bit to encode the strategy:\n//\n//      bottom bits:\n//          00     -   direct pointer\n//          01     -   4-item bucket (16 bytes, no length, NULLs)\n//          10     -   N-item array\n//          11     -   hash table\n\ntypedef struct stb_ps stb_ps;\n\nSTB_EXTERN int      stb_ps_find  (stb_ps *ps, void *value);\nSTB_EXTERN stb_ps * stb_ps_add   (stb_ps *ps, void *value);\nSTB_EXTERN stb_ps * stb_ps_remove(stb_ps *ps, void *value);\nSTB_EXTERN stb_ps * stb_ps_remove_any(stb_ps *ps, void **value);\nSTB_EXTERN void     stb_ps_delete(stb_ps *ps);\nSTB_EXTERN int      stb_ps_count (stb_ps *ps);\n\nSTB_EXTERN stb_ps * stb_ps_copy  (stb_ps *ps);\nSTB_EXTERN int      stb_ps_subset(stb_ps *bigger, stb_ps *smaller);\nSTB_EXTERN int      stb_ps_eq    (stb_ps *p0, stb_ps *p1);\n\nSTB_EXTERN void ** stb_ps_getlist  (stb_ps *ps, int *count);\nSTB_EXTERN int     stb_ps_writelist(stb_ps *ps, void **list, int size );\n\n// enum and fastlist don't allocate storage, but you must consume the\n// list before there's any chance the data structure gets screwed up;\nSTB_EXTERN int     stb_ps_enum     (stb_ps *ps, void *data,\n                                       int (*func)(void *value, void*data) );\nSTB_EXTERN void ** stb_ps_fastlist(stb_ps *ps, int *count);\n//  result:\n//     returns a list, *count is the length of that list,\n//     but some entries of the list may be invalid;\n//     test with 'stb_ps_fastlist_valid(x)'\n\n#define stb_ps_fastlist_valid(x)   ((stb_uinta) (x) > 1)\n\n#ifdef STB_DEFINE\n\nenum\n{\n   STB_ps_direct = 0,\n   STB_ps_bucket = 1,\n   STB_ps_array  = 2,\n   STB_ps_hash   = 3,\n};\n\n#define STB_BUCKET_SIZE  4\n\ntypedef struct\n{\n   void *p[STB_BUCKET_SIZE];\n} stb_ps_bucket;\n#define GetBucket(p)    ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket))\n#define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket))\n\nstatic void stb_bucket_free(stb_ps_bucket *b)\n{\n   free(b);\n}\n\nstatic stb_ps_bucket *stb_bucket_create2(void *v0, void *v1)\n{\n   stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));\n   b->p[0] = v0;\n   b->p[1] = v1;\n   b->p[2] = NULL;\n   b->p[3] = NULL;\n   return b;\n}\n\nstatic stb_ps_bucket * stb_bucket_create3(void **v)\n{\n   stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));\n   b->p[0] = v[0];\n   b->p[1] = v[1];\n   b->p[2] = v[2];\n   b->p[3] = NULL;\n   return b;\n}\n\n\n// could use stb_arr, but this will save us memory\ntypedef struct\n{\n   int count;\n   void *p[1];\n} stb_ps_array;\n#define GetArray(p)     ((stb_ps_array *) ((char *) (p) - STB_ps_array))\n#define EncodeArray(p)  ((stb_ps *) ((char *) (p) + STB_ps_array))\n\nstatic int stb_ps_array_max = 13;\n\ntypedef struct\n{\n   int size, mask;\n   int count, count_deletes;\n   int grow_threshhold;\n   int shrink_threshhold;\n   int rehash_threshhold;\n   int any_offset;\n   void *table[1];\n} stb_ps_hash;\n#define GetHash(p)      ((stb_ps_hash *) ((char *) (p) - STB_ps_hash))\n#define EncodeHash(p)   ((stb_ps *) ((char *) (p) + STB_ps_hash))\n\n#define stb_ps_empty(v)   (((stb_uint32) v) <= 1)\n\nstatic stb_ps_hash *stb_ps_makehash(int size, int old_size, void **old_data)\n{\n   int i;\n   stb_ps_hash *h = (stb_ps_hash *) malloc(sizeof(*h) + (size-1) * sizeof(h->table[0]));\n   assert(stb_is_pow2(size));\n   h->size = size;\n   h->mask = size-1;\n   h->shrink_threshhold = (int) (0.3f * size);\n   h->  grow_threshhold = (int) (0.8f * size);\n   h->rehash_threshhold = (int) (0.9f * size);\n   h->count = 0;\n   h->count_deletes = 0;\n   h->any_offset = 0;\n   memset(h->table, 0, size * sizeof(h->table[0]));\n   for (i=0; i < old_size; ++i)\n        if (!stb_ps_empty((size_t)old_data[i]))\n         stb_ps_add(EncodeHash(h), old_data[i]);\n   return h;\n}\n\nvoid stb_ps_delete(stb_ps *ps)\n{\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct: break;\n      case STB_ps_bucket: stb_bucket_free(GetBucket(ps)); break;\n      case STB_ps_array : free(GetArray(ps)); break;\n      case STB_ps_hash  : free(GetHash(ps)); break;\n   }\n}\n\nstb_ps *stb_ps_copy(stb_ps *ps)\n{\n   int i;\n   // not a switch: order based on expected performance/power-law distribution\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct: return ps;\n      case STB_ps_bucket: {\n         stb_ps_bucket *n = (stb_ps_bucket *) malloc(sizeof(*n));\n         *n = *GetBucket(ps);\n         return EncodeBucket(n);\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         stb_ps_array *n = (stb_ps_array *) malloc(sizeof(*n) + stb_ps_array_max * sizeof(n->p[0]));\n         n->count = a->count;\n         for (i=0; i < a->count; ++i)\n            n->p[i] = a->p[i];\n         return EncodeArray(n);\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         stb_ps_hash *n = stb_ps_makehash(h->size, h->size, h->table);\n         return EncodeHash(n);\n      }\n   }\n   assert(0); /* NOTREACHED */\n   return NULL;\n}\n\nint stb_ps_find(stb_ps *ps, void *value)\n{\n    int i, code = 3 & (int)(size_t) ps;\n    assert((3 & (int)(size_t) value) == STB_ps_direct);\n   assert(stb_ps_fastlist_valid(value));\n   // not a switch: order based on expected performance/power-law distribution\n   if (code == STB_ps_direct)\n      return value == ps;\n   if (code == STB_ps_bucket) {\n      stb_ps_bucket *b = GetBucket(ps);\n      assert(STB_BUCKET_SIZE == 4);\n      if (b->p[0] == value || b->p[1] == value ||\n          b->p[2] == value || b->p[3] == value)\n          return STB_TRUE;\n      return STB_FALSE;\n   }\n   if (code == STB_ps_array) {\n      stb_ps_array *a = GetArray(ps);\n      for (i=0; i < a->count; ++i)\n         if (a->p[i] == value)\n            return STB_TRUE;\n      return STB_FALSE;\n   } else {\n      stb_ps_hash *h = GetHash(ps);\n      stb_uint32 hash = stb_hashptr(value);\n      stb_uint32 s, n = hash & h->mask;\n      void **t = h->table;\n      if (t[n] == value) return STB_TRUE;\n      if (t[n] == NULL) return STB_FALSE;\n      s = stb_rehash(hash) | 1;\n      do {\n         n = (n + s) & h->mask;\n         if (t[n] == value) return STB_TRUE;\n      } while (t[n] != NULL);\n      return STB_FALSE;\n   }\n}\n\nstb_ps *  stb_ps_add   (stb_ps *ps, void *value)\n{\n   #ifdef STB_DEBUG\n   assert(!stb_ps_find(ps,value));\n   #endif\n   if (value == NULL) return ps; // ignore NULL adds to avoid bad breakage\n    assert((3 & (int)(size_t) value) == STB_ps_direct);\n   assert(stb_ps_fastlist_valid(value));\n   assert(value != STB_DEL);     // STB_DEL is less likely\n\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         if (ps == NULL) return (stb_ps *) value;\n         return EncodeBucket(stb_bucket_create2(ps,value));\n\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         stb_ps_array  *a;\n         assert(STB_BUCKET_SIZE == 4);\n         if (b->p[0] == NULL) { b->p[0] = value; return ps; }\n         if (b->p[1] == NULL) { b->p[1] = value; return ps; }\n         if (b->p[2] == NULL) { b->p[2] = value; return ps; }\n         if (b->p[3] == NULL) { b->p[3] = value; return ps; }\n         a = (stb_ps_array *) malloc(sizeof(*a) + 7 * sizeof(a->p[0])); // 8 slots, must be 2^k\n         memcpy(a->p, b, sizeof(*b));\n         a->p[4] = value;\n         a->count = 5;\n         stb_bucket_free(b);\n         return EncodeArray(a);\n      }\n\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         if (a->count == stb_ps_array_max) {\n            // promote from array to hash\n            stb_ps_hash *h = stb_ps_makehash(2 << stb_log2_ceil(a->count), a->count, a->p);\n            free(a);\n            return stb_ps_add(EncodeHash(h), value);\n         }\n         // do we need to resize the array? the array doubles in size when it\n         // crosses a power-of-two\n         if ((a->count & (a->count-1))==0) {\n            int newsize = a->count*2;\n            // clamp newsize to max if:\n            //    1. it's larger than max\n            //    2. newsize*1.5 is larger than max (to avoid extra resizing)\n            if (newsize + a->count > stb_ps_array_max)\n               newsize = stb_ps_array_max;\n            a = (stb_ps_array *) realloc(a, sizeof(*a) + (newsize-1) * sizeof(a->p[0]));\n         }\n         a->p[a->count++] = value;\n         return EncodeArray(a);\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         stb_uint32 hash = stb_hashptr(value);\n         stb_uint32 n = hash & h->mask;\n         void **t = h->table;\n         // find first NULL or STB_DEL entry\n          if (!stb_ps_empty((size_t)t[n])) {\n            stb_uint32 s = stb_rehash(hash) | 1;\n            do {\n               n = (n + s) & h->mask;\n            } while (!stb_ps_empty((size_t)t[n]));\n         }\n         if (t[n] == STB_DEL)\n            -- h->count_deletes;\n         t[n] = value;\n         ++ h->count;\n         if (h->count == h->grow_threshhold) {\n            stb_ps_hash *h2 = stb_ps_makehash(h->size*2, h->size, t);\n            free(h);\n            return EncodeHash(h2);\n         }\n         if (h->count + h->count_deletes == h->rehash_threshhold) {\n            stb_ps_hash *h2 = stb_ps_makehash(h->size, h->size, t);\n            free(h);\n            return EncodeHash(h2);\n         }\n         return ps;\n      }\n   }\n   return NULL; /* NOTREACHED */\n}\n\nstb_ps *stb_ps_remove(stb_ps *ps, void *value)\n{\n   #ifdef STB_DEBUG\n   assert(stb_ps_find(ps, value));\n   #endif\n    assert((3 & (int)(size_t) value) == STB_ps_direct);\n   if (value == NULL) return ps; // ignore NULL removes to avoid bad breakage\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         return ps == value ? NULL : ps;\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         int count=0;\n         assert(STB_BUCKET_SIZE == 4);\n         if (b->p[0] == value) b->p[0] = NULL; else count += (b->p[0] != NULL);\n         if (b->p[1] == value) b->p[1] = NULL; else count += (b->p[1] != NULL);\n         if (b->p[2] == value) b->p[2] = NULL; else count += (b->p[2] != NULL);\n         if (b->p[3] == value) b->p[3] = NULL; else count += (b->p[3] != NULL);\n         if (count == 1) { // shrink bucket at size 1\n            value = b->p[0];\n            if (value == NULL) value = b->p[1];\n            if (value == NULL) value = b->p[2];\n            if (value == NULL) value = b->p[3];\n            assert(value != NULL);\n            stb_bucket_free(b);\n            return (stb_ps *) value; // return STB_ps_direct of value\n         }\n         return ps;\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         int i;\n         for (i=0; i < a->count; ++i) {\n            if (a->p[i] == value) {\n               a->p[i] = a->p[--a->count];\n               if (a->count == 3) { // shrink to bucket!\n                  stb_ps_bucket *b = stb_bucket_create3(a->p);\n                  free(a);\n                  return EncodeBucket(b);\n               }\n               return ps;\n            }\n         }\n         return ps;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         stb_uint32 hash = stb_hashptr(value);\n         stb_uint32 s, n = hash & h->mask;\n         void **t = h->table;\n         if (t[n] != value) {\n            s = stb_rehash(hash) | 1;\n            do {\n               n = (n + s) & h->mask;\n            } while (t[n] != value);\n         }\n         t[n] = STB_DEL;\n         -- h->count;\n         ++ h->count_deletes;\n         // should we shrink down to an array?\n         if (h->count < stb_ps_array_max) {\n            int n = 1 << stb_log2_floor(stb_ps_array_max);\n            if (h->count < n) {\n               stb_ps_array *a = (stb_ps_array *) malloc(sizeof(*a) + (n-1) * sizeof(a->p[0]));\n               int i,j=0;\n               for (i=0; i < h->size; ++i)\n                    if (!stb_ps_empty((size_t)t[i]))\n                     a->p[j++] = t[i];\n               assert(j == h->count);\n               a->count = j;\n               free(h);\n               return EncodeArray(a);\n            }\n         }\n         if (h->count == h->shrink_threshhold) {\n            stb_ps_hash *h2 = stb_ps_makehash(h->size >> 1, h->size, t);\n            free(h);\n            return EncodeHash(h2);\n         }\n         return ps;\n      }\n   }\n   return ps; /* NOTREACHED */\n}\n\nstb_ps *stb_ps_remove_any(stb_ps *ps, void **value)\n{\n   assert(ps != NULL);\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         *value = ps;\n         return NULL;\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         int count=0, slast=0, last=0;\n         assert(STB_BUCKET_SIZE == 4);\n         if (b->p[0]) { ++count;               last = 0; }\n         if (b->p[1]) { ++count; slast = last; last = 1; }\n         if (b->p[2]) { ++count; slast = last; last = 2; }\n         if (b->p[3]) { ++count; slast = last; last = 3; }\n         *value = b->p[last];\n         b->p[last] = 0;\n         if (count == 2) {\n            void *leftover = b->p[slast]; // second to last\n            stb_bucket_free(b);\n            return (stb_ps *) leftover;\n         }\n         return ps;\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         *value = a->p[a->count-1];\n         if (a->count == 4)\n            return stb_ps_remove(ps, *value);\n         --a->count;\n         return ps;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         void **t = h->table;\n         stb_uint32 n = h->any_offset;\n          while (stb_ps_empty((size_t)t[n]))\n            n = (n + 1) & h->mask;\n         *value = t[n];\n         h->any_offset = (n+1) & h->mask;\n         // check if we need to skip down to the previous type\n         if (h->count-1 < stb_ps_array_max || h->count-1 == h->shrink_threshhold)\n            return stb_ps_remove(ps, *value);\n         t[n] = STB_DEL;\n         -- h->count;\n         ++ h->count_deletes;\n         return ps;\n      }\n   }\n   return ps; /* NOTREACHED */\n}\n\n\nvoid ** stb_ps_getlist(stb_ps *ps, int *count)\n{\n   int i,n=0;\n   void **p = NULL;\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         if (ps == NULL) { *count = 0; return NULL; }\n         p = (void **) malloc(sizeof(*p) * 1);\n         p[0] = ps;\n         *count = 1;\n         return p;\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         p = (void **) malloc(sizeof(*p) * STB_BUCKET_SIZE);\n         for (i=0; i < STB_BUCKET_SIZE; ++i)\n            if (b->p[i] != NULL)\n               p[n++] = b->p[i];\n         break;\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         p = (void **) malloc(sizeof(*p) * a->count);\n         memcpy(p, a->p, sizeof(*p) * a->count);\n         *count = a->count;\n         return p;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         p = (void **) malloc(sizeof(*p) * h->count);\n         for (i=0; i < h->size; ++i)\n              if (!stb_ps_empty((size_t)h->table[i]))\n               p[n++] = h->table[i];\n         break;\n      }\n   }\n   *count = n;\n   return p;\n}\n\nint stb_ps_writelist(stb_ps *ps, void **list, int size )\n{\n   int i,n=0;\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         if (ps == NULL || size <= 0) return 0;\n         list[0] = ps;\n         return 1;\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         for (i=0; i < STB_BUCKET_SIZE; ++i)\n            if (b->p[i] != NULL && n < size)\n               list[n++] = b->p[i];\n         return n;\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         n = stb_min(size, a->count);\n         memcpy(list, a->p, sizeof(*list) * n);\n         return n;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         if (size <= 0) return 0;\n         for (i=0; i < h->count; ++i) {\n             if (!stb_ps_empty((size_t)h->table[i])) {\n               list[n++] = h->table[i];\n               if (n == size) break;\n            }\n         }\n         return n;\n      }\n   }\n   return 0; /* NOTREACHED */\n}\n\nint stb_ps_enum(stb_ps *ps, void *data, int (*func)(void *value, void *data))\n{\n   int i;\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         if (ps == NULL) return STB_TRUE;\n         return func(ps, data);\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         for (i=0; i < STB_BUCKET_SIZE; ++i)\n            if (b->p[i] != NULL)\n               if (!func(b->p[i], data))\n                  return STB_FALSE;\n         return STB_TRUE;\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         for (i=0; i < a->count; ++i)\n            if (!func(a->p[i], data))\n               return STB_FALSE;\n         return STB_TRUE;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         for (i=0; i < h->count; ++i)\n              if (!stb_ps_empty((size_t)h->table[i]))\n               if (!func(h->table[i], data))\n                  return STB_FALSE;\n         return STB_TRUE;\n      }\n   }\n   return STB_TRUE; /* NOTREACHED */\n}\n\nint stb_ps_count (stb_ps *ps)\n{\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         return ps != NULL;\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         return (b->p[0] != NULL) + (b->p[1] != NULL) +\n                (b->p[2] != NULL) + (b->p[3] != NULL);\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         return a->count;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         return h->count;\n      }\n   }\n   return 0;\n}\n\nvoid ** stb_ps_fastlist(stb_ps *ps, int *count)\n{\n   static void *storage;\n\n    switch (3 & (int)(size_t) ps) {\n      case STB_ps_direct:\n         if (ps == NULL) { *count = 0; return NULL; }\n         storage = ps;\n         *count = 1;\n         return &storage;\n      case STB_ps_bucket: {\n         stb_ps_bucket *b = GetBucket(ps);\n         *count = STB_BUCKET_SIZE;\n         return b->p;\n      }\n      case STB_ps_array: {\n         stb_ps_array *a = GetArray(ps);\n         *count = a->count;\n         return a->p;\n      }\n      case STB_ps_hash: {\n         stb_ps_hash *h = GetHash(ps);\n         *count = h->size;\n         return h->table;\n      }\n   }\n   return NULL; /* NOTREACHED */\n}\n\nint stb_ps_subset(stb_ps *bigger, stb_ps *smaller)\n{\n   int i, listlen;\n   void **list = stb_ps_fastlist(smaller, &listlen);\n   for(i=0; i < listlen; ++i)\n      if (stb_ps_fastlist_valid(list[i]))\n         if (!stb_ps_find(bigger, list[i]))\n            return 0;\n   return 1;\n}\n\nint stb_ps_eq(stb_ps *p0, stb_ps *p1)\n{\n   if (stb_ps_count(p0) != stb_ps_count(p1))\n      return 0;\n   return stb_ps_subset(p0, p1);\n}\n\n#undef GetBucket\n#undef GetArray\n#undef GetHash\n\n#undef EncodeBucket\n#undef EncodeArray\n#undef EncodeHash\n\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//               Random Numbers via Meresenne Twister or LCG\n//\n\nSTB_EXTERN unsigned int  stb_srandLCG(unsigned int seed);\nSTB_EXTERN unsigned int  stb_randLCG(void);\nSTB_EXTERN double        stb_frandLCG(void);\n\nSTB_EXTERN void          stb_srand(unsigned int seed);\nSTB_EXTERN unsigned int  stb_rand(void);\nSTB_EXTERN double        stb_frand(void);\nSTB_EXTERN void          stb_shuffle(void *p, size_t n, size_t sz,\n                                        unsigned int seed);\nSTB_EXTERN void stb_reverse(void *p, size_t n, size_t sz);\n\nSTB_EXTERN unsigned int  stb_randLCG_explicit(unsigned int  seed);\n\n#define stb_rand_define(x,y)                                         \\\n                                                                     \\\n   unsigned int  x(void)                                             \\\n   {                                                                 \\\n      static unsigned int  stb__rand = y;                            \\\n      stb__rand = stb__rand * 2147001325 + 715136305; /* BCPL */     \\\n      return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));   \\\n   }\n\n#ifdef STB_DEFINE\nunsigned int  stb_randLCG_explicit(unsigned int seed)\n{\n   return seed * 2147001325 + 715136305;\n}\n\nstatic unsigned int  stb__rand_seed=0;\n\nunsigned int  stb_srandLCG(unsigned int seed)\n{\n   unsigned int  previous = stb__rand_seed;\n   stb__rand_seed = seed;\n   return previous;\n}\n\nunsigned int  stb_randLCG(void)\n{\n   stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator\n   // shuffle non-random bits to the middle, and xor to decorrelate with seed\n   return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16));\n}\n\ndouble stb_frandLCG(void)\n{\n   return stb_randLCG() / ((double) (1 << 16) * (1 << 16));\n}\n\nvoid stb_shuffle(void *p, size_t n, size_t sz, unsigned int seed)\n{\n   char *a;\n   unsigned int old_seed;\n   int i;\n   if (seed)\n      old_seed = stb_srandLCG(seed);\n   a = (char *) p + (n-1) * sz;\n\n   for (i=(int) n; i > 1; --i) {\n      int j = stb_randLCG() % i;\n      stb_swap(a, (char *) p + j * sz, sz);\n      a -= sz;\n   }\n   if (seed)\n      stb_srandLCG(old_seed);\n}\n\nvoid stb_reverse(void *p, size_t n, size_t sz)\n{\n   size_t i,j = n-1;\n   for (i=0; i < j; ++i,--j) {\n      stb_swap((char *) p + i * sz, (char *) p + j * sz, sz);\n   }\n}\n\n// public domain Mersenne Twister by Michael Brundage\n#define STB__MT_LEN       624\n\nint stb__mt_index = STB__MT_LEN*sizeof(int)+1;\nunsigned int stb__mt_buffer[STB__MT_LEN];\n\nvoid stb_srand(unsigned int seed)\n{\n   int i;\n   stb__mt_buffer[0]= seed & 0xffffffffUL;\n   for (i=1 ; i < STB__MT_LEN; ++i)\n      stb__mt_buffer[i] = (1812433253UL * (stb__mt_buffer[i-1] ^ (stb__mt_buffer[i-1] >> 30)) + i);\n   stb__mt_index = STB__MT_LEN*sizeof(unsigned int);\n}\n\n#define STB__MT_IA           397\n#define STB__MT_IB           (STB__MT_LEN - STB__MT_IA)\n#define STB__UPPER_MASK      0x80000000\n#define STB__LOWER_MASK      0x7FFFFFFF\n#define STB__MATRIX_A        0x9908B0DF\n#define STB__TWIST(b,i,j)    ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK)\n#define STB__MAGIC(s)        (((s)&1)*STB__MATRIX_A)\n\nunsigned int stb_rand()\n{\n   unsigned int  * b = stb__mt_buffer;\n   int idx = stb__mt_index;\n   unsigned int  s,r;\n   int i;\n\n   if (idx >= STB__MT_LEN*sizeof(unsigned int)) {\n      if (idx > STB__MT_LEN*sizeof(unsigned int))\n         stb_srand(0);\n      idx = 0;\n      i = 0;\n      for (; i < STB__MT_IB; i++) {\n         s = STB__TWIST(b, i, i+1);\n         b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s);\n      }\n      for (; i < STB__MT_LEN-1; i++) {\n         s = STB__TWIST(b, i, i+1);\n         b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s);\n      }\n\n      s = STB__TWIST(b, STB__MT_LEN-1, 0);\n      b[STB__MT_LEN-1] = b[STB__MT_IA-1] ^ (s >> 1) ^ STB__MAGIC(s);\n   }\n   stb__mt_index = idx + sizeof(unsigned int);\n\n   r = *(unsigned int *)((unsigned char *)b + idx);\n\n   r ^= (r >> 11);\n   r ^= (r << 7) & 0x9D2C5680;\n   r ^= (r << 15) & 0xEFC60000;\n   r ^= (r >> 18);\n\n   return r;\n}\n\ndouble stb_frand(void)\n{\n   return stb_rand() / ((double) (1 << 16) * (1 << 16));\n}\n\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                        stb_dupe\n//\n// stb_dupe is a duplicate-finding system for very, very large data\n// structures--large enough that sorting is too slow, but not so large\n// that we can't keep all the data in memory. using it works as follows:\n//\n//     1. create an stb_dupe:\n//          provide a hash function\n//          provide an equality function\n//          provide an estimate for the size\n//          optionally provide a comparison function\n//\n//     2. traverse your data, 'adding' pointers to the stb_dupe\n//\n//     3. finish and ask for duplicates\n//\n//        the stb_dupe will discard its intermediate data and build\n//        a collection of sorted lists of duplicates, with non-duplicate\n//        entries omitted entirely\n//\n//\n//  Implementation strategy:\n//\n//     while collecting the N items, we keep a hash table of approximate\n//     size sqrt(N). (if you tell use the N up front, the hash table is\n//     just that size exactly)\n//\n//     each entry in the hash table is just an stb__arr of pointers (no need\n//     to use stb_ps, because we don't need to delete from these)\n//\n//     for step 3, for each entry in the hash table, we apply stb_dupe to it\n//     recursively. once the size gets small enough (or doesn't decrease\n//     significantly), we switch to either using qsort() on the comparison\n//     function, or else we just do the icky N^2 gather\n\n\ntypedef struct stb_dupe stb_dupe;\n\ntypedef int (*stb_compare_func)(void *a, void *b);\ntypedef int (*stb_hash_func)(void *a, unsigned int seed);\n\nSTB_EXTERN void stb_dupe_free(stb_dupe *sd);\nSTB_EXTERN stb_dupe *stb_dupe_create(stb_hash_func hash,\n                          stb_compare_func eq, int size, stb_compare_func ineq);\nSTB_EXTERN void stb_dupe_add(stb_dupe *sd, void *item);\nSTB_EXTERN void stb_dupe_finish(stb_dupe *sd);\nSTB_EXTERN int stb_dupe_numsets(stb_dupe *sd);\nSTB_EXTERN void **stb_dupe_set(stb_dupe *sd, int num);\nSTB_EXTERN int stb_dupe_set_count(stb_dupe *sd, int num);\n\nstruct stb_dupe\n{\n   void ***hash_table;\n   int hash_size;\n   int size_log2;\n   int population;\n\n   int hash_shift;\n   stb_hash_func     hash;\n\n   stb_compare_func  eq;\n   stb_compare_func  ineq;\n\n   void ***dupes;\n};\n\n#ifdef STB_DEFINE\n\nint stb_dupe_numsets(stb_dupe *sd)\n{\n   assert(sd->hash_table == NULL);\n   return stb_arr_len(sd->dupes);\n}\n\nvoid **stb_dupe_set(stb_dupe *sd, int num)\n{\n   assert(sd->hash_table == NULL);\n   return sd->dupes[num];\n}\n\nint stb_dupe_set_count(stb_dupe *sd, int num)\n{\n   assert(sd->hash_table == NULL);\n   return stb_arr_len(sd->dupes[num]);\n}\n\nstb_dupe *stb_dupe_create(stb_hash_func hash, stb_compare_func eq, int size,\n                                              stb_compare_func ineq)\n{\n   int i, hsize;\n   stb_dupe *sd = (stb_dupe *) malloc(sizeof(*sd));\n\n   sd->size_log2 = 4;\n   hsize = 1 << sd->size_log2;\n   while (hsize * hsize < size) {\n      ++sd->size_log2;\n      hsize *= 2;\n   }\n\n   sd->hash = hash;\n   sd->eq   = eq;\n   sd->ineq = ineq;\n   sd->hash_shift = 0;\n\n   sd->population = 0;\n   sd->hash_size = hsize;\n   sd->hash_table = (void ***) malloc(sizeof(*sd->hash_table) * hsize);\n   for (i=0; i < hsize; ++i)\n      sd->hash_table[i] = NULL;\n\n   sd->dupes = NULL;\n\n   return sd;\n}\n\nvoid stb_dupe_add(stb_dupe *sd, void *item)\n{\n   stb_uint32 hash = sd->hash(item, sd->hash_shift);\n   int z = hash & (sd->hash_size-1);\n   stb_arr_push(sd->hash_table[z], item);\n   ++sd->population;\n}\n\nvoid stb_dupe_free(stb_dupe *sd)\n{\n   int i;\n   for (i=0; i < stb_arr_len(sd->dupes); ++i)\n      if (sd->dupes[i])\n         stb_arr_free(sd->dupes[i]);\n   stb_arr_free(sd->dupes);\n   free(sd);\n}\n\nstatic stb_compare_func stb__compare;\n\nstatic int stb__dupe_compare(const void *a, const void *b)\n{\n   void *p = *(void **) a;\n   void *q = *(void **) b;\n\n   return stb__compare(p,q);\n}\n\nvoid stb_dupe_finish(stb_dupe *sd)\n{\n   int i,j,k;\n   assert(sd->dupes == NULL);\n   for (i=0; i < sd->hash_size; ++i) {\n      void ** list = sd->hash_table[i];\n      if (list != NULL) {\n         int n = stb_arr_len(list);\n         // @TODO: measure to find good numbers instead of just making them up!\n         int thresh = (sd->ineq ? 200 : 20);\n         // if n is large enough to be worth it, and n is smaller than\n         // before (so we can guarantee we'll use a smaller hash table);\n         // and there are enough hash bits left, assuming full 32-bit hash\n         if (n > thresh && n < (sd->population >> 3) && sd->hash_shift + sd->size_log2*2 < 32) {\n\n            // recursively process this row using stb_dupe, O(N log log N)\n\n            stb_dupe *d = stb_dupe_create(sd->hash, sd->eq, n, sd->ineq);\n            d->hash_shift = stb_randLCG_explicit(sd->hash_shift);\n            for (j=0; j < n; ++j)\n               stb_dupe_add(d, list[j]);\n            stb_arr_free(sd->hash_table[i]);\n            stb_dupe_finish(d);\n            for (j=0; j < stb_arr_len(d->dupes); ++j) {\n               stb_arr_push(sd->dupes, d->dupes[j]);\n               d->dupes[j] = NULL; // take over ownership\n            }\n            stb_dupe_free(d);\n\n         } else if (sd->ineq) {\n\n            // process this row using qsort(), O(N log N)\n            stb__compare = sd->ineq;\n            qsort(list, n, sizeof(list[0]), stb__dupe_compare);\n\n            // find equal subsequences of the list\n            for (j=0; j < n-1; ) {\n               // find a subsequence from j..k\n               for (k=j; k < n; ++k)\n                  // only use ineq so eq can be left undefined\n                  if (sd->ineq(list[j], list[k]))\n                     break;\n               // k is the first one not in the subsequence\n               if (k-j > 1) {\n                  void **mylist = NULL;\n                  stb_arr_setlen(mylist, k-j);\n                  memcpy(mylist, list+j, sizeof(list[j]) * (k-j));\n                  stb_arr_push(sd->dupes, mylist);\n               }\n               j = k;\n            }\n            stb_arr_free(sd->hash_table[i]);\n         } else {\n\n            // process this row using eq(), O(N^2)\n            for (j=0; j < n; ++j) {\n               if (list[j] != NULL) {\n                  void **output  = NULL;\n                  for (k=j+1; k < n; ++k) {\n                     if (sd->eq(list[j], list[k])) {\n                        if (output == NULL)\n                           stb_arr_push(output, list[j]);\n                        stb_arr_push(output, list[k]);\n                        list[k] = NULL;\n                     }\n                  }\n                  list[j] = NULL;\n                  if (output)\n                     stb_arr_push(sd->dupes, output);\n               }\n            }\n            stb_arr_free(sd->hash_table[i]);\n         }\n      }\n   }\n   free(sd->hash_table);\n   sd->hash_table = NULL;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                       templatized Sort routine\n//\n// This is an attempt to implement a templated sorting algorithm.\n// To use it, you have to explicitly instantiate it as a _function_,\n// then you call that function. This allows the comparison to be inlined,\n// giving the sort similar performance to C++ sorts.\n//\n// It implements quicksort with three-way-median partitioning (generally\n// well-behaved), with a final insertion sort pass.\n//\n// When you define the compare expression, you should assume you have\n// elements of your array pointed to by 'a' and 'b', and perform the comparison\n// on those. OR you can use one or more statements; first say '0;', then\n// write whatever code you want, and compute the result into a variable 'c'.\n\n#define stb_declare_sort(FUNCNAME, TYPE)    \\\n                       void FUNCNAME(TYPE *p, int n)\n#define stb_define_sort(FUNCNAME,TYPE,COMPARE) \\\n                       stb__define_sort(       void, FUNCNAME,TYPE,COMPARE)\n#define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \\\n                       stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)\n\n#define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE)                       \\\n                                                                              \\\nstatic void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n)                          \\\n{                                                                             \\\n   int i,j;                                                                   \\\n   for (i=1; i < n; ++i) {                                                    \\\n      TYPE t = p[i], *a = &t;                                                 \\\n      j = i;                                                                  \\\n      while (j > 0) {                                                         \\\n         TYPE *b = &p[j-1];                                                   \\\n         int c = COMPARE;                                                     \\\n         if (!c) break;                                                       \\\n         p[j] = p[j-1];                                                       \\\n         --j;                                                                 \\\n      }                                                                       \\\n      if (i != j)                                                             \\\n         p[j] = t;                                                            \\\n   }                                                                          \\\n}                                                                             \\\n                                                                              \\\nstatic void STB_(FUNCNAME,_quicksort)(TYPE *p, int n)                         \\\n{                                                                             \\\n   /* threshold for transitioning to insertion sort */                       \\\n   while (n > 12) {                                                           \\\n      TYPE *a,*b,t;                                                           \\\n      int c01,c12,c,m,i,j;                                                    \\\n                                                                              \\\n      /* compute median of three */                                           \\\n      m = n >> 1;                                                             \\\n      a = &p[0];                                                              \\\n      b = &p[m];                                                              \\\n      c = COMPARE;                                                            \\\n      c01 = c;                                                                \\\n      a = &p[m];                                                              \\\n      b = &p[n-1];                                                            \\\n      c = COMPARE;                                                            \\\n      c12 = c;                                                                \\\n      /* if 0 >= mid >= end, or 0 < mid < end, then use mid */                \\\n      if (c01 != c12) {                                                       \\\n         /* otherwise, we'll need to swap something else to middle */         \\\n         int z;                                                               \\\n         a = &p[0];                                                           \\\n         b = &p[n-1];                                                         \\\n         c = COMPARE;                                                         \\\n         /* 0>mid && mid<n:  0>n => n; 0<n => 0 */                            \\\n         /* 0<mid && mid>n:  0>n => 0; 0<n => n */                            \\\n         z = (c == c12) ? 0 : n-1;                                            \\\n         t = p[z];                                                            \\\n         p[z] = p[m];                                                         \\\n         p[m] = t;                                                            \\\n      }                                                                       \\\n      /* now p[m] is the median-of-three */                                   \\\n      /* swap it to the beginning so it won't move around */                  \\\n      t = p[0];                                                               \\\n      p[0] = p[m];                                                            \\\n      p[m] = t;                                                               \\\n                                                                              \\\n      /* partition loop */                                                    \\\n      i=1;                                                                    \\\n      j=n-1;                                                                  \\\n      for(;;) {                                                               \\\n         /* handling of equality is crucial here */                           \\\n         /* for sentinels & efficiency with duplicates */                     \\\n         b = &p[0];                                                           \\\n         for (;;++i) {                                                        \\\n            a=&p[i];                                                          \\\n            c = COMPARE;                                                      \\\n            if (!c) break;                                                    \\\n         }                                                                    \\\n         a = &p[0];                                                           \\\n         for (;;--j) {                                                        \\\n            b=&p[j];                                                          \\\n            c = COMPARE;                                                      \\\n            if (!c) break;                                                    \\\n         }                                                                    \\\n         /* make sure we haven't crossed */                                   \\\n         if (i >= j) break;                                                   \\\n         t = p[i];                                                            \\\n         p[i] = p[j];                                                         \\\n         p[j] = t;                                                            \\\n                                                                              \\\n         ++i;                                                                 \\\n         --j;                                                                 \\\n      }                                                                       \\\n      /* recurse on smaller side, iterate on larger */                        \\\n      if (j < (n-i)) {                                                        \\\n         STB_(FUNCNAME,_quicksort)(p,j);                                       \\\n         p = p+i;                                                             \\\n         n = n-i;                                                             \\\n      } else {                                                                \\\n         STB_(FUNCNAME,_quicksort)(p+i, n-i);                                  \\\n         n = j;                                                               \\\n      }                                                                       \\\n   }                                                                          \\\n}                                                                             \\\n                                                                              \\\nMODE FUNCNAME(TYPE *p, int n)                                                 \\\n{                                                                             \\\n   STB_(FUNCNAME, _quicksort)(p, n);                                           \\\n   STB_(FUNCNAME, _ins_sort)(p, n);                                            \\\n}                                                                             \\\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//      stb_bitset   an array of booleans indexed by integers\n//\n\ntypedef stb_uint32 stb_bitset;\n\nSTB_EXTERN  stb_bitset *stb_bitset_new(int value, int len);\n\n#define stb_bitset_clearall(arr,len)     (memset(arr,   0, 4 * (len)))\n#define stb_bitset_setall(arr,len)       (memset(arr, 255, 4 * (len)))\n\n#define stb_bitset_setbit(arr,n)         ((arr)[(n) >> 5] |=  (1 << (n & 31)))\n#define stb_bitset_clearbit(arr,n)       ((arr)[(n) >> 5] &= ~(1 << (n & 31)))\n#define stb_bitset_testbit(arr,n)        ((arr)[(n) >> 5] &   (1 << (n & 31)))\n\nSTB_EXTERN  stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len);\n\nSTB_EXTERN  int *stb_bitset_getlist(stb_bitset *out, int start, int end);\n\nSTB_EXTERN  int  stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len);\nSTB_EXTERN  int  stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len);\nSTB_EXTERN  int  stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len);\nSTB_EXTERN  int  stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len);\nSTB_EXTERN  int  stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len);\n\n#ifdef STB_DEFINE\nint stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len)\n{\n   int i;\n   for (i=0; i < len; ++i)\n      if (p0[i] != p1[i]) return 0;\n   return 1;\n}\n\nint stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len)\n{\n   int i;\n   for (i=0; i < len; ++i)\n      if (p0[i] & p1[i]) return 0;\n   return 1;\n}\n\nint stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len)\n{\n   int i;\n   for (i=0; i < len; ++i)\n      if ((p0[i] | p1[i]) != 0xffffffff) return 0;\n   return 1;\n}\n\nint stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len)\n{\n   int i;\n   for (i=0; i < len; ++i)\n      if ((bigger[i] & smaller[i]) != smaller[i]) return 0;\n   return 1;\n}\n\nstb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len)\n{\n   int i;\n   stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);\n   for (i=0; i < len; ++i) d[i] = p0[i] | p1[i];\n   return d;\n}\n\nint stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len)\n{\n   int i, changed=0;\n   for (i=0; i < len; ++i) {\n      stb_bitset d = p0[i] | p1[i];\n      if (d != p0[i]) {\n         p0[i] = d;\n         changed = 1;\n      }\n   }\n   return changed;\n}\n\nstb_bitset *stb_bitset_new(int value, int len)\n{\n   int i;\n   stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);\n   if (value) value = 0xffffffff;\n   for (i=0; i < len; ++i) d[i] = value;\n   return d;\n}\n\nint *stb_bitset_getlist(stb_bitset *out, int start, int end)\n{\n   int *list = NULL;\n   int i;\n   for (i=start; i < end; ++i)\n      if (stb_bitset_testbit(out, i))\n         stb_arr_push(list, i);\n   return list;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//      stb_wordwrap    quality word-wrapping for fixed-width fonts\n//\n\nSTB_EXTERN int stb_wordwrap(int *pairs, int pair_max, int count, char *str);\nSTB_EXTERN int *stb_wordwrapalloc(int count, char *str);\n\n#ifdef STB_DEFINE\n\nint stb_wordwrap(int *pairs, int pair_max, int count, char *str)\n{\n   int n=0,i=0, start=0,nonwhite=0;\n   if (pairs == NULL) pair_max = 0x7ffffff0;\n   else pair_max *= 2;\n   // parse\n   for(;;) {\n      int s=i; // first whitespace char; last nonwhite+1\n      int w;   // word start\n      // accept whitespace\n      while (isspace(str[i])) {\n         if (str[i] == '\\n' || str[i] == '\\r') {\n            if (str[i] + str[i+1] == '\\n' + '\\r') ++i;\n            if (n >= pair_max) return -1;\n            if (pairs) pairs[n] = start, pairs[n+1] = s-start;\n            n += 2;\n            nonwhite=0;\n            start = i+1;\n            s = start;\n         }\n         ++i;\n      }\n      if (i >= start+count) {\n         // we've gone off the end using whitespace\n         if (nonwhite) {\n            if (n >= pair_max) return -1;\n            if (pairs) pairs[n] = start, pairs[n+1] = s-start;\n            n += 2;\n            start = s = i;\n            nonwhite=0;\n         } else {\n            // output all the whitespace\n            while (i >= start+count) {\n               if (n >= pair_max) return -1;\n               if (pairs) pairs[n] = start, pairs[n+1] = count;\n               n += 2;\n               start += count;\n            }\n            s = start;\n         }\n      }\n\n      if (str[i] == 0) break;\n      // now scan out a word and see if it fits\n      w = i;\n      while (str[i] && !isspace(str[i])) {\n         ++i;\n      }\n      // wrapped?\n      if (i > start + count) {\n         // huge?\n         if (i-s <= count) {\n            if (n >= pair_max) return -1;\n            if (pairs) pairs[n] = start, pairs[n+1] = s-start;\n            n += 2;\n            start = w;\n         } else {\n            // This word is longer than one line. If we wrap it onto N lines\n            // there are leftover chars. do those chars fit on the cur line?\n            // But if we have leading whitespace, we force it to start here.\n            if ((w-start) + ((i-w) % count) <= count || !nonwhite) {\n               // output a full line\n               if (n >= pair_max) return -1;\n               if (pairs) pairs[n] = start, pairs[n+1] = count;\n               n += 2;\n               start += count;\n               w = start;\n            } else {\n               // output a partial line, trimming trailing whitespace\n               if (s != start) {\n                  if (n >= pair_max) return -1;\n                  if (pairs) pairs[n] = start, pairs[n+1] = s-start;\n                  n += 2;\n                  start = w;\n               }\n            }\n            // now output full lines as needed\n            while (start + count <= i) {\n               if (n >= pair_max) return -1;\n               if (pairs) pairs[n] = start, pairs[n+1] = count;\n               n += 2;\n               start += count;\n            }\n         }\n      }\n      nonwhite=1;\n   }\n   if (start < i) {\n      if (n >= pair_max) return -1;\n      if (pairs) pairs[n] = start, pairs[n+1] = i-start;\n      n += 2;\n   }\n   return n>>1;\n}\n\nint *stb_wordwrapalloc(int count, char *str)\n{\n   int n = stb_wordwrap(NULL,0,count,str);\n   int *z = NULL;\n   stb_arr_setlen(z, n*2);\n   stb_wordwrap(z, n, count, str);\n   return z;\n}\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//         stb_match:    wildcards and regexping\n//\n\nSTB_EXTERN int stb_wildmatch (char *expr, char *candidate);\nSTB_EXTERN int stb_wildmatchi(char *expr, char *candidate);\nSTB_EXTERN int stb_wildfind  (char *expr, char *candidate);\nSTB_EXTERN int stb_wildfindi (char *expr, char *candidate);\n\nSTB_EXTERN int stb_regex(char *regex, char *candidate);\n\ntypedef struct stb_matcher stb_matcher;\n\nSTB_EXTERN stb_matcher *stb_regex_matcher(char *regex);\nSTB_EXTERN int stb_matcher_match(stb_matcher *m, char *str);\nSTB_EXTERN int stb_matcher_find(stb_matcher *m, char *str);\nSTB_EXTERN void stb_matcher_free(stb_matcher *f);\n\nSTB_EXTERN stb_matcher *stb_lex_matcher(void);\nSTB_EXTERN int stb_lex_item(stb_matcher *m, const char *str, int result);\nSTB_EXTERN int stb_lex_item_wild(stb_matcher *matcher, const char *regex, int result);\nSTB_EXTERN int stb_lex(stb_matcher *m, char *str, int *len);\n\n\n\n#ifdef STB_DEFINE\n\nstatic int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive)\n{\n   int i;\n   if (insensitive) {\n      for (i=0; i < qlen; ++i)\n         if (qstring[i] == '?') {\n            if (!candidate[i]) return 0;\n         } else\n            if (tolower(qstring[i]) != tolower(candidate[i]))\n               return 0;\n   } else {\n      for (i=0; i < qlen; ++i)\n         if (qstring[i] == '?') {\n            if (!candidate[i]) return 0;\n         } else\n            if (qstring[i] != candidate[i])\n               return 0;\n   }\n   return 1;\n}\n\nstatic int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive)\n{\n   char c;\n\n   int offset=0;\n   while (*qstring == '?') {\n      ++qstring;\n      --qlen;\n      ++candidate;\n      if (qlen == 0) return 0;\n      if (*candidate == 0) return -1;\n   }\n\n   c = *qstring++;\n   --qlen;\n   if (insensitive) c = tolower(c);\n\n   while (candidate[offset]) {\n      if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset]))\n         if (stb__match_qstring(candidate+offset+1, qstring, qlen, insensitive))\n            return offset;\n      ++offset;\n   }\n\n   return -1;\n}\n\nint stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive)\n{\n   int where=0;\n   int start = -1;\n\n   if (!search) {\n      // parse to first '*'\n      if (*expr != '*')\n         start = 0;\n      while (*expr != '*') {\n         if (!*expr)\n            return *candidate == 0 ? 0 : -1;\n         if (*expr == '?') {\n            if (!*candidate) return -1;\n         } else {\n            if (insensitive) {\n               if (tolower(*candidate) != tolower(*expr))\n                  return -1;\n            } else\n               if (*candidate != *expr)\n                  return -1;\n         }\n         ++candidate, ++expr, ++where;\n      }\n   } else {\n      // 0-length search string\n      if (!*expr)\n         return 0;\n   }\n\n   assert(search || *expr == '*');\n   if (!search)\n      ++expr;\n\n   // implicit '*' at this point\n\n   while (*expr) {\n      int o=0;\n      // combine redundant * characters\n      while (expr[0] == '*') ++expr;\n\n      // ok, at this point, expr[-1] == '*',\n      // and expr[0] != '*'\n\n      if (!expr[0]) return start >= 0 ? start : 0;\n\n      // now find next '*'\n      o = 0;\n      while (expr[o] != '*') {\n         if (expr[o] == 0)\n            break;\n         ++o;\n      }\n      // if no '*', scan to end, then match at end\n      if (expr[o] == 0 && !search) {\n         int z;\n         for (z=0; z < o; ++z)\n            if (candidate[z] == 0)\n               return -1;\n         while (candidate[z])\n            ++z;\n         // ok, now check if they match\n         if (stb__match_qstring(candidate+z-o, expr, o, insensitive))\n            return start >= 0 ? start : 0;\n         return -1;\n      } else {\n         // if yes '*', then do stb__find_qmatch on the intervening chars\n         int n = stb__find_qstring(candidate, expr, o, insensitive);\n         if (n < 0)\n            return -1;\n         if (start < 0)\n            start = where + n;\n         expr += o;\n         candidate += n+o;\n      }\n\n      if (*expr == 0) {\n         assert(search);\n         return start;\n      }\n\n      assert(*expr == '*');\n      ++expr;\n   }\n\n   return start >= 0 ? start : 0;\n}\n\nint stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive)\n{\n   char buffer[256];\n   // handle multiple search strings\n   char *s = strchr(expr, ';');\n   char *last = expr;\n   while (s) {\n      int z;\n      // need to allow for non-writeable strings... assume they're small\n      if (s - last < 256) {\n         stb_strncpy(buffer, last, (int) (s-last+1));\n         buffer[s-last] = 0;\n         z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);\n      } else {\n         *s = 0;\n         z = stb__wildmatch_raw2(last, candidate, search, insensitive);\n         *s = ';';\n      }\n      if (z >= 0) return z;\n      last = s+1;\n      s = strchr(last, ';');\n   }\n   return stb__wildmatch_raw2(last, candidate, search, insensitive);\n}\n\nint stb_wildmatch(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 0,0) >= 0;\n}\n\nint stb_wildmatchi(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 0,1) >= 0;\n}\n\nint stb_wildfind(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 1,0);\n}\n\nint stb_wildfindi(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 1,1);\n}\n\ntypedef struct\n{\n   stb_int16 transition[256];\n} stb_dfa;\n\n// an NFA node represents a state you're in; it then has\n// an arbitrary number of edges dangling off of it\n// note this isn't utf8-y\ntypedef struct\n{\n   stb_int16  match; // character/set to match\n   stb_uint16 node;  // output node to go to\n} stb_nfa_edge;\n\ntypedef struct\n{\n   stb_int16 goal;   // does reaching this win the prize?\n   stb_uint8 active; // is this in the active list\n   stb_nfa_edge *out;\n   stb_uint16 *eps;  // list of epsilon closures\n} stb_nfa_node;\n\n#define STB__DFA_UNDEF  -1\n#define STB__DFA_GOAL   -2\n#define STB__DFA_END    -3\n#define STB__DFA_MGOAL  -4\n#define STB__DFA_VALID  0\n\n#define STB__NFA_STOP_GOAL -1\n\n// compiled regexp\nstruct stb_matcher\n{\n   stb_uint16 start_node;\n   stb_int16 dfa_start;\n   stb_uint32 *charset;\n   int num_charset;\n   int match_start;\n   stb_nfa_node *nodes;\n   int does_lex;\n\n   // dfa matcher\n   stb_dfa    * dfa;\n   stb_uint32 * dfa_mapping;\n   stb_int16  * dfa_result;\n   int num_words_per_dfa;\n};\n\nstatic int stb__add_node(stb_matcher *matcher)\n{\n   stb_nfa_node z;\n   z.active = 0;\n   z.eps    = 0;\n   z.goal   = 0;\n   z.out    = 0;\n   stb_arr_push(matcher->nodes, z);\n   return stb_arr_len(matcher->nodes)-1;\n}\n\nstatic void stb__add_epsilon(stb_matcher *matcher, int from, int to)\n{\n   assert(from != to);\n   if (matcher->nodes[from].eps == NULL)\n      stb_arr_malloc((void **) &matcher->nodes[from].eps, matcher);\n   stb_arr_push(matcher->nodes[from].eps, to);\n}\n\nstatic void stb__add_edge(stb_matcher *matcher, int from, int to, int type)\n{\n    stb_nfa_edge z = { (stb_int16)type, (stb_uint16)to };\n   if (matcher->nodes[from].out == NULL)\n      stb_arr_malloc((void **) &matcher->nodes[from].out, matcher);\n   stb_arr_push(matcher->nodes[from].out, z);\n}\n\nstatic char *stb__reg_parse_alt(stb_matcher *m, int s, char *r, stb_uint16 *e);\nstatic char *stb__reg_parse(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)\n{\n   int n;\n   int last_start = -1;\n   stb_uint16 last_end = start;\n\n   while (*regex) {\n      switch (*regex) {\n         case '(':\n            last_start = last_end;\n            regex = stb__reg_parse_alt(matcher, last_end, regex+1, &last_end);\n            if (regex == NULL || *regex != ')')\n               return NULL;\n            ++regex;\n            break;\n\n         case '|':\n         case ')':\n            *end = last_end;\n            return regex;\n\n         case '?':\n            if (last_start < 0) return NULL;\n            stb__add_epsilon(matcher, last_start, last_end);\n            ++regex;\n            break;\n\n         case '*':\n            if (last_start < 0) return NULL;\n            stb__add_epsilon(matcher, last_start, last_end);\n\n            // fall through\n\n         case '+':\n            if (last_start < 0) return NULL;\n            stb__add_epsilon(matcher, last_end, last_start);\n            // prevent links back to last_end from chaining to last_start\n            n = stb__add_node(matcher);\n            stb__add_epsilon(matcher, last_end, n);\n            last_end = n;\n            ++regex;\n            break;\n\n         case '{':   // not supported!\n            // @TODO: given {n,m}, clone last_start to last_end m times,\n            // and include epsilons from start to first m-n blocks\n            return NULL;\n\n         case '\\\\':\n            ++regex;\n            if (!*regex) return NULL;\n\n            // fallthrough\n         default: // match exactly this character\n            n = stb__add_node(matcher);\n            stb__add_edge(matcher, last_end, n, *regex);\n            last_start = last_end;\n            last_end = n;\n            ++regex;\n            break;\n\n         case '$':\n            n = stb__add_node(matcher);\n            stb__add_edge(matcher, last_end, n, '\\n');\n            last_start = last_end;\n            last_end = n;\n            ++regex;\n            break;\n\n         case '.':\n            n = stb__add_node(matcher);\n            stb__add_edge(matcher, last_end, n, -1);\n            last_start = last_end;\n            last_end = n;\n            ++regex;\n            break;\n\n         case '[': {\n            stb_uint8 flags[256];\n            int invert = 0,z;\n            ++regex;\n            if (matcher->num_charset == 0) {\n               matcher->charset = (stb_uint *) stb_malloc(matcher, sizeof(*matcher->charset) * 256);\n               memset(matcher->charset, 0, sizeof(*matcher->charset) * 256);\n            }\n\n            memset(flags,0,sizeof(flags));\n\n            // leading ^ is special\n            if (*regex == '^')\n               ++regex, invert = 1;\n\n            // leading ] is special\n            if (*regex == ']') {\n               flags[(int) ']'] = 1;\n               ++regex;\n            }\n            while (*regex != ']') {\n               stb_uint a;\n               if (!*regex) return NULL;\n               a = *regex++;\n               if (regex[0] == '-' && regex[1] != ']') {\n                  stb_uint i,b = regex[1];\n                  regex += 2;\n                  if (b == 0) return NULL;\n                  if (a > b) return NULL;\n                  for (i=a; i <= b; ++i)\n                     flags[i] = 1;\n               } else\n                  flags[a] = 1;\n            }\n            ++regex;\n            if (invert) {\n               int i;\n               for (i=0; i < 256; ++i)\n                  flags[i] = 1-flags[i];\n            }\n\n            // now check if any existing charset matches\n            for (z=0; z < matcher->num_charset; ++z) {\n               int i, k[2] = { 0, 1 << z};\n               for (i=0; i < 256; ++i) {\n                  unsigned int f = k[flags[i]];\n                  if ((matcher->charset[i] & k[1]) != f)\n                     break;\n               }\n               if (i == 256) break;\n            }\n\n            if (z == matcher->num_charset) {\n               int i;\n               ++matcher->num_charset;\n               if (matcher->num_charset > 32) {\n                  assert(0); /* NOTREACHED */\n                  return NULL; // too many charsets, oops\n               }\n               for (i=0; i < 256; ++i)\n                  if (flags[i])\n                     matcher->charset[i] |= (1 << z);\n            }\n\n            n = stb__add_node(matcher);\n            stb__add_edge(matcher, last_end, n, -2 - z);\n            last_start = last_end;\n            last_end = n;\n            break;\n         }\n      }\n   }\n   *end = last_end;\n   return regex;\n}\n\nstatic char *stb__reg_parse_alt(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)\n{\n   stb_uint16 last_end = start;\n   stb_uint16 main_end;\n\n   int head, tail;\n\n   head = stb__add_node(matcher);\n   stb__add_epsilon(matcher, start, head);\n\n   regex = stb__reg_parse(matcher, head, regex, &last_end);\n   if (regex == NULL) return NULL;\n   if (*regex == 0 || *regex == ')') {\n      *end = last_end;\n      return regex;\n   }\n\n   main_end = last_end;\n   tail = stb__add_node(matcher);\n\n   stb__add_epsilon(matcher, last_end, tail);\n\n   // start alternatives from the same starting node; use epsilon\n   // transitions to combine their endings\n   while(*regex && *regex != ')') {\n      assert(*regex == '|');\n      head = stb__add_node(matcher);\n      stb__add_epsilon(matcher, start, head);\n      regex = stb__reg_parse(matcher, head, regex+1, &last_end);\n      if (regex == NULL)\n         return NULL;\n      stb__add_epsilon(matcher, last_end, tail);\n   }\n\n   *end = tail;\n   return regex;\n}\n\nstatic char *stb__wild_parse(stb_matcher *matcher, int start, char *str, stb_uint16 *end)\n{\n   int n;\n   stb_uint16 last_end;\n\n   last_end = stb__add_node(matcher);\n   stb__add_epsilon(matcher, start, last_end);\n\n   while (*str) {\n      switch (*str) {\n            // fallthrough\n         default: // match exactly this character\n            n = stb__add_node(matcher);\n            if (toupper(*str) == tolower(*str)) {\n               stb__add_edge(matcher, last_end, n, *str);\n            } else {\n               stb__add_edge(matcher, last_end, n, tolower(*str));\n               stb__add_edge(matcher, last_end, n, toupper(*str));\n            }\n            last_end = n;\n            ++str;\n            break;\n\n         case '?':\n            n = stb__add_node(matcher);\n            stb__add_edge(matcher, last_end, n, -1);\n            last_end = n;\n            ++str;\n            break;\n\n         case '*':\n            n = stb__add_node(matcher);\n            stb__add_edge(matcher, last_end, n, -1);\n            stb__add_epsilon(matcher, last_end, n);\n            stb__add_epsilon(matcher, n, last_end);\n            last_end = n;\n            ++str;\n            break;\n      }\n   }\n\n   // now require end of string to match\n   n = stb__add_node(matcher);\n   stb__add_edge(matcher, last_end, n, 0);\n   last_end = n;\n\n   *end = last_end;\n   return str;\n}\n\nstatic int stb__opt(stb_matcher *m, int n)\n{\n   for(;;) {\n      stb_nfa_node *p = &m->nodes[n];\n      if (p->goal)                  return n;\n      if (stb_arr_len(p->out))      return n;\n      if (stb_arr_len(p->eps) != 1) return n;\n      n = p->eps[0];\n   }\n}\n\nstatic void stb__optimize(stb_matcher *m)\n{\n   // if the target of any edge is a node with exactly\n   // one out-epsilon, shorten it\n   int i,j;\n   for (i=0; i < stb_arr_len(m->nodes); ++i) {\n      stb_nfa_node *p = &m->nodes[i];\n      for (j=0; j < stb_arr_len(p->out); ++j)\n         p->out[j].node = stb__opt(m,p->out[j].node);\n      for (j=0; j < stb_arr_len(p->eps); ++j)\n         p->eps[j]      = stb__opt(m,p->eps[j]     );\n   }\n   m->start_node = stb__opt(m,m->start_node);\n}\n\nvoid stb_matcher_free(stb_matcher *f)\n{\n   stb_free(f);\n}\n\nstatic stb_matcher *stb__alloc_matcher(void)\n{\n   stb_matcher *matcher = (stb_matcher *) stb_malloc(0,sizeof(*matcher));\n\n   matcher->start_node  = 0;\n   stb_arr_malloc((void **) &matcher->nodes, matcher);\n   matcher->num_charset = 0;\n   matcher->match_start = 0;\n   matcher->does_lex    = 0;\n\n   matcher->dfa_start   = STB__DFA_UNDEF;\n   stb_arr_malloc((void **) &matcher->dfa, matcher);\n   stb_arr_malloc((void **) &matcher->dfa_mapping, matcher);\n   stb_arr_malloc((void **) &matcher->dfa_result, matcher);\n\n   stb__add_node(matcher);\n\n   return matcher;\n}\n\nstatic void stb__lex_reset(stb_matcher *matcher)\n{\n   // flush cached dfa data\n   stb_arr_setlen(matcher->dfa, 0);\n   stb_arr_setlen(matcher->dfa_mapping, 0);\n   stb_arr_setlen(matcher->dfa_result, 0);\n   matcher->dfa_start = STB__DFA_UNDEF;\n}\n\nstb_matcher *stb_regex_matcher(char *regex)\n{\n   char *z;\n   stb_uint16 end;\n   stb_matcher *matcher = stb__alloc_matcher();\n   if (*regex == '^') {\n      matcher->match_start = 1;\n      ++regex;\n   }\n\n   z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);\n\n   if (!z || *z) {\n      stb_free(matcher);\n      return NULL;\n   }\n\n   ((matcher->nodes)[(int) end]).goal = STB__NFA_STOP_GOAL;\n\n   return matcher;\n}\n\nstb_matcher *stb_lex_matcher(void)\n{\n   stb_matcher *matcher = stb__alloc_matcher();\n\n   matcher->match_start = 1;\n   matcher->does_lex    = 1;\n\n   return matcher;\n}\n\nint stb_lex_item(stb_matcher *matcher, const char *regex, int result)\n{\n   char *z;\n   stb_uint16 end;\n\n   z = stb__reg_parse_alt(matcher, matcher->start_node, (char*) regex, &end);\n\n   if (z == NULL)\n      return 0;\n\n   stb__lex_reset(matcher);\n\n   matcher->nodes[(int) end].goal = result;\n   return 1;\n}\n\nint stb_lex_item_wild(stb_matcher *matcher, const char *regex, int result)\n{\n   char *z;\n   stb_uint16 end;\n\n   z = stb__wild_parse(matcher, matcher->start_node, (char*) regex, &end);\n\n   if (z == NULL)\n      return 0;\n\n   stb__lex_reset(matcher);\n\n   matcher->nodes[(int) end].goal = result;\n   return 1;\n}\n\nstatic void stb__clear(stb_matcher *m, stb_uint16 *list)\n{\n   int i;\n   for (i=0; i < stb_arr_len(list); ++i)\n      m->nodes[(int) list[i]].active = 0;\n}\n\nstatic int stb__clear_goalcheck(stb_matcher *m, stb_uint16 *list)\n{\n   int i, t=0;\n   for (i=0; i < stb_arr_len(list); ++i) {\n      t += m->nodes[(int) list[i]].goal;\n      m->nodes[(int) list[i]].active = 0;\n   }\n   return t;\n}\n\nstatic stb_uint16 * stb__add_if_inactive(stb_matcher *m, stb_uint16 *list, int n)\n{\n   if (!m->nodes[n].active) {\n      stb_arr_push(list, n);\n      m->nodes[n].active = 1;\n   }\n   return list;\n}\n\nstatic stb_uint16 * stb__eps_closure(stb_matcher *m, stb_uint16 *list)\n{\n   int i,n = stb_arr_len(list);\n\n   for(i=0; i < n; ++i) {\n      stb_uint16 *e = m->nodes[(int) list[i]].eps;\n      if (e) {\n         int j,k = stb_arr_len(e);\n         for (j=0; j < k; ++j)\n            list = stb__add_if_inactive(m, list, e[j]);\n         n = stb_arr_len(list);\n      }\n   }\n\n   return list;\n}\n\nint stb_matcher_match(stb_matcher *m, char *str)\n{\n   int result = 0;\n   int i,j,y,z;\n   stb_uint16 *previous = NULL;\n   stb_uint16 *current = NULL;\n   stb_uint16 *temp;\n\n   stb_arr_setsize(previous, 4);\n   stb_arr_setsize(current, 4);\n\n   previous = stb__add_if_inactive(m, previous, m->start_node);\n   previous = stb__eps_closure(m,previous);\n   stb__clear(m, previous);\n\n   while (*str && stb_arr_len(previous)) {\n      y = stb_arr_len(previous);\n      for (i=0; i < y; ++i) {\n         stb_nfa_node *n = &m->nodes[(int) previous[i]];\n         z = stb_arr_len(n->out);\n         for (j=0; j < z; ++j) {\n            if (n->out[j].match >= 0) {\n               if (n->out[j].match == *str)\n                  current = stb__add_if_inactive(m, current, n->out[j].node);\n            } else if (n->out[j].match == -1) {\n               if (*str != '\\n')\n                  current = stb__add_if_inactive(m, current, n->out[j].node);\n            } else if (n->out[j].match < -1) {\n               int z = -n->out[j].match - 2;\n               if (m->charset[(stb_uint8) *str] & (1 << z))\n                  current = stb__add_if_inactive(m, current, n->out[j].node);\n            }\n         }\n      }\n      stb_arr_setlen(previous, 0);\n\n      temp = previous;\n      previous = current;\n      current = temp;\n\n      previous = stb__eps_closure(m,previous);\n      stb__clear(m, previous);\n\n      ++str;\n   }\n\n   // transition to pick up a '$' at the end\n   y = stb_arr_len(previous);\n   for (i=0; i < y; ++i)\n      m->nodes[(int) previous[i]].active = 1;\n\n   for (i=0; i < y; ++i) {\n      stb_nfa_node *n = &m->nodes[(int) previous[i]];\n      z = stb_arr_len(n->out);\n      for (j=0; j < z; ++j) {\n         if (n->out[j].match == '\\n')\n            current = stb__add_if_inactive(m, current, n->out[j].node);\n      }\n   }\n\n   previous = stb__eps_closure(m,previous);\n   stb__clear(m, previous);\n\n   y = stb_arr_len(previous);\n   for (i=0; i < y; ++i)\n      if (m->nodes[(int) previous[i]].goal)\n         result = 1;\n\n   stb_arr_free(previous);\n   stb_arr_free(current);\n\n   return result && *str == 0;\n}\n\nstb_int16 stb__get_dfa_node(stb_matcher *m, stb_uint16 *list)\n{\n   stb_uint16 node;\n   stb_uint32 data[8], *state, *newstate;\n   int i,j,n;\n\n   state = (stb_uint32 *) stb_temp(data, m->num_words_per_dfa * 4);\n   memset(state, 0, m->num_words_per_dfa*4);\n\n   n = stb_arr_len(list);\n   for (i=0; i < n; ++i) {\n      int x = list[i];\n      state[x >> 5] |= 1 << (x & 31);\n   }\n\n   // @TODO use a hash table\n   n = stb_arr_len(m->dfa_mapping);\n   i=j=0;\n   for(; j < n; ++i, j += m->num_words_per_dfa) {\n      // @TODO special case for <= 32\n      if (!memcmp(state, m->dfa_mapping + j, m->num_words_per_dfa*4)) {\n         node = i;\n         goto done;\n      }\n   }\n\n   assert(stb_arr_len(m->dfa) == i);\n   node = i;\n\n   newstate = stb_arr_addn(m->dfa_mapping, m->num_words_per_dfa);\n   memcpy(newstate, state, m->num_words_per_dfa*4);\n\n   // set all transitions to 'unknown'\n   stb_arr_add(m->dfa);\n   memset(m->dfa[i].transition, -1, sizeof(m->dfa[i].transition));\n\n   if (m->does_lex) {\n      int result = -1;\n      n = stb_arr_len(list);\n      for (i=0; i < n; ++i) {\n         if (m->nodes[(int) list[i]].goal > result)\n            result = m->nodes[(int) list[i]].goal;\n      }\n\n      stb_arr_push(m->dfa_result, result);\n   }\n\ndone:\n   stb_tempfree(data, state);\n   return node;\n}\n\nstatic int stb__matcher_dfa(stb_matcher *m, char *str_c, int *len)\n{\n   stb_uint8 *str = (stb_uint8 *) str_c;\n   stb_int16 node,prevnode;\n   stb_dfa *trans;\n   int match_length = 0;\n   stb_int16 match_result=0;\n\n   if (m->dfa_start == STB__DFA_UNDEF) {\n      stb_uint16 *list;\n\n      m->num_words_per_dfa = (stb_arr_len(m->nodes)+31) >> 5;\n      stb__optimize(m);\n\n      list = stb__add_if_inactive(m, NULL, m->start_node);\n      list = stb__eps_closure(m,list);\n      if (m->does_lex) {\n         m->dfa_start = stb__get_dfa_node(m,list);\n         stb__clear(m, list);\n         // DON'T allow start state to be a goal state!\n         // this allows people to specify regexes that can match 0\n         // characters without them actually matching (also we don't\n         // check _before_ advancing anyway\n         if (m->dfa_start <= STB__DFA_MGOAL)\n            m->dfa_start = -(m->dfa_start - STB__DFA_MGOAL);\n      } else {\n         if (stb__clear_goalcheck(m, list))\n            m->dfa_start = STB__DFA_GOAL;\n         else\n            m->dfa_start = stb__get_dfa_node(m,list);\n      }\n      stb_arr_free(list);\n   }\n\n   prevnode = STB__DFA_UNDEF;\n   node = m->dfa_start;\n   trans = m->dfa;\n\n   if (m->dfa_start == STB__DFA_GOAL)\n      return 1;\n\n   for(;;) {\n      assert(node >= STB__DFA_VALID);\n\n      // fast inner DFA loop; especially if STB__DFA_VALID is 0\n\n      do {\n         prevnode = node;\n         node = trans[node].transition[*str++];\n      } while (node >= STB__DFA_VALID);\n\n      assert(node >= STB__DFA_MGOAL - stb_arr_len(m->dfa));\n      assert(node < stb_arr_len(m->dfa));\n\n      // special case for lex: need _longest_ match, so notice goal\n      // state without stopping\n      if (node <= STB__DFA_MGOAL) {\n         match_length = (int) (str - (stb_uint8 *) str_c);\n         node = -(node - STB__DFA_MGOAL);\n         match_result = node;\n         continue;\n      }\n\n      // slow NFA->DFA conversion\n\n      // or we hit the goal or the end of the string, but those\n      // can only happen once per search...\n\n      if (node == STB__DFA_UNDEF) {\n         // build a list  -- @TODO special case <= 32 states\n         // heck, use a more compact data structure for <= 16 and <= 8 ?!\n\n         // @TODO keep states/newstates around instead of reallocating them\n         stb_uint16 *states = NULL;\n         stb_uint16 *newstates = NULL;\n         int i,j,y,z;\n         stb_uint32 *flags = &m->dfa_mapping[prevnode * m->num_words_per_dfa];\n         assert(prevnode != STB__DFA_UNDEF);\n         stb_arr_setsize(states, 4);\n         stb_arr_setsize(newstates,4);\n         for (j=0; j < m->num_words_per_dfa; ++j) {\n            for (i=0; i < 32; ++i) {\n               if (*flags & (1 << i))\n                  stb_arr_push(states, j*32+i);\n            }\n            ++flags;\n         }\n         // states is now the states we were in in the previous node;\n         // so now we can compute what node it transitions to on str[-1]\n\n         y = stb_arr_len(states);\n         for (i=0; i < y; ++i) {\n            stb_nfa_node *n = &m->nodes[(int) states[i]];\n            z = stb_arr_len(n->out);\n            for (j=0; j < z; ++j) {\n               if (n->out[j].match >= 0) {\n                  if (n->out[j].match == str[-1] || (str[-1] == 0 && n->out[j].match == '\\n'))\n                     newstates = stb__add_if_inactive(m, newstates, n->out[j].node);\n               } else if (n->out[j].match == -1) {\n                  if (str[-1] != '\\n' && str[-1])\n                     newstates = stb__add_if_inactive(m, newstates, n->out[j].node);\n               } else if (n->out[j].match < -1) {\n                  int z = -n->out[j].match - 2;\n                  if (m->charset[str[-1]] & (1 << z))\n                     newstates = stb__add_if_inactive(m, newstates, n->out[j].node);\n               }\n            }\n         }\n         // AND add in the start state!\n         if (!m->match_start || (str[-1] == '\\n' && !m->does_lex))\n            newstates = stb__add_if_inactive(m, newstates, m->start_node);\n         // AND epsilon close it\n         newstates = stb__eps_closure(m, newstates);\n         // if it's a goal state, then that's all there is to it\n         if (stb__clear_goalcheck(m, newstates)) {\n            if (m->does_lex) {\n               match_length = (int) (str - (stb_uint8 *) str_c);\n               node = stb__get_dfa_node(m,newstates);\n               match_result = node;\n               node = -node + STB__DFA_MGOAL;\n               trans = m->dfa; // could have gotten realloc()ed\n            } else\n               node = STB__DFA_GOAL;\n         } else if (str[-1] == 0 || stb_arr_len(newstates) == 0) {\n            node = STB__DFA_END;\n         } else {\n            node = stb__get_dfa_node(m,newstates);\n            trans = m->dfa; // could have gotten realloc()ed\n         }\n         trans[prevnode].transition[str[-1]] = node;\n         if (node <= STB__DFA_MGOAL)\n            node = -(node - STB__DFA_MGOAL);\n         stb_arr_free(newstates);\n         stb_arr_free(states);\n      }\n\n      if (node == STB__DFA_GOAL) {\n         return 1;\n      }\n      if (node == STB__DFA_END) {\n         if (m->does_lex) {\n            if (match_result) {\n               if (len) *len = match_length;\n               return m->dfa_result[(int) match_result];\n            }\n         }\n         return 0;\n      }\n\n      assert(node != STB__DFA_UNDEF);\n   }\n}\n\nint stb_matcher_find(stb_matcher *m, char *str)\n{\n   assert(m->does_lex == 0);\n   return stb__matcher_dfa(m, str, NULL);\n}\n\nint stb_lex(stb_matcher *m, char *str, int *len)\n{\n   assert(m->does_lex);\n   return stb__matcher_dfa(m, str, len);\n}\n\n#ifdef STB_PERFECT_HASH\nint stb_regex(char *regex, char *str)\n{\n   static stb_perfect p;\n   static stb_matcher ** matchers;\n   static char        ** regexps;\n   static char        ** regexp_cache;\n   static unsigned short *mapping;\n    int z = stb_perfect_hash(&p, (int)(size_t) regex);\n   if (z >= 0) {\n      if (strcmp(regex, regexp_cache[(int) mapping[z]])) {\n         int i = mapping[z];\n         stb_matcher_free(matchers[i]);\n         free(regexp_cache[i]);\n         regexps[i] = regex;\n         regexp_cache[i] = stb_p_strdup(regex);\n         matchers[i] = stb_regex_matcher(regex);\n      }\n   } else {\n      int i,n;\n      if (regex == NULL) {\n         for (i=0; i < stb_arr_len(matchers); ++i) {\n            stb_matcher_free(matchers[i]);\n            free(regexp_cache[i]);\n         }\n         stb_arr_free(matchers);\n         stb_arr_free(regexps);\n         stb_arr_free(regexp_cache);\n         stb_perfect_destroy(&p);\n         free(mapping); mapping = NULL;\n         return -1;\n      }\n      stb_arr_push(regexps, regex);\n      stb_arr_push(regexp_cache, stb_p_strdup(regex));\n      stb_arr_push(matchers, stb_regex_matcher(regex));\n      stb_perfect_destroy(&p);\n      n = stb_perfect_create(&p, (unsigned int *) (char **) regexps, stb_arr_len(regexps));\n      mapping = (unsigned short *) realloc(mapping, n * sizeof(*mapping));\n      for (i=0; i < stb_arr_len(regexps); ++i)\n          mapping[stb_perfect_hash(&p, (int)(size_t) regexps[i])] = i;\n      z = stb_perfect_hash(&p, (int)(size_t) regex);\n   }\n   return stb_matcher_find(matchers[(int) mapping[z]], str);\n}\n#endif\n#endif // STB_DEFINE\n\n\n#if 0\n//////////////////////////////////////////////////////////////////////////////\n//\n//                      C source-code introspection\n//\n\n// runtime structure\ntypedef struct\n{\n   char *name;\n   char *type;     // base type\n   char *comment;  // content of comment field\n   int   size;     // size of base type\n   int   offset;   // field offset\n   int   arrcount[8]; // array sizes; -1 = pointer indirection; 0 = end of list\n} stb_info_field;\n\ntypedef struct\n{\n   char *structname;\n   int size;\n   int num_fields;\n   stb_info_field *fields;\n} stb_info_struct;\n\nextern stb_info_struct stb_introspect_output[];\n\n//\n\nSTB_EXTERN void stb_introspect_precompiled(stb_info_struct *compiled);\nSTB_EXTERN void stb__introspect(char *path, char *file);\n\n#define stb_introspect_ship()            stb__introspect(NULL, NULL, stb__introspect_output)\n\n#ifdef STB_SHIP\n#define stb_introspect()                 stb_introspect_ship()\n#define stb_introspect_path(p)           stb_introspect_ship()\n#else\n// bootstrapping: define stb_introspect() (or 'path') the first time\n#define stb_introspect()                 stb__introspect(NULL, __FILE__, NULL)\n#define stb_introspect_auto()            stb__introspect(NULL, __FILE__, stb__introspect_output)\n\n#define stb_introspect_path(p)           stb__introspect(p, __FILE__, NULL)\n#define stb_introspect_path(p)           stb__introspect(p, __FILE__, NULL)\n#endif\n\n#ifdef STB_DEFINE\n\n#ifndef STB_INTROSPECT_CPP\n   #ifdef __cplusplus\n   #define STB_INTROSPECT_CPP 1\n   #else\n   #define STB_INTROSPECT_CPP 0\n   #endif\n#endif\n\nvoid stb_introspect_precompiled(stb_info_struct *compiled)\n{\n\n}\n\n\nstatic void stb__introspect_filename(char *buffer, char *path)\n{\n   #if STB_INTROSPECT_CPP\n   stb_p_sprintf(buffer stb_p_size(9999), \"%s/stb_introspect.cpp\", path);\n   #else\n   stb_p_sprintf(buffer stb_p_size(9999), \"%s/stb_introspect.c\", path);\n   #endif\n}\n\nstatic void stb__introspect_compute(char *path, char *file)\n{\n   int i;\n   char ** include_list = NULL;\n   char ** introspect_list = NULL;\n   FILE *f;\n   f = stb_p_fopen(file, \"w\");\n   if (!f) return;\n\n   fputs(\"// if you get compiler errors, change the following 0 to a 1:\\n\", f);\n   fputs(\"#define STB_INTROSPECT_INVALID 0\\n\\n\", f);\n   fputs(\"// this will force the code to compile, and force the introspector\\n\", f);\n   fputs(\"// to run and then exit, allowing you to recompile\\n\\n\\n\", f);\n   fputs(\"#include \\\"stb.h\\\"\\n\\n\",f );\n   fputs(\"#if STB_INTROSPECT_INVALID\\n\", f);\n   fputs(\"   stb_info_struct stb__introspect_output[] = { (void *) 1 }\\n\", f);\n   fputs(\"#else\\n\\n\", f);\n   for (i=0; i < stb_arr_len(include_list); ++i)\n      fprintf(f, \" #include \\\"%s\\\"\\n\", include_list[i]);\n\n   fputs(\" stb_info_struct stb__introspect_output[] =\\n{\\n\", f);\n   for (i=0; i < stb_arr_len(introspect_list); ++i)\n      fprintf(f, \"  stb_introspect_%s,\\n\", introspect_list[i]);\n   fputs(\" };\\n\", f);\n   fputs(\"#endif\\n\", f);\n   fclose(f);\n}\n\nstatic stb_info_struct *stb__introspect_info;\n\n#ifndef STB_SHIP\n\n#endif\n\nvoid stb__introspect(char *path, char *file, stb_info_struct *compiled)\n{\n   static int first=1;\n   if (!first) return;\n   first=0;\n\n   stb__introspect_info = compiled;\n\n   #ifndef STB_SHIP\n   if (path || file) {\n      int bail_flag = compiled && compiled[0].structname == (void *) 1;\n      int needs_building = bail_flag;\n      struct stb__stat st;\n      char buffer[1024], buffer2[1024];\n      if (!path) {\n         stb_splitpath(buffer, file, STB_PATH);\n         path = buffer;\n      }\n      // bail if the source path doesn't exist\n      if (!stb_fexists(path)) return;\n\n      stb__introspect_filename(buffer2, path);\n\n      // get source/include files timestamps, compare to output-file timestamp;\n      // if mismatched, regenerate\n\n      if (stb__stat(buffer2, &st))\n         needs_building = STB_TRUE;\n\n      {\n         // find any file that contains an introspection command and is newer\n         // if needs_building is already true, we don't need to do this test,\n         // but we still need these arrays, so go ahead and get them\n         char **all[3];\n         all[0] = stb_readdir_files_mask(path, \"*.h\");\n         all[1] = stb_readdir_files_mask(path, \"*.c\");\n         all[2] = stb_readdir_files_mask(path, \"*.cpp\");\n         int i,j;\n         if (needs_building) {\n            for (j=0; j < 3; ++j) {\n               for (i=0; i < stb_arr_len(all[j]); ++i) {\n                  struct stb__stat st2;\n                  if (!stb__stat(all[j][i], &st2)) {\n                     if (st.st_mtime < st2.st_mtime) {\n                        char *z = stb_filec(all[j][i], NULL);\n                        int found=STB_FALSE;\n                        while (y) {\n                           y = strstr(y, \"//si\");\n                           if (y && isspace(y[4])) {\n                              found = STB_TRUE;\n                              break;\n                           }\n                        }\n                        needs_building = STB_TRUE;\n                        goto done;\n                     }\n                  }\n               }\n            }\n           done:;\n         }\n               char *z = stb_filec(all[i], NULL), *y = z;\n               int found=STB_FALSE;\n               while (y) {\n                  y = strstr(y, \"//si\");\n                  if (y && isspace(y[4])) {\n                     found = STB_TRUE;\n                     break;\n                  }\n               }\n               if (found)\n                  stb_arr_push(introspect_h, stb_p_strdup(all[i]));\n               free(z);\n            }\n         }\n         stb_readdir_free(all);\n         if (!needs_building) {\n            for (i=0; i < stb_arr_len(introspect_h); ++i) {\n               struct stb__stat st2;\n               if (!stb__stat(introspect_h[i], &st2))\n                  if (st.st_mtime < st2.st_mtime)\n                     needs_building = STB_TRUE;\n            }\n         }\n\n         if (needs_building) {\n            stb__introspect_compute(path, buffer2);\n         }\n      }\n   }\n   #endif\n}\n#endif\n#endif\n\n#ifdef STB_INTROSPECT\n// compile-time code-generator\n#define INTROSPECT(x)   int main(int argc, char **argv) { stb__introspect(__FILE__); return 0; }\n#define FILE(x)\n\nvoid stb__introspect(char *filename)\n{\n   char *file = stb_file(filename, NULL);\n   char *s = file, *t, **p;\n   char *out_name = \"stb_introspect.c\";\n   char *out_path;\n   STB_ARR(char) filelist = NULL;\n   int i,n;\n   if (!file) stb_fatal(\"Couldn't open %s\", filename);\n\n   out_path = stb_splitpathdup(filename, STB_PATH);\n\n   // search for the macros\n   while (*s) {\n      char buffer[256];\n      while (*s && !isupper(*s)) ++s;\n      s = stb_strtok_invert(buffer, s, \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n      s = stb_skipwhite(s);\n      if (*s == '(') {\n         ++s;\n         t = strchr(s, ')');\n         if (t == NULL) stb_fatal(\"Error parsing %s\", filename);\n\n      }\n   }\n}\n\n\n\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//             STB-C sliding-window dictionary compression\n//\n//  This uses a DEFLATE-style sliding window, but no bitwise entropy.\n//  Everything is on byte boundaries, so you could then apply a byte-wise\n//  entropy code, though that's nowhere near as effective.\n//\n//  An STB-C stream begins with a 16-byte header:\n//      4 bytes: 0x57 0xBC 0x00 0x00\n//      8 bytes: big-endian size of decompressed data, 64-bits\n//      4 bytes: big-endian size of window (how far back decompressor may need)\n//\n//  The following symbols appear in the stream (these were determined ad hoc,\n//  not by analysis):\n//\n//  [dict]      00000100 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx\n//  [END]       00000101 11111010 cccccccc cccccccc cccccccc cccccccc\n//  [dict]      00000110 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx\n//  [literals]  00000111 zzzzzzzz zzzzzzzz\n//  [literals]  00001zzz zzzzzzzz\n//  [dict]      00010yyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx\n//  [dict]      00011yyy yyyyyyyy yyyyyyyy xxxxxxxx\n//  [literals]  001zzzzz\n//  [dict]      01yyyyyy yyyyyyyy xxxxxxxx\n//  [dict]      1xxxxxxx yyyyyyyy\n//\n//      xxxxxxxx: match length - 1\n//      yyyyyyyy: backwards distance - 1\n//      zzzzzzzz: num literals - 1\n//      cccccccc: adler32 checksum of decompressed data\n//   (all big-endian)\n\n\nSTB_EXTERN stb_uint stb_decompress_length(stb_uchar *input);\nSTB_EXTERN stb_uint stb_decompress(stb_uchar *out,stb_uchar *in,stb_uint len);\nSTB_EXTERN stb_uint stb_compress  (stb_uchar *out,stb_uchar *in,stb_uint len);\nSTB_EXTERN void stb_compress_window(int z);\nSTB_EXTERN void stb_compress_hashsize(unsigned int z);\n\nSTB_EXTERN int stb_compress_tofile(char *filename, char *in,  stb_uint  len);\nSTB_EXTERN int stb_compress_intofile(FILE *f, char *input,    stb_uint  len);\nSTB_EXTERN char *stb_decompress_fromfile(char *filename,      stb_uint *len);\n\nSTB_EXTERN int stb_compress_stream_start(FILE *f);\nSTB_EXTERN void stb_compress_stream_end(int close);\nSTB_EXTERN void stb_write(char *data, int data_len);\n\n#ifdef STB_DEFINE\n\nstb_uint stb_decompress_length(stb_uchar *input)\n{\n   return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];\n}\n\n////////////////////           decompressor         ///////////////////////\n\n// simple implementation that just writes whole thing into big block\n\nstatic unsigned char *stb__barrier;\nstatic unsigned char *stb__barrier2;\nstatic unsigned char *stb__barrier3;\nstatic unsigned char *stb__barrier4;\n\nstatic stb_uchar *stb__dout;\nstatic void stb__match(stb_uchar *data, stb_uint length)\n{\n   // INVERSE of memmove... write each byte before copying the next...\n   assert (stb__dout + length <= stb__barrier);\n   if (stb__dout + length > stb__barrier) { stb__dout += length; return; }\n   if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }\n   while (length--) *stb__dout++ = *data++;\n}\n\nstatic void stb__lit(stb_uchar *data, stb_uint length)\n{\n   assert (stb__dout + length <= stb__barrier);\n   if (stb__dout + length > stb__barrier) { stb__dout += length; return; }\n   if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }\n   memcpy(stb__dout, data, length);\n   stb__dout += length;\n}\n\n#define stb__in2(x)   ((i[x] << 8) + i[(x)+1])\n#define stb__in3(x)   ((i[x] << 16) + stb__in2((x)+1))\n#define stb__in4(x)   ((i[x] << 24) + stb__in3((x)+1))\n\nstatic stb_uchar *stb_decompress_token(stb_uchar *i)\n{\n   if (*i >= 0x20) { // use fewer if's for cases that expand small\n      if (*i >= 0x80)       stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;\n      else if (*i >= 0x40)  stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;\n      else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);\n   } else { // more ifs for cases that expand large, since overhead is amortized\n      if (*i >= 0x18)       stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;\n      else if (*i >= 0x10)  stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;\n      else if (*i >= 0x08)  stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);\n      else if (*i == 0x07)  stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);\n      else if (*i == 0x06)  stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;\n      else if (*i == 0x04)  stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;\n   }\n   return i;\n}\n\nstb_uint stb_decompress(stb_uchar *output, stb_uchar *i, stb_uint length)\n{\n   stb_uint olen;\n   if (stb__in4(0) != 0x57bC0000) return 0;\n   if (stb__in4(4) != 0)          return 0; // error! stream is > 4GB\n   olen = stb_decompress_length(i);\n   stb__barrier2 = i;\n   stb__barrier3 = i+length;\n   stb__barrier = output + olen;\n   stb__barrier4 = output;\n   i += 16;\n\n   stb__dout = output;\n   while (1) {\n      stb_uchar *old_i = i;\n      i = stb_decompress_token(i);\n      if (i == old_i) {\n         if (*i == 0x05 && i[1] == 0xfa) {\n            assert(stb__dout == output + olen);\n            if (stb__dout != output + olen) return 0;\n            if (stb_adler32(1, output, olen) != (stb_uint) stb__in4(2))\n               return 0;\n            return olen;\n         } else {\n            assert(0); /* NOTREACHED */\n            return 0;\n         }\n      }\n      assert(stb__dout <= output + olen);\n      if (stb__dout > output + olen)\n         return 0;\n   }\n}\n\nchar *stb_decompress_fromfile(char *filename, unsigned int *len)\n{\n   unsigned int n;\n   char *q;\n   unsigned char *p;\n   FILE *f = stb_p_fopen(filename, \"rb\");   if (f == NULL) return NULL;\n   fseek(f, 0, SEEK_END);\n   n = ftell(f);\n   fseek(f, 0, SEEK_SET);\n   p = (unsigned char * ) malloc(n); if (p == NULL) return NULL;\n   fread(p, 1, n, f);\n   fclose(f);\n   if (p == NULL) return NULL;\n   if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; }\n   q = (char *) malloc(stb_decompress_length(p)+1);\n   if (!q) { free(p); return NULL; }\n   *len = stb_decompress((unsigned char *) q, p, n);\n   if (*len) q[*len] = 0;\n   free(p);\n   return q;\n}\n\n#if 0\n//  streaming decompressor\n\nstatic struct\n{\n   stb__uchar *in_buffer;\n   stb__uchar *match;\n\n   stb__uint pending_literals;\n   stb__uint pending_match;\n} xx;\n\n\n\nstatic void stb__match(stb_uchar *data, stb_uint length)\n{\n   // INVERSE of memmove... write each byte before copying the next...\n   assert (stb__dout + length <= stb__barrier);\n   if (stb__dout + length > stb__barrier) { stb__dout += length; return; }\n   if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }\n   while (length--) *stb__dout++ = *data++;\n}\n\nstatic void stb__lit(stb_uchar *data, stb_uint length)\n{\n   assert (stb__dout + length <= stb__barrier);\n   if (stb__dout + length > stb__barrier) { stb__dout += length; return; }\n   if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }\n   memcpy(stb__dout, data, length);\n   stb__dout += length;\n}\n\nstatic void sx_match(stb_uchar *data, stb_uint length)\n{\n   xx.match = data;\n   xx.pending_match = length;\n}\n\nstatic void sx_lit(stb_uchar *data, stb_uint length)\n{\n   xx.pending_lit = length;\n}\n\nstatic int stb_decompress_token_state(void)\n{\n   stb__uchar *i = xx.in_buffer;\n\n   if (*i >= 0x20) { // use fewer if's for cases that expand small\n      if (*i >= 0x80)       sx_match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;\n      else if (*i >= 0x40)  sx_match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;\n      else /* *i >= 0x20 */ sx_lit(i+1, i[0] - 0x20 + 1), i += 1;\n   } else { // more ifs for cases that expand large, since overhead is amortized\n      if (*i >= 0x18)       sx_match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;\n      else if (*i >= 0x10)  sx_match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;\n      else if (*i >= 0x08)  sx_lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2;\n      else if (*i == 0x07)  sx_lit(i+3, stb__in2(1) + 1), i += 3;\n      else if (*i == 0x06)  sx_match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;\n      else if (*i == 0x04)  sx_match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;\n      else return 0;\n   }\n   xx.in_buffer = i;\n   return 1;\n}\n#endif\n\n\n\n////////////////////           compressor         ///////////////////////\n\nstatic unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)\n{\n   stb_uint i;\n   for (i=0; i < maxlen; ++i)\n      if (m1[i] != m2[i]) return i;\n   return i;\n}\n\n// simple implementation that just takes the source data in a big block\n\nstatic stb_uchar *stb__out;\nstatic FILE      *stb__outfile;\nstatic stb_uint   stb__outbytes;\n\nstatic void stb__write(unsigned char v)\n{\n   fputc(v, stb__outfile);\n   ++stb__outbytes;\n}\n\n#define stb_out(v)    (stb__out ? (void)(*stb__out++ = (stb_uchar) (v)) : stb__write((stb_uchar) (v)))\n\nstatic void stb_out2(stb_uint v)\n{\n   stb_out(v >> 8);\n   stb_out(v);\n}\n\nstatic void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }\nstatic void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16);\n                                   stb_out(v >> 8 ); stb_out(v);                  }\n\nstatic void outliterals(stb_uchar *in, ptrdiff_t numlit)\n{\n   while (numlit > 65536) {\n      outliterals(in,65536);\n      in     += 65536;\n      numlit -= 65536;\n   }\n\n   if      (numlit ==     0)    ;\n   else if (numlit <=    32)    stb_out (0x000020 + (stb_uint) numlit-1);\n   else if (numlit <=  2048)    stb_out2(0x000800 + (stb_uint) numlit-1);\n   else /*  numlit <= 65536) */ stb_out3(0x070000 + (stb_uint) numlit-1);\n\n   if (stb__out) {\n      memcpy(stb__out,in,numlit);\n      stb__out += numlit;\n   } else\n      fwrite(in, 1, numlit, stb__outfile);\n}\n\nstatic int stb__window = 0x40000; // 256K\nvoid stb_compress_window(int z)\n{\n   if (z >= 0x1000000) z = 0x1000000; // limit of implementation\n   if (z <      0x100) z = 0x100;   // insanely small\n   stb__window = z;\n}\n\nstatic int stb_not_crap(int best, int dist)\n{\n   return   ((best > 2  &&  dist <= 0x00100)\n          || (best > 5  &&  dist <= 0x04000)\n          || (best > 7  &&  dist <= 0x80000));\n}\n\nstatic  stb_uint stb__hashsize = 32768;\nvoid stb_compress_hashsize(unsigned int y)\n{\n   unsigned int z = 1024;\n   while (z < y) z <<= 1;\n   stb__hashsize = z >> 2;   // pass in bytes, store #pointers\n}\n\n// note that you can play with the hashing functions all you\n// want without needing to change the decompressor\n#define stb__hc(q,h,c)      (((h) << 7) + ((h) >> 25) + q[c])\n#define stb__hc2(q,h,c,d)   (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])\n#define stb__hc3(q,c,d,e)   ((q[c] << 14) + (q[d] << 7) + q[e])\n\nstatic stb_uint32 stb__running_adler;\n\nstatic int stb_compress_chunk(stb_uchar *history,\n                              stb_uchar *start,\n                              stb_uchar *end,\n                              int length,\n                              int *pending_literals,\n                              stb_uchar **chash,\n                              stb_uint mask)\n{\n   int window = stb__window;\n   stb_uint match_max;\n   stb_uchar *lit_start = start - *pending_literals;\n   stb_uchar *q = start;\n\n   #define STB__SCRAMBLE(h)   (((h) + ((h) >> 16)) & mask)\n\n   // stop short of the end so we don't scan off the end doing\n   // the hashing; this means we won't compress the last few bytes\n   // unless they were part of something longer\n   while (q < start+length && q+12 < end) {\n      int m;\n      stb_uint h1,h2,h3,h4, h;\n      stb_uchar *t;\n      int best = 2, dist=0;\n\n      if (q+65536 > end)\n         match_max = (stb_uint) (end-q);\n      else\n         match_max = 65536u;\n\n      #define stb__nc(b,d)  ((d) <= window && ((b) > 9 || stb_not_crap(b,d)))\n\n      #define STB__TRY(t,p)  /* avoid retrying a match we already tried */ \\\n                      if (p ? dist != (int) (q-t) : 1)                     \\\n                      if ((m = (int) stb_matchlen(t, q, match_max)) > best)\\\n                      if (stb__nc(m,(int) (q-(t))))                        \\\n                          best = m, dist = (int) (q - (t))\n\n      // rather than search for all matches, only try 4 candidate locations,\n      // chosen based on 4 different hash functions of different lengths.\n      // this strategy is inspired by LZO; hashing is unrolled here using the\n      // 'hc' macro\n      h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);\n                                      t = chash[h1]; if (t) STB__TRY(t,0);\n      h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);\n      h = stb__hc2(q,h, 5, 6);        t = chash[h2]; if (t) STB__TRY(t,1);\n      h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);\n      h = stb__hc2(q,h, 9,10);        t = chash[h3]; if (t) STB__TRY(t,1);\n      h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);\n                                      t = chash[h4]; if (t) STB__TRY(t,1);\n\n      // because we use a shared hash table, can only update it\n      // _after_ we've probed all of them\n      chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;\n\n      if (best > 2)\n         assert(dist > 0);\n\n      // see if our best match qualifies\n      if (best < 3) { // fast path literals\n         ++q;\n      } else if (best > 2  &&  best <= 0x80    &&  dist <= 0x100) {\n         outliterals(lit_start, q-lit_start); lit_start = (q += best);\n         stb_out(0x80 + best-1);\n         stb_out(dist-1);\n      } else if (best > 5  &&  best <= 0x100   &&  dist <= 0x4000) {\n         outliterals(lit_start, q-lit_start); lit_start = (q += best);\n         stb_out2(0x4000 + dist-1);\n         stb_out(best-1);\n      } else if (best > 7  &&  best <= 0x100   &&  dist <= 0x80000) {\n         outliterals(lit_start, q-lit_start); lit_start = (q += best);\n         stb_out3(0x180000 + dist-1);\n         stb_out(best-1);\n      } else if (best > 8  &&  best <= 0x10000 &&  dist <= 0x80000) {\n         outliterals(lit_start, q-lit_start); lit_start = (q += best);\n         stb_out3(0x100000 + dist-1);\n         stb_out2(best-1);\n      } else if (best > 9                      &&  dist <= 0x1000000) {\n         if (best > 65536) best = 65536;\n         outliterals(lit_start, q-lit_start); lit_start = (q += best);\n         if (best <= 0x100) {\n            stb_out(0x06);\n            stb_out3(dist-1);\n            stb_out(best-1);\n         } else {\n            stb_out(0x04);\n            stb_out3(dist-1);\n            stb_out2(best-1);\n         }\n      } else {  // fallback literals if no match was a balanced tradeoff\n         ++q;\n      }\n   }\n\n   // if we didn't get all the way, add the rest to literals\n   if (q-start < length)\n      q = start+length;\n\n   // the literals are everything from lit_start to q\n   *pending_literals = (int) (q - lit_start);\n\n   stb__running_adler = stb_adler32(stb__running_adler, start, (int) (q - start));\n   return (int) (q - start);\n}\n\nstatic int stb_compress_inner(stb_uchar *input, stb_uint length)\n{\n   int literals = 0;\n   stb_uint len,i;\n\n   stb_uchar **chash;\n   chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));\n   if (chash == NULL) return 0; // failure\n   for (i=0; i < stb__hashsize; ++i)\n      chash[i] = NULL;\n\n   // stream signature\n   stb_out(0x57); stb_out(0xbc);\n   stb_out2(0);\n\n   stb_out4(0);       // 64-bit length requires 32-bit leading 0\n   stb_out4(length);\n   stb_out4(stb__window);\n\n   stb__running_adler = 1;\n\n   len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);\n   assert(len == length);\n\n   outliterals(input+length - literals, literals);\n\n   free(chash);\n\n   stb_out2(0x05fa); // end opcode\n\n   stb_out4(stb__running_adler);\n\n   return 1; // success\n}\n\nstb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)\n{\n   stb__out = out;\n   stb__outfile = NULL;\n\n   stb_compress_inner(input, length);\n\n   return (stb_uint) (stb__out - out);\n}\n\nint stb_compress_tofile(char *filename, char *input, unsigned int length)\n{\n   //int maxlen = length + 512 + (length >> 2); // total guess\n   //char *buffer = (char *) malloc(maxlen);\n   //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);\n\n   stb__out = NULL;\n   stb__outfile = stb_p_fopen(filename, \"wb\");\n   if (!stb__outfile) return 0;\n\n   stb__outbytes = 0;\n\n   if (!stb_compress_inner((stb_uchar*)input, length))\n      return 0;\n\n   fclose(stb__outfile);\n\n   return stb__outbytes;\n}\n\nint stb_compress_intofile(FILE *f, char *input, unsigned int length)\n{\n   //int maxlen = length + 512 + (length >> 2); // total guess\n   //char *buffer = (char*)malloc(maxlen);\n   //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);\n\n   stb__out = NULL;\n   stb__outfile = f;\n   if (!stb__outfile) return 0;\n\n   stb__outbytes = 0;\n\n   if (!stb_compress_inner((stb_uchar*)input, length))\n      return 0;\n\n   return stb__outbytes;\n}\n\n//////////////////////    streaming I/O version    /////////////////////\n\n\nstatic size_t stb_out_backpatch_id(void)\n{\n   if (stb__out)\n      return (size_t) stb__out;\n   else\n      return ftell(stb__outfile);\n}\n\nstatic void stb_out_backpatch(size_t id, stb_uint value)\n{\n   stb_uchar data[4] = { (stb_uchar)(value >> 24), (stb_uchar)(value >> 16), (stb_uchar)(value >> 8), (stb_uchar)(value) };\n   if (stb__out) {\n      memcpy((void *) id, data, 4);\n   } else {\n      stb_uint where = ftell(stb__outfile);\n      fseek(stb__outfile, (long) id, SEEK_SET);\n      fwrite(data, 4, 1, stb__outfile);\n      fseek(stb__outfile, where, SEEK_SET);\n   }\n}\n\n// ok, the wraparound buffer was a total failure. let's instead\n// use a copying-in-place buffer, which lets us share the code.\n// This is way less efficient but it'll do for now.\n\nstatic struct\n{\n   stb_uchar *buffer;\n   int size;           // physical size of buffer in bytes\n\n   int valid;          // amount of valid data in bytes\n   int start;          // bytes of data already output\n\n   int window;\n   int fsize;\n\n   int pending_literals; // bytes not-quite output but counted in start\n   int length_id;\n\n   stb_uint total_bytes;\n\n   stb_uchar **chash;\n   stb_uint    hashmask;\n} xtb;\n\nstatic int stb_compress_streaming_start(void)\n{\n   stb_uint i;\n   xtb.size = stb__window * 3;\n   xtb.buffer = (stb_uchar*)malloc(xtb.size);\n   if (!xtb.buffer) return 0;\n\n   xtb.chash = (stb_uchar**)malloc(sizeof(*xtb.chash) * stb__hashsize);\n   if (!xtb.chash) {\n      free(xtb.buffer);\n      return 0;\n   }\n\n   for (i=0; i < stb__hashsize; ++i)\n      xtb.chash[i] = NULL;\n\n   xtb.hashmask = stb__hashsize-1;\n\n   xtb.valid        = 0;\n   xtb.start        = 0;\n   xtb.window       = stb__window;\n   xtb.fsize        = stb__window;\n   xtb.pending_literals = 0;\n   xtb.total_bytes  = 0;\n\n      // stream signature\n   stb_out(0x57); stb_out(0xbc); stb_out2(0);\n\n   stb_out4(0);       // 64-bit length requires 32-bit leading 0\n\n   xtb.length_id = (int) stb_out_backpatch_id();\n   stb_out4(0);       // we don't know the output length yet\n\n   stb_out4(stb__window);\n\n   stb__running_adler = 1;\n\n   return 1;\n}\n\nstatic int stb_compress_streaming_end(void)\n{\n   // flush out any remaining data\n   stb_compress_chunk(xtb.buffer, xtb.buffer+xtb.start, xtb.buffer+xtb.valid,\n                      xtb.valid-xtb.start, &xtb.pending_literals, xtb.chash, xtb.hashmask);\n\n   // write out pending literals\n   outliterals(xtb.buffer + xtb.valid - xtb.pending_literals, xtb.pending_literals);\n\n   stb_out2(0x05fa); // end opcode\n   stb_out4(stb__running_adler);\n\n   stb_out_backpatch(xtb.length_id, xtb.total_bytes);\n\n   free(xtb.buffer);\n   free(xtb.chash);\n   return 1;\n}\n\nvoid stb_write(char *data, int data_len)\n{\n   stb_uint i;\n\n   // @TODO: fast path for filling the buffer and doing nothing else\n   //   if (xtb.valid + data_len < xtb.size)\n\n   xtb.total_bytes += data_len;\n\n   while (data_len) {\n      // fill buffer\n      if (xtb.valid < xtb.size) {\n         int amt = xtb.size - xtb.valid;\n         if (data_len < amt) amt = data_len;\n         memcpy(xtb.buffer + xtb.valid, data, amt);\n         data_len -= amt;\n         data     += amt;\n         xtb.valid += amt;\n      }\n      if (xtb.valid < xtb.size)\n         return;\n\n      // at this point, the buffer is full\n\n      // if we can process some data, go for it; make sure\n      // we leave an 'fsize's worth of data, though\n      if (xtb.start + xtb.fsize < xtb.valid) {\n         int amount = (xtb.valid - xtb.fsize) - xtb.start;\n         int n;\n         assert(amount > 0);\n         n = stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid,\n                                amount, &xtb.pending_literals, xtb.chash, xtb.hashmask);\n         xtb.start += n;\n      }\n\n      assert(xtb.start + xtb.fsize >= xtb.valid);\n      // at this point, our future size is too small, so we\n      // need to flush some history. we, in fact, flush exactly\n      // one window's worth of history\n\n      {\n         int flush = xtb.window;\n         assert(xtb.start >= flush);\n         assert(xtb.valid >= flush);\n\n         // if 'pending literals' extends back into the shift region,\n         // write them out\n         if (xtb.start - xtb.pending_literals < flush) {\n            outliterals(xtb.buffer + xtb.start - xtb.pending_literals, xtb.pending_literals);\n            xtb.pending_literals = 0;\n         }\n\n         // now shift the window\n         memmove(xtb.buffer, xtb.buffer + flush, xtb.valid - flush);\n         xtb.start -= flush;\n         xtb.valid -= flush;\n\n         for (i=0; i <= xtb.hashmask; ++i)\n            if (xtb.chash[i] < xtb.buffer + flush)\n               xtb.chash[i] = NULL;\n            else\n               xtb.chash[i] -= flush;\n      }\n      // and now that we've made room for more data, go back to the top\n   }\n}\n\nint stb_compress_stream_start(FILE *f)\n{\n   stb__out = NULL;\n   stb__outfile = f;\n\n   if (f == NULL)\n      return 0;\n\n   if (!stb_compress_streaming_start())\n      return 0;\n\n   return 1;\n}\n\nvoid stb_compress_stream_end(int close)\n{\n   stb_compress_streaming_end();\n   if (close && stb__outfile) {\n      fclose(stb__outfile);\n   }\n}\n\n#endif // STB_DEFINE\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  File abstraction... tired of not having this... we can write\n//  compressors to be layers over these that auto-close their children.\n\n\ntypedef struct stbfile\n{\n   int (*getbyte)(struct stbfile *);  // -1 on EOF\n   unsigned int (*getdata)(struct stbfile *, void *block, unsigned int len);\n\n   int (*putbyte)(struct stbfile *, int byte);\n   unsigned int (*putdata)(struct stbfile *, void *block, unsigned int len);\n\n   unsigned int (*size)(struct stbfile *);\n\n   unsigned int (*tell)(struct stbfile *);\n   void (*backpatch)(struct stbfile *, unsigned int tell, void *block, unsigned int len);\n\n   void (*close)(struct stbfile *);\n\n   FILE *f;  // file to fread/fwrite\n   unsigned char *buffer; // input/output buffer\n   unsigned char *indata, *inend; // input buffer\n   union {\n      int various;\n      void *ptr;\n   };\n} stbfile;\n\nSTB_EXTERN unsigned int stb_getc(stbfile *f); // read\nSTB_EXTERN int stb_putc(stbfile *f, int ch); // write\nSTB_EXTERN unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len); // read\nSTB_EXTERN unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len); // write\nSTB_EXTERN unsigned int stb_tell(stbfile *f); // read\nSTB_EXTERN unsigned int stb_size(stbfile *f); // read/write\nSTB_EXTERN void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len); // write\n\n#ifdef STB_DEFINE\n\nunsigned int stb_getc(stbfile *f) { return f->getbyte(f); }\nint stb_putc(stbfile *f, int ch)  { return f->putbyte(f, ch); }\n\nunsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len)\n{\n   return f->getdata(f, buffer, len);\n}\nunsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len)\n{\n   return f->putdata(f, buffer, len);\n}\nvoid stb_close(stbfile *f)\n{\n   f->close(f);\n   free(f);\n}\nunsigned int stb_tell(stbfile *f) { return f->tell(f); }\nunsigned int stb_size(stbfile *f) { return f->size(f); }\nvoid stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len)\n{\n   f->backpatch(f,tell,buffer,len);\n}\n\n// FILE * implementation\nstatic int stb__fgetbyte(stbfile *f) { return fgetc(f->f); }\nstatic int stb__fputbyte(stbfile *f, int ch) { return fputc(ch, f->f)==0; }\nstatic unsigned int stb__fgetdata(stbfile *f, void *buffer, unsigned int len) { return (unsigned int) fread(buffer,1,len,f->f); }\nstatic unsigned int stb__fputdata(stbfile *f, void *buffer, unsigned int len) { return (unsigned int) fwrite(buffer,1,len,f->f); }\nstatic unsigned int stb__fsize(stbfile *f) { return (unsigned int) stb_filelen(f->f); }\nstatic unsigned int stb__ftell(stbfile *f) { return (unsigned int) ftell(f->f); }\nstatic void stb__fbackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len)\n{\n   fseek(f->f, where, SEEK_SET);\n   fwrite(buffer, 1, len, f->f);\n   fseek(f->f, 0, SEEK_END);\n}\nstatic void         stb__fclose(stbfile *f) { fclose(f->f); }\n\nstbfile *stb_openf(FILE *f)\n{\n   stbfile m = { stb__fgetbyte, stb__fgetdata,\n                 stb__fputbyte, stb__fputdata,\n                 stb__fsize, stb__ftell, stb__fbackpatch, stb__fclose,\n                 0,0,0, };\n   stbfile *z = (stbfile *) malloc(sizeof(*z));\n   if (z) {\n      *z = m;\n      z->f = f;\n   }\n   return z;\n}\n\nstatic int stb__nogetbyte(stbfile *f) { assert(0); return -1; }\nstatic unsigned int stb__nogetdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }\nstatic int stb__noputbyte(stbfile *f, int ch) { assert(0); return 0; }\nstatic unsigned int stb__noputdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }\nstatic void stb__nobackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) { assert(0); }\n\nstatic int stb__bgetbyte(stbfile *s)\n{\n   if (s->indata < s->inend)\n      return *s->indata++;\n   else\n      return -1;\n}\n\nstatic unsigned int stb__bgetdata(stbfile *s, void *buffer, unsigned int len)\n{\n   if (s->indata + len > s->inend)\n      len = (unsigned int) (s->inend - s->indata);\n   memcpy(buffer, s->indata, len);\n   s->indata += len;\n   return len;\n}\nstatic unsigned int stb__bsize(stbfile *s) { return (unsigned int) (s->inend  - s->buffer); }\nstatic unsigned int stb__btell(stbfile *s) { return (unsigned int) (s->indata - s->buffer); }\n\nstatic void stb__bclose(stbfile *s)\n{\n   if (s->various)\n      free(s->buffer);\n}\n\nstbfile *stb_open_inbuffer(void *buffer, unsigned int len)\n{\n   stbfile m = { stb__bgetbyte, stb__bgetdata,\n                 stb__noputbyte, stb__noputdata,\n                 stb__bsize, stb__btell, stb__nobackpatch, stb__bclose };\n   stbfile *z = (stbfile *) malloc(sizeof(*z));\n   if (z) {\n      *z = m;\n      z->buffer = (unsigned char *) buffer;\n      z->indata = z->buffer;\n      z->inend = z->indata + len;\n   }\n   return z;\n}\n\nstbfile *stb_open_inbuffer_free(void *buffer, unsigned int len)\n{\n   stbfile *z = stb_open_inbuffer(buffer, len);\n   if (z)\n      z->various = 1; // free\n   return z;\n}\n\n#ifndef STB_VERSION\n// if we've been cut-and-pasted elsewhere, you get a limited\n// version of stb_open, without the 'k' flag and utf8 support\nstatic void stb__fclose2(stbfile *f)\n{\n   fclose(f->f);\n}\n\nstbfile *stb_open(char *filename, char *mode)\n{\n   FILE *f = stb_p_fopen(filename, mode);\n   stbfile *s;\n   if (f == NULL) return NULL;\n   s = stb_openf(f);\n   if (s)\n      s->close = stb__fclose2;\n   return s;\n}\n#else\n// the full version depends on some code in stb.h; this\n// also includes the memory buffer output format implemented with stb_arr\nstatic void stb__fclose2(stbfile *f)\n{\n   stb_fclose(f->f, f->various);\n}\n\nstbfile *stb_open(char *filename, char *mode)\n{\n   FILE *f = stb_fopen(filename, mode[0] == 'k' ? mode+1 : mode);\n   stbfile *s;\n   if (f == NULL) return NULL;\n   s = stb_openf(f);\n   if (s) {\n      s->close = stb__fclose2;\n      s->various = mode[0] == 'k' ? stb_keep_if_different : stb_keep_yes;\n   }\n   return s;\n}\n\nstatic int stb__aputbyte(stbfile *f, int ch)\n{\n   stb_arr_push(f->buffer, ch);\n   return 1;\n}\nstatic unsigned int stb__aputdata(stbfile *f, void *data, unsigned int len)\n{\n   memcpy(stb_arr_addn(f->buffer, (int) len), data, len);\n   return len;\n}\nstatic unsigned int stb__asize(stbfile *f) { return stb_arr_len(f->buffer); }\nstatic void stb__abackpatch(stbfile *f, unsigned int where, void *data, unsigned int len)\n{\n   memcpy(f->buffer+where, data, len);\n}\nstatic void stb__aclose(stbfile *f)\n{\n   *(unsigned char **) f->ptr = f->buffer;\n}\n\nstbfile *stb_open_outbuffer(unsigned char **update_on_close)\n{\n   stbfile m = { stb__nogetbyte, stb__nogetdata,\n                 stb__aputbyte, stb__aputdata,\n                 stb__asize, stb__asize, stb__abackpatch, stb__aclose };\n   stbfile *z = (stbfile *) malloc(sizeof(*z));\n   if (z) {\n      z->ptr = update_on_close;\n      *z = m;\n   }\n   return z;\n}\n#endif\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  Arithmetic coder... based on cbloom's notes on the subject, should be\n//  less code than a huffman code.\n\ntypedef struct\n{\n   unsigned int range_low;\n   unsigned int range_high;\n   unsigned int code, range; // decode\n   int buffered_u8;\n   int pending_ffs;\n   stbfile *output;\n} stb_arith;\n\nSTB_EXTERN void stb_arith_init_encode(stb_arith *a, stbfile *out);\nSTB_EXTERN void stb_arith_init_decode(stb_arith *a, stbfile *in);\nSTB_EXTERN stbfile *stb_arith_encode_close(stb_arith *a);\nSTB_EXTERN stbfile *stb_arith_decode_close(stb_arith *a);\n\nSTB_EXTERN void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);\nSTB_EXTERN void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);\nSTB_EXTERN unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq);\nSTB_EXTERN void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);\nSTB_EXTERN unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2);\nSTB_EXTERN void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);\n\nSTB_EXTERN void stb_arith_encode_byte(stb_arith *a, int byte);\nSTB_EXTERN int  stb_arith_decode_byte(stb_arith *a);\n\n// this is a memory-inefficient way of doing things, but it's\n// fast(?) and simple\ntypedef struct\n{\n   unsigned short cumfreq;\n   unsigned short samples;\n} stb_arith_symstate_item;\n\ntypedef struct\n{\n   int num_sym;\n   unsigned int pow2;\n   int countdown;\n   stb_arith_symstate_item data[1];\n} stb_arith_symstate;\n\n#ifdef STB_DEFINE\nvoid stb_arith_init_encode(stb_arith *a, stbfile *out)\n{\n   a->range_low = 0;\n   a->range_high = 0xffffffff;\n   a->pending_ffs = -1; // means no buffered character currently, to speed up normal case\n   a->output = out;\n}\n\nstatic void stb__arith_carry(stb_arith *a)\n{\n   int i;\n   assert(a->pending_ffs != -1); // can't carry with no data\n   stb_putc(a->output, a->buffered_u8);\n   for (i=0; i < a->pending_ffs; ++i)\n      stb_putc(a->output, 0);\n}\n\nstatic void stb__arith_putbyte(stb_arith *a, int byte)\n{\n   if (a->pending_ffs) {\n      if (a->pending_ffs == -1) { // means no buffered data; encoded for fast path efficiency\n         if (byte == 0xff)\n            stb_putc(a->output, byte); // just write it immediately\n         else {\n            a->buffered_u8 = byte;\n            a->pending_ffs = 0;\n         }\n      } else if (byte == 0xff) {\n         ++a->pending_ffs;\n      } else {\n         int i;\n         stb_putc(a->output, a->buffered_u8);\n         for (i=0; i < a->pending_ffs; ++i)\n            stb_putc(a->output, 0xff);\n      }\n   } else if (byte == 0xff) {\n      ++a->pending_ffs;\n   } else {\n      // fast path\n      stb_putc(a->output, a->buffered_u8);\n      a->buffered_u8 = byte;\n   }\n}\n\nstatic void stb__arith_flush(stb_arith *a)\n{\n   if (a->pending_ffs >= 0) {\n      int i;\n      stb_putc(a->output, a->buffered_u8);\n      for (i=0; i < a->pending_ffs; ++i)\n         stb_putc(a->output, 0xff);\n   }\n}\n\nstatic void stb__renorm_encoder(stb_arith *a)\n{\n   stb__arith_putbyte(a, a->range_low >> 24);\n   a->range_low <<= 8;\n   a->range_high = (a->range_high << 8) | 0xff;\n}\n\nstatic void stb__renorm_decoder(stb_arith *a)\n{\n   int c = stb_getc(a->output);\n   a->code = (a->code << 8) + (c >= 0 ? c : 0); // if EOF, insert 0\n}\n\nvoid stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)\n{\n   unsigned int range = a->range_high - a->range_low;\n   unsigned int old = a->range_low;\n   range /= totalfreq;\n   a->range_low += range * cumfreq;\n   a->range_high = a->range_low + range*freq;\n   if (a->range_low < old)\n      stb__arith_carry(a);\n   while (a->range_high - a->range_low < 0x1000000)\n      stb__renorm_encoder(a);\n}\n\nvoid stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)\n{\n   unsigned int range = a->range_high - a->range_low;\n   unsigned int old = a->range_low;\n   range >>= totalfreq2;\n   a->range_low += range * cumfreq;\n   a->range_high = a->range_low + range*freq;\n   if (a->range_low < old)\n      stb__arith_carry(a);\n   while (a->range_high - a->range_low < 0x1000000)\n      stb__renorm_encoder(a);\n}\n\nunsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq)\n{\n   unsigned int freqsize = a->range / totalfreq;\n   unsigned int z = a->code / freqsize;\n   return z >= totalfreq ? totalfreq-1 : z;\n}\n\nvoid stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)\n{\n   unsigned int freqsize = a->range / totalfreq; // @OPTIMIZE, share with above divide somehow?\n   a->code -= freqsize * cumfreq;\n   a->range = freqsize * freq;\n   while (a->range < 0x1000000)\n      stb__renorm_decoder(a);\n}\n\nunsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2)\n{\n   unsigned int freqsize = a->range >> totalfreq2;\n   unsigned int z = a->code / freqsize;\n   return z >= (1U<<totalfreq2) ? (1U<<totalfreq2)-1 : z;\n}\n\nvoid stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)\n{\n   unsigned int freqsize = a->range >> totalfreq2;\n   a->code -= freqsize * cumfreq;\n   a->range = freqsize * freq;\n   while (a->range < 0x1000000)\n      stb__renorm_decoder(a);\n}\n\nstbfile *stb_arith_encode_close(stb_arith *a)\n{\n   // put exactly as many bytes as we'll read, so we can turn on/off arithmetic coding in a stream\n   stb__arith_putbyte(a, a->range_low >> 24);\n   stb__arith_putbyte(a, a->range_low >> 16);\n   stb__arith_putbyte(a, a->range_low >>  8);\n   stb__arith_putbyte(a, a->range_low >>  0);\n   stb__arith_flush(a);\n   return a->output;\n}\n\nstbfile *stb_arith_decode_close(stb_arith *a)\n{\n   return a->output;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Threads\n//\n\n#ifndef _WIN32\n#ifdef STB_THREADS\n#error \"threads not implemented except for Windows\"\n#endif\n#endif\n\n// call this function to free any global variables for memory testing\nSTB_EXTERN void stb_thread_cleanup(void);\n\ntypedef void * (*stb_thread_func)(void *);\n\n// do not rely on these types, this is an implementation detail.\n// compare against STB_THREAD_NULL and ST_SEMAPHORE_NULL\ntypedef void *stb_thread;\ntypedef void *stb_semaphore;\ntypedef void *stb_mutex;\ntypedef struct stb__sync *stb_sync;\n\n#define STB_SEMAPHORE_NULL    NULL\n#define STB_THREAD_NULL       NULL\n#define STB_MUTEX_NULL        NULL\n#define STB_SYNC_NULL         NULL\n\n// get the number of processors (limited to those in the affinity mask for this process).\nSTB_EXTERN int stb_processor_count(void);\n// force to run on a single core -- needed for RDTSC to work, e.g. for iprof\nSTB_EXTERN void stb_force_uniprocessor(void);\n\n// stb_work functions: queue up work to be done by some worker threads\n\n// set number of threads to serve the queue; you can change this on the fly,\n// but if you decrease it, it won't decrease until things currently on the\n// queue are finished\nSTB_EXTERN void          stb_work_numthreads(int n);\n// set maximum number of units in the queue; you can only set this BEFORE running any work functions\nSTB_EXTERN int           stb_work_maxunits(int n);\n// enqueue some work to be done (can do this from any thread, or even from a piece of work);\n// return value of f is stored in *return_code if non-NULL\nSTB_EXTERN int           stb_work(stb_thread_func f, void *d, volatile void **return_code);\n// as above, but stb_sync_reach is called on 'rel' after work is complete\nSTB_EXTERN int           stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);\n\n\n// necessary to call this when using volatile to order writes/reads\nSTB_EXTERN void          stb_barrier(void);\n\n// support for independent queues with their own threads\n\ntypedef struct stb__workqueue stb_workqueue;\n\nSTB_EXTERN stb_workqueue*stb_workq_new(int numthreads, int max_units);\nSTB_EXTERN stb_workqueue*stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex);\nSTB_EXTERN void          stb_workq_delete(stb_workqueue *q);\nSTB_EXTERN void          stb_workq_numthreads(stb_workqueue *q, int n);\nSTB_EXTERN int           stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code);\nSTB_EXTERN int           stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);\nSTB_EXTERN int           stb_workq_length(stb_workqueue *q);\n\nSTB_EXTERN stb_thread    stb_create_thread (stb_thread_func f, void *d);\nSTB_EXTERN stb_thread    stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel);\nSTB_EXTERN void          stb_destroy_thread(stb_thread t);\n\nSTB_EXTERN stb_semaphore stb_sem_new(int max_val);\nSTB_EXTERN stb_semaphore stb_sem_new_extra(int max_val, int start_val);\nSTB_EXTERN void          stb_sem_delete (stb_semaphore s);\nSTB_EXTERN void          stb_sem_waitfor(stb_semaphore s);\nSTB_EXTERN void          stb_sem_release(stb_semaphore s);\n\nSTB_EXTERN stb_mutex     stb_mutex_new(void);\nSTB_EXTERN void          stb_mutex_delete(stb_mutex m);\nSTB_EXTERN void          stb_mutex_begin(stb_mutex m);\nSTB_EXTERN void          stb_mutex_end(stb_mutex m);\n\nSTB_EXTERN stb_sync      stb_sync_new(void);\nSTB_EXTERN void          stb_sync_delete(stb_sync s);\nSTB_EXTERN int           stb_sync_set_target(stb_sync s, int count);\nSTB_EXTERN void          stb_sync_reach_and_wait(stb_sync s);    // wait for 'target' reachers\nSTB_EXTERN int           stb_sync_reach(stb_sync s);\n\ntypedef struct stb__threadqueue stb_threadqueue;\n#define STB_THREADQ_DYNAMIC   0\nSTB_EXTERN stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove);\nSTB_EXTERN void             stb_threadq_delete(stb_threadqueue *tq);\nSTB_EXTERN int              stb_threadq_get(stb_threadqueue *tq, void *output);\nSTB_EXTERN void             stb_threadq_get_block(stb_threadqueue *tq, void *output);\nSTB_EXTERN int              stb_threadq_add(stb_threadqueue *tq, void *input);\n// can return FALSE if STB_THREADQ_DYNAMIC and attempt to grow fails\nSTB_EXTERN int              stb_threadq_add_block(stb_threadqueue *tq, void *input);\n\n#ifdef STB_THREADS\n#ifdef STB_DEFINE\n\ntypedef struct\n{\n   stb_thread_func f;\n   void *d;\n   volatile void **return_val;\n   stb_semaphore sem;\n} stb__thread;\n\n// this is initialized along all possible paths to create threads, therefore\n// it's always initialized before any other threads are create, therefore\n// it's free of races AS LONG AS you only create threads through stb_*\nstatic stb_mutex stb__threadmutex, stb__workmutex;\n\nstatic void stb__threadmutex_init(void)\n{\n   if (stb__threadmutex == STB_SEMAPHORE_NULL) {\n      stb__threadmutex = stb_mutex_new();\n      stb__workmutex = stb_mutex_new();\n   }\n}\n\n#ifdef STB_THREAD_TEST\nvolatile float stb__t1=1, stb__t2;\n\nstatic void stb__wait(int n)\n{\n   float z = 0;\n   int i;\n   for (i=0; i < n; ++i)\n      z += 1 / (stb__t1+i);\n   stb__t2 = z;\n}\n#else\n#define stb__wait(x)\n#endif\n\n#ifdef _WIN32\n\n// avoid including windows.h -- note that our definitions aren't\n// exactly the same (we don't define the security descriptor struct)\n// so if you want to include windows.h, make sure you do it first.\n#include <process.h>\n\n#ifndef _WINDOWS_  // check windows.h guard\n#define STB__IMPORT   STB_EXTERN __declspec(dllimport)\n#define STB__DW       unsigned long\n\nSTB__IMPORT int     __stdcall TerminateThread(void *, STB__DW);\nSTB__IMPORT void *  __stdcall CreateSemaphoreA(void *sec, long,long,char*);\nSTB__IMPORT int     __stdcall CloseHandle(void *);\nSTB__IMPORT STB__DW __stdcall WaitForSingleObject(void *, STB__DW);\nSTB__IMPORT int     __stdcall ReleaseSemaphore(void *, long, long *);\nSTB__IMPORT void    __stdcall Sleep(STB__DW);\n#endif\n\n// necessary to call this when using volatile to order writes/reads\nvoid stb_barrier(void)\n{\n   #ifdef MemoryBarrier\n   MemoryBarrier();\n   #else\n   long temp;\n   __asm xchg temp,eax;\n   #endif\n}\n\nstatic void stb__thread_run(void *t)\n{\n   void *res;\n   stb__thread info = * (stb__thread *) t;\n   free(t);\n   res = info.f(info.d);\n   if (info.return_val)\n      *info.return_val = res;\n   if (info.sem != STB_SEMAPHORE_NULL)\n      stb_sem_release(info.sem);\n}\n\nstatic stb_thread stb_create_thread_raw(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)\n{\n#ifdef _MT\n#if defined(STB_FASTMALLOC) && !defined(STB_FASTMALLOC_ITS_OKAY_I_ONLY_MALLOC_IN_ONE_THREAD)\n   stb_fatal(\"Error! Cannot use STB_FASTMALLOC with threads.\\n\");\n   return STB_THREAD_NULL;\n#else\n   unsigned long id;\n   stb__thread *data = (stb__thread *) malloc(sizeof(*data));\n   if (!data) return NULL;\n   stb__threadmutex_init();\n   data->f = f;\n   data->d = d;\n   data->return_val = return_code;\n   data->sem = rel;\n   id = _beginthread(stb__thread_run, 0, data);\n   if (id == -1) return NULL;\n   return (void *) id;\n#endif\n#else\n#ifdef STB_NO_STB_STRINGS\n   stb_fatal(\"Invalid compilation\");\n#else\n   stb_fatal(\"Must compile mult-threaded to use stb_thread/stb_work.\");\n#endif\n   return NULL;\n#endif\n}\n\n// trivial win32 wrappers\nvoid          stb_destroy_thread(stb_thread t)   { TerminateThread(t,0); }\nstb_semaphore stb_sem_new(int maxv)                {return CreateSemaphoreA(NULL,0,maxv,NULL); }\nstb_semaphore stb_sem_new_extra(int maxv,int start){return CreateSemaphoreA(NULL,start,maxv,NULL); }\nvoid          stb_sem_delete(stb_semaphore s)    { if (s != NULL) CloseHandle(s); }\nvoid          stb_sem_waitfor(stb_semaphore s)   { WaitForSingleObject(s, 0xffffffff); } // INFINITE\nvoid          stb_sem_release(stb_semaphore s)   { ReleaseSemaphore(s,1,NULL); }\nstatic void   stb__thread_sleep(int ms)          { Sleep(ms); }\n\n#ifndef _WINDOWS_\nSTB__IMPORT int __stdcall GetProcessAffinityMask(void *, STB__DW *, STB__DW *);\nSTB__IMPORT void * __stdcall GetCurrentProcess(void);\nSTB__IMPORT int __stdcall SetProcessAffinityMask(void *, STB__DW);\n#endif\n\nint stb_processor_count(void)\n{\n   unsigned long proc,sys;\n   GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);\n   return stb_bitcount(proc);\n}\n\nvoid stb_force_uniprocessor(void)\n{\n   unsigned long proc,sys;\n   GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);\n   if (stb_bitcount(proc) > 1) {\n      int z;\n      for (z=0; z < 32; ++z)\n         if (proc & (1 << z))\n            break;\n      if (z < 32) {\n         proc = 1 << z;\n         SetProcessAffinityMask(GetCurrentProcess(), proc);\n      }\n   }\n}\n\n#ifdef _WINDOWS_\n#define STB_MUTEX_NATIVE\nvoid *stb_mutex_new(void)\n{\n   CRITICAL_SECTION *p = (CRITICAL_SECTION *) malloc(sizeof(*p));\n   if (p)\n#if _WIN32_WINNT >= 0x0500\n      InitializeCriticalSectionAndSpinCount(p, 500);\n#else\n      InitializeCriticalSection(p);\n#endif\n   return p;\n}\n\nvoid stb_mutex_delete(void *p)\n{\n   if (p) {\n      DeleteCriticalSection((CRITICAL_SECTION *) p);\n      free(p);\n   }\n}\n\nvoid stb_mutex_begin(void *p)\n{\n   stb__wait(500);\n   if (p)\n      EnterCriticalSection((CRITICAL_SECTION *) p);\n}\n\nvoid stb_mutex_end(void *p)\n{\n   if (p)\n      LeaveCriticalSection((CRITICAL_SECTION *) p);\n   stb__wait(500);\n}\n#endif // _WINDOWS_\n\n#if 0\n// for future reference,\n// InterlockedCompareExchange for x86:\n int cas64_mp(void * dest, void * xcmp, void * xxchg) {\n        __asm\n        {\n                mov             esi, [xxchg]            ; exchange\n                mov             ebx, [esi + 0]\n                mov             ecx, [esi + 4]\n\n                mov             esi, [xcmp]                     ; comparand\n                mov             eax, [esi + 0]\n                mov             edx, [esi + 4]\n\n                mov             edi, [dest]                     ; destination\n                lock cmpxchg8b  [edi]\n                jz              yyyy;\n\n                mov             [esi + 0], eax;\n                mov             [esi + 4], edx;\n\nyyyy:\n                xor             eax, eax;\n                setz    al;\n        };\n\ninline unsigned __int64 _InterlockedCompareExchange64(volatile unsigned __int64 *dest\n                           ,unsigned __int64 exchange\n                           ,unsigned __int64 comperand)\n{\n    //value returned in eax::edx\n    __asm {\n        lea esi,comperand;\n        lea edi,exchange;\n\n        mov eax,[esi];\n        mov edx,4[esi];\n        mov ebx,[edi];\n        mov ecx,4[edi];\n        mov esi,dest;\n        lock CMPXCHG8B [esi];\n    }\n#endif // #if 0\n\n#endif // _WIN32\n\nstb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)\n{\n   return stb_create_thread_raw(f,d,return_code,rel);\n}\n\nstb_thread stb_create_thread(stb_thread_func f, void *d)\n{\n   return stb_create_thread2(f,d,NULL,STB_SEMAPHORE_NULL);\n}\n\n// mutex implemented by wrapping semaphore\n#ifndef STB_MUTEX_NATIVE\nstb_mutex stb_mutex_new(void)            { return stb_sem_new_extra(1,1); }\nvoid      stb_mutex_delete(stb_mutex m)  { stb_sem_delete (m);      }\nvoid      stb_mutex_begin(stb_mutex m)   { stb__wait(500); if (m) stb_sem_waitfor(m); }\nvoid      stb_mutex_end(stb_mutex m)     { if (m) stb_sem_release(m); stb__wait(500); }\n#endif\n\n// thread merge operation\nstruct stb__sync\n{\n   int target;  // target number of threads to hit it\n   int sofar;   // total threads that hit it\n   int waiting; // total threads waiting\n\n   stb_mutex start;   // mutex to prevent starting again before finishing previous\n   stb_mutex mutex;   // mutex while tweaking state\n   stb_semaphore release; // semaphore wake up waiting threads\n      // we have to wake them up one at a time, rather than using a single release\n      // call, because win32 semaphores don't let you dynamically change the max count!\n};\n\nstb_sync stb_sync_new(void)\n{\n   stb_sync s = (stb_sync) malloc(sizeof(*s));\n   if (!s) return s;\n\n   s->target = s->sofar = s->waiting = 0;\n   s->mutex   = stb_mutex_new();\n   s->start   = stb_mutex_new();\n   s->release = stb_sem_new(1);\n   if (s->mutex == STB_MUTEX_NULL || s->release == STB_SEMAPHORE_NULL || s->start == STB_MUTEX_NULL) {\n      stb_mutex_delete(s->mutex);\n      stb_mutex_delete(s->mutex);\n      stb_sem_delete(s->release);\n      free(s);\n      return NULL;\n   }\n   return s;\n}\n\nvoid stb_sync_delete(stb_sync s)\n{\n   if (s->waiting) {\n      // it's bad to delete while there are threads waiting!\n      // shall we wait for them to reach, or just bail? just bail\n      assert(0);\n   }\n   stb_mutex_delete(s->mutex);\n   stb_mutex_delete(s->release);\n   free(s);\n}\n\nint stb_sync_set_target(stb_sync s, int count)\n{\n   // don't allow setting a target until the last one is fully released;\n   // note that this can lead to inefficient pipelining, and maybe we'd\n   // be better off ping-ponging between two internal syncs?\n   // I tried seeing how often this happened using TryEnterCriticalSection\n   // and could _never_ get it to happen in imv(stb), even with more threads\n   // than processors. So who knows!\n   stb_mutex_begin(s->start);\n\n   // this mutex is pointless, since it's not valid for threads\n   // to call reach() before anyone calls set_target() anyway\n   stb_mutex_begin(s->mutex);\n\n   assert(s->target == 0); // enforced by start mutex\n   s->target  = count;\n   s->sofar   = 0;\n   s->waiting = 0;\n   stb_mutex_end(s->mutex);\n   return STB_TRUE;\n}\n\nvoid stb__sync_release(stb_sync s)\n{\n   if (s->waiting)\n      stb_sem_release(s->release);\n   else {\n      s->target = 0;\n      stb_mutex_end(s->start);\n   }\n}\n\nint stb_sync_reach(stb_sync s)\n{\n   int n;\n   stb_mutex_begin(s->mutex);\n   assert(s->sofar < s->target);\n   n = ++s->sofar; // record this value to avoid possible race if we did 'return s->sofar';\n   if (s->sofar == s->target)\n      stb__sync_release(s);\n   stb_mutex_end(s->mutex);\n   return n;\n}\n\nvoid stb_sync_reach_and_wait(stb_sync s)\n{\n   stb_mutex_begin(s->mutex);\n   assert(s->sofar < s->target);\n   ++s->sofar;\n   if (s->sofar == s->target) {\n      stb__sync_release(s);\n      stb_mutex_end(s->mutex);\n   } else {\n      ++s->waiting; // we're waiting, so one more waiter\n      stb_mutex_end(s->mutex); // release the mutex to other threads\n\n      stb_sem_waitfor(s->release); // wait for merge completion\n\n      stb_mutex_begin(s->mutex); // on merge completion, grab the mutex\n      --s->waiting; // we're done waiting\n      stb__sync_release(s);    // restart the next waiter\n      stb_mutex_end(s->mutex); // and now we're done\n      // this ends the same as the first case, but it's a lot\n      // clearer to understand without sharing the code\n   }\n}\n\nstruct stb__threadqueue\n{\n   stb_mutex add, remove;\n   stb_semaphore nonempty, nonfull;\n   int head_blockers;  // number of threads blocking--used to know whether to release(avail)\n   int tail_blockers;\n   int head, tail, array_size, growable;\n   int item_size;\n   char *data;\n};\n\nstatic int stb__tq_wrap(volatile stb_threadqueue *z, int p)\n{\n   if (p == z->array_size)\n      return p - z->array_size;\n   else\n      return p;\n}\n\nint stb__threadq_get_raw(stb_threadqueue *tq2, void *output, int block)\n{\n   volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;\n   if (tq->head == tq->tail && !block) return 0;\n\n   stb_mutex_begin(tq->remove);\n\n   while (tq->head == tq->tail) {\n      if (!block) {\n         stb_mutex_end(tq->remove);\n         return 0;\n      }\n      ++tq->head_blockers;\n      stb_mutex_end(tq->remove);\n\n      stb_sem_waitfor(tq->nonempty);\n\n      stb_mutex_begin(tq->remove);\n      --tq->head_blockers;\n   }\n\n   memcpy(output, tq->data + tq->head*tq->item_size, tq->item_size);\n   stb_barrier();\n   tq->head = stb__tq_wrap(tq, tq->head+1);\n\n   stb_sem_release(tq->nonfull);\n   if (tq->head_blockers) // can't check if actually non-empty due to race?\n      stb_sem_release(tq->nonempty); // if there are other blockers, wake one\n\n   stb_mutex_end(tq->remove);\n   return STB_TRUE;\n}\n\nint stb__threadq_grow(volatile stb_threadqueue *tq)\n{\n   int n;\n   char *p;\n   assert(tq->remove != STB_MUTEX_NULL); // must have this to allow growth!\n   stb_mutex_begin(tq->remove);\n\n   n = tq->array_size * 2;\n   p = (char *) realloc(tq->data, n * tq->item_size);\n   if (p == NULL) {\n      stb_mutex_end(tq->remove);\n      stb_mutex_end(tq->add);\n      return STB_FALSE;\n   }\n   if (tq->tail < tq->head) {\n      memcpy(p + tq->array_size * tq->item_size, p, tq->tail * tq->item_size);\n      tq->tail += tq->array_size;\n   }\n   tq->data = p;\n   tq->array_size = n;\n\n   stb_mutex_end(tq->remove);\n   return STB_TRUE;\n}\n\nint stb__threadq_add_raw(stb_threadqueue *tq2, void *input, int block)\n{\n   int tail,pos;\n   volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;\n   stb_mutex_begin(tq->add);\n   for(;;) {\n      pos = tq->tail;\n      tail = stb__tq_wrap(tq, pos+1);\n      if (tail != tq->head) break;\n\n      // full\n      if (tq->growable) {\n         if (!stb__threadq_grow(tq)) {\n            stb_mutex_end(tq->add);\n            return STB_FALSE; // out of memory\n         }\n      } else if (!block) {\n         stb_mutex_end(tq->add);\n         return STB_FALSE;\n      } else {\n         ++tq->tail_blockers;\n         stb_mutex_end(tq->add);\n\n         stb_sem_waitfor(tq->nonfull);\n\n         stb_mutex_begin(tq->add);\n         --tq->tail_blockers;\n      }\n   }\n   memcpy(tq->data + tq->item_size * pos, input, tq->item_size);\n   stb_barrier();\n   tq->tail = tail;\n   stb_sem_release(tq->nonempty);\n   if (tq->tail_blockers) // can't check if actually non-full due to race?\n      stb_sem_release(tq->nonfull);\n   stb_mutex_end(tq->add);\n   return STB_TRUE;\n}\n\nint stb_threadq_length(stb_threadqueue *tq2)\n{\n   int a,b,n;\n   volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;\n   stb_mutex_begin(tq->add);\n   a = tq->head;\n   b = tq->tail;\n   n = tq->array_size;\n   stb_mutex_end(tq->add);\n   if (a > b) b += n;\n   return b-a;\n}\n\nint stb_threadq_get(stb_threadqueue *tq, void *output)\n{\n   return stb__threadq_get_raw(tq, output, STB_FALSE);\n}\n\nvoid stb_threadq_get_block(stb_threadqueue *tq, void *output)\n{\n   stb__threadq_get_raw(tq, output, STB_TRUE);\n}\n\nint stb_threadq_add(stb_threadqueue *tq, void *input)\n{\n   return stb__threadq_add_raw(tq, input, STB_FALSE);\n}\n\nint stb_threadq_add_block(stb_threadqueue *tq, void *input)\n{\n   return stb__threadq_add_raw(tq, input, STB_TRUE);\n}\n\nvoid stb_threadq_delete(stb_threadqueue *tq)\n{\n   if (tq) {\n      free(tq->data);\n      stb_mutex_delete(tq->add);\n      stb_mutex_delete(tq->remove);\n      stb_sem_delete(tq->nonempty);\n      stb_sem_delete(tq->nonfull);\n      free(tq);\n   }\n}\n\n#define STB_THREADQUEUE_DYNAMIC   0\nstb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove)\n{\n   int error=0;\n   stb_threadqueue *tq = (stb_threadqueue *) malloc(sizeof(*tq));\n   if (tq == NULL) return NULL;\n\n   if (num_items == STB_THREADQUEUE_DYNAMIC) {\n      tq->growable = STB_TRUE;\n      num_items = 32;\n   } else\n      tq->growable = STB_FALSE;\n\n   tq->item_size = item_size;\n   tq->array_size = num_items+1;\n\n   tq->add = tq->remove = STB_MUTEX_NULL;\n   tq->nonempty = tq->nonfull = STB_SEMAPHORE_NULL;\n   tq->data = NULL;\n   if (many_add)\n      { tq->add    = stb_mutex_new(); if (tq->add    == STB_MUTEX_NULL) goto error; }\n   if (many_remove || tq->growable)\n      { tq->remove = stb_mutex_new(); if (tq->remove == STB_MUTEX_NULL) goto error; }\n   tq->nonempty = stb_sem_new(1); if (tq->nonempty == STB_SEMAPHORE_NULL) goto error;\n   tq->nonfull  = stb_sem_new(1); if (tq->nonfull  == STB_SEMAPHORE_NULL) goto error;\n   tq->data = (char *) malloc(tq->item_size * tq->array_size);\n   if (tq->data == NULL) goto error;\n\n   tq->head = tq->tail = 0;\n   tq->head_blockers = tq->tail_blockers = 0;\n\n   return tq;\n\nerror:\n   stb_threadq_delete(tq);\n   return NULL;\n}\n\ntypedef struct\n{\n   stb_thread_func f;\n   void *d;\n   volatile void **retval;\n   stb_sync sync;\n} stb__workinfo;\n\n//static volatile stb__workinfo *stb__work;\n\nstruct stb__workqueue\n{\n   int numthreads;\n   stb_threadqueue *tq;\n};\n\nstatic stb_workqueue *stb__work_global;\n\nstatic void *stb__thread_workloop(void *p)\n{\n   volatile stb_workqueue *q = (volatile stb_workqueue *) p;\n   for(;;) {\n      void *z;\n      stb__workinfo w;\n      stb_threadq_get_block(q->tq, &w);\n      if (w.f == NULL) // null work is a signal to end the thread\n         return NULL;\n      z = w.f(w.d);\n      if (w.retval) { stb_barrier(); *w.retval = z; }\n      if (w.sync != STB_SYNC_NULL) stb_sync_reach(w.sync);\n   }\n}\n\nstb_workqueue *stb_workq_new(int num_threads, int max_units)\n{\n   return stb_workq_new_flags(num_threads, max_units, 0,0);\n}\n\nstb_workqueue *stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex)\n{\n   stb_workqueue *q = (stb_workqueue *) malloc(sizeof(*q));\n   if (q == NULL) return NULL;\n   q->tq = stb_threadq_new(sizeof(stb__workinfo), max_units, !no_add_mutex, !no_remove_mutex);\n   if (q->tq == NULL) { free(q); return NULL; }\n   q->numthreads = 0;\n   stb_workq_numthreads(q, numthreads);\n   return q;\n}\n\nvoid stb_workq_delete(stb_workqueue *q)\n{\n   while (stb_workq_length(q) != 0)\n      stb__thread_sleep(1);\n   stb_threadq_delete(q->tq);\n   free(q);\n}\n\nstatic int stb__work_maxitems = STB_THREADQUEUE_DYNAMIC;\n\nstatic void stb_work_init(int num_threads)\n{\n   if (stb__work_global == NULL) {\n      stb__threadmutex_init();\n      stb_mutex_begin(stb__workmutex);\n      stb_barrier();\n      if (*(stb_workqueue * volatile *) &stb__work_global == NULL)\n         stb__work_global = stb_workq_new(num_threads, stb__work_maxitems);\n      stb_mutex_end(stb__workmutex);\n   }\n}\n\nstatic int stb__work_raw(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)\n{\n   stb__workinfo w;\n   if (q == NULL) {\n      stb_work_init(1);\n      q = stb__work_global;\n   }\n   w.f = f;\n   w.d = d;\n   w.retval = return_code;\n   w.sync = rel;\n   return stb_threadq_add(q->tq, &w);\n}\n\nint stb_workq_length(stb_workqueue *q)\n{\n   return stb_threadq_length(q->tq);\n}\n\nint stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code)\n{\n   if (f == NULL) return 0;\n   return stb_workq_reach(q, f, d, return_code, NULL);\n}\n\nint stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)\n{\n   if (f == NULL) return 0;\n   return stb__work_raw(q, f, d, return_code, rel);\n}\n\nstatic void stb__workq_numthreads(stb_workqueue *q, int n)\n{\n   while (q->numthreads < n) {\n      stb_create_thread(stb__thread_workloop, q);\n      ++q->numthreads;\n   }\n   while (q->numthreads > n) {\n      stb__work_raw(q, NULL, NULL, NULL, NULL);\n      --q->numthreads;\n   }\n}\n\nvoid stb_workq_numthreads(stb_workqueue *q, int n)\n{\n   stb_mutex_begin(stb__threadmutex);\n   stb__workq_numthreads(q,n);\n   stb_mutex_end(stb__threadmutex);\n}\n\nint stb_work_maxunits(int n)\n{\n   if (stb__work_global == NULL) {\n      stb__work_maxitems = n;\n      stb_work_init(1);\n   }\n   return stb__work_maxitems;\n}\n\nint stb_work(stb_thread_func f, void *d, volatile void **return_code)\n{\n   return stb_workq(stb__work_global, f,d,return_code);\n}\n\nint stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)\n{\n   return stb_workq_reach(stb__work_global, f,d,return_code,rel);\n}\n\nvoid stb_work_numthreads(int n)\n{\n   if (stb__work_global == NULL)\n      stb_work_init(n);\n   else\n      stb_workq_numthreads(stb__work_global, n);\n}\n#endif // STB_DEFINE\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Background disk I/O\n//\n//\n\n#define STB_BGIO_READ_ALL   (-1)\nSTB_EXTERN int stb_bgio_read    (char *filename, int offset, int len, stb_uchar **result, int *olen);\nSTB_EXTERN int stb_bgio_readf   (FILE *f       , int offset, int len, stb_uchar **result, int *olen);\nSTB_EXTERN int stb_bgio_read_to (char *filename, int offset, int len, stb_uchar  *buffer, int *olen);\nSTB_EXTERN int stb_bgio_readf_to(FILE *f       , int offset, int len, stb_uchar  *buffer, int *olen);\n\ntypedef struct\n{\n   int have_data;\n   int is_valid;\n   int is_dir;\n   time_t filetime;\n   stb_int64 filesize;\n} stb_bgstat;\n\nSTB_EXTERN int stb_bgio_stat    (char *filename, stb_bgstat *result);\n\n#ifdef STB_DEFINE\n\nstatic stb_workqueue *stb__diskio;\nstatic stb_mutex stb__diskio_mutex;\n\nvoid stb_thread_cleanup(void)\n{\n   if (stb__work_global) stb_workq_delete(stb__work_global); stb__work_global = NULL;\n   if (stb__threadmutex) stb_mutex_delete(stb__threadmutex); stb__threadmutex = NULL;\n   if (stb__workmutex)   stb_mutex_delete(stb__workmutex);   stb__workmutex   = NULL;\n   if (stb__diskio)      stb_workq_delete(stb__diskio);      stb__diskio      = NULL;\n   if (stb__diskio_mutex)stb_mutex_delete(stb__diskio_mutex);stb__diskio_mutex= NULL;\n}\n\n\ntypedef struct\n{\n   char *filename;\n   FILE *f;\n   int offset;\n   int len;\n\n   stb_bgstat *stat_out;\n   stb_uchar *output;\n   stb_uchar **result;\n   int *len_output;\n   int *flag;\n} stb__disk_command;\n\n#define STB__MAX_DISK_COMMAND 100\nstatic stb__disk_command stb__dc_queue[STB__MAX_DISK_COMMAND];\nstatic int stb__dc_offset;\n\nvoid stb__io_init(void)\n{\n   if (!stb__diskio) {\n      stb__threadmutex_init();\n      stb_mutex_begin(stb__threadmutex);\n      stb_barrier();\n      if (*(stb_thread * volatile *) &stb__diskio == NULL) {\n         stb__diskio_mutex = stb_mutex_new();\n         // use many threads so OS can try to schedule seeks\n         stb__diskio = stb_workq_new_flags(16,STB__MAX_DISK_COMMAND,STB_FALSE,STB_FALSE);\n      }\n      stb_mutex_end(stb__threadmutex);\n   }\n}\n\nstatic void * stb__io_error(stb__disk_command *dc)\n{\n   if (dc->len_output) *dc->len_output = 0;\n   if (dc->result) *dc->result = NULL;\n   if (dc->flag) *dc->flag = -1;\n   return NULL;\n}\n\nstatic void * stb__io_task(void *p)\n{\n   stb__disk_command *dc = (stb__disk_command *) p;\n   int len;\n   FILE *f;\n   stb_uchar *buf;\n\n   if (dc->stat_out) {\n      struct _stati64 s;\n      if (!_stati64(dc->filename, &s)) {\n         dc->stat_out->filesize = s.st_size;\n         dc->stat_out->filetime = s.st_mtime;\n         dc->stat_out->is_dir = s.st_mode & _S_IFDIR;\n         dc->stat_out->is_valid = (s.st_mode & _S_IFREG) || dc->stat_out->is_dir;\n      } else\n         dc->stat_out->is_valid = 0;\n      stb_barrier();\n      dc->stat_out->have_data = 1;\n      free(dc->filename);\n      return 0;\n   }\n   if (dc->f) {\n      #ifdef WIN32\n      f = _fdopen(_dup(_fileno(dc->f)), \"rb\");\n      #else\n      f = fdopen(dup(fileno(dc->f)), \"rb\");\n      #endif\n      if (!f)\n         return stb__io_error(dc);\n   } else {\n      f = fopen(dc->filename, \"rb\");\n      free(dc->filename);\n      if (!f)\n         return stb__io_error(dc);\n   }\n\n   len = dc->len;\n   if (len < 0) {\n      fseek(f, 0, SEEK_END);\n      len = ftell(f) - dc->offset;\n   }\n\n   if (fseek(f, dc->offset, SEEK_SET)) {\n      fclose(f);\n      return stb__io_error(dc);\n   }\n\n   if (dc->output)\n      buf = dc->output;\n   else {\n      buf = (stb_uchar *) malloc(len);\n      if (buf == NULL) {\n         fclose(f);\n         return stb__io_error(dc);\n      }\n   }\n\n   len = fread(buf, 1, len, f);\n   fclose(f);\n   if (dc->len_output) *dc->len_output = len;\n   if (dc->result) *dc->result = buf;\n   if (dc->flag) *dc->flag = 1;\n\n   return NULL;\n}\n\nint stb__io_add(char *fname, FILE *f, int off, int len, stb_uchar *out, stb_uchar **result, int *olen, int *flag, stb_bgstat *stat)\n{\n   int res;\n   stb__io_init();\n   // do memory allocation outside of mutex\n   if (fname) fname = stb_p_strdup(fname);\n   stb_mutex_begin(stb__diskio_mutex);\n   {\n      stb__disk_command *dc = &stb__dc_queue[stb__dc_offset];\n      dc->filename = fname;\n      dc->f = f;\n      dc->offset = off;\n      dc->len = len;\n      dc->output = out;\n      dc->result = result;\n      dc->len_output = olen;\n      dc->flag = flag;\n      dc->stat_out = stat;\n      res = stb_workq(stb__diskio, stb__io_task, dc, NULL);\n      if (res)\n         stb__dc_offset = (stb__dc_offset + 1 == STB__MAX_DISK_COMMAND ? 0 : stb__dc_offset+1);\n   }\n   stb_mutex_end(stb__diskio_mutex);\n   return res;\n}\n\nint stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen)\n{\n   return stb__io_add(filename,NULL,offset,len,NULL,result,olen,NULL,NULL);\n}\n\nint stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen)\n{\n   return stb__io_add(NULL,f,offset,len,NULL,result,olen,NULL,NULL);\n}\n\nint stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen)\n{\n   return stb__io_add(filename,NULL,offset,len,buffer,NULL,olen,NULL,NULL);\n}\n\nint stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen)\n{\n   return stb__io_add(NULL,f,offset,len,buffer,NULL,olen,NULL,NULL);\n}\n\nSTB_EXTERN int stb_bgio_stat    (char *filename, stb_bgstat *result)\n{\n   result->have_data = 0;\n   return stb__io_add(filename,NULL,0,0,0,NULL,0,NULL, result);\n}\n#endif\n#endif\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Fast malloc implementation\n//\n//   This is a clone of TCMalloc, but without the thread support.\n//      1. large objects are allocated directly, page-aligned\n//      2. small objects are allocated in homogeonous heaps, 0 overhead\n//\n//   We keep an allocation table for pages a la TCMalloc. This would\n//   require 4MB for the entire address space, but we only allocate\n//   the parts that are in use. The overhead from using homogenous heaps\n//   everywhere is 3MB. (That is, if you allocate 1 object of each size,\n//   you'll use 3MB.)\n\n#if defined(STB_DEFINE) && ((defined(_WIN32) && !defined(_M_AMD64)) || defined(STB_FASTMALLOC))\n\n#ifdef _WIN32\n   #ifndef _WINDOWS_\n   #ifndef STB__IMPORT\n   #define STB__IMPORT   STB_EXTERN __declspec(dllimport)\n   #define STB__DW       unsigned long\n   #endif\n   STB__IMPORT void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);\n   STB__IMPORT int   __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);\n   #endif\n   #define stb__alloc_pages_raw(x)     (stb_uint32) VirtualAlloc(NULL, (x), 0x3000, 0x04)\n   #define stb__dealloc_pages_raw(p)   VirtualFree((void *) p, 0, 0x8000)\n#else\n   #error \"Platform not currently supported\"\n#endif\n\ntypedef struct stb__span\n{\n   int                start, len;\n   struct stb__span  *next, *prev;\n   void              *first_free;\n   unsigned short     list; // 1..256 free; 257..511 sizeclass; 0=large block\n   short              allocations; // # outstanding allocations for sizeclass\n} stb__span;  // 24\n\nstatic stb__span **stb__span_for_page;\nstatic int stb__firstpage, stb__lastpage;\nstatic void stb__update_page_range(int first, int last)\n{\n   stb__span **sfp;\n   int i, f,l;\n   if (first >= stb__firstpage && last <= stb__lastpage) return;\n   if (stb__span_for_page == NULL) {\n      f = first;\n      l = f+stb_max(last-f, 16384);\n      l = stb_min(l, 1<<20);\n   } else if (last > stb__lastpage) {\n      f = stb__firstpage;\n      l = f + (stb__lastpage - f) * 2;\n      l = stb_clamp(last, l,1<<20);\n   } else {\n      l = stb__lastpage;\n      f = l - (l - stb__firstpage) * 2;\n      f = stb_clamp(f, 0,first);\n   }\n   sfp = (stb__span **) stb__alloc_pages_raw(sizeof(void *) * (l-f));\n   for (i=f; i < stb__firstpage; ++i) sfp[i - f] = NULL;\n   for (   ; i < stb__lastpage ; ++i) sfp[i - f] = stb__span_for_page[i - stb__firstpage];\n   for (   ; i < l             ; ++i) sfp[i - f] = NULL;\n   if (stb__span_for_page) stb__dealloc_pages_raw(stb__span_for_page);\n   stb__firstpage = f;\n   stb__lastpage  = l;\n   stb__span_for_page = sfp;\n}\n\nstatic stb__span *stb__span_free=NULL;\nstatic stb__span *stb__span_first, *stb__span_end;\nstatic stb__span *stb__span_alloc(void)\n{\n   stb__span *s = stb__span_free;\n   if (s)\n      stb__span_free = s->next;\n   else {\n      if (!stb__span_first) {\n         stb__span_first = (stb__span *) stb__alloc_pages_raw(65536);\n         if (stb__span_first == NULL) return NULL;\n         stb__span_end = stb__span_first + (65536 / sizeof(stb__span));\n      }\n      s = stb__span_first++;\n      if (stb__span_first == stb__span_end) stb__span_first = NULL;\n   }\n   return s;\n}\n\nstatic stb__span *stb__spanlist[512];\n\nstatic void stb__spanlist_unlink(stb__span *s)\n{\n   if (s->prev)\n      s->prev->next = s->next;\n   else {\n      int n = s->list;\n      assert(stb__spanlist[n] == s);\n      stb__spanlist[n] = s->next;\n   }\n   if (s->next)\n      s->next->prev = s->prev;\n   s->next = s->prev = NULL;\n   s->list = 0;\n}\n\nstatic void stb__spanlist_add(int n, stb__span *s)\n{\n   s->list = n;\n   s->next = stb__spanlist[n];\n   s->prev = NULL;\n   stb__spanlist[n] = s;\n   if (s->next) s->next->prev = s;\n}\n\n#define stb__page_shift       12\n#define stb__page_size        (1 << stb__page_shift)\n#define stb__page_number(x)   ((x) >> stb__page_shift)\n#define stb__page_address(x)  ((x) << stb__page_shift)\n\nstatic void stb__set_span_for_page(stb__span *s)\n{\n   int i;\n   for (i=0; i < s->len; ++i)\n      stb__span_for_page[s->start + i - stb__firstpage] = s;\n}\n\nstatic stb__span *stb__coalesce(stb__span *a, stb__span *b)\n{\n   assert(a->start + a->len == b->start);\n   if (a->list) stb__spanlist_unlink(a);\n   if (b->list) stb__spanlist_unlink(b);\n   a->len += b->len;\n   b->len = 0;\n   b->next = stb__span_free;\n   stb__span_free = b;\n   stb__set_span_for_page(a);\n   return a;\n}\n\nstatic void stb__free_span(stb__span *s)\n{\n   stb__span *n = NULL;\n   if (s->start > stb__firstpage) {\n      n = stb__span_for_page[s->start-1 - stb__firstpage];\n      if (n && n->allocations == -2 && n->start + n->len == s->start) s = stb__coalesce(n,s);\n   }\n   if (s->start + s->len < stb__lastpage) {\n      n = stb__span_for_page[s->start + s->len - stb__firstpage];\n      if (n && n->allocations == -2 && s->start + s->len == n->start) s = stb__coalesce(s,n);\n   }\n   s->allocations = -2;\n   stb__spanlist_add(s->len > 256 ? 256 : s->len, s);\n}\n\nstatic stb__span *stb__alloc_pages(int num)\n{\n   stb__span *s = stb__span_alloc();\n   int p;\n   if (!s) return NULL;\n   p = stb__alloc_pages_raw(num << stb__page_shift);\n   if (p == 0) { s->next = stb__span_free; stb__span_free = s; return 0; }\n   assert(stb__page_address(stb__page_number(p)) == p);\n   p = stb__page_number(p);\n   stb__update_page_range(p, p+num);\n   s->start = p;\n   s->len   = num;\n   s->next  = NULL;\n   s->prev  = NULL;\n   stb__set_span_for_page(s);\n   return s;\n}\n\nstatic stb__span *stb__alloc_span(int pagecount)\n{\n   int i;\n   stb__span *p = NULL;\n   for(i=pagecount; i < 256; ++i)\n      if (stb__spanlist[i]) {\n         p = stb__spanlist[i];\n         break;\n      }\n   if (!p) {\n      p = stb__spanlist[256];\n      while (p && p->len < pagecount)\n         p = p->next;\n   }\n   if (!p) {\n      p = stb__alloc_pages(pagecount < 16 ? 16 : pagecount);\n      if (p == NULL) return 0;\n   } else\n      stb__spanlist_unlink(p);\n\n   if (p->len > pagecount) {\n      stb__span *q = stb__span_alloc();\n      if (q) {\n         q->start = p->start + pagecount;\n         q->len   = p->len   - pagecount;\n         p->len   = pagecount;\n         for (i=0; i < q->len; ++i)\n            stb__span_for_page[q->start+i - stb__firstpage] = q;\n         stb__spanlist_add(q->len > 256 ? 256 : q->len, q);\n      }\n   }\n   return p;\n}\n\n#define STB__MAX_SMALL_SIZE     32768\n#define STB__MAX_SIZE_CLASSES   256\n\nstatic unsigned char stb__class_base[32];\nstatic unsigned char stb__class_shift[32];\nstatic unsigned char stb__pages_for_class[STB__MAX_SIZE_CLASSES];\nstatic           int stb__size_for_class[STB__MAX_SIZE_CLASSES];\n\nstb__span *stb__get_nonempty_sizeclass(int c)\n{\n   int s = c + 256, i, size, tsize; // remap to span-list index\n   char *z;\n   void *q;\n   stb__span *p = stb__spanlist[s];\n   if (p) {\n      if (p->first_free) return p; // fast path: it's in the first one in list\n      for (p=p->next; p; p=p->next)\n         if (p->first_free) {\n            // move to front for future queries\n            stb__spanlist_unlink(p);\n            stb__spanlist_add(s, p);\n            return p;\n         }\n   }\n   // no non-empty ones, so allocate a new one\n   p = stb__alloc_span(stb__pages_for_class[c]);\n   if (!p) return NULL;\n   // create the free list up front\n   size = stb__size_for_class[c];\n   tsize = stb__pages_for_class[c] << stb__page_shift;\n   i = 0;\n   z = (char *) stb__page_address(p->start);\n   q = NULL;\n   while (i + size <= tsize) {\n      * (void **) z = q; q = z;\n      z += size;\n      i += size;\n   }\n   p->first_free = q;\n   p->allocations = 0;\n   stb__spanlist_add(s,p);\n   return p;\n}\n\nstatic int stb__sizeclass(size_t sz)\n{\n   int z = stb_log2_floor(sz); // -1 below to group e.g. 13,14,15,16 correctly\n   return stb__class_base[z] + ((sz-1) >> stb__class_shift[z]);\n}\n\nstatic void stb__init_sizeclass(void)\n{\n   int i, size, overhead;\n   int align_shift = 2;  // allow 4-byte and 12-byte blocks as well, vs. TCMalloc\n   int next_class = 1;\n   int last_log = 0;\n\n   for (i = 0; i < align_shift; i++) {\n      stb__class_base [i] = next_class;\n      stb__class_shift[i] = align_shift;\n   }\n\n   for (size = 1 << align_shift; size <= STB__MAX_SMALL_SIZE; size += 1 << align_shift) {\n      i = stb_log2_floor(size);\n      if (i > last_log) {\n         if (size == 16) ++align_shift; // switch from 4-byte to 8-byte alignment\n         else if (size >= 128 && align_shift < 8) ++align_shift;\n         stb__class_base[i]  = next_class - ((size-1) >> align_shift);\n         stb__class_shift[i] = align_shift;\n         last_log = i;\n      }\n      stb__size_for_class[next_class++] = size;\n   }\n\n   for (i=1; i <= STB__MAX_SMALL_SIZE; ++i)\n      assert(i <= stb__size_for_class[stb__sizeclass(i)]);\n\n   overhead = 0;\n   for (i = 1; i < next_class; i++) {\n      int s = stb__size_for_class[i];\n      size = stb__page_size;\n      while (size % s > size >> 3)\n         size += stb__page_size;\n      stb__pages_for_class[i] = (unsigned char) (size >> stb__page_shift);\n      overhead += size;\n   }\n   assert(overhead < (4 << 20)); // make sure it's under 4MB of overhead\n}\n\n#ifdef STB_DEBUG\n#define stb__smemset(a,b,c)  memset((void *) a, b, c)\n#elif defined(STB_FASTMALLOC_INIT)\n#define stb__smemset(a,b,c)  memset((void *) a, b, c)\n#else\n#define stb__smemset(a,b,c)\n#endif\nvoid *stb_smalloc(size_t sz)\n{\n   stb__span *s;\n   if (sz == 0) return NULL;\n   if (stb__size_for_class[1] == 0) stb__init_sizeclass();\n   if (sz > STB__MAX_SMALL_SIZE) {\n      s = stb__alloc_span((sz + stb__page_size - 1) >> stb__page_shift);\n      if (s == NULL) return NULL;\n      s->list = 0;\n      s->next = s->prev = NULL;\n      s->allocations = -32767;\n      stb__smemset(stb__page_address(s->start), 0xcd, (sz+3)&~3);\n      return (void *) stb__page_address(s->start);\n   } else {\n      void *p;\n      int c = stb__sizeclass(sz);\n      s = stb__spanlist[256+c];\n      if (!s || !s->first_free)\n         s = stb__get_nonempty_sizeclass(c);\n      if (s == NULL) return NULL;\n      p = s->first_free;\n      s->first_free = * (void **) p;\n      ++s->allocations;\n      stb__smemset(p,0xcd, sz);\n      return p;\n   }\n}\n\nint stb_ssize(void *p)\n{\n   stb__span *s;\n   if (p == NULL) return 0;\n   s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];\n   if (s->list >= 256) {\n      return stb__size_for_class[s->list - 256];\n   } else {\n      assert(s->list == 0);\n      return s->len << stb__page_shift;\n   }\n}\n\nvoid stb_sfree(void *p)\n{\n   stb__span *s;\n   if (p == NULL) return;\n   s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];\n   if (s->list >= 256) {\n      stb__smemset(p, 0xfe, stb__size_for_class[s->list-256]);\n      * (void **) p = s->first_free;\n      s->first_free = p;\n      if (--s->allocations == 0) {\n         stb__spanlist_unlink(s);\n         stb__free_span(s);\n      }\n   } else {\n      assert(s->list == 0);\n      stb__smemset(p, 0xfe, stb_ssize(p));\n      stb__free_span(s);\n   }\n}\n\nvoid *stb_srealloc(void *p, size_t sz)\n{\n   size_t cur_size;\n   if (p == NULL) return stb_smalloc(sz);\n   if (sz == 0) { stb_sfree(p); return NULL; }\n   cur_size = stb_ssize(p);\n   if (sz > cur_size || sz <= (cur_size >> 1)) {\n      void *q;\n      if (sz > cur_size && sz < (cur_size << 1)) sz = cur_size << 1;\n      q = stb_smalloc(sz); if (q == NULL) return NULL;\n      memcpy(q, p, sz < cur_size ? sz : cur_size);\n      stb_sfree(p);\n      return q;\n   }\n   return p;\n}\n\nvoid *stb_scalloc(size_t n, size_t sz)\n{\n   void *p;\n   if (n == 0 || sz == 0) return NULL;\n   if (stb_log2_ceil(n) + stb_log2_ceil(n) >= 32) return NULL;\n   p = stb_smalloc(n*sz);\n   if (p) memset(p, 0, n*sz);\n   return p;\n}\n\nchar *stb_sstrdup(char *s)\n{\n   int n = strlen(s);\n   char *p = (char *) stb_smalloc(n+1);\n   if (p) stb_p_strcpy_s(p,n+1,s);\n   return p;\n}\n#endif // STB_DEFINE\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Source code constants\n//\n// This is a trivial system to let you specify constants in source code,\n// then while running you can change the constants.\n//\n// Note that you can't wrap the #defines, because we need to know their\n// names. So we provide a pre-wrapped version without 'STB_' for convenience;\n// to request it, #define STB_CONVENIENT_H, yielding:\n//       KI -- integer\n//       KU -- unsigned integer\n//       KF -- float\n//       KD -- double\n//       KS -- string constant\n//\n// Defaults to functioning in debug build, not in release builds.\n// To force on, define STB_ALWAYS_H\n\n#ifdef STB_CONVENIENT_H\n#define KI(x) STB_I(x)\n#define KU(x) STB_UI(x)\n#define KF(x) STB_F(x)\n#define KD(x) STB_D(x)\n#define KS(x) STB_S(x)\n#endif\n\nSTB_EXTERN void stb_source_path(char *str);\n#ifdef STB_DEFINE\nchar *stb__source_path;\nvoid stb_source_path(char *path)\n{\n   stb__source_path = path;\n}\n\nchar *stb__get_sourcefile_path(char *file)\n{\n   static char filebuf[512];\n   if (stb__source_path) {\n      stb_p_sprintf(filebuf stb_p_size(sizeof(filebuf)), \"%s/%s\", stb__source_path, file);\n      if (stb_fexists(filebuf)) return filebuf;\n   }\n\n   if (stb_fexists(file)) return file;\n\n   stb_p_sprintf(filebuf stb_p_size(sizeof(filebuf)), \"../%s\", file);\n   if (!stb_fexists(filebuf)) return filebuf;\n\n   return file;\n}\n#endif\n\n#define STB_F(x)   ((float) STB_H(x))\n#define STB_UI(x)  ((unsigned int) STB_I(x))\n\n#if !defined(STB_DEBUG) && !defined(STB_ALWAYS_H)\n#define STB_D(x)   ((double) (x))\n#define STB_I(x)   ((int) (x))\n#define STB_S(x)   ((char *) (x))\n#else\n#define STB_D(x)   stb__double_constant(__FILE__, __LINE__-1, (x))\n#define STB_I(x)   stb__int_constant(__FILE__, __LINE__-1, (x))\n#define STB_S(x)   stb__string_constant(__FILE__, __LINE__-1, (x))\n\nSTB_EXTERN double stb__double_constant(char *file, int line, double x);\nSTB_EXTERN int    stb__int_constant(char *file, int line, int x);\nSTB_EXTERN char * stb__string_constant(char *file, int line, char *str);\n\n#ifdef STB_DEFINE\n\nenum\n{\n   STB__CTYPE_int,\n   STB__CTYPE_uint,\n   STB__CTYPE_float,\n   STB__CTYPE_double,\n   STB__CTYPE_string,\n};\n\ntypedef struct\n{\n   int line;\n   int type;\n   union {\n      int ival;\n      double dval;\n      char *sval;\n   };\n} stb__Entry;\n\ntypedef struct\n{\n   stb__Entry *entries;\n   char *filename;\n   time_t timestamp;\n   char **file_data;\n   int file_len;\n   unsigned short *line_index;\n} stb__FileEntry;\n\nstatic void stb__constant_parse(stb__FileEntry *f, int i)\n{\n   char *s;\n   int n;\n   if (!stb_arr_valid(f->entries, i)) return;\n   n = f->entries[i].line;\n   if (n >= f->file_len) return;\n   s = f->file_data[n];\n   switch (f->entries[i].type) {\n      case STB__CTYPE_float:\n         while (*s) {\n            if (!strncmp(s, \"STB_D(\", 6)) { s+=6; goto matched_float; }\n            if (!strncmp(s, \"STB_F(\", 6)) { s+=6; goto matched_float; }\n            if (!strncmp(s, \"KD(\", 3)) { s+=3; goto matched_float; }\n            if (!strncmp(s, \"KF(\", 3)) { s+=3; goto matched_float; }\n            ++s;\n         }\n         break;\n      matched_float:\n         f->entries[i].dval = strtod(s, NULL);\n         break;\n      case STB__CTYPE_int:\n         while (*s) {\n            if (!strncmp(s, \"STB_I(\", 6)) { s+=6; goto matched_int; }\n            if (!strncmp(s, \"STB_UI(\", 7)) { s+=7; goto matched_int; }\n            if (!strncmp(s, \"KI(\", 3)) { s+=3; goto matched_int; }\n            if (!strncmp(s, \"KU(\", 3)) { s+=3; goto matched_int; }\n            ++s;\n         }\n         break;\n      matched_int: {\n         int neg=0;\n         s = stb_skipwhite(s);\n         while (*s == '-') { neg = !neg; s = stb_skipwhite(s+1); } // handle '- - 5', pointlessly\n         if (s[0] == '0' && tolower(s[1]) == 'x')\n            f->entries[i].ival = strtol(s, NULL, 16);\n         else if (s[0] == '0')\n            f->entries[i].ival = strtol(s, NULL, 8);\n         else\n            f->entries[i].ival = strtol(s, NULL, 10);\n         if (neg) f->entries[i].ival = -f->entries[i].ival;\n         break;\n      }\n      case STB__CTYPE_string:\n         // @TODO\n         break;\n   }\n}\n\nstatic stb_sdict *stb__constant_file_hash;\n\nstb__Entry *stb__constant_get_entry(char *filename, int line, int type)\n{\n   int i;\n   stb__FileEntry *f;\n   if (stb__constant_file_hash == NULL)\n      stb__constant_file_hash = stb_sdict_new(STB_TRUE);\n   f = (stb__FileEntry*) stb_sdict_get(stb__constant_file_hash, filename);\n   if (f == NULL) {\n      char *s = stb__get_sourcefile_path(filename);\n      if (s == NULL || !stb_fexists(s)) return 0;\n      f = (stb__FileEntry *) malloc(sizeof(*f));\n      f->timestamp = stb_ftimestamp(s);\n      f->file_data = stb_stringfile(s, &f->file_len);\n      f->filename = stb_p_strdup(s); // cache the full path\n      f->entries = NULL;\n      f->line_index = 0;\n      stb_arr_setlen(f->line_index, f->file_len);\n      memset(f->line_index, 0xff, stb_arr_storage(f->line_index));\n   } else {\n      time_t t = stb_ftimestamp(f->filename);\n      if (f->timestamp != t) {\n         f->timestamp = t;\n         free(f->file_data);\n         f->file_data = stb_stringfile(f->filename, &f->file_len);\n         stb_arr_setlen(f->line_index, f->file_len);\n         for (i=0; i < stb_arr_len(f->entries); ++i)\n            stb__constant_parse(f, i);\n      }\n   }\n\n   if (line >= f->file_len) return 0;\n\n   if (f->line_index[line] >= stb_arr_len(f->entries)) {\n      // need a new entry\n      int n = stb_arr_len(f->entries);\n      stb__Entry e;\n      e.line = line;\n      if (line < f->file_len)\n         f->line_index[line] = n;\n      e.type = type;\n      stb_arr_push(f->entries, e);\n      stb__constant_parse(f, n);\n   }\n   return f->entries + f->line_index[line];\n}\n\ndouble stb__double_constant(char *file, int line, double x)\n{\n   stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_float);\n   if (!e) return x;\n   return e->dval;\n}\n\nint    stb__int_constant(char *file, int line, int x)\n{\n   stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_int);\n   if (!e) return x;\n   return e->ival;\n}\n\nchar * stb__string_constant(char *file, int line, char *x)\n{\n   stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_string);\n   if (!e) return x;\n   return e->sval;\n}\n\n#endif // STB_DEFINE\n#endif // !STB_DEBUG && !STB_ALWAYS_H\n\n#undef STB_EXTERN\n#endif // STB_INCLUDE_STB_H\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "deprecated/stb_image.c",
    "content": "/* stb_image - v1.35 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\n   when you control the images you're loading\n                                     no warranty implied; use at your own risk\n\n   QUICK NOTES:\n      Primarily of interest to game developers and other people who can\n          avoid problematic images and only need the trivial interface\n\n      JPEG baseline (no JPEG progressive)\n      PNG 8-bit-per-channel only\n\n      TGA (not sure what subset, if a subset)\n      BMP non-1bpp, non-RLE\n      PSD (composited view only, no extra channels)\n\n      GIF (*comp always reports as 4-channel)\n      HDR (radiance rgbE format)\n      PIC (Softimage PIC)\n\n      - decode from memory or through FILE (define STBI_NO_STDIO to remove code)\n      - decode from arbitrary I/O callbacks\n      - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)\n\n   Latest revisions:\n      1.35 (2014-05-27) warnings, bugfixes, TGA optimization, etc\n      1.34 (unknown   ) warning fix\n      1.33 (2011-07-14) minor fixes suggested by Dave Moore\n      1.32 (2011-07-13) info support for all filetypes (SpartanJ)\n      1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)\n      1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)\n      1.29 (2010-08-16) various warning fixes from Aurelien Pocheville \n      1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)\n\n   See end of file for full revision history.\n\n   TODO:\n      stbi_info support for BMP,PSD,HDR,PIC\n\n\n ============================    Contributors    =========================\n              \n Image formats                                Bug fixes & warning fixes\n    Sean Barrett (jpeg, png, bmp)                Marc LeBlanc\n    Nicolas Schulz (hdr, psd)                    Christpher Lloyd\n    Jonathan Dummer (tga)                        Dave Moore\n    Jean-Marc Lienher (gif)                      Won Chun\n    Tom Seddon (pic)                             the Horde3D community\n    Thatcher Ulrich (psd)                        Janez Zemva\n                                                 Jonathan Blow\n                                                 Laurent Gomila\n Extensions, features                            Aruelien Pocheville\n    Jetro Lauha (stbi_info)                      Ryamond Barbiero\n    James \"moose2000\" Brown (iPhone PNG)         David Woo\n    Ben \"Disch\" Wenger (io callbacks)            Roy Eltham\n    Martin \"SpartanJ\" Golini                     Luke Graham\n                                                 Thomas Ruf\n                                                 John Bartholomew\n Optimizations & bugfixes                        Ken Hamada\n    Fabian \"ryg\" Giesen                          Cort Stratton\n    Arseny Kapoulkine                            Blazej Dariusz Roszkowski\n                                                 Thibault Reuille\n If your name should be here but                 Paul Du Bois\n isn't let Sean know.                            Guillaume George\n\n*/\n\n#ifndef STBI_INCLUDE_STB_IMAGE_H\n#define STBI_INCLUDE_STB_IMAGE_H\n\n// To get a header file for this, either cut and paste the header,\n// or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and\n// then include stb_image.c from it.\n\n////   begin header file  ////////////////////////////////////////////////////\n//\n// Limitations:\n//    - no jpeg progressive support\n//    - non-HDR formats support 8-bit samples only (jpeg, png)\n//    - no delayed line count (jpeg) -- IJG doesn't support either\n//    - no 1-bit BMP\n//    - GIF always returns *comp=4\n//\n// Basic usage (see HDR discussion below):\n//    int x,y,n;\n//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);\n//    // ... process data if not NULL ... \n//    // ... x = width, y = height, n = # 8-bit components per pixel ...\n//    // ... replace '0' with '1'..'4' to force that many components per pixel\n//    // ... but 'n' will always be the number that it would have been if you said 0\n//    stbi_image_free(data)\n//\n// Standard parameters:\n//    int *x       -- outputs image width in pixels\n//    int *y       -- outputs image height in pixels\n//    int *comp    -- outputs # of image components in image file\n//    int req_comp -- if non-zero, # of image components requested in result\n//\n// The return value from an image loader is an 'unsigned char *' which points\n// to the pixel data. The pixel data consists of *y scanlines of *x pixels,\n// with each pixel consisting of N interleaved 8-bit components; the first\n// pixel pointed to is top-left-most in the image. There is no padding between\n// image scanlines or between pixels, regardless of format. The number of\n// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.\n// If req_comp is non-zero, *comp has the number of components that _would_\n// have been output otherwise. E.g. if you set req_comp to 4, you will always\n// get RGBA output, but you can check *comp to easily see if it's opaque.\n//\n// An output image with N components has the following components interleaved\n// in this order in each pixel:\n//\n//     N=#comp     components\n//       1           grey\n//       2           grey, alpha\n//       3           red, green, blue\n//       4           red, green, blue, alpha\n//\n// If image loading fails for any reason, the return value will be NULL,\n// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()\n// can be queried for an extremely brief, end-user unfriendly explanation\n// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid\n// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly\n// more user-friendly ones.\n//\n// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.\n//\n// ===========================================================================\n//\n// iPhone PNG support:\n//\n// By default we convert iphone-formatted PNGs back to RGB; nominally they\n// would silently load as BGR, except the existing code should have just\n// failed on such iPhone PNGs. But you can disable this conversion by\n// by calling stbi_convert_iphone_png_to_rgb(0), in which case\n// you will always just get the native iphone \"format\" through.\n//\n// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per\n// pixel to remove any premultiplied alpha *only* if the image file explicitly\n// says there's premultiplied data (currently only happens in iPhone images,\n// and only if iPhone convert-to-rgb processing is on).\n//\n// ===========================================================================\n//\n// HDR image support   (disable by defining STBI_NO_HDR)\n//\n// stb_image now supports loading HDR images in general, and currently\n// the Radiance .HDR file format, although the support is provided\n// generically. You can still load any file through the existing interface;\n// if you attempt to load an HDR file, it will be automatically remapped to\n// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;\n// both of these constants can be reconfigured through this interface:\n//\n//     stbi_hdr_to_ldr_gamma(2.2f);\n//     stbi_hdr_to_ldr_scale(1.0f);\n//\n// (note, do not use _inverse_ constants; stbi_image will invert them\n// appropriately).\n//\n// Additionally, there is a new, parallel interface for loading files as\n// (linear) floats to preserve the full dynamic range:\n//\n//    float *data = stbi_loadf(filename, &x, &y, &n, 0);\n// \n// If you load LDR images through this interface, those images will\n// be promoted to floating point values, run through the inverse of\n// constants corresponding to the above:\n//\n//     stbi_ldr_to_hdr_scale(1.0f);\n//     stbi_ldr_to_hdr_gamma(2.2f);\n//\n// Finally, given a filename (or an open file or memory block--see header\n// file for details) containing image data, you can query for the \"most\n// appropriate\" interface to use (that is, whether the image is HDR or\n// not), using:\n//\n//     stbi_is_hdr(char *filename);\n//\n// ===========================================================================\n//\n// I/O callbacks\n//\n// I/O callbacks allow you to read from arbitrary sources, like packaged\n// files or some other source. Data read from callbacks are processed\n// through a small internal buffer (currently 128 bytes) to try to reduce\n// overhead. \n//\n// The three functions you must define are \"read\" (reads some bytes of data),\n// \"skip\" (skips some bytes of data), \"eof\" (reports if the stream is at the end).\n\n\n#ifndef STBI_NO_STDIO\n\n#if defined(_MSC_VER) && _MSC_VER >= 1400\n#define _CRT_SECURE_NO_WARNINGS // suppress warnings about fopen()\n#pragma warning(push)\n#pragma warning(disable:4996)   // suppress even more warnings about fopen()\n#endif\n#include <stdio.h>\n#endif // STBI_NO_STDIO\n\n#define STBI_VERSION 1\n\nenum\n{\n   STBI_default = 0, // only used for req_comp\n\n   STBI_grey       = 1,\n   STBI_grey_alpha = 2,\n   STBI_rgb        = 3,\n   STBI_rgb_alpha  = 4\n};\n\ntypedef unsigned char stbi_uc;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// PRIMARY API - works on images of any type\n//\n\n//\n// load image by filename, open file, or memory buffer\n//\n\nextern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\n\n#ifndef STBI_NO_STDIO\nextern stbi_uc *stbi_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);\nextern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\n// for stbi_load_from_file, file pointer is left pointing immediately after image\n#endif\n\ntypedef struct\n{\n   int      (*read)  (void *user,char *data,int size);   // fill 'data' with 'size' bytes.  return number of bytes actually read \n   void     (*skip)  (void *user,int n);                 // skip the next 'n' bytes, or 'unget' the last -n bytes if negative\n   int      (*eof)   (void *user);                       // returns nonzero if we are at end of file/data\n} stbi_io_callbacks;\n\nextern stbi_uc *stbi_load_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);\n\n#ifndef STBI_NO_HDR\n   extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\n\n   #ifndef STBI_NO_STDIO\n   extern float *stbi_loadf            (char const *filename,   int *x, int *y, int *comp, int req_comp);\n   extern float *stbi_loadf_from_file  (FILE *f,                int *x, int *y, int *comp, int req_comp);\n   #endif\n   \n   extern float *stbi_loadf_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);\n\n   extern void   stbi_hdr_to_ldr_gamma(float gamma);\n   extern void   stbi_hdr_to_ldr_scale(float scale);\n\n   extern void   stbi_ldr_to_hdr_gamma(float gamma);\n   extern void   stbi_ldr_to_hdr_scale(float scale);\n#endif // STBI_NO_HDR\n\n// stbi_is_hdr is always defined\nextern int    stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);\nextern int    stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);\n#ifndef STBI_NO_STDIO\nextern int      stbi_is_hdr          (char const *filename);\nextern int      stbi_is_hdr_from_file(FILE *f);\n#endif // STBI_NO_STDIO\n\n\n// get a VERY brief reason for failure\n// NOT THREADSAFE\nextern const char *stbi_failure_reason  (void); \n\n// free the loaded image -- this is just free()\nextern void     stbi_image_free      (void *retval_from_stbi_load);\n\n// get image dimensions & components without fully decoding\nextern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\nextern int      stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);\n\n#ifndef STBI_NO_STDIO\nextern int      stbi_info            (char const *filename,     int *x, int *y, int *comp);\nextern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\n\n#endif\n\n\n\n// for image formats that explicitly notate that they have premultiplied alpha,\n// we just return the colors as stored in the file. set this flag to force\n// unpremultiplication. results are undefined if the unpremultiply overflow.\nextern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);\n\n// indicate whether we should process iphone images back to canonical format,\n// or just pass them through \"as-is\"\nextern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);\n\n\n// ZLIB client - used by PNG, available for other purposes\n\nextern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);\nextern char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);\nextern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);\nextern int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\n\nextern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);\nextern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\n\n\n// define faster low-level operations (typically SIMD support)\n#ifdef STBI_SIMD\ntypedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);\n// compute an integer IDCT on \"input\"\n//     input[x] = data[x] * dequantize[x]\n//     write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'\n//                             CLAMP results to 0..255\ntypedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const  *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);\n// compute a conversion from YCbCr to RGB\n//     'count' pixels\n//     write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B\n//     y: Y input channel\n//     cb: Cb input channel; scale/biased to be 0..255\n//     cr: Cr input channel; scale/biased to be 0..255\n\nextern void stbi_install_idct(stbi_idct_8x8 func);\nextern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);\n#endif // STBI_SIMD\n\n\n#ifdef __cplusplus\n}\n#endif\n\n//\n//\n////   end header file   /////////////////////////////////////////////////////\n#endif // STBI_INCLUDE_STB_IMAGE_H\n\n#ifndef STBI_HEADER_FILE_ONLY\n\n#ifndef STBI_NO_HDR\n#include <math.h>  // ldexp\n#include <string.h> // strcmp, strtok\n#endif\n\n#ifndef STBI_NO_STDIO\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <memory.h>\n#include <assert.h>\n#include <stdarg.h>\n#include <stddef.h> // ptrdiff_t on osx\n\n#ifndef _MSC_VER\n   #ifdef __cplusplus\n   #define stbi_inline inline\n   #else\n   #define stbi_inline\n   #endif\n#else\n   #define stbi_inline __forceinline\n#endif\n\n\n#ifdef _MSC_VER\ntypedef unsigned char  stbi__uint8;\ntypedef unsigned short stbi__uint16;\ntypedef   signed short stbi__int16;\ntypedef unsigned int   stbi__uint32;\ntypedef   signed int   stbi__int32;\n#else\n#include <stdint.h>\ntypedef uint8_t  stbi__uint8;\ntypedef uint16_t stbi__uint16;\ntypedef int16_t  stbi__int16;\ntypedef uint32_t stbi__uint32;\ntypedef int32_t  stbi__int32;\n#endif\n\n// should produce compiler error if size is wrong\ntypedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];\n\n#ifdef _MSC_VER\n#define STBI_NOTUSED(v)  (void)(v)\n#else\n#define STBI_NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#ifdef _MSC_VER\n#define STBI_HAS_LROTL\n#endif\n\n#ifdef STBI_HAS_LROTL\n   #define stbi_lrot(x,y)  _lrotl(x,y)\n#else\n   #define stbi_lrot(x,y)  (((x) << (y)) | ((x) >> (32 - (y))))\n#endif\n\n///////////////////////////////////////////////\n//\n//  stbi struct and start_xxx functions\n\n// stbi structure is our basic context used by all images, so it\n// contains all the IO context, plus some basic image information\ntypedef struct\n{\n   stbi__uint32 img_x, img_y;\n   int img_n, img_out_n;\n   \n   stbi_io_callbacks io;\n   void *io_user_data;\n\n   int read_from_callbacks;\n   int buflen;\n   stbi__uint8 buffer_start[128];\n\n   stbi__uint8 *img_buffer, *img_buffer_end;\n   stbi__uint8 *img_buffer_original;\n} stbi;\n\n\nstatic void refill_buffer(stbi *s);\n\n// initialize a memory-decode context\nstatic void start_mem(stbi *s, stbi__uint8 const *buffer, int len)\n{\n   s->io.read = NULL;\n   s->read_from_callbacks = 0;\n   s->img_buffer = s->img_buffer_original = (stbi__uint8 *) buffer;\n   s->img_buffer_end = (stbi__uint8 *) buffer+len;\n}\n\n// initialize a callback-based context\nstatic void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user)\n{\n   s->io = *c;\n   s->io_user_data = user;\n   s->buflen = sizeof(s->buffer_start);\n   s->read_from_callbacks = 1;\n   s->img_buffer_original = s->buffer_start;\n   refill_buffer(s);\n}\n\n#ifndef STBI_NO_STDIO\n\nstatic int stdio_read(void *user, char *data, int size)\n{\n   return (int) fread(data,1,size,(FILE*) user);\n}\n\nstatic void stdio_skip(void *user, int n)\n{\n   fseek((FILE*) user, n, SEEK_CUR);\n}\n\nstatic int stdio_eof(void *user)\n{\n   return feof((FILE*) user);\n}\n\nstatic stbi_io_callbacks stbi_stdio_callbacks =\n{\n   stdio_read,\n   stdio_skip,\n   stdio_eof,\n};\n\nstatic void start_file(stbi *s, FILE *f)\n{\n   start_callbacks(s, &stbi_stdio_callbacks, (void *) f);\n}\n\n//static void stop_file(stbi *s) { }\n\n#endif // !STBI_NO_STDIO\n\nstatic void stbi_rewind(stbi *s)\n{\n   // conceptually rewind SHOULD rewind to the beginning of the stream,\n   // but we just rewind to the beginning of the initial buffer, because\n   // we only use it after doing 'test', which only ever looks at at most 92 bytes\n   s->img_buffer = s->img_buffer_original;\n}\n\nstatic int      stbi_jpeg_test(stbi *s);\nstatic stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);\nstatic int      stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);\nstatic int      stbi_png_test(stbi *s);\nstatic stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);\nstatic int      stbi_png_info(stbi *s, int *x, int *y, int *comp);\nstatic int      stbi_bmp_test(stbi *s);\nstatic stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);\nstatic int      stbi_tga_test(stbi *s);\nstatic stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);\nstatic int      stbi_tga_info(stbi *s, int *x, int *y, int *comp);\nstatic int      stbi_psd_test(stbi *s);\nstatic stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);\n#ifndef STBI_NO_HDR\nstatic int      stbi_hdr_test(stbi *s);\nstatic float   *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);\n#endif\nstatic int      stbi_pic_test(stbi *s);\nstatic stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);\nstatic int      stbi_gif_test(stbi *s);\nstatic stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);\nstatic int      stbi_gif_info(stbi *s, int *x, int *y, int *comp);\n\n\n// this is not threadsafe\nstatic const char *failure_reason;\n\nconst char *stbi_failure_reason(void)\n{\n   return failure_reason;\n}\n\nstatic int e(const char *str)\n{\n   failure_reason = str;\n   return 0;\n}\n\n// e - error\n// epf - error returning pointer to float\n// epuc - error returning pointer to unsigned char\n\n#ifdef STBI_NO_FAILURE_STRINGS\n   #define e(x,y)  0\n#elif defined(STBI_FAILURE_USERMSG)\n   #define e(x,y)  e(y)\n#else\n   #define e(x,y)  e(x)\n#endif\n\n#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))\n#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))\n\nvoid stbi_image_free(void *retval_from_stbi_load)\n{\n   free(retval_from_stbi_load);\n}\n\n#ifndef STBI_NO_HDR\nstatic float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);\nstatic stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);\n#endif\n\nstatic unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);\n   if (stbi_png_test(s))  return stbi_png_load(s,x,y,comp,req_comp);\n   if (stbi_bmp_test(s))  return stbi_bmp_load(s,x,y,comp,req_comp);\n   if (stbi_gif_test(s))  return stbi_gif_load(s,x,y,comp,req_comp);\n   if (stbi_psd_test(s))  return stbi_psd_load(s,x,y,comp,req_comp);\n   if (stbi_pic_test(s))  return stbi_pic_load(s,x,y,comp,req_comp);\n\n   #ifndef STBI_NO_HDR\n   if (stbi_hdr_test(s)) {\n      float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);\n      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\n   }\n   #endif\n\n   // test tga last because it's a crappy test!\n   if (stbi_tga_test(s))\n      return stbi_tga_load(s,x,y,comp,req_comp);\n   return epuc(\"unknown image type\", \"Image not of any known type, or corrupt\");\n}\n\n#ifndef STBI_NO_STDIO\nunsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)\n{\n   FILE *f = fopen(filename, \"rb\");\n   unsigned char *result;\n   if (!f) return epuc(\"can't fopen\", \"Unable to open file\");\n   result = stbi_load_from_file(f,x,y,comp,req_comp);\n   fclose(f);\n   return result;\n}\n\nunsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\n{\n   unsigned char *result;\n   stbi s;\n   start_file(&s,f);\n   result = stbi_load_main(&s,x,y,comp,req_comp);\n   if (result) {\n      // need to 'unget' all the characters in the IO buffer\n      fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);\n   }\n   return result;\n}\n#endif //!STBI_NO_STDIO\n\nunsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\n{\n   stbi s;\n   start_mem(&s,buffer,len);\n   return stbi_load_main(&s,x,y,comp,req_comp);\n}\n\nunsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)\n{\n   stbi s;\n   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);\n   return stbi_load_main(&s,x,y,comp,req_comp);\n}\n\n#ifndef STBI_NO_HDR\n\nfloat *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   unsigned char *data;\n   #ifndef STBI_NO_HDR\n   if (stbi_hdr_test(s))\n      return stbi_hdr_load(s,x,y,comp,req_comp);\n   #endif\n   data = stbi_load_main(s, x, y, comp, req_comp);\n   if (data)\n      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\n   return epf(\"unknown image type\", \"Image not of any known type, or corrupt\");\n}\n\nfloat *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\n{\n   stbi s;\n   start_mem(&s,buffer,len);\n   return stbi_loadf_main(&s,x,y,comp,req_comp);\n}\n\nfloat *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)\n{\n   stbi s;\n   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);\n   return stbi_loadf_main(&s,x,y,comp,req_comp);\n}\n\n#ifndef STBI_NO_STDIO\nfloat *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)\n{\n   FILE *f = fopen(filename, \"rb\");\n   float *result;\n   if (!f) return epf(\"can't fopen\", \"Unable to open file\");\n   result = stbi_loadf_from_file(f,x,y,comp,req_comp);\n   fclose(f);\n   return result;\n}\n\nfloat *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\n{\n   stbi s;\n   start_file(&s,f);\n   return stbi_loadf_main(&s,x,y,comp,req_comp);\n}\n#endif // !STBI_NO_STDIO\n\n#endif // !STBI_NO_HDR\n\n// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is\n// defined, for API simplicity; if STBI_NO_HDR is defined, it always\n// reports false!\n\nint stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)\n{\n   #ifndef STBI_NO_HDR\n   stbi s;\n   start_mem(&s,buffer,len);\n   return stbi_hdr_test(&s);\n   #else\n   STBI_NOTUSED(buffer);\n   STBI_NOTUSED(len);\n   return 0;\n   #endif\n}\n\n#ifndef STBI_NO_STDIO\nextern int      stbi_is_hdr          (char const *filename)\n{\n   FILE *f = fopen(filename, \"rb\");\n   int result=0;\n   if (f) {\n      result = stbi_is_hdr_from_file(f);\n      fclose(f);\n   }\n   return result;\n}\n\nextern int      stbi_is_hdr_from_file(FILE *f)\n{\n   #ifndef STBI_NO_HDR\n   stbi s;\n   start_file(&s,f);\n   return stbi_hdr_test(&s);\n   #else\n   return 0;\n   #endif\n}\n#endif // !STBI_NO_STDIO\n\nextern int      stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)\n{\n   #ifndef STBI_NO_HDR\n   stbi s;\n   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);\n   return stbi_hdr_test(&s);\n   #else\n   return 0;\n   #endif\n}\n\n#ifndef STBI_NO_HDR\nstatic float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;\nstatic float l2h_gamma=2.2f, l2h_scale=1.0f;\n\nvoid   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }\nvoid   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }\n\nvoid   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }\nvoid   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Common code used by all image loaders\n//\n\nenum\n{\n   SCAN_load=0,\n   SCAN_type,\n   SCAN_header\n};\n\nstatic void refill_buffer(stbi *s)\n{\n   int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);\n   if (n == 0) {\n      // at end of file, treat same as if from memory, but need to handle case\n      // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file\n      s->read_from_callbacks = 0;\n      s->img_buffer = s->buffer_start;\n      s->img_buffer_end = s->buffer_start+1;\n      *s->img_buffer = 0;\n   } else {\n      s->img_buffer = s->buffer_start;\n      s->img_buffer_end = s->buffer_start + n;\n   }\n}\n\nstbi_inline static int get8(stbi *s)\n{\n   if (s->img_buffer < s->img_buffer_end)\n      return *s->img_buffer++;\n   if (s->read_from_callbacks) {\n      refill_buffer(s);\n      return *s->img_buffer++;\n   }\n   return 0;\n}\n\nstbi_inline static int at_eof(stbi *s)\n{\n   if (s->io.read) {\n      if (!(s->io.eof)(s->io_user_data)) return 0;\n      // if feof() is true, check if buffer = end\n      // special case: we've only got the special 0 character at the end\n      if (s->read_from_callbacks == 0) return 1;\n   }\n\n   return s->img_buffer >= s->img_buffer_end;   \n}\n\nstbi_inline static stbi__uint8 get8u(stbi *s)\n{\n   return (stbi__uint8) get8(s);\n}\n\nstatic void skip(stbi *s, int n)\n{\n   if (s->io.read) {\n      int blen = (int) (s->img_buffer_end - s->img_buffer);\n      if (blen < n) {\n         s->img_buffer = s->img_buffer_end;\n         (s->io.skip)(s->io_user_data, n - blen);\n         return;\n      }\n   }\n   s->img_buffer += n;\n}\n\nstatic int getn(stbi *s, stbi_uc *buffer, int n)\n{\n   if (s->io.read) {\n      int blen = (int) (s->img_buffer_end - s->img_buffer);\n      if (blen < n) {\n         int res, count;\n\n         memcpy(buffer, s->img_buffer, blen);\n         \n         count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);\n         res = (count == (n-blen));\n         s->img_buffer = s->img_buffer_end;\n         return res;\n      }\n   }\n\n   if (s->img_buffer+n <= s->img_buffer_end) {\n      memcpy(buffer, s->img_buffer, n);\n      s->img_buffer += n;\n      return 1;\n   } else\n      return 0;\n}\n\nstatic int get16(stbi *s)\n{\n   int z = get8(s);\n   return (z << 8) + get8(s);\n}\n\nstatic stbi__uint32 get32(stbi *s)\n{\n   stbi__uint32 z = get16(s);\n   return (z << 16) + get16(s);\n}\n\nstatic int get16le(stbi *s)\n{\n   int z = get8(s);\n   return z + (get8(s) << 8);\n}\n\nstatic stbi__uint32 get32le(stbi *s)\n{\n   stbi__uint32 z = get16le(s);\n   return z + (get16le(s) << 16);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  generic converter from built-in img_n to req_comp\n//    individual types do this automatically as much as possible (e.g. jpeg\n//    does all cases internally since it needs to colorspace convert anyway,\n//    and it never has alpha, so very few cases ). png can automatically\n//    interleave an alpha=255 channel, but falls back to this for other cases\n//\n//  assume data buffer is malloced, so malloc a new one and free that one\n//  only failure mode is malloc failing\n\nstatic stbi__uint8 compute_y(int r, int g, int b)\n{\n   return (stbi__uint8) (((r*77) + (g*150) +  (29*b)) >> 8);\n}\n\nstatic unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)\n{\n   int i,j;\n   unsigned char *good;\n\n   if (req_comp == img_n) return data;\n   assert(req_comp >= 1 && req_comp <= 4);\n\n   good = (unsigned char *) malloc(req_comp * x * y);\n   if (good == NULL) {\n      free(data);\n      return epuc(\"outofmem\", \"Out of memory\");\n   }\n\n   for (j=0; j < (int) y; ++j) {\n      unsigned char *src  = data + j * x * img_n   ;\n      unsigned char *dest = good + j * x * req_comp;\n\n      #define COMBO(a,b)  ((a)*8+(b))\n      #define CASE(a,b)   case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\n      // convert source image with img_n components to one with req_comp components;\n      // avoid switch per pixel, so use switch per scanline and massive macros\n      switch (COMBO(img_n, req_comp)) {\n         CASE(1,2) dest[0]=src[0], dest[1]=255; break;\n         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;\n         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;\n         CASE(2,1) dest[0]=src[0]; break;\n         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;\n         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;\n         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;\n         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\n         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;\n         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\n         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;\n         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;\n         default: assert(0);\n      }\n      #undef CASE\n   }\n\n   free(data);\n   return good;\n}\n\n#ifndef STBI_NO_HDR\nstatic float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)\n{\n   int i,k,n;\n   float *output = (float *) malloc(x * y * comp * sizeof(float));\n   if (output == NULL) { free(data); return epf(\"outofmem\", \"Out of memory\"); }\n   // compute number of non-alpha components\n   if (comp & 1) n = comp; else n = comp-1;\n   for (i=0; i < x*y; ++i) {\n      for (k=0; k < n; ++k) {\n         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;\n      }\n      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;\n   }\n   free(data);\n   return output;\n}\n\n#define float2int(x)   ((int) (x))\nstatic stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)\n{\n   int i,k,n;\n   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);\n   if (output == NULL) { free(data); return epuc(\"outofmem\", \"Out of memory\"); }\n   // compute number of non-alpha components\n   if (comp & 1) n = comp; else n = comp-1;\n   for (i=0; i < x*y; ++i) {\n      for (k=0; k < n; ++k) {\n         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;\n         if (z < 0) z = 0;\n         if (z > 255) z = 255;\n         output[i*comp + k] = (stbi__uint8) float2int(z);\n      }\n      if (k < comp) {\n         float z = data[i*comp+k] * 255 + 0.5f;\n         if (z < 0) z = 0;\n         if (z > 255) z = 255;\n         output[i*comp + k] = (stbi__uint8) float2int(z);\n      }\n   }\n   free(data);\n   return output;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  \"baseline\" JPEG/JFIF decoder (not actually fully baseline implementation)\n//\n//    simple implementation\n//      - channel subsampling of at most 2 in each dimension\n//      - doesn't support delayed output of y-dimension\n//      - simple interface (only one output format: 8-bit interleaved RGB)\n//      - doesn't try to recover corrupt jpegs\n//      - doesn't allow partial loading, loading multiple at once\n//      - still fast on x86 (copying globals into locals doesn't help x86)\n//      - allocates lots of intermediate memory (full size of all components)\n//        - non-interleaved case requires this anyway\n//        - allows good upsampling (see next)\n//    high-quality\n//      - upsampled channels are bilinearly interpolated, even across blocks\n//      - quality integer IDCT derived from IJG's 'slow'\n//    performance\n//      - fast huffman; reasonable integer IDCT\n//      - uses a lot of intermediate memory, could cache poorly\n//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4\n//          stb_jpeg:   1.34 seconds (MSVC6, default release build)\n//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)\n//          IJL11.dll:  1.08 seconds (compiled by intel)\n//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)\n//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)\n\n// huffman decoding acceleration\n#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache\n\ntypedef struct\n{\n   stbi__uint8  fast[1 << FAST_BITS];\n   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win\n   stbi__uint16 code[256];\n   stbi__uint8  values[256];\n   stbi__uint8  size[257];\n   unsigned int maxcode[18];\n   int    delta[17];   // old 'firstsymbol' - old 'firstcode'\n} huffman;\n\ntypedef struct\n{\n   #ifdef STBI_SIMD\n   unsigned short dequant2[4][64];\n   #endif\n   stbi *s;\n   huffman huff_dc[4];\n   huffman huff_ac[4];\n   stbi__uint8 dequant[4][64];\n\n// sizes for components, interleaved MCUs\n   int img_h_max, img_v_max;\n   int img_mcu_x, img_mcu_y;\n   int img_mcu_w, img_mcu_h;\n\n// definition of jpeg image component\n   struct\n   {\n      int id;\n      int h,v;\n      int tq;\n      int hd,ha;\n      int dc_pred;\n\n      int x,y,w2,h2;\n      stbi__uint8 *data;\n      void *raw_data;\n      stbi__uint8 *linebuf;\n   } img_comp[4];\n\n   stbi__uint32         code_buffer; // jpeg entropy-coded buffer\n   int            code_bits;   // number of valid bits\n   unsigned char  marker;      // marker seen while filling entropy buffer\n   int            nomore;      // flag if we saw a marker so must stop\n\n   int scan_n, order[4];\n   int restart_interval, todo;\n} jpeg;\n\nstatic int build_huffman(huffman *h, int *count)\n{\n   int i,j,k=0,code;\n   // build size list for each symbol (from JPEG spec)\n   for (i=0; i < 16; ++i)\n      for (j=0; j < count[i]; ++j)\n         h->size[k++] = (stbi__uint8) (i+1);\n   h->size[k] = 0;\n\n   // compute actual symbols (from jpeg spec)\n   code = 0;\n   k = 0;\n   for(j=1; j <= 16; ++j) {\n      // compute delta to add to code to compute symbol id\n      h->delta[j] = k - code;\n      if (h->size[k] == j) {\n         while (h->size[k] == j)\n            h->code[k++] = (stbi__uint16) (code++);\n         if (code-1 >= (1 << j)) return e(\"bad code lengths\",\"Corrupt JPEG\");\n      }\n      // compute largest code + 1 for this size, preshifted as needed later\n      h->maxcode[j] = code << (16-j);\n      code <<= 1;\n   }\n   h->maxcode[j] = 0xffffffff;\n\n   // build non-spec acceleration table; 255 is flag for not-accelerated\n   memset(h->fast, 255, 1 << FAST_BITS);\n   for (i=0; i < k; ++i) {\n      int s = h->size[i];\n      if (s <= FAST_BITS) {\n         int c = h->code[i] << (FAST_BITS-s);\n         int m = 1 << (FAST_BITS-s);\n         for (j=0; j < m; ++j) {\n            h->fast[c+j] = (stbi__uint8) i;\n         }\n      }\n   }\n   return 1;\n}\n\nstatic void grow_buffer_unsafe(jpeg *j)\n{\n   do {\n      int b = j->nomore ? 0 : get8(j->s);\n      if (b == 0xff) {\n         int c = get8(j->s);\n         if (c != 0) {\n            j->marker = (unsigned char) c;\n            j->nomore = 1;\n            return;\n         }\n      }\n      j->code_buffer |= b << (24 - j->code_bits);\n      j->code_bits += 8;\n   } while (j->code_bits <= 24);\n}\n\n// (1 << n) - 1\nstatic stbi__uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};\n\n// decode a jpeg huffman value from the bitstream\nstbi_inline static int decode(jpeg *j, huffman *h)\n{\n   unsigned int temp;\n   int c,k;\n\n   if (j->code_bits < 16) grow_buffer_unsafe(j);\n\n   // look at the top FAST_BITS and determine what symbol ID it is,\n   // if the code is <= FAST_BITS\n   c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);\n   k = h->fast[c];\n   if (k < 255) {\n      int s = h->size[k];\n      if (s > j->code_bits)\n         return -1;\n      j->code_buffer <<= s;\n      j->code_bits -= s;\n      return h->values[k];\n   }\n\n   // naive test is to shift the code_buffer down so k bits are\n   // valid, then test against maxcode. To speed this up, we've\n   // preshifted maxcode left so that it has (16-k) 0s at the\n   // end; in other words, regardless of the number of bits, it\n   // wants to be compared against something shifted to have 16;\n   // that way we don't need to shift inside the loop.\n   temp = j->code_buffer >> 16;\n   for (k=FAST_BITS+1 ; ; ++k)\n      if (temp < h->maxcode[k])\n         break;\n   if (k == 17) {\n      // error! code not found\n      j->code_bits -= 16;\n      return -1;\n   }\n\n   if (k > j->code_bits)\n      return -1;\n\n   // convert the huffman code to the symbol id\n   c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k];\n   assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);\n\n   // convert the id to a symbol\n   j->code_bits -= k;\n   j->code_buffer <<= k;\n   return h->values[c];\n}\n\n// combined JPEG 'receive' and JPEG 'extend', since baseline\n// always extends everything it receives.\nstbi_inline static int extend_receive(jpeg *j, int n)\n{\n   unsigned int m = 1 << (n-1);\n   unsigned int k;\n   if (j->code_bits < n) grow_buffer_unsafe(j);\n\n   #if 1\n   k = stbi_lrot(j->code_buffer, n);\n   j->code_buffer = k & ~bmask[n];\n   k &= bmask[n];\n   j->code_bits -= n;\n   #else\n   k = (j->code_buffer >> (32 - n)) & bmask[n];\n   j->code_bits -= n;\n   j->code_buffer <<= n;\n   #endif\n   // the following test is probably a random branch that won't\n   // predict well. I tried to table accelerate it but failed.\n   // maybe it's compiling as a conditional move?\n   if (k < m)\n      return (-1 << n) + k + 1;\n   else\n      return k;\n}\n\n// given a value that's at position X in the zigzag stream,\n// where does it appear in the 8x8 matrix coded as row-major?\nstatic stbi__uint8 dezigzag[64+15] =\n{\n    0,  1,  8, 16,  9,  2,  3, 10,\n   17, 24, 32, 25, 18, 11,  4,  5,\n   12, 19, 26, 33, 40, 48, 41, 34,\n   27, 20, 13,  6,  7, 14, 21, 28,\n   35, 42, 49, 56, 57, 50, 43, 36,\n   29, 22, 15, 23, 30, 37, 44, 51,\n   58, 59, 52, 45, 38, 31, 39, 46,\n   53, 60, 61, 54, 47, 55, 62, 63,\n   // let corrupt input sample past end\n   63, 63, 63, 63, 63, 63, 63, 63,\n   63, 63, 63, 63, 63, 63, 63\n};\n\n// decode one 64-entry block--\nstatic int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)\n{\n   int diff,dc,k;\n   int t = decode(j, hdc);\n   if (t < 0) return e(\"bad huffman code\",\"Corrupt JPEG\");\n\n   // 0 all the ac values now so we can do it 32-bits at a time\n   memset(data,0,64*sizeof(data[0]));\n\n   diff = t ? extend_receive(j, t) : 0;\n   dc = j->img_comp[b].dc_pred + diff;\n   j->img_comp[b].dc_pred = dc;\n   data[0] = (short) dc;\n\n   // decode AC components, see JPEG spec\n   k = 1;\n   do {\n      int r,s;\n      int rs = decode(j, hac);\n      if (rs < 0) return e(\"bad huffman code\",\"Corrupt JPEG\");\n      s = rs & 15;\n      r = rs >> 4;\n      if (s == 0) {\n         if (rs != 0xf0) break; // end block\n         k += 16;\n      } else {\n         k += r;\n         // decode into unzigzag'd location\n         data[dezigzag[k++]] = (short) extend_receive(j,s);\n      }\n   } while (k < 64);\n   return 1;\n}\n\n// take a -128..127 value and clamp it and convert to 0..255\nstbi_inline static stbi__uint8 clamp(int x)\n{\n   // trick to use a single test to catch both cases\n   if ((unsigned int) x > 255) {\n      if (x < 0) return 0;\n      if (x > 255) return 255;\n   }\n   return (stbi__uint8) x;\n}\n\n#define f2f(x)  (int) (((x) * 4096 + 0.5))\n#define fsh(x)  ((x) << 12)\n\n// derived from jidctint -- DCT_ISLOW\n#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \\\n   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \\\n   p2 = s2;                                    \\\n   p3 = s6;                                    \\\n   p1 = (p2+p3) * f2f(0.5411961f);             \\\n   t2 = p1 + p3*f2f(-1.847759065f);            \\\n   t3 = p1 + p2*f2f( 0.765366865f);            \\\n   p2 = s0;                                    \\\n   p3 = s4;                                    \\\n   t0 = fsh(p2+p3);                            \\\n   t1 = fsh(p2-p3);                            \\\n   x0 = t0+t3;                                 \\\n   x3 = t0-t3;                                 \\\n   x1 = t1+t2;                                 \\\n   x2 = t1-t2;                                 \\\n   t0 = s7;                                    \\\n   t1 = s5;                                    \\\n   t2 = s3;                                    \\\n   t3 = s1;                                    \\\n   p3 = t0+t2;                                 \\\n   p4 = t1+t3;                                 \\\n   p1 = t0+t3;                                 \\\n   p2 = t1+t2;                                 \\\n   p5 = (p3+p4)*f2f( 1.175875602f);            \\\n   t0 = t0*f2f( 0.298631336f);                 \\\n   t1 = t1*f2f( 2.053119869f);                 \\\n   t2 = t2*f2f( 3.072711026f);                 \\\n   t3 = t3*f2f( 1.501321110f);                 \\\n   p1 = p5 + p1*f2f(-0.899976223f);            \\\n   p2 = p5 + p2*f2f(-2.562915447f);            \\\n   p3 = p3*f2f(-1.961570560f);                 \\\n   p4 = p4*f2f(-0.390180644f);                 \\\n   t3 += p1+p4;                                \\\n   t2 += p2+p3;                                \\\n   t1 += p2+p4;                                \\\n   t0 += p1+p3;\n\n#ifdef STBI_SIMD\ntypedef unsigned short stbi_dequantize_t;\n#else\ntypedef stbi__uint8 stbi_dequantize_t;\n#endif\n\n// .344 seconds on 3*anemones.jpg\nstatic void idct_block(stbi__uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)\n{\n   int i,val[64],*v=val;\n   stbi_dequantize_t *dq = dequantize;\n   stbi__uint8 *o;\n   short *d = data;\n\n   // columns\n   for (i=0; i < 8; ++i,++d,++dq, ++v) {\n      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\n      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\n           && d[40]==0 && d[48]==0 && d[56]==0) {\n         //    no shortcut                 0     seconds\n         //    (1|2|3|4|5|6|7)==0          0     seconds\n         //    all separate               -0.047 seconds\n         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\n         int dcterm = d[0] * dq[0] << 2;\n         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\n      } else {\n         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],\n                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])\n         // constants scaled things up by 1<<12; let's bring them back\n         // down, but keep 2 extra bits of precision\n         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\n         v[ 0] = (x0+t3) >> 10;\n         v[56] = (x0-t3) >> 10;\n         v[ 8] = (x1+t2) >> 10;\n         v[48] = (x1-t2) >> 10;\n         v[16] = (x2+t1) >> 10;\n         v[40] = (x2-t1) >> 10;\n         v[24] = (x3+t0) >> 10;\n         v[32] = (x3-t0) >> 10;\n      }\n   }\n\n   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\n      // no fast case since the first 1D IDCT spread components out\n      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\n      // constants scaled things up by 1<<12, plus we had 1<<2 from first\n      // loop, plus horizontal and vertical each scale by sqrt(8) so together\n      // we've got an extra 1<<3, so 1<<17 total we need to remove.\n      // so we want to round that, which means adding 0.5 * 1<<17,\n      // aka 65536. Also, we'll end up with -128 to 127 that we want\n      // to encode as 0..255 by adding 128, so we'll add that before the shift\n      x0 += 65536 + (128<<17);\n      x1 += 65536 + (128<<17);\n      x2 += 65536 + (128<<17);\n      x3 += 65536 + (128<<17);\n      // tried computing the shifts into temps, or'ing the temps to see\n      // if any were out of range, but that was slower\n      o[0] = clamp((x0+t3) >> 17);\n      o[7] = clamp((x0-t3) >> 17);\n      o[1] = clamp((x1+t2) >> 17);\n      o[6] = clamp((x1-t2) >> 17);\n      o[2] = clamp((x2+t1) >> 17);\n      o[5] = clamp((x2-t1) >> 17);\n      o[3] = clamp((x3+t0) >> 17);\n      o[4] = clamp((x3-t0) >> 17);\n   }\n}\n\n#ifdef STBI_SIMD\nstatic stbi_idct_8x8 stbi_idct_installed = idct_block;\n\nvoid stbi_install_idct(stbi_idct_8x8 func)\n{\n   stbi_idct_installed = func;\n}\n#endif\n\n#define MARKER_none  0xff\n// if there's a pending marker from the entropy stream, return that\n// otherwise, fetch from the stream and get a marker. if there's no\n// marker, return 0xff, which is never a valid marker value\nstatic stbi__uint8 get_marker(jpeg *j)\n{\n   stbi__uint8 x;\n   if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }\n   x = get8u(j->s);\n   if (x != 0xff) return MARKER_none;\n   while (x == 0xff)\n      x = get8u(j->s);\n   return x;\n}\n\n// in each scan, we'll have scan_n components, and the order\n// of the components is specified by order[]\n#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)\n\n// after a restart interval, reset the entropy decoder and\n// the dc prediction\nstatic void reset(jpeg *j)\n{\n   j->code_bits = 0;\n   j->code_buffer = 0;\n   j->nomore = 0;\n   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;\n   j->marker = MARKER_none;\n   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;\n   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,\n   // since we don't even allow 1<<30 pixels\n}\n\nstatic int parse_entropy_coded_data(jpeg *z)\n{\n   reset(z);\n   if (z->scan_n == 1) {\n      int i,j;\n      #ifdef STBI_SIMD\n      __declspec(align(16))\n      #endif\n      short data[64];\n      int n = z->order[0];\n      // non-interleaved data, we just need to process one block at a time,\n      // in trivial scanline order\n      // number of blocks to do just depends on how many actual \"pixels\" this\n      // component has, independent of interleaved MCU blocking and such\n      int w = (z->img_comp[n].x+7) >> 3;\n      int h = (z->img_comp[n].y+7) >> 3;\n      for (j=0; j < h; ++j) {\n         for (i=0; i < w; ++i) {\n            if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;\n            #ifdef STBI_SIMD\n            stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);\n            #else\n            idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);\n            #endif\n            // every data block is an MCU, so countdown the restart interval\n            if (--z->todo <= 0) {\n               if (z->code_bits < 24) grow_buffer_unsafe(z);\n               // if it's NOT a restart, then just bail, so we get corrupt data\n               // rather than no data\n               if (!RESTART(z->marker)) return 1;\n               reset(z);\n            }\n         }\n      }\n   } else { // interleaved!\n      int i,j,k,x,y;\n      short data[64];\n      for (j=0; j < z->img_mcu_y; ++j) {\n         for (i=0; i < z->img_mcu_x; ++i) {\n            // scan an interleaved mcu... process scan_n components in order\n            for (k=0; k < z->scan_n; ++k) {\n               int n = z->order[k];\n               // scan out an mcu's worth of this component; that's just determined\n               // by the basic H and V specified for the component\n               for (y=0; y < z->img_comp[n].v; ++y) {\n                  for (x=0; x < z->img_comp[n].h; ++x) {\n                     int x2 = (i*z->img_comp[n].h + x)*8;\n                     int y2 = (j*z->img_comp[n].v + y)*8;\n                     if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;\n                     #ifdef STBI_SIMD\n                     stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);\n                     #else\n                     idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);\n                     #endif\n                  }\n               }\n            }\n            // after all interleaved components, that's an interleaved MCU,\n            // so now count down the restart interval\n            if (--z->todo <= 0) {\n               if (z->code_bits < 24) grow_buffer_unsafe(z);\n               // if it's NOT a restart, then just bail, so we get corrupt data\n               // rather than no data\n               if (!RESTART(z->marker)) return 1;\n               reset(z);\n            }\n         }\n      }\n   }\n   return 1;\n}\n\nstatic int process_marker(jpeg *z, int m)\n{\n   int L;\n   switch (m) {\n      case MARKER_none: // no marker found\n         return e(\"expected marker\",\"Corrupt JPEG\");\n\n      case 0xC2: // SOF - progressive\n         return e(\"progressive jpeg\",\"JPEG format not supported (progressive)\");\n\n      case 0xDD: // DRI - specify restart interval\n         if (get16(z->s) != 4) return e(\"bad DRI len\",\"Corrupt JPEG\");\n         z->restart_interval = get16(z->s);\n         return 1;\n\n      case 0xDB: // DQT - define quantization table\n         L = get16(z->s)-2;\n         while (L > 0) {\n            int q = get8(z->s);\n            int p = q >> 4;\n            int t = q & 15,i;\n            if (p != 0) return e(\"bad DQT type\",\"Corrupt JPEG\");\n            if (t > 3) return e(\"bad DQT table\",\"Corrupt JPEG\");\n            for (i=0; i < 64; ++i)\n               z->dequant[t][dezigzag[i]] = get8u(z->s);\n            #ifdef STBI_SIMD\n            for (i=0; i < 64; ++i)\n               z->dequant2[t][i] = z->dequant[t][i];\n            #endif\n            L -= 65;\n         }\n         return L==0;\n\n      case 0xC4: // DHT - define huffman table\n         L = get16(z->s)-2;\n         while (L > 0) {\n            stbi__uint8 *v;\n            int sizes[16],i,n=0;\n            int q = get8(z->s);\n            int tc = q >> 4;\n            int th = q & 15;\n            if (tc > 1 || th > 3) return e(\"bad DHT header\",\"Corrupt JPEG\");\n            for (i=0; i < 16; ++i) {\n               sizes[i] = get8(z->s);\n               n += sizes[i];\n            }\n            L -= 17;\n            if (tc == 0) {\n               if (!build_huffman(z->huff_dc+th, sizes)) return 0;\n               v = z->huff_dc[th].values;\n            } else {\n               if (!build_huffman(z->huff_ac+th, sizes)) return 0;\n               v = z->huff_ac[th].values;\n            }\n            for (i=0; i < n; ++i)\n               v[i] = get8u(z->s);\n            L -= n;\n         }\n         return L==0;\n   }\n   // check for comment block or APP blocks\n   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {\n      skip(z->s, get16(z->s)-2);\n      return 1;\n   }\n   return 0;\n}\n\n// after we see SOS\nstatic int process_scan_header(jpeg *z)\n{\n   int i;\n   int Ls = get16(z->s);\n   z->scan_n = get8(z->s);\n   if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return e(\"bad SOS component count\",\"Corrupt JPEG\");\n   if (Ls != 6+2*z->scan_n) return e(\"bad SOS len\",\"Corrupt JPEG\");\n   for (i=0; i < z->scan_n; ++i) {\n      int id = get8(z->s), which;\n      int q = get8(z->s);\n      for (which = 0; which < z->s->img_n; ++which)\n         if (z->img_comp[which].id == id)\n            break;\n      if (which == z->s->img_n) return 0;\n      z->img_comp[which].hd = q >> 4;   if (z->img_comp[which].hd > 3) return e(\"bad DC huff\",\"Corrupt JPEG\");\n      z->img_comp[which].ha = q & 15;   if (z->img_comp[which].ha > 3) return e(\"bad AC huff\",\"Corrupt JPEG\");\n      z->order[i] = which;\n   }\n   if (get8(z->s) != 0) return e(\"bad SOS\",\"Corrupt JPEG\");\n   get8(z->s); // should be 63, but might be 0\n   if (get8(z->s) != 0) return e(\"bad SOS\",\"Corrupt JPEG\");\n\n   return 1;\n}\n\nstatic int process_frame_header(jpeg *z, int scan)\n{\n   stbi *s = z->s;\n   int Lf,p,i,q, h_max=1,v_max=1,c;\n   Lf = get16(s);         if (Lf < 11) return e(\"bad SOF len\",\"Corrupt JPEG\"); // JPEG\n   p  = get8(s);          if (p != 8) return e(\"only 8-bit\",\"JPEG format not supported: 8-bit only\"); // JPEG baseline\n   s->img_y = get16(s);   if (s->img_y == 0) return e(\"no header height\", \"JPEG format not supported: delayed height\"); // Legal, but we don't handle it--but neither does IJG\n   s->img_x = get16(s);   if (s->img_x == 0) return e(\"0 width\",\"Corrupt JPEG\"); // JPEG requires\n   c = get8(s);\n   if (c != 3 && c != 1) return e(\"bad component count\",\"Corrupt JPEG\");    // JFIF requires\n   s->img_n = c;\n   for (i=0; i < c; ++i) {\n      z->img_comp[i].data = NULL;\n      z->img_comp[i].linebuf = NULL;\n   }\n\n   if (Lf != 8+3*s->img_n) return e(\"bad SOF len\",\"Corrupt JPEG\");\n\n   for (i=0; i < s->img_n; ++i) {\n      z->img_comp[i].id = get8(s);\n      if (z->img_comp[i].id != i+1)   // JFIF requires\n         if (z->img_comp[i].id != i)  // some version of jpegtran outputs non-JFIF-compliant files!\n            return e(\"bad component ID\",\"Corrupt JPEG\");\n      q = get8(s);\n      z->img_comp[i].h = (q >> 4);  if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e(\"bad H\",\"Corrupt JPEG\");\n      z->img_comp[i].v = q & 15;    if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e(\"bad V\",\"Corrupt JPEG\");\n      z->img_comp[i].tq = get8(s);  if (z->img_comp[i].tq > 3) return e(\"bad TQ\",\"Corrupt JPEG\");\n   }\n\n   if (scan != SCAN_load) return 1;\n\n   if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e(\"too large\", \"Image too large to decode\");\n\n   for (i=0; i < s->img_n; ++i) {\n      if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;\n      if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;\n   }\n\n   // compute interleaved mcu info\n   z->img_h_max = h_max;\n   z->img_v_max = v_max;\n   z->img_mcu_w = h_max * 8;\n   z->img_mcu_h = v_max * 8;\n   z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;\n   z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;\n\n   for (i=0; i < s->img_n; ++i) {\n      // number of effective pixels (e.g. for non-interleaved MCU)\n      z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;\n      z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;\n      // to simplify generation, we'll allocate enough memory to decode\n      // the bogus oversized data from using interleaved MCUs and their\n      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't\n      // discard the extra data until colorspace conversion\n      z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;\n      z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;\n      z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);\n      if (z->img_comp[i].raw_data == NULL) {\n         for(--i; i >= 0; --i) {\n            free(z->img_comp[i].raw_data);\n            z->img_comp[i].data = NULL;\n         }\n         return e(\"outofmem\", \"Out of memory\");\n      }\n      // align blocks for installable-idct using mmx/sse\n      z->img_comp[i].data = (stbi__uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);\n      z->img_comp[i].linebuf = NULL;\n   }\n\n   return 1;\n}\n\n// use comparisons since in some cases we handle more than one case (e.g. SOF)\n#define DNL(x)         ((x) == 0xdc)\n#define SOI(x)         ((x) == 0xd8)\n#define EOI(x)         ((x) == 0xd9)\n#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)\n#define SOS(x)         ((x) == 0xda)\n\nstatic int decode_jpeg_header(jpeg *z, int scan)\n{\n   int m;\n   z->marker = MARKER_none; // initialize cached marker to empty\n   m = get_marker(z);\n   if (!SOI(m)) return e(\"no SOI\",\"Corrupt JPEG\");\n   if (scan == SCAN_type) return 1;\n   m = get_marker(z);\n   while (!SOF(m)) {\n      if (!process_marker(z,m)) return 0;\n      m = get_marker(z);\n      while (m == MARKER_none) {\n         // some files have extra padding after their blocks, so ok, we'll scan\n         if (at_eof(z->s)) return e(\"no SOF\", \"Corrupt JPEG\");\n         m = get_marker(z);\n      }\n   }\n   if (!process_frame_header(z, scan)) return 0;\n   return 1;\n}\n\nstatic int decode_jpeg_image(jpeg *j)\n{\n   int m;\n   j->restart_interval = 0;\n   if (!decode_jpeg_header(j, SCAN_load)) return 0;\n   m = get_marker(j);\n   while (!EOI(m)) {\n      if (SOS(m)) {\n         if (!process_scan_header(j)) return 0;\n         if (!parse_entropy_coded_data(j)) return 0;\n         if (j->marker == MARKER_none ) {\n            // handle 0s at the end of image data from IP Kamera 9060\n            while (!at_eof(j->s)) {\n               int x = get8(j->s);\n               if (x == 255) {\n                  j->marker = get8u(j->s);\n                  break;\n               } else if (x != 0) {\n                  return 0;\n               }\n            }\n            // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0\n         }\n      } else {\n         if (!process_marker(j, m)) return 0;\n      }\n      m = get_marker(j);\n   }\n   return 1;\n}\n\n// static jfif-centered resampling (across block boundaries)\n\ntypedef stbi__uint8 *(*resample_row_func)(stbi__uint8 *out, stbi__uint8 *in0, stbi__uint8 *in1,\n                                    int w, int hs);\n\n#define div4(x) ((stbi__uint8) ((x) >> 2))\n\nstatic stbi__uint8 *resample_row_1(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)\n{\n   STBI_NOTUSED(out);\n   STBI_NOTUSED(in_far);\n   STBI_NOTUSED(w);\n   STBI_NOTUSED(hs);\n   return in_near;\n}\n\nstatic stbi__uint8* resample_row_v_2(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)\n{\n   // need to generate two samples vertically for every one in input\n   int i;\n   STBI_NOTUSED(hs);\n   for (i=0; i < w; ++i)\n      out[i] = div4(3*in_near[i] + in_far[i] + 2);\n   return out;\n}\n\nstatic stbi__uint8*  resample_row_h_2(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)\n{\n   // need to generate two samples horizontally for every one in input\n   int i;\n   stbi__uint8 *input = in_near;\n\n   if (w == 1) {\n      // if only one sample, can't do any interpolation\n      out[0] = out[1] = input[0];\n      return out;\n   }\n\n   out[0] = input[0];\n   out[1] = div4(input[0]*3 + input[1] + 2);\n   for (i=1; i < w-1; ++i) {\n      int n = 3*input[i]+2;\n      out[i*2+0] = div4(n+input[i-1]);\n      out[i*2+1] = div4(n+input[i+1]);\n   }\n   out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);\n   out[i*2+1] = input[w-1];\n\n   STBI_NOTUSED(in_far);\n   STBI_NOTUSED(hs);\n\n   return out;\n}\n\n#define div16(x) ((stbi__uint8) ((x) >> 4))\n\nstatic stbi__uint8 *resample_row_hv_2(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)\n{\n   // need to generate 2x2 samples for every one in input\n   int i,t0,t1;\n   if (w == 1) {\n      out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);\n      return out;\n   }\n\n   t1 = 3*in_near[0] + in_far[0];\n   out[0] = div4(t1+2);\n   for (i=1; i < w; ++i) {\n      t0 = t1;\n      t1 = 3*in_near[i]+in_far[i];\n      out[i*2-1] = div16(3*t0 + t1 + 8);\n      out[i*2  ] = div16(3*t1 + t0 + 8);\n   }\n   out[w*2-1] = div4(t1+2);\n\n   STBI_NOTUSED(hs);\n\n   return out;\n}\n\nstatic stbi__uint8 *resample_row_generic(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)\n{\n   // resample with nearest-neighbor\n   int i,j;\n   STBI_NOTUSED(in_far);\n   for (i=0; i < w; ++i)\n      for (j=0; j < hs; ++j)\n         out[i*hs+j] = in_near[i];\n   return out;\n}\n\n#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))\n\n// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)\n// VC6 without processor=Pro is generating multiple LEAs per multiply!\nstatic void YCbCr_to_RGB_row(stbi__uint8 *out, const stbi__uint8 *y, const stbi__uint8 *pcb, const stbi__uint8 *pcr, int count, int step)\n{\n   int i;\n   for (i=0; i < count; ++i) {\n      int y_fixed = (y[i] << 16) + 32768; // rounding\n      int r,g,b;\n      int cr = pcr[i] - 128;\n      int cb = pcb[i] - 128;\n      r = y_fixed + cr*float2fixed(1.40200f);\n      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);\n      b = y_fixed                            + cb*float2fixed(1.77200f);\n      r >>= 16;\n      g >>= 16;\n      b >>= 16;\n      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }\n      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }\n      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }\n      out[0] = (stbi__uint8)r;\n      out[1] = (stbi__uint8)g;\n      out[2] = (stbi__uint8)b;\n      out[3] = 255;\n      out += step;\n   }\n}\n\n#ifdef STBI_SIMD\nstatic stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;\n\nvoid stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)\n{\n   stbi_YCbCr_installed = func;\n}\n#endif\n\n\n// clean up the temporary component buffers\nstatic void cleanup_jpeg(jpeg *j)\n{\n   int i;\n   for (i=0; i < j->s->img_n; ++i) {\n      if (j->img_comp[i].data) {\n         free(j->img_comp[i].raw_data);\n         j->img_comp[i].data = NULL;\n      }\n      if (j->img_comp[i].linebuf) {\n         free(j->img_comp[i].linebuf);\n         j->img_comp[i].linebuf = NULL;\n      }\n   }\n}\n\ntypedef struct\n{\n   resample_row_func resample;\n   stbi__uint8 *line0,*line1;\n   int hs,vs;   // expansion factor in each axis\n   int w_lores; // horizontal pixels pre-expansion \n   int ystep;   // how far through vertical expansion we are\n   int ypos;    // which pre-expansion row we're on\n} stbi_resample;\n\nstatic stbi__uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)\n{\n   int n, decode_n;\n   // validate req_comp\n   if (req_comp < 0 || req_comp > 4) return epuc(\"bad req_comp\", \"Internal error\");\n   z->s->img_n = 0;\n\n   // load a jpeg image from whichever source\n   if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }\n\n   // determine actual number of components to generate\n   n = req_comp ? req_comp : z->s->img_n;\n\n   if (z->s->img_n == 3 && n < 3)\n      decode_n = 1;\n   else\n      decode_n = z->s->img_n;\n\n   // resample and color-convert\n   {\n      int k;\n      unsigned int i,j;\n      stbi__uint8 *output;\n      stbi__uint8 *coutput[4];\n\n      stbi_resample res_comp[4];\n\n      for (k=0; k < decode_n; ++k) {\n         stbi_resample *r = &res_comp[k];\n\n         // allocate line buffer big enough for upsampling off the edges\n         // with upsample factor of 4\n         z->img_comp[k].linebuf = (stbi__uint8 *) malloc(z->s->img_x + 3);\n         if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc(\"outofmem\", \"Out of memory\"); }\n\n         r->hs      = z->img_h_max / z->img_comp[k].h;\n         r->vs      = z->img_v_max / z->img_comp[k].v;\n         r->ystep   = r->vs >> 1;\n         r->w_lores = (z->s->img_x + r->hs-1) / r->hs;\n         r->ypos    = 0;\n         r->line0   = r->line1 = z->img_comp[k].data;\n\n         if      (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;\n         else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;\n         else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;\n         else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;\n         else                               r->resample = resample_row_generic;\n      }\n\n      // can't error after this so, this is safe\n      output = (stbi__uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1);\n      if (!output) { cleanup_jpeg(z); return epuc(\"outofmem\", \"Out of memory\"); }\n\n      // now go ahead and resample\n      for (j=0; j < z->s->img_y; ++j) {\n         stbi__uint8 *out = output + n * z->s->img_x * j;\n         for (k=0; k < decode_n; ++k) {\n            stbi_resample *r = &res_comp[k];\n            int y_bot = r->ystep >= (r->vs >> 1);\n            coutput[k] = r->resample(z->img_comp[k].linebuf,\n                                     y_bot ? r->line1 : r->line0,\n                                     y_bot ? r->line0 : r->line1,\n                                     r->w_lores, r->hs);\n            if (++r->ystep >= r->vs) {\n               r->ystep = 0;\n               r->line0 = r->line1;\n               if (++r->ypos < z->img_comp[k].y)\n                  r->line1 += z->img_comp[k].w2;\n            }\n         }\n         if (n >= 3) {\n            stbi__uint8 *y = coutput[0];\n            if (z->s->img_n == 3) {\n               #ifdef STBI_SIMD\n               stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s->img_x, n);\n               #else\n               YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);\n               #endif\n            } else\n               for (i=0; i < z->s->img_x; ++i) {\n                  out[0] = out[1] = out[2] = y[i];\n                  out[3] = 255; // not used if n==3\n                  out += n;\n               }\n         } else {\n            stbi__uint8 *y = coutput[0];\n            if (n == 1)\n               for (i=0; i < z->s->img_x; ++i) out[i] = y[i];\n            else\n               for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;\n         }\n      }\n      cleanup_jpeg(z);\n      *out_x = z->s->img_x;\n      *out_y = z->s->img_y;\n      if (comp) *comp  = z->s->img_n; // report original components, not output\n      return output;\n   }\n}\n\nstatic unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   jpeg j;\n   j.s = s;\n   return load_jpeg_image(&j, x,y,comp,req_comp);\n}\n\nstatic int stbi_jpeg_test(stbi *s)\n{\n   int r;\n   jpeg j;\n   j.s = s;\n   r = decode_jpeg_header(&j, SCAN_type);\n   stbi_rewind(s);\n   return r;\n}\n\nstatic int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)\n{\n   if (!decode_jpeg_header(j, SCAN_header)) {\n      stbi_rewind( j->s );\n      return 0;\n   }\n   if (x) *x = j->s->img_x;\n   if (y) *y = j->s->img_y;\n   if (comp) *comp = j->s->img_n;\n   return 1;\n}\n\nstatic int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp)\n{\n   jpeg j;\n   j.s = s;\n   return stbi_jpeg_info_raw(&j, x, y, comp);\n}\n\n// public domain zlib decode    v0.2  Sean Barrett 2006-11-18\n//    simple implementation\n//      - all input must be provided in an upfront buffer\n//      - all output is written to a single output buffer (can malloc/realloc)\n//    performance\n//      - fast huffman\n\n// fast-way is faster to check than jpeg huffman, but slow way is slower\n#define ZFAST_BITS  9 // accelerate all cases in default tables\n#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)\n\n// zlib-style huffman encoding\n// (jpegs packs from left, zlib from right, so can't share code)\ntypedef struct\n{\n   stbi__uint16 fast[1 << ZFAST_BITS];\n   stbi__uint16 firstcode[16];\n   int maxcode[17];\n   stbi__uint16 firstsymbol[16];\n   stbi__uint8  size[288];\n   stbi__uint16 value[288]; \n} zhuffman;\n\nstbi_inline static int bitreverse16(int n)\n{\n  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);\n  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);\n  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);\n  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);\n  return n;\n}\n\nstbi_inline static int bit_reverse(int v, int bits)\n{\n   assert(bits <= 16);\n   // to bit reverse n bits, reverse 16 and shift\n   // e.g. 11 bits, bit reverse and shift away 5\n   return bitreverse16(v) >> (16-bits);\n}\n\nstatic int zbuild_huffman(zhuffman *z, stbi__uint8 *sizelist, int num)\n{\n   int i,k=0;\n   int code, next_code[16], sizes[17];\n\n   // DEFLATE spec for generating codes\n   memset(sizes, 0, sizeof(sizes));\n   memset(z->fast, 255, sizeof(z->fast));\n   for (i=0; i < num; ++i) \n      ++sizes[sizelist[i]];\n   sizes[0] = 0;\n   for (i=1; i < 16; ++i)\n      assert(sizes[i] <= (1 << i));\n   code = 0;\n   for (i=1; i < 16; ++i) {\n      next_code[i] = code;\n      z->firstcode[i] = (stbi__uint16) code;\n      z->firstsymbol[i] = (stbi__uint16) k;\n      code = (code + sizes[i]);\n      if (sizes[i])\n         if (code-1 >= (1 << i)) return e(\"bad codelengths\",\"Corrupt JPEG\");\n      z->maxcode[i] = code << (16-i); // preshift for inner loop\n      code <<= 1;\n      k += sizes[i];\n   }\n   z->maxcode[16] = 0x10000; // sentinel\n   for (i=0; i < num; ++i) {\n      int s = sizelist[i];\n      if (s) {\n         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];\n         z->size[c] = (stbi__uint8)s;\n         z->value[c] = (stbi__uint16)i;\n         if (s <= ZFAST_BITS) {\n            int k = bit_reverse(next_code[s],s);\n            while (k < (1 << ZFAST_BITS)) {\n               z->fast[k] = (stbi__uint16) c;\n               k += (1 << s);\n            }\n         }\n         ++next_code[s];\n      }\n   }\n   return 1;\n}\n\n// zlib-from-memory implementation for PNG reading\n//    because PNG allows splitting the zlib stream arbitrarily,\n//    and it's annoying structurally to have PNG call ZLIB call PNG,\n//    we require PNG read all the IDATs and combine them into a single\n//    memory buffer\n\ntypedef struct\n{\n   stbi__uint8 *zbuffer, *zbuffer_end;\n   int num_bits;\n   stbi__uint32 code_buffer;\n\n   char *zout;\n   char *zout_start;\n   char *zout_end;\n   int   z_expandable;\n\n   zhuffman z_length, z_distance;\n} zbuf;\n\nstbi_inline static int zget8(zbuf *z)\n{\n   if (z->zbuffer >= z->zbuffer_end) return 0;\n   return *z->zbuffer++;\n}\n\nstatic void fill_bits(zbuf *z)\n{\n   do {\n      assert(z->code_buffer < (1U << z->num_bits));\n      z->code_buffer |= zget8(z) << z->num_bits;\n      z->num_bits += 8;\n   } while (z->num_bits <= 24);\n}\n\nstbi_inline static unsigned int zreceive(zbuf *z, int n)\n{\n   unsigned int k;\n   if (z->num_bits < n) fill_bits(z);\n   k = z->code_buffer & ((1 << n) - 1);\n   z->code_buffer >>= n;\n   z->num_bits -= n;\n   return k;   \n}\n\nstbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)\n{\n   int b,s,k;\n   if (a->num_bits < 16) fill_bits(a);\n   b = z->fast[a->code_buffer & ZFAST_MASK];\n   if (b < 0xffff) {\n      s = z->size[b];\n      a->code_buffer >>= s;\n      a->num_bits -= s;\n      return z->value[b];\n   }\n\n   // not resolved by fast table, so compute it the slow way\n   // use jpeg approach, which requires MSbits at top\n   k = bit_reverse(a->code_buffer, 16);\n   for (s=ZFAST_BITS+1; ; ++s)\n      if (k < z->maxcode[s])\n         break;\n   if (s == 16) return -1; // invalid code!\n   // code size is s, so:\n   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];\n   assert(z->size[b] == s);\n   a->code_buffer >>= s;\n   a->num_bits -= s;\n   return z->value[b];\n}\n\nstatic int expand(zbuf *z, int n)  // need to make room for n bytes\n{\n   char *q;\n   int cur, limit;\n   if (!z->z_expandable) return e(\"output buffer limit\",\"Corrupt PNG\");\n   cur   = (int) (z->zout     - z->zout_start);\n   limit = (int) (z->zout_end - z->zout_start);\n   while (cur + n > limit)\n      limit *= 2;\n   q = (char *) realloc(z->zout_start, limit);\n   if (q == NULL) return e(\"outofmem\", \"Out of memory\");\n   z->zout_start = q;\n   z->zout       = q + cur;\n   z->zout_end   = q + limit;\n   return 1;\n}\n\nstatic int length_base[31] = {\n   3,4,5,6,7,8,9,10,11,13,\n   15,17,19,23,27,31,35,43,51,59,\n   67,83,99,115,131,163,195,227,258,0,0 };\n\nstatic int length_extra[31]= \n{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };\n\nstatic int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,\n257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};\n\nstatic int dist_extra[32] =\n{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\n\nstatic int parse_huffman_block(zbuf *a)\n{\n   for(;;) {\n      int z = zhuffman_decode(a, &a->z_length);\n      if (z < 256) {\n         if (z < 0) return e(\"bad huffman code\",\"Corrupt PNG\"); // error in huffman codes\n         if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;\n         *a->zout++ = (char) z;\n      } else {\n         stbi__uint8 *p;\n         int len,dist;\n         if (z == 256) return 1;\n         z -= 257;\n         len = length_base[z];\n         if (length_extra[z]) len += zreceive(a, length_extra[z]);\n         z = zhuffman_decode(a, &a->z_distance);\n         if (z < 0) return e(\"bad huffman code\",\"Corrupt PNG\");\n         dist = dist_base[z];\n         if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);\n         if (a->zout - a->zout_start < dist) return e(\"bad dist\",\"Corrupt PNG\");\n         if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;\n         p = (stbi__uint8 *) (a->zout - dist);\n         while (len--)\n            *a->zout++ = *p++;\n      }\n   }\n}\n\nstatic int compute_huffman_codes(zbuf *a)\n{\n   static stbi__uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };\n   zhuffman z_codelength;\n   stbi__uint8 lencodes[286+32+137];//padding for maximum single op\n   stbi__uint8 codelength_sizes[19];\n   int i,n;\n\n   int hlit  = zreceive(a,5) + 257;\n   int hdist = zreceive(a,5) + 1;\n   int hclen = zreceive(a,4) + 4;\n\n   memset(codelength_sizes, 0, sizeof(codelength_sizes));\n   for (i=0; i < hclen; ++i) {\n      int s = zreceive(a,3);\n      codelength_sizes[length_dezigzag[i]] = (stbi__uint8) s;\n   }\n   if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;\n\n   n = 0;\n   while (n < hlit + hdist) {\n      int c = zhuffman_decode(a, &z_codelength);\n      assert(c >= 0 && c < 19);\n      if (c < 16)\n         lencodes[n++] = (stbi__uint8) c;\n      else if (c == 16) {\n         c = zreceive(a,2)+3;\n         memset(lencodes+n, lencodes[n-1], c);\n         n += c;\n      } else if (c == 17) {\n         c = zreceive(a,3)+3;\n         memset(lencodes+n, 0, c);\n         n += c;\n      } else {\n         assert(c == 18);\n         c = zreceive(a,7)+11;\n         memset(lencodes+n, 0, c);\n         n += c;\n      }\n   }\n   if (n != hlit+hdist) return e(\"bad codelengths\",\"Corrupt PNG\");\n   if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;\n   if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;\n   return 1;\n}\n\nstatic int parse_uncompressed_block(zbuf *a)\n{\n   stbi__uint8 header[4];\n   int len,nlen,k;\n   if (a->num_bits & 7)\n      zreceive(a, a->num_bits & 7); // discard\n   // drain the bit-packed data into header\n   k = 0;\n   while (a->num_bits > 0) {\n      header[k++] = (stbi__uint8) (a->code_buffer & 255); // wtf this warns?\n      a->code_buffer >>= 8;\n      a->num_bits -= 8;\n   }\n   assert(a->num_bits == 0);\n   // now fill header the normal way\n   while (k < 4)\n      header[k++] = (stbi__uint8) zget8(a);\n   len  = header[1] * 256 + header[0];\n   nlen = header[3] * 256 + header[2];\n   if (nlen != (len ^ 0xffff)) return e(\"zlib corrupt\",\"Corrupt PNG\");\n   if (a->zbuffer + len > a->zbuffer_end) return e(\"read past buffer\",\"Corrupt PNG\");\n   if (a->zout + len > a->zout_end)\n      if (!expand(a, len)) return 0;\n   memcpy(a->zout, a->zbuffer, len);\n   a->zbuffer += len;\n   a->zout += len;\n   return 1;\n}\n\nstatic int parse_zlib_header(zbuf *a)\n{\n   int cmf   = zget8(a);\n   int cm    = cmf & 15;\n   /* int cinfo = cmf >> 4; */\n   int flg   = zget8(a);\n   if ((cmf*256+flg) % 31 != 0) return e(\"bad zlib header\",\"Corrupt PNG\"); // zlib spec\n   if (flg & 32) return e(\"no preset dict\",\"Corrupt PNG\"); // preset dictionary not allowed in png\n   if (cm != 8) return e(\"bad compression\",\"Corrupt PNG\"); // DEFLATE required for png\n   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output\n   return 1;\n}\n\n// @TODO: should statically initialize these for optimal thread safety\nstatic stbi__uint8 default_length[288], default_distance[32];\nstatic void init_defaults(void)\n{\n   int i;   // use <= to match clearly with spec\n   for (i=0; i <= 143; ++i)     default_length[i]   = 8;\n   for (   ; i <= 255; ++i)     default_length[i]   = 9;\n   for (   ; i <= 279; ++i)     default_length[i]   = 7;\n   for (   ; i <= 287; ++i)     default_length[i]   = 8;\n\n   for (i=0; i <=  31; ++i)     default_distance[i] = 5;\n}\n\nint stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead\nstatic int parse_zlib(zbuf *a, int parse_header)\n{\n   int final, type;\n   if (parse_header)\n      if (!parse_zlib_header(a)) return 0;\n   a->num_bits = 0;\n   a->code_buffer = 0;\n   do {\n      final = zreceive(a,1);\n      type = zreceive(a,2);\n      if (type == 0) {\n         if (!parse_uncompressed_block(a)) return 0;\n      } else if (type == 3) {\n         return 0;\n      } else {\n         if (type == 1) {\n            // use fixed code lengths\n            if (!default_distance[31]) init_defaults();\n            if (!zbuild_huffman(&a->z_length  , default_length  , 288)) return 0;\n            if (!zbuild_huffman(&a->z_distance, default_distance,  32)) return 0;\n         } else {\n            if (!compute_huffman_codes(a)) return 0;\n         }\n         if (!parse_huffman_block(a)) return 0;\n      }\n      if (stbi_png_partial && a->zout - a->zout_start > 65536)\n         break;\n   } while (!final);\n   return 1;\n}\n\nstatic int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)\n{\n   a->zout_start = obuf;\n   a->zout       = obuf;\n   a->zout_end   = obuf + olen;\n   a->z_expandable = exp;\n\n   return parse_zlib(a, parse_header);\n}\n\nchar *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)\n{\n   zbuf a;\n   char *p = (char *) malloc(initial_size);\n   if (p == NULL) return NULL;\n   a.zbuffer = (stbi__uint8 *) buffer;\n   a.zbuffer_end = (stbi__uint8 *) buffer + len;\n   if (do_zlib(&a, p, initial_size, 1, 1)) {\n      if (outlen) *outlen = (int) (a.zout - a.zout_start);\n      return a.zout_start;\n   } else {\n      free(a.zout_start);\n      return NULL;\n   }\n}\n\nchar *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)\n{\n   return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);\n}\n\nchar *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)\n{\n   zbuf a;\n   char *p = (char *) malloc(initial_size);\n   if (p == NULL) return NULL;\n   a.zbuffer = (stbi__uint8 *) buffer;\n   a.zbuffer_end = (stbi__uint8 *) buffer + len;\n   if (do_zlib(&a, p, initial_size, 1, parse_header)) {\n      if (outlen) *outlen = (int) (a.zout - a.zout_start);\n      return a.zout_start;\n   } else {\n      free(a.zout_start);\n      return NULL;\n   }\n}\n\nint stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)\n{\n   zbuf a;\n   a.zbuffer = (stbi__uint8 *) ibuffer;\n   a.zbuffer_end = (stbi__uint8 *) ibuffer + ilen;\n   if (do_zlib(&a, obuffer, olen, 0, 1))\n      return (int) (a.zout - a.zout_start);\n   else\n      return -1;\n}\n\nchar *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)\n{\n   zbuf a;\n   char *p = (char *) malloc(16384);\n   if (p == NULL) return NULL;\n   a.zbuffer = (stbi__uint8 *) buffer;\n   a.zbuffer_end = (stbi__uint8 *) buffer+len;\n   if (do_zlib(&a, p, 16384, 1, 0)) {\n      if (outlen) *outlen = (int) (a.zout - a.zout_start);\n      return a.zout_start;\n   } else {\n      free(a.zout_start);\n      return NULL;\n   }\n}\n\nint stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)\n{\n   zbuf a;\n   a.zbuffer = (stbi__uint8 *) ibuffer;\n   a.zbuffer_end = (stbi__uint8 *) ibuffer + ilen;\n   if (do_zlib(&a, obuffer, olen, 0, 0))\n      return (int) (a.zout - a.zout_start);\n   else\n      return -1;\n}\n\n// public domain \"baseline\" PNG decoder   v0.10  Sean Barrett 2006-11-18\n//    simple implementation\n//      - only 8-bit samples\n//      - no CRC checking\n//      - allocates lots of intermediate memory\n//        - avoids problem of streaming data between subsystems\n//        - avoids explicit window management\n//    performance\n//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding\n\n\ntypedef struct\n{\n   stbi__uint32 length;\n   stbi__uint32 type;\n} chunk;\n\n#define PNG_TYPE(a,b,c,d)  (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))\n\nstatic chunk get_chunk_header(stbi *s)\n{\n   chunk c;\n   c.length = get32(s);\n   c.type   = get32(s);\n   return c;\n}\n\nstatic int check_png_header(stbi *s)\n{\n   static stbi__uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };\n   int i;\n   for (i=0; i < 8; ++i)\n      if (get8u(s) != png_sig[i]) return e(\"bad png sig\",\"Not a PNG\");\n   return 1;\n}\n\ntypedef struct\n{\n   stbi *s;\n   stbi__uint8 *idata, *expanded, *out;\n} png;\n\n\nenum {\n   F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,\n   F_avg_first, F_paeth_first\n};\n\nstatic stbi__uint8 first_row_filter[5] =\n{\n   F_none, F_sub, F_none, F_avg_first, F_paeth_first\n};\n\nstatic int paeth(int a, int b, int c)\n{\n   int p = a + b - c;\n   int pa = abs(p-a);\n   int pb = abs(p-b);\n   int pc = abs(p-c);\n   if (pa <= pb && pa <= pc) return a;\n   if (pb <= pc) return b;\n   return c;\n}\n\n// create the png data from post-deflated data\nstatic int create_png_image_raw(png *a, stbi__uint8 *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y)\n{\n   stbi *s = a->s;\n   stbi__uint32 i,j,stride = x*out_n;\n   int k;\n   int img_n = s->img_n; // copy it into a local for later\n   assert(out_n == s->img_n || out_n == s->img_n+1);\n   if (stbi_png_partial) y = 1;\n   a->out = (stbi__uint8 *) malloc(x * y * out_n);\n   if (!a->out) return e(\"outofmem\", \"Out of memory\");\n   if (!stbi_png_partial) {\n      if (s->img_x == x && s->img_y == y) {\n         if (raw_len != (img_n * x + 1) * y) return e(\"not enough pixels\",\"Corrupt PNG\");\n      } else { // interlaced:\n         if (raw_len < (img_n * x + 1) * y) return e(\"not enough pixels\",\"Corrupt PNG\");\n      }\n   }\n   for (j=0; j < y; ++j) {\n      stbi__uint8 *cur = a->out + stride*j;\n      stbi__uint8 *prior = cur - stride;\n      int filter = *raw++;\n      if (filter > 4) return e(\"invalid filter\",\"Corrupt PNG\");\n      // if first row, use special filter that doesn't sample previous row\n      if (j == 0) filter = first_row_filter[filter];\n      // handle first pixel explicitly\n      for (k=0; k < img_n; ++k) {\n         switch (filter) {\n            case F_none       : cur[k] = raw[k]; break;\n            case F_sub        : cur[k] = raw[k]; break;\n            case F_up         : cur[k] = raw[k] + prior[k]; break;\n            case F_avg        : cur[k] = raw[k] + (prior[k]>>1); break;\n            case F_paeth      : cur[k] = (stbi__uint8) (raw[k] + paeth(0,prior[k],0)); break;\n            case F_avg_first  : cur[k] = raw[k]; break;\n            case F_paeth_first: cur[k] = raw[k]; break;\n         }\n      }\n      if (img_n != out_n) cur[img_n] = 255;\n      raw += img_n;\n      cur += out_n;\n      prior += out_n;\n      // this is a little gross, so that we don't switch per-pixel or per-component\n      if (img_n == out_n) {\n         #define CASE(f) \\\n             case f:     \\\n                for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \\\n                   for (k=0; k < img_n; ++k)\n         switch (filter) {\n            CASE(F_none)  cur[k] = raw[k]; break;\n            CASE(F_sub)   cur[k] = raw[k] + cur[k-img_n]; break;\n            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\n            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;\n            CASE(F_paeth)  cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;\n            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-img_n] >> 1); break;\n            CASE(F_paeth_first)  cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;\n         }\n         #undef CASE\n      } else {\n         assert(img_n+1 == out_n);\n         #define CASE(f) \\\n             case f:     \\\n                for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \\\n                   for (k=0; k < img_n; ++k)\n         switch (filter) {\n            CASE(F_none)  cur[k] = raw[k]; break;\n            CASE(F_sub)   cur[k] = raw[k] + cur[k-out_n]; break;\n            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\n            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;\n            CASE(F_paeth)  cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;\n            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-out_n] >> 1); break;\n            CASE(F_paeth_first)  cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;\n         }\n         #undef CASE\n      }\n   }\n   return 1;\n}\n\nstatic int create_png_image(png *a, stbi__uint8 *raw, stbi__uint32 raw_len, int out_n, int interlaced)\n{\n   stbi__uint8 *final;\n   int p;\n   int save;\n   if (!interlaced)\n      return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);\n   save = stbi_png_partial;\n   stbi_png_partial = 0;\n\n   // de-interlacing\n   final = (stbi__uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);\n   for (p=0; p < 7; ++p) {\n      int xorig[] = { 0,4,0,2,0,1,0 };\n      int yorig[] = { 0,0,4,0,2,0,1 };\n      int xspc[]  = { 8,8,4,4,2,2,1 };\n      int yspc[]  = { 8,8,8,4,4,2,2 };\n      int i,j,x,y;\n      // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1\n      x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];\n      y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];\n      if (x && y) {\n         if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {\n            free(final);\n            return 0;\n         }\n         for (j=0; j < y; ++j)\n            for (i=0; i < x; ++i)\n               memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,\n                      a->out + (j*x+i)*out_n, out_n);\n         free(a->out);\n         raw += (x*out_n+1)*y;\n         raw_len -= (x*out_n+1)*y;\n      }\n   }\n   a->out = final;\n\n   stbi_png_partial = save;\n   return 1;\n}\n\nstatic int compute_transparency(png *z, stbi__uint8 tc[3], int out_n)\n{\n   stbi *s = z->s;\n   stbi__uint32 i, pixel_count = s->img_x * s->img_y;\n   stbi__uint8 *p = z->out;\n\n   // compute color-based transparency, assuming we've\n   // already got 255 as the alpha value in the output\n   assert(out_n == 2 || out_n == 4);\n\n   if (out_n == 2) {\n      for (i=0; i < pixel_count; ++i) {\n         p[1] = (p[0] == tc[0] ? 0 : 255);\n         p += 2;\n      }\n   } else {\n      for (i=0; i < pixel_count; ++i) {\n         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])\n            p[3] = 0;\n         p += 4;\n      }\n   }\n   return 1;\n}\n\nstatic int expand_palette(png *a, stbi__uint8 *palette, int len, int pal_img_n)\n{\n   stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;\n   stbi__uint8 *p, *temp_out, *orig = a->out;\n\n   p = (stbi__uint8 *) malloc(pixel_count * pal_img_n);\n   if (p == NULL) return e(\"outofmem\", \"Out of memory\");\n\n   // between here and free(out) below, exitting would leak\n   temp_out = p;\n\n   if (pal_img_n == 3) {\n      for (i=0; i < pixel_count; ++i) {\n         int n = orig[i]*4;\n         p[0] = palette[n  ];\n         p[1] = palette[n+1];\n         p[2] = palette[n+2];\n         p += 3;\n      }\n   } else {\n      for (i=0; i < pixel_count; ++i) {\n         int n = orig[i]*4;\n         p[0] = palette[n  ];\n         p[1] = palette[n+1];\n         p[2] = palette[n+2];\n         p[3] = palette[n+3];\n         p += 4;\n      }\n   }\n   free(a->out);\n   a->out = temp_out;\n\n   STBI_NOTUSED(len);\n\n   return 1;\n}\n\nstatic int stbi_unpremultiply_on_load = 0;\nstatic int stbi_de_iphone_flag = 0;\n\nvoid stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)\n{\n   stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;\n}\nvoid stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)\n{\n   stbi_de_iphone_flag = flag_true_if_should_convert;\n}\n\nstatic void stbi_de_iphone(png *z)\n{\n   stbi *s = z->s;\n   stbi__uint32 i, pixel_count = s->img_x * s->img_y;\n   stbi__uint8 *p = z->out;\n\n   if (s->img_out_n == 3) {  // convert bgr to rgb\n      for (i=0; i < pixel_count; ++i) {\n         stbi__uint8 t = p[0];\n         p[0] = p[2];\n         p[2] = t;\n         p += 3;\n      }\n   } else {\n      assert(s->img_out_n == 4);\n      if (stbi_unpremultiply_on_load) {\n         // convert bgr to rgb and unpremultiply\n         for (i=0; i < pixel_count; ++i) {\n            stbi__uint8 a = p[3];\n            stbi__uint8 t = p[0];\n            if (a) {\n               p[0] = p[2] * 255 / a;\n               p[1] = p[1] * 255 / a;\n               p[2] =  t   * 255 / a;\n            } else {\n               p[0] = p[2];\n               p[2] = t;\n            } \n            p += 4;\n         }\n      } else {\n         // convert bgr to rgb\n         for (i=0; i < pixel_count; ++i) {\n            stbi__uint8 t = p[0];\n            p[0] = p[2];\n            p[2] = t;\n            p += 4;\n         }\n      }\n   }\n}\n\nstatic int parse_png_file(png *z, int scan, int req_comp)\n{\n   stbi__uint8 palette[1024], pal_img_n=0;\n   stbi__uint8 has_trans=0, tc[3];\n   stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;\n   int first=1,k,interlace=0, iphone=0;\n   stbi *s = z->s;\n\n   z->expanded = NULL;\n   z->idata = NULL;\n   z->out = NULL;\n\n   if (!check_png_header(s)) return 0;\n\n   if (scan == SCAN_type) return 1;\n\n   for (;;) {\n      chunk c = get_chunk_header(s);\n      switch (c.type) {\n         case PNG_TYPE('C','g','B','I'):\n            iphone = stbi_de_iphone_flag;\n            skip(s, c.length);\n            break;\n         case PNG_TYPE('I','H','D','R'): {\n            int depth,color,comp,filter;\n            if (!first) return e(\"multiple IHDR\",\"Corrupt PNG\");\n            first = 0;\n            if (c.length != 13) return e(\"bad IHDR len\",\"Corrupt PNG\");\n            s->img_x = get32(s); if (s->img_x > (1 << 24)) return e(\"too large\",\"Very large image (corrupt?)\");\n            s->img_y = get32(s); if (s->img_y > (1 << 24)) return e(\"too large\",\"Very large image (corrupt?)\");\n            depth = get8(s);  if (depth != 8)        return e(\"8bit only\",\"PNG not supported: 8-bit only\");\n            color = get8(s);  if (color > 6)         return e(\"bad ctype\",\"Corrupt PNG\");\n            if (color == 3) pal_img_n = 3; else if (color & 1) return e(\"bad ctype\",\"Corrupt PNG\");\n            comp  = get8(s);  if (comp) return e(\"bad comp method\",\"Corrupt PNG\");\n            filter= get8(s);  if (filter) return e(\"bad filter method\",\"Corrupt PNG\");\n            interlace = get8(s); if (interlace>1) return e(\"bad interlace method\",\"Corrupt PNG\");\n            if (!s->img_x || !s->img_y) return e(\"0-pixel image\",\"Corrupt PNG\");\n            if (!pal_img_n) {\n               s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);\n               if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e(\"too large\", \"Image too large to decode\");\n               if (scan == SCAN_header) return 1;\n            } else {\n               // if paletted, then pal_n is our final components, and\n               // img_n is # components to decompress/filter.\n               s->img_n = 1;\n               if ((1 << 30) / s->img_x / 4 < s->img_y) return e(\"too large\",\"Corrupt PNG\");\n               // if SCAN_header, have to scan to see if we have a tRNS\n            }\n            break;\n         }\n\n         case PNG_TYPE('P','L','T','E'):  {\n            if (first) return e(\"first not IHDR\", \"Corrupt PNG\");\n            if (c.length > 256*3) return e(\"invalid PLTE\",\"Corrupt PNG\");\n            pal_len = c.length / 3;\n            if (pal_len * 3 != c.length) return e(\"invalid PLTE\",\"Corrupt PNG\");\n            for (i=0; i < pal_len; ++i) {\n               palette[i*4+0] = get8u(s);\n               palette[i*4+1] = get8u(s);\n               palette[i*4+2] = get8u(s);\n               palette[i*4+3] = 255;\n            }\n            break;\n         }\n\n         case PNG_TYPE('t','R','N','S'): {\n            if (first) return e(\"first not IHDR\", \"Corrupt PNG\");\n            if (z->idata) return e(\"tRNS after IDAT\",\"Corrupt PNG\");\n            if (pal_img_n) {\n               if (scan == SCAN_header) { s->img_n = 4; return 1; }\n               if (pal_len == 0) return e(\"tRNS before PLTE\",\"Corrupt PNG\");\n               if (c.length > pal_len) return e(\"bad tRNS len\",\"Corrupt PNG\");\n               pal_img_n = 4;\n               for (i=0; i < c.length; ++i)\n                  palette[i*4+3] = get8u(s);\n            } else {\n               if (!(s->img_n & 1)) return e(\"tRNS with alpha\",\"Corrupt PNG\");\n               if (c.length != (stbi__uint32) s->img_n*2) return e(\"bad tRNS len\",\"Corrupt PNG\");\n               has_trans = 1;\n               for (k=0; k < s->img_n; ++k)\n                  tc[k] = (stbi__uint8) get16(s); // non 8-bit images will be larger\n            }\n            break;\n         }\n\n         case PNG_TYPE('I','D','A','T'): {\n            if (first) return e(\"first not IHDR\", \"Corrupt PNG\");\n            if (pal_img_n && !pal_len) return e(\"no PLTE\",\"Corrupt PNG\");\n            if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }\n            if (ioff + c.length > idata_limit) {\n               stbi__uint8 *p;\n               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;\n               while (ioff + c.length > idata_limit)\n                  idata_limit *= 2;\n               p = (stbi__uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e(\"outofmem\", \"Out of memory\");\n               z->idata = p;\n            }\n            if (!getn(s, z->idata+ioff,c.length)) return e(\"outofdata\",\"Corrupt PNG\");\n            ioff += c.length;\n            break;\n         }\n\n         case PNG_TYPE('I','E','N','D'): {\n            stbi__uint32 raw_len;\n            if (first) return e(\"first not IHDR\", \"Corrupt PNG\");\n            if (scan != SCAN_load) return 1;\n            if (z->idata == NULL) return e(\"no IDAT\",\"Corrupt PNG\");\n            z->expanded = (stbi__uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);\n            if (z->expanded == NULL) return 0; // zlib should set error\n            free(z->idata); z->idata = NULL;\n            if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)\n               s->img_out_n = s->img_n+1;\n            else\n               s->img_out_n = s->img_n;\n            if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;\n            if (has_trans)\n               if (!compute_transparency(z, tc, s->img_out_n)) return 0;\n            if (iphone && s->img_out_n > 2)\n               stbi_de_iphone(z);\n            if (pal_img_n) {\n               // pal_img_n == 3 or 4\n               s->img_n = pal_img_n; // record the actual colors we had\n               s->img_out_n = pal_img_n;\n               if (req_comp >= 3) s->img_out_n = req_comp;\n               if (!expand_palette(z, palette, pal_len, s->img_out_n))\n                  return 0;\n            }\n            free(z->expanded); z->expanded = NULL;\n            return 1;\n         }\n\n         default:\n            // if critical, fail\n            if (first) return e(\"first not IHDR\", \"Corrupt PNG\");\n            if ((c.type & (1 << 29)) == 0) {\n               #ifndef STBI_NO_FAILURE_STRINGS\n               // not threadsafe\n               static char invalid_chunk[] = \"XXXX chunk not known\";\n               invalid_chunk[0] = (stbi__uint8) (c.type >> 24);\n               invalid_chunk[1] = (stbi__uint8) (c.type >> 16);\n               invalid_chunk[2] = (stbi__uint8) (c.type >>  8);\n               invalid_chunk[3] = (stbi__uint8) (c.type >>  0);\n               #endif\n               return e(invalid_chunk, \"PNG not supported: unknown chunk type\");\n            }\n            skip(s, c.length);\n            break;\n      }\n      // end of chunk, read and skip CRC\n      get32(s);\n   }\n}\n\nstatic unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)\n{\n   unsigned char *result=NULL;\n   if (req_comp < 0 || req_comp > 4) return epuc(\"bad req_comp\", \"Internal error\");\n   if (parse_png_file(p, SCAN_load, req_comp)) {\n      result = p->out;\n      p->out = NULL;\n      if (req_comp && req_comp != p->s->img_out_n) {\n         result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);\n         p->s->img_out_n = req_comp;\n         if (result == NULL) return result;\n      }\n      *x = p->s->img_x;\n      *y = p->s->img_y;\n      if (n) *n = p->s->img_n;\n   }\n   free(p->out);      p->out      = NULL;\n   free(p->expanded); p->expanded = NULL;\n   free(p->idata);    p->idata    = NULL;\n\n   return result;\n}\n\nstatic unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   png p;\n   p.s = s;\n   return do_png(&p, x,y,comp,req_comp);\n}\n\nstatic int stbi_png_test(stbi *s)\n{\n   int r;\n   r = check_png_header(s);\n   stbi_rewind(s);\n   return r;\n}\n\nstatic int stbi_png_info_raw(png *p, int *x, int *y, int *comp)\n{\n   if (!parse_png_file(p, SCAN_header, 0)) {\n      stbi_rewind( p->s );\n      return 0;\n   }\n   if (x) *x = p->s->img_x;\n   if (y) *y = p->s->img_y;\n   if (comp) *comp = p->s->img_n;\n   return 1;\n}\n\nstatic int      stbi_png_info(stbi *s, int *x, int *y, int *comp)\n{\n   png p;\n   p.s = s;\n   return stbi_png_info_raw(&p, x, y, comp);\n}\n\n// Microsoft/Windows BMP image\n\nstatic int bmp_test(stbi *s)\n{\n   int sz;\n   if (get8(s) != 'B') return 0;\n   if (get8(s) != 'M') return 0;\n   get32le(s); // discard filesize\n   get16le(s); // discard reserved\n   get16le(s); // discard reserved\n   get32le(s); // discard data offset\n   sz = get32le(s);\n   if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;\n   return 0;\n}\n\nstatic int stbi_bmp_test(stbi *s)\n{\n   int r = bmp_test(s);\n   stbi_rewind(s);\n   return r;\n}\n\n\n// returns 0..31 for the highest set bit\nstatic int high_bit(unsigned int z)\n{\n   int n=0;\n   if (z == 0) return -1;\n   if (z >= 0x10000) n += 16, z >>= 16;\n   if (z >= 0x00100) n +=  8, z >>=  8;\n   if (z >= 0x00010) n +=  4, z >>=  4;\n   if (z >= 0x00004) n +=  2, z >>=  2;\n   if (z >= 0x00002) n +=  1, z >>=  1;\n   return n;\n}\n\nstatic int bitcount(unsigned int a)\n{\n   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2\n   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4\n   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits\n   a = (a + (a >> 8)); // max 16 per 8 bits\n   a = (a + (a >> 16)); // max 32 per 8 bits\n   return a & 0xff;\n}\n\nstatic int shiftsigned(int v, int shift, int bits)\n{\n   int result;\n   int z=0;\n\n   if (shift < 0) v <<= -shift;\n   else v >>= shift;\n   result = v;\n\n   z = bits;\n   while (z < 8) {\n      result += v >> z;\n      z += bits;\n   }\n   return result;\n}\n\nstatic stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__uint8 *out;\n   unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;\n   stbi_uc pal[256][4];\n   int psize=0,i,j,compress=0,width;\n   int bpp, flip_vertically, pad, target, offset, hsz;\n   if (get8(s) != 'B' || get8(s) != 'M') return epuc(\"not BMP\", \"Corrupt BMP\");\n   get32le(s); // discard filesize\n   get16le(s); // discard reserved\n   get16le(s); // discard reserved\n   offset = get32le(s);\n   hsz = get32le(s);\n   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc(\"unknown BMP\", \"BMP type not supported: unknown\");\n   if (hsz == 12) {\n      s->img_x = get16le(s);\n      s->img_y = get16le(s);\n   } else {\n      s->img_x = get32le(s);\n      s->img_y = get32le(s);\n   }\n   if (get16le(s) != 1) return epuc(\"bad BMP\", \"bad BMP\");\n   bpp = get16le(s);\n   if (bpp == 1) return epuc(\"monochrome\", \"BMP type not supported: 1-bit\");\n   flip_vertically = ((int) s->img_y) > 0;\n   s->img_y = abs((int) s->img_y);\n   if (hsz == 12) {\n      if (bpp < 24)\n         psize = (offset - 14 - 24) / 3;\n   } else {\n      compress = get32le(s);\n      if (compress == 1 || compress == 2) return epuc(\"BMP RLE\", \"BMP type not supported: RLE\");\n      get32le(s); // discard sizeof\n      get32le(s); // discard hres\n      get32le(s); // discard vres\n      get32le(s); // discard colorsused\n      get32le(s); // discard max important\n      if (hsz == 40 || hsz == 56) {\n         if (hsz == 56) {\n            get32le(s);\n            get32le(s);\n            get32le(s);\n            get32le(s);\n         }\n         if (bpp == 16 || bpp == 32) {\n            mr = mg = mb = 0;\n            if (compress == 0) {\n               if (bpp == 32) {\n                  mr = 0xffu << 16;\n                  mg = 0xffu <<  8;\n                  mb = 0xffu <<  0;\n                  ma = 0xffu << 24;\n                  fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255\n                  STBI_NOTUSED(fake_a);\n               } else {\n                  mr = 31u << 10;\n                  mg = 31u <<  5;\n                  mb = 31u <<  0;\n               }\n            } else if (compress == 3) {\n               mr = get32le(s);\n               mg = get32le(s);\n               mb = get32le(s);\n               // not documented, but generated by photoshop and handled by mspaint\n               if (mr == mg && mg == mb) {\n                  // ?!?!?\n                  return epuc(\"bad BMP\", \"bad BMP\");\n               }\n            } else\n               return epuc(\"bad BMP\", \"bad BMP\");\n         }\n      } else {\n         assert(hsz == 108);\n         mr = get32le(s);\n         mg = get32le(s);\n         mb = get32le(s);\n         ma = get32le(s);\n         get32le(s); // discard color space\n         for (i=0; i < 12; ++i)\n            get32le(s); // discard color space parameters\n      }\n      if (bpp < 16)\n         psize = (offset - 14 - hsz) >> 2;\n   }\n   s->img_n = ma ? 4 : 3;\n   if (req_comp && req_comp >= 3) // we can directly decode 3 or 4\n      target = req_comp;\n   else\n      target = s->img_n; // if they want monochrome, we'll post-convert\n   out = (stbi_uc *) malloc(target * s->img_x * s->img_y);\n   if (!out) return epuc(\"outofmem\", \"Out of memory\");\n   if (bpp < 16) {\n      int z=0;\n      if (psize == 0 || psize > 256) { free(out); return epuc(\"invalid\", \"Corrupt BMP\"); }\n      for (i=0; i < psize; ++i) {\n         pal[i][2] = get8u(s);\n         pal[i][1] = get8u(s);\n         pal[i][0] = get8u(s);\n         if (hsz != 12) get8(s);\n         pal[i][3] = 255;\n      }\n      skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));\n      if (bpp == 4) width = (s->img_x + 1) >> 1;\n      else if (bpp == 8) width = s->img_x;\n      else { free(out); return epuc(\"bad bpp\", \"Corrupt BMP\"); }\n      pad = (-width)&3;\n      for (j=0; j < (int) s->img_y; ++j) {\n         for (i=0; i < (int) s->img_x; i += 2) {\n            int v=get8(s),v2=0;\n            if (bpp == 4) {\n               v2 = v & 15;\n               v >>= 4;\n            }\n            out[z++] = pal[v][0];\n            out[z++] = pal[v][1];\n            out[z++] = pal[v][2];\n            if (target == 4) out[z++] = 255;\n            if (i+1 == (int) s->img_x) break;\n            v = (bpp == 8) ? get8(s) : v2;\n            out[z++] = pal[v][0];\n            out[z++] = pal[v][1];\n            out[z++] = pal[v][2];\n            if (target == 4) out[z++] = 255;\n         }\n         skip(s, pad);\n      }\n   } else {\n      int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;\n      int z = 0;\n      int easy=0;\n      skip(s, offset - 14 - hsz);\n      if (bpp == 24) width = 3 * s->img_x;\n      else if (bpp == 16) width = 2*s->img_x;\n      else /* bpp = 32 and pad = 0 */ width=0;\n      pad = (-width) & 3;\n      if (bpp == 24) {\n         easy = 1;\n      } else if (bpp == 32) {\n         if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)\n            easy = 2;\n      }\n      if (!easy) {\n         if (!mr || !mg || !mb) { free(out); return epuc(\"bad masks\", \"Corrupt BMP\"); }\n         // right shift amt to put high bit in position #7\n         rshift = high_bit(mr)-7; rcount = bitcount(mr);\n         gshift = high_bit(mg)-7; gcount = bitcount(mg);\n         bshift = high_bit(mb)-7; bcount = bitcount(mb);\n         ashift = high_bit(ma)-7; acount = bitcount(ma);\n      }\n      for (j=0; j < (int) s->img_y; ++j) {\n         if (easy) {\n            for (i=0; i < (int) s->img_x; ++i) {\n               int a;\n               out[z+2] = get8u(s);\n               out[z+1] = get8u(s);\n               out[z+0] = get8u(s);\n               z += 3;\n               a = (easy == 2 ? get8(s) : 255);\n               if (target == 4) out[z++] = (stbi__uint8) a;\n            }\n         } else {\n            for (i=0; i < (int) s->img_x; ++i) {\n               stbi__uint32 v = (stbi__uint32) (bpp == 16 ? get16le(s) : get32le(s));\n               int a;\n               out[z++] = (stbi__uint8) shiftsigned(v & mr, rshift, rcount);\n               out[z++] = (stbi__uint8) shiftsigned(v & mg, gshift, gcount);\n               out[z++] = (stbi__uint8) shiftsigned(v & mb, bshift, bcount);\n               a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);\n               if (target == 4) out[z++] = (stbi__uint8) a; \n            }\n         }\n         skip(s, pad);\n      }\n   }\n   if (flip_vertically) {\n      stbi_uc t;\n      for (j=0; j < (int) s->img_y>>1; ++j) {\n         stbi_uc *p1 = out +      j     *s->img_x*target;\n         stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;\n         for (i=0; i < (int) s->img_x*target; ++i) {\n            t = p1[i], p1[i] = p2[i], p2[i] = t;\n         }\n      }\n   }\n\n   if (req_comp && req_comp != target) {\n      out = convert_format(out, target, req_comp, s->img_x, s->img_y);\n      if (out == NULL) return out; // convert_format frees input on failure\n   }\n\n   *x = s->img_x;\n   *y = s->img_y;\n   if (comp) *comp = s->img_n;\n   return out;\n}\n\nstatic stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)\n{\n   return bmp_load(s, x,y,comp,req_comp);\n}\n\n\n// Targa Truevision - TGA\n// by Jonathan Dummer\n\nstatic int tga_info(stbi *s, int *x, int *y, int *comp)\n{\n    int tga_w, tga_h, tga_comp;\n    int sz;\n    get8u(s);                   // discard Offset\n    sz = get8u(s);              // color type\n    if( sz > 1 ) {\n        stbi_rewind(s);\n        return 0;      // only RGB or indexed allowed\n    }\n    sz = get8u(s);              // image type\n    // only RGB or grey allowed, +/- RLE\n    if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;\n    skip(s,9);\n    tga_w = get16le(s);\n    if( tga_w < 1 ) {\n        stbi_rewind(s);\n        return 0;   // test width\n    }\n    tga_h = get16le(s);\n    if( tga_h < 1 ) {\n        stbi_rewind(s);\n        return 0;   // test height\n    }\n    sz = get8(s);               // bits per pixel\n    // only RGB or RGBA or grey allowed\n    if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {\n        stbi_rewind(s);\n        return 0;\n    }\n    tga_comp = sz;\n    if (x) *x = tga_w;\n    if (y) *y = tga_h;\n    if (comp) *comp = tga_comp / 8;\n    return 1;                   // seems to have passed everything\n}\n\nint stbi_tga_info(stbi *s, int *x, int *y, int *comp)\n{\n    return tga_info(s, x, y, comp);\n}\n\nstatic int tga_test(stbi *s)\n{\n   int sz;\n   get8u(s);      //   discard Offset\n   sz = get8u(s);   //   color type\n   if ( sz > 1 ) return 0;   //   only RGB or indexed allowed\n   sz = get8u(s);   //   image type\n   if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0;   //   only RGB or grey allowed, +/- RLE\n   get16(s);      //   discard palette start\n   get16(s);      //   discard palette length\n   get8(s);         //   discard bits per palette color entry\n   get16(s);      //   discard x origin\n   get16(s);      //   discard y origin\n   if ( get16(s) < 1 ) return 0;      //   test width\n   if ( get16(s) < 1 ) return 0;      //   test height\n   sz = get8(s);   //   bits per pixel\n   if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0;   //   only RGB or RGBA or grey allowed\n   return 1;      //   seems to have passed everything\n}\n\nstatic int stbi_tga_test(stbi *s)\n{\n   int res = tga_test(s);\n   stbi_rewind(s);\n   return res;\n}\n\nstatic stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   //   read in the TGA header stuff\n   int tga_offset = get8u(s);\n   int tga_indexed = get8u(s);\n   int tga_image_type = get8u(s);\n   int tga_is_RLE = 0;\n   int tga_palette_start = get16le(s);\n   int tga_palette_len = get16le(s);\n   int tga_palette_bits = get8u(s);\n   int tga_x_origin = get16le(s);\n   int tga_y_origin = get16le(s);\n   int tga_width = get16le(s);\n   int tga_height = get16le(s);\n   int tga_bits_per_pixel = get8u(s);\n   int tga_comp = tga_bits_per_pixel / 8;\n   int tga_inverted = get8u(s);\n   //   image data\n   unsigned char *tga_data;\n   unsigned char *tga_palette = NULL;\n   int i, j;\n   unsigned char raw_data[4];\n   int RLE_count = 0;\n   int RLE_repeating = 0;\n   int read_next_pixel = 1;\n\n   //   do a tiny bit of precessing\n   if ( tga_image_type >= 8 )\n   {\n      tga_image_type -= 8;\n      tga_is_RLE = 1;\n   }\n   /* int tga_alpha_bits = tga_inverted & 15; */\n   tga_inverted = 1 - ((tga_inverted >> 5) & 1);\n\n   //   error check\n   if ( //(tga_indexed) ||\n      (tga_width < 1) || (tga_height < 1) ||\n      (tga_image_type < 1) || (tga_image_type > 3) ||\n      ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&\n      (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))\n      )\n   {\n      return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA\n   }\n\n   //   If I'm paletted, then I'll use the number of bits from the palette\n   if ( tga_indexed )\n   {\n      tga_comp = tga_palette_bits / 8;\n   }\n\n   //   tga info\n   *x = tga_width;\n   *y = tga_height;\n   if (comp) *comp = tga_comp;\n\n   tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );\n   if (!tga_data) return epuc(\"outofmem\", \"Out of memory\");\n\n   //   skip to the data's starting position (offset usually = 0)\n   skip(s, tga_offset );\n\n   if ( !tga_indexed && !tga_is_RLE) {\n      for (i=0; i < tga_height; ++i) {\n         int y = tga_inverted ? tga_height -i - 1 : i;\n         stbi__uint8 *tga_row = tga_data + y*tga_width*tga_comp;\n         getn(s, tga_row, tga_width * tga_comp);\n      }\n   } else  {\n      //   do I need to load a palette?\n      if ( tga_indexed)\n      {\n         //   any data to skip? (offset usually = 0)\n         skip(s, tga_palette_start );\n         //   load the palette\n         tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );\n         if (!tga_palette) {\n            free(tga_data);\n            return epuc(\"outofmem\", \"Out of memory\");\n         }\n         if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {\n            free(tga_data);\n            free(tga_palette);\n            return epuc(\"bad palette\", \"Corrupt TGA\");\n         }\n      }\n      //   load the data\n      for (i=0; i < tga_width * tga_height; ++i)\n      {\n         //   if I'm in RLE mode, do I need to get a RLE chunk?\n         if ( tga_is_RLE )\n         {\n            if ( RLE_count == 0 )\n            {\n               //   yep, get the next byte as a RLE command\n               int RLE_cmd = get8u(s);\n               RLE_count = 1 + (RLE_cmd & 127);\n               RLE_repeating = RLE_cmd >> 7;\n               read_next_pixel = 1;\n            } else if ( !RLE_repeating )\n            {\n               read_next_pixel = 1;\n            }\n         } else\n         {\n            read_next_pixel = 1;\n         }\n         //   OK, if I need to read a pixel, do it now\n         if ( read_next_pixel )\n         {\n            //   load however much data we did have\n            if ( tga_indexed )\n            {\n               //   read in 1 byte, then perform the lookup\n               int pal_idx = get8u(s);\n               if ( pal_idx >= tga_palette_len )\n               {\n                  //   invalid index\n                  pal_idx = 0;\n               }\n               pal_idx *= tga_bits_per_pixel / 8;\n               for (j = 0; j*8 < tga_bits_per_pixel; ++j)\n               {\n                  raw_data[j] = tga_palette[pal_idx+j];\n               }\n            } else\n            {\n               //   read in the data raw\n               for (j = 0; j*8 < tga_bits_per_pixel; ++j)\n               {\n                  raw_data[j] = get8u(s);\n               }\n            }\n            //   clear the reading flag for the next pixel\n            read_next_pixel = 0;\n         } // end of reading a pixel\n\n         // copy data\n         for (j = 0; j < tga_comp; ++j)\n           tga_data[i*tga_comp+j] = raw_data[j];\n\n         //   in case we're in RLE mode, keep counting down\n         --RLE_count;\n      }\n      //   do I need to invert the image?\n      if ( tga_inverted )\n      {\n         for (j = 0; j*2 < tga_height; ++j)\n         {\n            int index1 = j * tga_width * req_comp;\n            int index2 = (tga_height - 1 - j) * tga_width * req_comp;\n            for (i = tga_width * req_comp; i > 0; --i)\n            {\n               unsigned char temp = tga_data[index1];\n               tga_data[index1] = tga_data[index2];\n               tga_data[index2] = temp;\n               ++index1;\n               ++index2;\n            }\n         }\n      }\n      //   clear my palette, if I had one\n      if ( tga_palette != NULL )\n      {\n         free( tga_palette );\n      }\n   }\n\n   // swap RGB\n   if (tga_comp >= 3)\n   {\n      unsigned char* tga_pixel = tga_data;\n      for (i=0; i < tga_width * tga_height; ++i)\n      {\n         unsigned char temp = tga_pixel[0];\n         tga_pixel[0] = tga_pixel[2];\n         tga_pixel[2] = temp;\n         tga_pixel += tga_comp;\n      }\n   }\n\n   // convert to target component count\n   if (req_comp && req_comp != tga_comp)\n      tga_data = convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);\n\n   //   the things I do to get rid of an error message, and yet keep\n   //   Microsoft's C compilers happy... [8^(\n   tga_palette_start = tga_palette_len = tga_palette_bits =\n         tga_x_origin = tga_y_origin = 0;\n   //   OK, done\n   return tga_data;\n}\n\nstatic stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   return tga_load(s,x,y,comp,req_comp);\n}\n\n\n// *************************************************************************************************\n// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB\n\nstatic int psd_test(stbi *s)\n{\n   if (get32(s) != 0x38425053) return 0;   // \"8BPS\"\n   else return 1;\n}\n\nstatic int stbi_psd_test(stbi *s)\n{\n   int r = psd_test(s);\n   stbi_rewind(s);\n   return r;\n}\n\nstatic stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   int   pixelCount;\n   int channelCount, compression;\n   int channel, i, count, len;\n   int w,h;\n   stbi__uint8 *out;\n\n   // Check identifier\n   if (get32(s) != 0x38425053)   // \"8BPS\"\n      return epuc(\"not PSD\", \"Corrupt PSD image\");\n\n   // Check file type version.\n   if (get16(s) != 1)\n      return epuc(\"wrong version\", \"Unsupported version of PSD image\");\n\n   // Skip 6 reserved bytes.\n   skip(s, 6 );\n\n   // Read the number of channels (R, G, B, A, etc).\n   channelCount = get16(s);\n   if (channelCount < 0 || channelCount > 16)\n      return epuc(\"wrong channel count\", \"Unsupported number of channels in PSD image\");\n\n   // Read the rows and columns of the image.\n   h = get32(s);\n   w = get32(s);\n   \n   // Make sure the depth is 8 bits.\n   if (get16(s) != 8)\n      return epuc(\"unsupported bit depth\", \"PSD bit depth is not 8 bit\");\n\n   // Make sure the color mode is RGB.\n   // Valid options are:\n   //   0: Bitmap\n   //   1: Grayscale\n   //   2: Indexed color\n   //   3: RGB color\n   //   4: CMYK color\n   //   7: Multichannel\n   //   8: Duotone\n   //   9: Lab color\n   if (get16(s) != 3)\n      return epuc(\"wrong color format\", \"PSD is not in RGB color format\");\n\n   // Skip the Mode Data.  (It's the palette for indexed color; other info for other modes.)\n   skip(s,get32(s) );\n\n   // Skip the image resources.  (resolution, pen tool paths, etc)\n   skip(s, get32(s) );\n\n   // Skip the reserved data.\n   skip(s, get32(s) );\n\n   // Find out if the data is compressed.\n   // Known values:\n   //   0: no compression\n   //   1: RLE compressed\n   compression = get16(s);\n   if (compression > 1)\n      return epuc(\"bad compression\", \"PSD has an unknown compression format\");\n\n   // Create the destination image.\n   out = (stbi_uc *) malloc(4 * w*h);\n   if (!out) return epuc(\"outofmem\", \"Out of memory\");\n   pixelCount = w*h;\n\n   // Initialize the data to zero.\n   //memset( out, 0, pixelCount * 4 );\n   \n   // Finally, the image data.\n   if (compression) {\n      // RLE as used by .PSD and .TIFF\n      // Loop until you get the number of unpacked bytes you are expecting:\n      //     Read the next source byte into n.\n      //     If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.\n      //     Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.\n      //     Else if n is 128, noop.\n      // Endloop\n\n      // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,\n      // which we're going to just skip.\n      skip(s, h * channelCount * 2 );\n\n      // Read the RLE data by channel.\n      for (channel = 0; channel < 4; channel++) {\n         stbi__uint8 *p;\n         \n         p = out+channel;\n         if (channel >= channelCount) {\n            // Fill this channel with default data.\n            for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;\n         } else {\n            // Read the RLE data.\n            count = 0;\n            while (count < pixelCount) {\n               len = get8(s);\n               if (len == 128) {\n                  // No-op.\n               } else if (len < 128) {\n                  // Copy next len+1 bytes literally.\n                  len++;\n                  count += len;\n                  while (len) {\n                     *p = get8u(s);\n                     p += 4;\n                     len--;\n                  }\n               } else if (len > 128) {\n                  stbi__uint8   val;\n                  // Next -len+1 bytes in the dest are replicated from next source byte.\n                  // (Interpret len as a negative 8-bit int.)\n                  len ^= 0x0FF;\n                  len += 2;\n                  val = get8u(s);\n                  count += len;\n                  while (len) {\n                     *p = val;\n                     p += 4;\n                     len--;\n                  }\n               }\n            }\n         }\n      }\n      \n   } else {\n      // We're at the raw image data.  It's each channel in order (Red, Green, Blue, Alpha, ...)\n      // where each channel consists of an 8-bit value for each pixel in the image.\n      \n      // Read the data by channel.\n      for (channel = 0; channel < 4; channel++) {\n         stbi__uint8 *p;\n         \n         p = out + channel;\n         if (channel > channelCount) {\n            // Fill this channel with default data.\n            for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;\n         } else {\n            // Read the data.\n            for (i = 0; i < pixelCount; i++)\n               *p = get8u(s), p += 4;\n         }\n      }\n   }\n\n   if (req_comp && req_comp != 4) {\n      out = convert_format(out, 4, req_comp, w, h);\n      if (out == NULL) return out; // convert_format frees input on failure\n   }\n\n   if (comp) *comp = channelCount;\n   *y = h;\n   *x = w;\n   \n   return out;\n}\n\nstatic stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   return psd_load(s,x,y,comp,req_comp);\n}\n\n// *************************************************************************************************\n// Softimage PIC loader\n// by Tom Seddon\n//\n// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format\n// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/\n\nstatic int pic_is4(stbi *s,const char *str)\n{\n   int i;\n   for (i=0; i<4; ++i)\n      if (get8(s) != (stbi_uc)str[i])\n         return 0;\n\n   return 1;\n}\n\nstatic int pic_test(stbi *s)\n{\n   int i;\n\n   if (!pic_is4(s,\"\\x53\\x80\\xF6\\x34\"))\n      return 0;\n\n   for(i=0;i<84;++i)\n      get8(s);\n\n   if (!pic_is4(s,\"PICT\"))\n      return 0;\n\n   return 1;\n}\n\ntypedef struct\n{\n   stbi_uc size,type,channel;\n} pic_packet_t;\n\nstatic stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)\n{\n   int mask=0x80, i;\n\n   for (i=0; i<4; ++i, mask>>=1) {\n      if (channel & mask) {\n         if (at_eof(s)) return epuc(\"bad file\",\"PIC file too short\");\n         dest[i]=get8u(s);\n      }\n   }\n\n   return dest;\n}\n\nstatic void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)\n{\n   int mask=0x80,i;\n\n   for (i=0;i<4; ++i, mask>>=1)\n      if (channel&mask)\n         dest[i]=src[i];\n}\n\nstatic stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)\n{\n   int act_comp=0,num_packets=0,y,chained;\n   pic_packet_t packets[10];\n\n   // this will (should...) cater for even some bizarre stuff like having data\n    // for the same channel in multiple packets.\n   do {\n      pic_packet_t *packet;\n\n      if (num_packets==sizeof(packets)/sizeof(packets[0]))\n         return epuc(\"bad format\",\"too many packets\");\n\n      packet = &packets[num_packets++];\n\n      chained = get8(s);\n      packet->size    = get8u(s);\n      packet->type    = get8u(s);\n      packet->channel = get8u(s);\n\n      act_comp |= packet->channel;\n\n      if (at_eof(s))          return epuc(\"bad file\",\"file too short (reading packets)\");\n      if (packet->size != 8)  return epuc(\"bad format\",\"packet isn't 8bpp\");\n   } while (chained);\n\n   *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?\n\n   for(y=0; y<height; ++y) {\n      int packet_idx;\n\n      for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {\n         pic_packet_t *packet = &packets[packet_idx];\n         stbi_uc *dest = result+y*width*4;\n\n         switch (packet->type) {\n            default:\n               return epuc(\"bad format\",\"packet has bad compression type\");\n\n            case 0: {//uncompressed\n               int x;\n\n               for(x=0;x<width;++x, dest+=4)\n                  if (!pic_readval(s,packet->channel,dest))\n                     return 0;\n               break;\n            }\n\n            case 1://Pure RLE\n               {\n                  int left=width, i;\n\n                  while (left>0) {\n                     stbi_uc count,value[4];\n\n                     count=get8u(s);\n                     if (at_eof(s))   return epuc(\"bad file\",\"file too short (pure read count)\");\n\n                     if (count > left)\n                        count = (stbi__uint8) left;\n\n                     if (!pic_readval(s,packet->channel,value))  return 0;\n\n                     for(i=0; i<count; ++i,dest+=4)\n                        pic_copyval(packet->channel,dest,value);\n                     left -= count;\n                  }\n               }\n               break;\n\n            case 2: {//Mixed RLE\n               int left=width;\n               while (left>0) {\n                  int count = get8(s), i;\n                  if (at_eof(s))  return epuc(\"bad file\",\"file too short (mixed read count)\");\n\n                  if (count >= 128) { // Repeated\n                     stbi_uc value[4];\n                     int i;\n\n                     if (count==128)\n                        count = get16(s);\n                     else\n                        count -= 127;\n                     if (count > left)\n                        return epuc(\"bad file\",\"scanline overrun\");\n\n                     if (!pic_readval(s,packet->channel,value))\n                        return 0;\n\n                     for(i=0;i<count;++i, dest += 4)\n                        pic_copyval(packet->channel,dest,value);\n                  } else { // Raw\n                     ++count;\n                     if (count>left) return epuc(\"bad file\",\"scanline overrun\");\n\n                     for(i=0;i<count;++i, dest+=4)\n                        if (!pic_readval(s,packet->channel,dest))\n                           return 0;\n                  }\n                  left-=count;\n               }\n               break;\n            }\n         }\n      }\n   }\n\n   return result;\n}\n\nstatic stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)\n{\n   stbi_uc *result;\n   int i, x,y;\n\n   for (i=0; i<92; ++i)\n      get8(s);\n\n   x = get16(s);\n   y = get16(s);\n   if (at_eof(s))  return epuc(\"bad file\",\"file too short (pic header)\");\n   if ((1 << 28) / x < y) return epuc(\"too large\", \"Image too large to decode\");\n\n   get32(s); //skip `ratio'\n   get16(s); //skip `fields'\n   get16(s); //skip `pad'\n\n   // intermediate buffer is RGBA\n   result = (stbi_uc *) malloc(x*y*4);\n   memset(result, 0xff, x*y*4);\n\n   if (!pic_load2(s,x,y,comp, result)) {\n      free(result);\n      result=0;\n   }\n   *px = x;\n   *py = y;\n   if (req_comp == 0) req_comp = *comp;\n   result=convert_format(result,4,req_comp,x,y);\n\n   return result;\n}\n\nstatic int stbi_pic_test(stbi *s)\n{\n   int r = pic_test(s);\n   stbi_rewind(s);\n   return r;\n}\n\nstatic stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   return pic_load(s,x,y,comp,req_comp);\n}\n\n// *************************************************************************************************\n// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb\ntypedef struct stbi_gif_lzw_struct {\n   stbi__int16 prefix;\n   stbi__uint8 first;\n   stbi__uint8 suffix;\n} stbi_gif_lzw;\n\ntypedef struct stbi_gif_struct\n{\n   int w,h;\n   stbi_uc *out;                 // output buffer (always 4 components)\n   int flags, bgindex, ratio, transparent, eflags;\n   stbi__uint8  pal[256][4];\n   stbi__uint8 lpal[256][4];\n   stbi_gif_lzw codes[4096];\n   stbi__uint8 *color_table;\n   int parse, step;\n   int lflags;\n   int start_x, start_y;\n   int max_x, max_y;\n   int cur_x, cur_y;\n   int line_size;\n} stbi_gif;\n\nstatic int gif_test(stbi *s)\n{\n   int sz;\n   if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;\n   sz = get8(s);\n   if (sz != '9' && sz != '7') return 0;\n   if (get8(s) != 'a') return 0;\n   return 1;\n}\n\nstatic int stbi_gif_test(stbi *s)\n{\n   int r = gif_test(s);\n   stbi_rewind(s);\n   return r;\n}\n\nstatic void stbi_gif_parse_colortable(stbi *s, stbi__uint8 pal[256][4], int num_entries, int transp)\n{\n   int i;\n   for (i=0; i < num_entries; ++i) {\n      pal[i][2] = get8u(s);\n      pal[i][1] = get8u(s);\n      pal[i][0] = get8u(s);\n      pal[i][3] = transp ? 0 : 255;\n   }   \n}\n\nstatic int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)\n{\n   stbi__uint8 version;\n   if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')\n      return e(\"not GIF\", \"Corrupt GIF\");\n\n   version = get8u(s);\n   if (version != '7' && version != '9')    return e(\"not GIF\", \"Corrupt GIF\");\n   if (get8(s) != 'a')                      return e(\"not GIF\", \"Corrupt GIF\");\n \n   failure_reason = \"\";\n   g->w = get16le(s);\n   g->h = get16le(s);\n   g->flags = get8(s);\n   g->bgindex = get8(s);\n   g->ratio = get8(s);\n   g->transparent = -1;\n\n   if (comp != 0) *comp = 4;  // can't actually tell whether it's 3 or 4 until we parse the comments\n\n   if (is_info) return 1;\n\n   if (g->flags & 0x80)\n      stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);\n\n   return 1;\n}\n\nstatic int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)\n{\n   stbi_gif g;   \n   if (!stbi_gif_header(s, &g, comp, 1)) {\n      stbi_rewind( s );\n      return 0;\n   }\n   if (x) *x = g.w;\n   if (y) *y = g.h;\n   return 1;\n}\n\nstatic void stbi_out_gif_code(stbi_gif *g, stbi__uint16 code)\n{\n   stbi__uint8 *p, *c;\n\n   // recurse to decode the prefixes, since the linked-list is backwards,\n   // and working backwards through an interleaved image would be nasty\n   if (g->codes[code].prefix >= 0)\n      stbi_out_gif_code(g, g->codes[code].prefix);\n\n   if (g->cur_y >= g->max_y) return;\n  \n   p = &g->out[g->cur_x + g->cur_y];\n   c = &g->color_table[g->codes[code].suffix * 4];\n\n   if (c[3] >= 128) {\n      p[0] = c[2];\n      p[1] = c[1];\n      p[2] = c[0];\n      p[3] = c[3];\n   }\n   g->cur_x += 4;\n\n   if (g->cur_x >= g->max_x) {\n      g->cur_x = g->start_x;\n      g->cur_y += g->step;\n\n      while (g->cur_y >= g->max_y && g->parse > 0) {\n         g->step = (1 << g->parse) * g->line_size;\n         g->cur_y = g->start_y + (g->step >> 1);\n         --g->parse;\n      }\n   }\n}\n\nstatic stbi__uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)\n{\n   stbi__uint8 lzw_cs;\n   stbi__int32 len, code;\n   stbi__uint32 first;\n   stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;\n   stbi_gif_lzw *p;\n\n   lzw_cs = get8u(s);\n   clear = 1 << lzw_cs;\n   first = 1;\n   codesize = lzw_cs + 1;\n   codemask = (1 << codesize) - 1;\n   bits = 0;\n   valid_bits = 0;\n   for (code = 0; code < clear; code++) {\n      g->codes[code].prefix = -1;\n      g->codes[code].first = (stbi__uint8) code;\n      g->codes[code].suffix = (stbi__uint8) code;\n   }\n\n   // support no starting clear code\n   avail = clear+2;\n   oldcode = -1;\n\n   len = 0;\n   for(;;) {\n      if (valid_bits < codesize) {\n         if (len == 0) {\n            len = get8(s); // start new block\n            if (len == 0) \n               return g->out;\n         }\n         --len;\n         bits |= (stbi__int32) get8(s) << valid_bits;\n         valid_bits += 8;\n      } else {\n         stbi__int32 code = bits & codemask;\n         bits >>= codesize;\n         valid_bits -= codesize;\n         // @OPTIMIZE: is there some way we can accelerate the non-clear path?\n         if (code == clear) {  // clear code\n            codesize = lzw_cs + 1;\n            codemask = (1 << codesize) - 1;\n            avail = clear + 2;\n            oldcode = -1;\n            first = 0;\n         } else if (code == clear + 1) { // end of stream code\n            skip(s, len);\n            while ((len = get8(s)) > 0)\n               skip(s,len);\n            return g->out;\n         } else if (code <= avail) {\n            if (first) return epuc(\"no clear code\", \"Corrupt GIF\");\n\n            if (oldcode >= 0) {\n               p = &g->codes[avail++];\n               if (avail > 4096)        return epuc(\"too many codes\", \"Corrupt GIF\");\n               p->prefix = (stbi__int16) oldcode;\n               p->first = g->codes[oldcode].first;\n               p->suffix = (code == avail) ? p->first : g->codes[code].first;\n            } else if (code == avail)\n               return epuc(\"illegal code in raster\", \"Corrupt GIF\");\n\n            stbi_out_gif_code(g, (stbi__uint16) code);\n\n            if ((avail & codemask) == 0 && avail <= 0x0FFF) {\n               codesize++;\n               codemask = (1 << codesize) - 1;\n            }\n\n            oldcode = code;\n         } else {\n            return epuc(\"illegal code in raster\", \"Corrupt GIF\");\n         }\n      } \n   }\n}\n\nstatic void stbi_fill_gif_background(stbi_gif *g)\n{\n   int i;\n   stbi__uint8 *c = g->pal[g->bgindex];\n   // @OPTIMIZE: write a dword at a time\n   for (i = 0; i < g->w * g->h * 4; i += 4) {\n      stbi__uint8 *p  = &g->out[i];\n      p[0] = c[2];\n      p[1] = c[1];\n      p[2] = c[0];\n      p[3] = c[3];\n   }\n}\n\n// this function is designed to support animated gifs, although stb_image doesn't support it\nstatic stbi__uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)\n{\n   int i;\n   stbi__uint8 *old_out = 0;\n\n   if (g->out == 0) {\n      if (!stbi_gif_header(s, g, comp,0))     return 0; // failure_reason set by stbi_gif_header\n      g->out = (stbi__uint8 *) malloc(4 * g->w * g->h);\n      if (g->out == 0)                      return epuc(\"outofmem\", \"Out of memory\");\n      stbi_fill_gif_background(g);\n   } else {\n      // animated-gif-only path\n      if (((g->eflags & 0x1C) >> 2) == 3) {\n         old_out = g->out;\n         g->out = (stbi__uint8 *) malloc(4 * g->w * g->h);\n         if (g->out == 0)                   return epuc(\"outofmem\", \"Out of memory\");\n         memcpy(g->out, old_out, g->w*g->h*4);\n      }\n   }\n    \n   for (;;) {\n      switch (get8(s)) {\n         case 0x2C: /* Image Descriptor */\n         {\n            stbi__int32 x, y, w, h;\n            stbi__uint8 *o;\n\n            x = get16le(s);\n            y = get16le(s);\n            w = get16le(s);\n            h = get16le(s);\n            if (((x + w) > (g->w)) || ((y + h) > (g->h)))\n               return epuc(\"bad Image Descriptor\", \"Corrupt GIF\");\n\n            g->line_size = g->w * 4;\n            g->start_x = x * 4;\n            g->start_y = y * g->line_size;\n            g->max_x   = g->start_x + w * 4;\n            g->max_y   = g->start_y + h * g->line_size;\n            g->cur_x   = g->start_x;\n            g->cur_y   = g->start_y;\n\n            g->lflags = get8(s);\n\n            if (g->lflags & 0x40) {\n               g->step = 8 * g->line_size; // first interlaced spacing\n               g->parse = 3;\n            } else {\n               g->step = g->line_size;\n               g->parse = 0;\n            }\n\n            if (g->lflags & 0x80) {\n               stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);\n               g->color_table = (stbi__uint8 *) g->lpal;       \n            } else if (g->flags & 0x80) {\n               for (i=0; i < 256; ++i)  // @OPTIMIZE: reset only the previous transparent\n                  g->pal[i][3] = 255; \n               if (g->transparent >= 0 && (g->eflags & 0x01))\n                  g->pal[g->transparent][3] = 0;\n               g->color_table = (stbi__uint8 *) g->pal;\n            } else\n               return epuc(\"missing color table\", \"Corrupt GIF\");\n   \n            o = stbi_process_gif_raster(s, g);\n            if (o == NULL) return NULL;\n\n            if (req_comp && req_comp != 4)\n               o = convert_format(o, 4, req_comp, g->w, g->h);\n            return o;\n         }\n\n         case 0x21: // Comment Extension.\n         {\n            int len;\n            if (get8(s) == 0xF9) { // Graphic Control Extension.\n               len = get8(s);\n               if (len == 4) {\n                  g->eflags = get8(s);\n                  get16le(s); // delay\n                  g->transparent = get8(s);\n               } else {\n                  skip(s, len);\n                  break;\n               }\n            }\n            while ((len = get8(s)) != 0)\n               skip(s, len);\n            break;\n         }\n\n         case 0x3B: // gif stream termination code\n            return (stbi__uint8 *) 1;\n\n         default:\n            return epuc(\"unknown code\", \"Corrupt GIF\");\n      }\n   }\n}\n\nstatic stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__uint8 *u = 0;\n   stbi_gif g={0};\n\n   u = stbi_gif_load_next(s, &g, comp, req_comp);\n   if (u == (void *) 1) u = 0;  // end of animated gif marker\n   if (u) {\n      *x = g.w;\n      *y = g.h;\n   }\n\n   return u;\n}\n\nstatic int stbi_gif_info(stbi *s, int *x, int *y, int *comp)\n{\n   return stbi_gif_info_raw(s,x,y,comp);\n}\n\n\n// *************************************************************************************************\n// Radiance RGBE HDR loader\n// originally by Nicolas Schulz\n#ifndef STBI_NO_HDR\nstatic int hdr_test(stbi *s)\n{\n   const char *signature = \"#?RADIANCE\\n\";\n   int i;\n   for (i=0; signature[i]; ++i)\n      if (get8(s) != signature[i])\n         return 0;\n   return 1;\n}\n\nstatic int stbi_hdr_test(stbi* s)\n{\n   int r = hdr_test(s);\n   stbi_rewind(s);\n   return r;\n}\n\n#define HDR_BUFLEN  1024\nstatic char *hdr_gettoken(stbi *z, char *buffer)\n{\n   int len=0;\n   char c = '\\0';\n\n   c = (char) get8(z);\n\n   while (!at_eof(z) && c != '\\n') {\n      buffer[len++] = c;\n      if (len == HDR_BUFLEN-1) {\n         // flush to end of line\n         while (!at_eof(z) && get8(z) != '\\n')\n            ;\n         break;\n      }\n      c = (char) get8(z);\n   }\n\n   buffer[len] = 0;\n   return buffer;\n}\n\nstatic void hdr_convert(float *output, stbi_uc *input, int req_comp)\n{\n   if ( input[3] != 0 ) {\n      float f1;\n      // Exponent\n      f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));\n      if (req_comp <= 2)\n         output[0] = (input[0] + input[1] + input[2]) * f1 / 3;\n      else {\n         output[0] = input[0] * f1;\n         output[1] = input[1] * f1;\n         output[2] = input[2] * f1;\n      }\n      if (req_comp == 2) output[1] = 1;\n      if (req_comp == 4) output[3] = 1;\n   } else {\n      switch (req_comp) {\n         case 4: output[3] = 1; /* fallthrough */\n         case 3: output[0] = output[1] = output[2] = 0;\n                 break;\n         case 2: output[1] = 1; /* fallthrough */\n         case 1: output[0] = 0;\n                 break;\n      }\n   }\n}\n\nstatic float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   char buffer[HDR_BUFLEN];\n   char *token;\n   int valid = 0;\n   int width, height;\n   stbi_uc *scanline;\n   float *hdr_data;\n   int len;\n   unsigned char count, value;\n   int i, j, k, c1,c2, z;\n\n\n   // Check identifier\n   if (strcmp(hdr_gettoken(s,buffer), \"#?RADIANCE\") != 0)\n      return epf(\"not HDR\", \"Corrupt HDR image\");\n   \n   // Parse header\n   for(;;) {\n      token = hdr_gettoken(s,buffer);\n      if (token[0] == 0) break;\n      if (strcmp(token, \"FORMAT=32-bit_rle_rgbe\") == 0) valid = 1;\n   }\n\n   if (!valid)    return epf(\"unsupported format\", \"Unsupported HDR format\");\n\n   // Parse width and height\n   // can't use sscanf() if we're not using stdio!\n   token = hdr_gettoken(s,buffer);\n   if (strncmp(token, \"-Y \", 3))  return epf(\"unsupported data layout\", \"Unsupported HDR format\");\n   token += 3;\n   height = (int) strtol(token, &token, 10);\n   while (*token == ' ') ++token;\n   if (strncmp(token, \"+X \", 3))  return epf(\"unsupported data layout\", \"Unsupported HDR format\");\n   token += 3;\n   width = (int) strtol(token, NULL, 10);\n\n   *x = width;\n   *y = height;\n\n   *comp = 3;\n   if (req_comp == 0) req_comp = 3;\n\n   // Read data\n   hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));\n\n   // Load image data\n   // image data is stored as some number of sca\n   if ( width < 8 || width >= 32768) {\n      // Read flat data\n      for (j=0; j < height; ++j) {\n         for (i=0; i < width; ++i) {\n            stbi_uc rgbe[4];\n           main_decode_loop:\n            getn(s, rgbe, 4);\n            hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);\n         }\n      }\n   } else {\n      // Read RLE-encoded data\n      scanline = NULL;\n\n      for (j = 0; j < height; ++j) {\n         c1 = get8(s);\n         c2 = get8(s);\n         len = get8(s);\n         if (c1 != 2 || c2 != 2 || (len & 0x80)) {\n            // not run-length encoded, so we have to actually use THIS data as a decoded\n            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)\n            stbi__uint8 rgbe[4];\n            rgbe[0] = (stbi__uint8) c1;\n            rgbe[1] = (stbi__uint8) c2;\n            rgbe[2] = (stbi__uint8) len;\n            rgbe[3] = (stbi__uint8) get8u(s);\n            hdr_convert(hdr_data, rgbe, req_comp);\n            i = 1;\n            j = 0;\n            free(scanline);\n            goto main_decode_loop; // yes, this makes no sense\n         }\n         len <<= 8;\n         len |= get8(s);\n         if (len != width) { free(hdr_data); free(scanline); return epf(\"invalid decoded scanline length\", \"corrupt HDR\"); }\n         if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);\n            \n         for (k = 0; k < 4; ++k) {\n            i = 0;\n            while (i < width) {\n               count = get8u(s);\n               if (count > 128) {\n                  // Run\n                  value = get8u(s);\n                  count -= 128;\n                  for (z = 0; z < count; ++z)\n                     scanline[i++ * 4 + k] = value;\n               } else {\n                  // Dump\n                  for (z = 0; z < count; ++z)\n                     scanline[i++ * 4 + k] = get8u(s);\n               }\n            }\n         }\n         for (i=0; i < width; ++i)\n            hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);\n      }\n      free(scanline);\n   }\n\n   return hdr_data;\n}\n\nstatic float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)\n{\n   return hdr_load(s,x,y,comp,req_comp);\n}\n\nstatic int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)\n{\n   char buffer[HDR_BUFLEN];\n   char *token;\n   int valid = 0;\n\n   if (strcmp(hdr_gettoken(s,buffer), \"#?RADIANCE\") != 0) {\n       stbi_rewind( s );\n       return 0;\n   }\n\n   for(;;) {\n      token = hdr_gettoken(s,buffer);\n      if (token[0] == 0) break;\n      if (strcmp(token, \"FORMAT=32-bit_rle_rgbe\") == 0) valid = 1;\n   }\n\n   if (!valid) {\n       stbi_rewind( s );\n       return 0;\n   }\n   token = hdr_gettoken(s,buffer);\n   if (strncmp(token, \"-Y \", 3)) {\n       stbi_rewind( s );\n       return 0;\n   }\n   token += 3;\n   *y = (int) strtol(token, &token, 10);\n   while (*token == ' ') ++token;\n   if (strncmp(token, \"+X \", 3)) {\n       stbi_rewind( s );\n       return 0;\n   }\n   token += 3;\n   *x = (int) strtol(token, NULL, 10);\n   *comp = 3;\n   return 1;\n}\n#endif // STBI_NO_HDR\n\nstatic int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)\n{\n   int hsz;\n   if (get8(s) != 'B' || get8(s) != 'M') {\n       stbi_rewind( s );\n       return 0;\n   }\n   skip(s,12);\n   hsz = get32le(s);\n   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {\n       stbi_rewind( s );\n       return 0;\n   }\n   if (hsz == 12) {\n      *x = get16le(s);\n      *y = get16le(s);\n   } else {\n      *x = get32le(s);\n      *y = get32le(s);\n   }\n   if (get16le(s) != 1) {\n       stbi_rewind( s );\n       return 0;\n   }\n   *comp = get16le(s) / 8;\n   return 1;\n}\n\nstatic int stbi_psd_info(stbi *s, int *x, int *y, int *comp)\n{\n   int channelCount;\n   if (get32(s) != 0x38425053) {\n       stbi_rewind( s );\n       return 0;\n   }\n   if (get16(s) != 1) {\n       stbi_rewind( s );\n       return 0;\n   }\n   skip(s, 6);\n   channelCount = get16(s);\n   if (channelCount < 0 || channelCount > 16) {\n       stbi_rewind( s );\n       return 0;\n   }\n   *y = get32(s);\n   *x = get32(s);\n   if (get16(s) != 8) {\n       stbi_rewind( s );\n       return 0;\n   }\n   if (get16(s) != 3) {\n       stbi_rewind( s );\n       return 0;\n   }\n   *comp = 4;\n   return 1;\n}\n\nstatic int stbi_pic_info(stbi *s, int *x, int *y, int *comp)\n{\n   int act_comp=0,num_packets=0,chained;\n   pic_packet_t packets[10];\n\n   skip(s, 92);\n\n   *x = get16(s);\n   *y = get16(s);\n   if (at_eof(s))  return 0;\n   if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {\n       stbi_rewind( s );\n       return 0;\n   }\n\n   skip(s, 8);\n\n   do {\n      pic_packet_t *packet;\n\n      if (num_packets==sizeof(packets)/sizeof(packets[0]))\n         return 0;\n\n      packet = &packets[num_packets++];\n      chained = get8(s);\n      packet->size    = get8u(s);\n      packet->type    = get8u(s);\n      packet->channel = get8u(s);\n      act_comp |= packet->channel;\n\n      if (at_eof(s)) {\n          stbi_rewind( s );\n          return 0;\n      }\n      if (packet->size != 8) {\n          stbi_rewind( s );\n          return 0;\n      }\n   } while (chained);\n\n   *comp = (act_comp & 0x10 ? 4 : 3);\n\n   return 1;\n}\n\nstatic int stbi_info_main(stbi *s, int *x, int *y, int *comp)\n{\n   if (stbi_jpeg_info(s, x, y, comp))\n       return 1;\n   if (stbi_png_info(s, x, y, comp))\n       return 1;\n   if (stbi_gif_info(s, x, y, comp))\n       return 1;\n   if (stbi_bmp_info(s, x, y, comp))\n       return 1;\n   if (stbi_psd_info(s, x, y, comp))\n       return 1;\n   if (stbi_pic_info(s, x, y, comp))\n       return 1;\n   #ifndef STBI_NO_HDR\n   if (stbi_hdr_info(s, x, y, comp))\n       return 1;\n   #endif\n   // test tga last because it's a crappy test!\n   if (stbi_tga_info(s, x, y, comp))\n       return 1;\n   return e(\"unknown image type\", \"Image not of any known type, or corrupt\");\n}\n\n#ifndef STBI_NO_STDIO\nint stbi_info(char const *filename, int *x, int *y, int *comp)\n{\n    FILE *f = fopen(filename, \"rb\");\n    int result;\n    if (!f) return e(\"can't fopen\", \"Unable to open file\");\n    result = stbi_info_from_file(f, x, y, comp);\n    fclose(f);\n    return result;\n}\n\nint stbi_info_from_file(FILE *f, int *x, int *y, int *comp)\n{\n   int r;\n   stbi s;\n   long pos = ftell(f);\n   start_file(&s, f);\n   r = stbi_info_main(&s,x,y,comp);\n   fseek(f,pos,SEEK_SET);\n   return r;\n}\n#endif // !STBI_NO_STDIO\n\nint stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\n{\n   stbi s;\n   start_mem(&s,buffer,len);\n   return stbi_info_main(&s,x,y,comp);\n}\n\nint stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)\n{\n   stbi s;\n   start_callbacks(&s, (stbi_io_callbacks *) c, user);\n   return stbi_info_main(&s,x,y,comp);\n}\n\n#endif // STBI_HEADER_FILE_ONLY\n\n#if !defined(STBI_NO_STDIO) && defined(_MSC_VER) && _MSC_VER >= 1400\n#pragma warning(pop)\n#endif\n\n\n/*\n   revision history:\n      1.35 (2014-05-27)\n             various warnings\n             fix broken STBI_SIMD path\n             fix bug where stbi_load_from_file no longer left file pointer in correct place\n             fix broken non-easy path for 32-bit BMP (possibly never used)\n             TGA optimization by Arseny Kapoulkine\n      1.34 (unknown)\n             use STBI_NOTUSED in resample_row_generic(), fix one more leak in tga failure case\n      1.33 (2011-07-14)\n             make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements\n      1.32 (2011-07-13)\n             support for \"info\" function for all supported filetypes (SpartanJ)\n      1.31 (2011-06-20)\n             a few more leak fixes, bug in PNG handling (SpartanJ)\n      1.30 (2011-06-11)\n             added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)\n             removed deprecated format-specific test/load functions\n             removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway\n             error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)\n             fix inefficiency in decoding 32-bit BMP (David Woo)\n      1.29 (2010-08-16)\n             various warning fixes from Aurelien Pocheville \n      1.28 (2010-08-01)\n             fix bug in GIF palette transparency (SpartanJ)\n      1.27 (2010-08-01)\n             cast-to-stbi__uint8 to fix warnings\n      1.26 (2010-07-24)\n             fix bug in file buffering for PNG reported by SpartanJ\n      1.25 (2010-07-17)\n             refix trans_data warning (Won Chun)\n      1.24 (2010-07-12)\n             perf improvements reading from files on platforms with lock-heavy fgetc()\n             minor perf improvements for jpeg\n             deprecated type-specific functions so we'll get feedback if they're needed\n             attempt to fix trans_data warning (Won Chun)\n      1.23   fixed bug in iPhone support\n      1.22 (2010-07-10)\n             removed image *writing* support\n             stbi_info support from Jetro Lauha\n             GIF support from Jean-Marc Lienher\n             iPhone PNG-extensions from James Brown\n             warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva)\n      1.21   fix use of 'stbi__uint8' in header (reported by jon blow)\n      1.20   added support for Softimage PIC, by Tom Seddon\n      1.19   bug in interlaced PNG corruption check (found by ryg)\n      1.18 2008-08-02\n             fix a threading bug (local mutable static)\n      1.17   support interlaced PNG\n      1.16   major bugfix - convert_format converted one too many pixels\n      1.15   initialize some fields for thread safety\n      1.14   fix threadsafe conversion bug\n             header-file-only version (#define STBI_HEADER_FILE_ONLY before including)\n      1.13   threadsafe\n      1.12   const qualifiers in the API\n      1.11   Support installable IDCT, colorspace conversion routines\n      1.10   Fixes for 64-bit (don't use \"unsigned long\")\n             optimized upsampling by Fabian \"ryg\" Giesen\n      1.09   Fix format-conversion for PSD code (bad global variables!)\n      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz\n      1.07   attempt to fix C++ warning/errors again\n      1.06   attempt to fix C++ warning/errors again\n      1.05   fix TGA loading to return correct *comp and use good luminance calc\n      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free\n      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR\n      1.02   support for (subset of) HDR files, float interface for preferred access to them\n      1.01   fix bug: possible bug in handling right-side up bmps... not sure\n             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all\n      1.00   interface to zlib that skips zlib header\n      0.99   correct handling of alpha in palette\n      0.98   TGA loader by lonesock; dynamically add loaders (untested)\n      0.97   jpeg errors on too large a file; also catch another malloc failure\n      0.96   fix detection of invalid v value - particleman@mollyrocket forum\n      0.95   during header scan, seek to markers in case of padding\n      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same\n      0.93   handle jpegtran output; verbose errors\n      0.92   read 4,8,16,24,32-bit BMP files of several formats\n      0.91   output 24-bit Windows 3.0 BMP files\n      0.90   fix a few more warnings; bump version number to approach 1.0\n      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd\n      0.60   fix compiling as c++\n      0.59   fix warnings: merge Dave Moore's -Wall fixes\n      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian\n      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available\n      0.56   fix bug: zlib uncompressed mode len vs. nlen\n      0.55   fix bug: restart_interval not initialized to 0\n      0.54   allow NULL for 'int *comp'\n      0.53   fix bug in png 3->4; speedup png decoding\n      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments\n      0.51   obey req_comp requests, 1-component jpegs return as 1-component,\n             on 'test' only check type, not whether we support this variant\n      0.50   first released version\n*/\n"
  },
  {
    "path": "deprecated/stb_image_resize.h",
    "content": "/* stb_image_resize - v0.97 - public domain image resizing\n   by Jorge L Rodriguez (@VinoBS) - 2014\n   http://github.com/nothings/stb\n\n   Written with emphasis on usability, portability, and efficiency. (No\n   SIMD or threads, so it be easily outperformed by libs that use those.)\n   Only scaling and translation is supported, no rotations or shears.\n   Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation.\n\n   COMPILING & LINKING\n      In one C/C++ file that #includes this file, do this:\n         #define STB_IMAGE_RESIZE_IMPLEMENTATION\n      before the #include. That will create the implementation in that file.\n\n   QUICKSTART\n      stbir_resize_uint8(      input_pixels , in_w , in_h , 0,\n                               output_pixels, out_w, out_h, 0, num_channels)\n      stbir_resize_float(...)\n      stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0,\n                               output_pixels, out_w, out_h, 0,\n                               num_channels , alpha_chan  , 0)\n      stbir_resize_uint8_srgb_edgemode(\n                               input_pixels , in_w , in_h , 0,\n                               output_pixels, out_w, out_h, 0,\n                               num_channels , alpha_chan  , 0, STBIR_EDGE_CLAMP)\n                                                            // WRAP/REFLECT/ZERO\n\n   FULL API\n      See the \"header file\" section of the source for API documentation.\n\n   ADDITIONAL DOCUMENTATION\n\n      SRGB & FLOATING POINT REPRESENTATION\n         The sRGB functions presume IEEE floating point. If you do not have\n         IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use\n         a slower implementation.\n\n      MEMORY ALLOCATION\n         The resize functions here perform a single memory allocation using\n         malloc. To control the memory allocation, before the #include that\n         triggers the implementation, do:\n\n            #define STBIR_MALLOC(size,context) ...\n            #define STBIR_FREE(ptr,context)   ...\n\n         Each resize function makes exactly one call to malloc/free, so to use\n         temp memory, store the temp memory in the context and return that.\n\n      ASSERT\n         Define STBIR_ASSERT(boolval) to override assert() and not use assert.h\n\n      OPTIMIZATION\n         Define STBIR_SATURATE_INT to compute clamp values in-range using\n         integer operations instead of float operations. This may be faster\n         on some platforms.\n\n      DEFAULT FILTERS\n         For functions which don't provide explicit control over what filters\n         to use, you can change the compile-time defaults with\n\n            #define STBIR_DEFAULT_FILTER_UPSAMPLE     STBIR_FILTER_something\n            #define STBIR_DEFAULT_FILTER_DOWNSAMPLE   STBIR_FILTER_something\n\n         See stbir_filter in the header-file section for the list of filters.\n\n      NEW FILTERS\n         A number of 1D filter kernels are used. For a list of\n         supported filters see the stbir_filter enum. To add a new filter,\n         write a filter function and add it to stbir__filter_info_table.\n\n      PROGRESS\n         For interactive use with slow resize operations, you can install\n         a progress-report callback:\n\n            #define STBIR_PROGRESS_REPORT(val)   some_func(val)\n\n         The parameter val is a float which goes from 0 to 1 as progress is made.\n\n         For example:\n\n            static void my_progress_report(float progress);\n            #define STBIR_PROGRESS_REPORT(val) my_progress_report(val)\n\n            #define STB_IMAGE_RESIZE_IMPLEMENTATION\n            #include \"stb_image_resize.h\"\n\n            static void my_progress_report(float progress)\n            {\n               printf(\"Progress: %f%%\\n\", progress*100);\n            }\n\n      MAX CHANNELS\n         If your image has more than 64 channels, define STBIR_MAX_CHANNELS\n         to the max you'll have.\n\n      ALPHA CHANNEL\n         Most of the resizing functions provide the ability to control how\n         the alpha channel of an image is processed. The important things\n         to know about this:\n\n         1. The best mathematically-behaved version of alpha to use is\n         called \"premultiplied alpha\", in which the other color channels\n         have had the alpha value multiplied in. If you use premultiplied\n         alpha, linear filtering (such as image resampling done by this\n         library, or performed in texture units on GPUs) does the \"right\n         thing\". While premultiplied alpha is standard in the movie CGI\n         industry, it is still uncommon in the videogame/real-time world.\n\n         If you linearly filter non-premultiplied alpha, strange effects\n         occur. (For example, the 50/50 average of 99% transparent bright green\n         and 1% transparent black produces 50% transparent dark green when\n         non-premultiplied, whereas premultiplied it produces 50%\n         transparent near-black. The former introduces green energy\n         that doesn't exist in the source image.)\n\n         2. Artists should not edit premultiplied-alpha images; artists\n         want non-premultiplied alpha images. Thus, art tools generally output\n         non-premultiplied alpha images.\n\n         3. You will get best results in most cases by converting images\n         to premultiplied alpha before processing them mathematically.\n\n         4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the\n         resizer does not do anything special for the alpha channel;\n         it is resampled identically to other channels. This produces\n         the correct results for premultiplied-alpha images, but produces\n         less-than-ideal results for non-premultiplied-alpha images.\n\n         5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED,\n         then the resizer weights the contribution of input pixels\n         based on their alpha values, or, equivalently, it multiplies\n         the alpha value into the color channels, resamples, then divides\n         by the resultant alpha value. Input pixels which have alpha=0 do\n         not contribute at all to output pixels unless _all_ of the input\n         pixels affecting that output pixel have alpha=0, in which case\n         the result for that pixel is the same as it would be without\n         STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for\n         input images in integer formats. For input images in float format,\n         input pixels with alpha=0 have no effect, and output pixels\n         which have alpha=0 will be 0 in all channels. (For float images,\n         you can manually achieve the same result by adding a tiny epsilon\n         value to the alpha channel of every image, and then subtracting\n         or clamping it at the end.)\n\n         6. You can suppress the behavior described in #5 and make\n         all-0-alpha pixels have 0 in all channels by #defining\n         STBIR_NO_ALPHA_EPSILON.\n\n         7. You can separately control whether the alpha channel is\n         interpreted as linear or affected by the colorspace. By default\n         it is linear; you almost never want to apply the colorspace.\n         (For example, graphics hardware does not apply sRGB conversion\n         to the alpha channel.)\n\n   CONTRIBUTORS\n      Jorge L Rodriguez: Implementation\n      Sean Barrett: API design, optimizations\n      Aras Pranckevicius: bugfix\n      Nathan Reed: warning fixes\n\n   REVISIONS\n      0.97 (2020-02-02) fixed warning\n      0.96 (2019-03-04) fixed warnings\n      0.95 (2017-07-23) fixed warnings\n      0.94 (2017-03-18) fixed warnings\n      0.93 (2017-03-03) fixed bug with certain combinations of heights\n      0.92 (2017-01-02) fix integer overflow on large (>2GB) images\n      0.91 (2016-04-02) fix warnings; fix handling of subpixel regions\n      0.90 (2014-09-17) first released version\n\n   LICENSE\n     See end of file for license information.\n\n   TODO\n      Don't decode all of the image data when only processing a partial tile\n      Don't use full-width decode buffers when only processing a partial tile\n      When processing wide images, break processing into tiles so data fits in L1 cache\n      Installable filters?\n      Resize that respects alpha test coverage\n         (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage:\n         https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp )\n*/\n\n#ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H\n#define STBIR_INCLUDE_STB_IMAGE_RESIZE_H\n\n#ifdef _MSC_VER\ntypedef unsigned char  stbir_uint8;\ntypedef unsigned short stbir_uint16;\ntypedef unsigned int   stbir_uint32;\n#else\n#include <stdint.h>\ntypedef uint8_t  stbir_uint8;\ntypedef uint16_t stbir_uint16;\ntypedef uint32_t stbir_uint32;\n#endif\n\n#ifndef STBIRDEF\n#ifdef STB_IMAGE_RESIZE_STATIC\n#define STBIRDEF static\n#else\n#ifdef __cplusplus\n#define STBIRDEF extern \"C\"\n#else\n#define STBIRDEF extern\n#endif\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Easy-to-use API:\n//\n//     * \"input pixels\" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4)\n//     * input_w is input image width (x-axis), input_h is input image height (y-axis)\n//     * stride is the offset between successive rows of image data in memory, in bytes. you can\n//       specify 0 to mean packed continuously in memory\n//     * alpha channel is treated identically to other channels.\n//     * colorspace is linear or sRGB as specified by function name\n//     * returned result is 1 for success or 0 in case of an error.\n//       #define STBIR_ASSERT() to trigger an assert on parameter validation errors.\n//     * Memory required grows approximately linearly with input and output size, but with\n//       discontinuities at input_w == output_w and input_h == output_h.\n//     * These functions use a \"default\" resampling filter defined at compile time. To change the filter,\n//       you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE\n//       and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API.\n\nSTBIRDEF int stbir_resize_uint8(     const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels);\n\nSTBIRDEF int stbir_resize_float(     const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels);\n\n\n// The following functions interpret image data as gamma-corrected sRGB.\n// Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel,\n// or otherwise provide the index of the alpha channel. Flags value\n// of 0 will probably do the right thing if you're not sure what\n// the flags mean.\n\n#define STBIR_ALPHA_CHANNEL_NONE       -1\n\n// Set this flag if your texture has premultiplied alpha. Otherwise, stbir will\n// use alpha-weighted resampling (effectively premultiplying, resampling,\n// then unpremultiplying).\n#define STBIR_FLAG_ALPHA_PREMULTIPLIED    (1 << 0)\n// The specified alpha channel should be handled as gamma-corrected value even\n// when doing sRGB operations.\n#define STBIR_FLAG_ALPHA_USES_COLORSPACE  (1 << 1)\n\nSTBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels, int alpha_channel, int flags);\n\n\ntypedef enum\n{\n    STBIR_EDGE_CLAMP   = 1,\n    STBIR_EDGE_REFLECT = 2,\n    STBIR_EDGE_WRAP    = 3,\n    STBIR_EDGE_ZERO    = 4,\n} stbir_edge;\n\n// This function adds the ability to specify how requests to sample off the edge of the image are handled.\nSTBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                                    unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                              int num_channels, int alpha_channel, int flags,\n                                              stbir_edge edge_wrap_mode);\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Medium-complexity API\n//\n// This extends the easy-to-use API as follows:\n//\n//     * Alpha-channel can be processed separately\n//       * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE\n//         * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT)\n//         * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)\n//     * Filter can be selected explicitly\n//     * uint16 image type\n//     * sRGB colorspace available for all types\n//     * context parameter for passing to STBIR_MALLOC\n\ntypedef enum\n{\n    STBIR_FILTER_DEFAULT      = 0,  // use same filter type that easy-to-use API chooses\n    STBIR_FILTER_BOX          = 1,  // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios\n    STBIR_FILTER_TRIANGLE     = 2,  // On upsampling, produces same results as bilinear texture filtering\n    STBIR_FILTER_CUBICBSPLINE = 3,  // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque\n    STBIR_FILTER_CATMULLROM   = 4,  // An interpolating cubic spline\n    STBIR_FILTER_MITCHELL     = 5,  // Mitchell-Netrevalli filter with B=1/3, C=1/3\n} stbir_filter;\n\ntypedef enum\n{\n    STBIR_COLORSPACE_LINEAR,\n    STBIR_COLORSPACE_SRGB,\n\n    STBIR_MAX_COLORSPACES,\n} stbir_colorspace;\n\n// The following functions are all identical except for the type of the image data\n\nSTBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                               unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,\n                                         void *alloc_context);\n\nSTBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels  , int input_w , int input_h , int input_stride_in_bytes,\n                                               stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,\n                                         void *alloc_context);\n\nSTBIRDEF int stbir_resize_float_generic( const float *input_pixels         , int input_w , int input_h , int input_stride_in_bytes,\n                                               float *output_pixels        , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,\n                                         void *alloc_context);\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Full-complexity API\n//\n// This extends the medium API as follows:\n//\n//       * uint32 image type\n//     * not typesafe\n//     * separate filter types for each axis\n//     * separate edge modes for each axis\n//     * can specify scale explicitly for subpixel correctness\n//     * can specify image source tile using texture coordinates\n\ntypedef enum\n{\n    STBIR_TYPE_UINT8 ,\n    STBIR_TYPE_UINT16,\n    STBIR_TYPE_UINT32,\n    STBIR_TYPE_FLOAT ,\n\n    STBIR_MAX_TYPES\n} stbir_datatype;\n\nSTBIRDEF int stbir_resize(         const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,\n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context);\n\nSTBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,\n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float x_scale, float y_scale,\n                                   float x_offset, float y_offset);\n\nSTBIRDEF int stbir_resize_region(  const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,\n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float s0, float t0, float s1, float t1);\n// (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use.\n\n//\n//\n////   end header file   /////////////////////////////////////////////////////\n#endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H\n\n\n\n\n\n#ifdef STB_IMAGE_RESIZE_IMPLEMENTATION\n\n#ifndef STBIR_ASSERT\n#include <assert.h>\n#define STBIR_ASSERT(x) assert(x)\n#endif\n\n// For memset\n#include <string.h>\n\n#include <math.h>\n\n#ifndef STBIR_MALLOC\n#include <stdlib.h>\n// use comma operator to evaluate c, to avoid \"unused parameter\" warnings\n#define STBIR_MALLOC(size,c) ((void)(c), malloc(size))\n#define STBIR_FREE(ptr,c)    ((void)(c), free(ptr))\n#endif\n\n#ifndef _MSC_VER\n#ifdef __cplusplus\n#define stbir__inline inline\n#else\n#define stbir__inline\n#endif\n#else\n#define stbir__inline __forceinline\n#endif\n\n\n// should produce compiler error if size is wrong\ntypedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1];\n\n#ifdef _MSC_VER\n#define STBIR__NOTUSED(v)  (void)(v)\n#else\n#define STBIR__NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0]))\n\n#ifndef STBIR_DEFAULT_FILTER_UPSAMPLE\n#define STBIR_DEFAULT_FILTER_UPSAMPLE    STBIR_FILTER_CATMULLROM\n#endif\n\n#ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE\n#define STBIR_DEFAULT_FILTER_DOWNSAMPLE  STBIR_FILTER_MITCHELL\n#endif\n\n#ifndef STBIR_PROGRESS_REPORT\n#define STBIR_PROGRESS_REPORT(float_0_to_1)\n#endif\n\n#ifndef STBIR_MAX_CHANNELS\n#define STBIR_MAX_CHANNELS 64\n#endif\n\n#if STBIR_MAX_CHANNELS > 65536\n#error \"Too many channels; STBIR_MAX_CHANNELS must be no more than 65536.\"\n// because we store the indices in 16-bit variables\n#endif\n\n// This value is added to alpha just before premultiplication to avoid\n// zeroing out color values. It is equivalent to 2^-80. If you don't want\n// that behavior (it may interfere if you have floating point images with\n// very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to\n// disable it.\n#ifndef STBIR_ALPHA_EPSILON\n#define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20))\n#endif\n\n\n\n#ifdef _MSC_VER\n#define STBIR__UNUSED_PARAM(v)  (void)(v)\n#else\n#define STBIR__UNUSED_PARAM(v)  (void)sizeof(v)\n#endif\n\n// must match stbir_datatype\nstatic unsigned char stbir__type_size[] = {\n    1, // STBIR_TYPE_UINT8\n    2, // STBIR_TYPE_UINT16\n    4, // STBIR_TYPE_UINT32\n    4, // STBIR_TYPE_FLOAT\n};\n\n// Kernel function centered at 0\ntypedef float (stbir__kernel_fn)(float x, float scale);\ntypedef float (stbir__support_fn)(float scale);\n\ntypedef struct\n{\n    stbir__kernel_fn* kernel;\n    stbir__support_fn* support;\n} stbir__filter_info;\n\n// When upsampling, the contributors are which source pixels contribute.\n// When downsampling, the contributors are which destination pixels are contributed to.\ntypedef struct\n{\n    int n0; // First contributing pixel\n    int n1; // Last contributing pixel\n} stbir__contributors;\n\ntypedef struct\n{\n    const void* input_data;\n    int input_w;\n    int input_h;\n    int input_stride_bytes;\n\n    void* output_data;\n    int output_w;\n    int output_h;\n    int output_stride_bytes;\n\n    float s0, t0, s1, t1;\n\n    float horizontal_shift; // Units: output pixels\n    float vertical_shift;   // Units: output pixels\n    float horizontal_scale;\n    float vertical_scale;\n\n    int channels;\n    int alpha_channel;\n    stbir_uint32 flags;\n    stbir_datatype type;\n    stbir_filter horizontal_filter;\n    stbir_filter vertical_filter;\n    stbir_edge edge_horizontal;\n    stbir_edge edge_vertical;\n    stbir_colorspace colorspace;\n\n    stbir__contributors* horizontal_contributors;\n    float* horizontal_coefficients;\n\n    stbir__contributors* vertical_contributors;\n    float* vertical_coefficients;\n\n    int decode_buffer_pixels;\n    float* decode_buffer;\n\n    float* horizontal_buffer;\n\n    // cache these because ceil/floor are inexplicably showing up in profile\n    int horizontal_coefficient_width;\n    int vertical_coefficient_width;\n    int horizontal_filter_pixel_width;\n    int vertical_filter_pixel_width;\n    int horizontal_filter_pixel_margin;\n    int vertical_filter_pixel_margin;\n    int horizontal_num_contributors;\n    int vertical_num_contributors;\n\n    int ring_buffer_length_bytes;   // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter)\n    int ring_buffer_num_entries;    // Total number of entries in the ring buffer.\n    int ring_buffer_first_scanline;\n    int ring_buffer_last_scanline;\n    int ring_buffer_begin_index;    // first_scanline is at this index in the ring buffer\n    float* ring_buffer;\n\n    float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds.\n\n    int horizontal_contributors_size;\n    int horizontal_coefficients_size;\n    int vertical_contributors_size;\n    int vertical_coefficients_size;\n    int decode_buffer_size;\n    int horizontal_buffer_size;\n    int ring_buffer_size;\n    int encode_buffer_size;\n} stbir__info;\n\n\nstatic const float stbir__max_uint8_as_float  = 255.0f;\nstatic const float stbir__max_uint16_as_float = 65535.0f;\nstatic const double stbir__max_uint32_as_float = 4294967295.0;\n\n\nstatic stbir__inline int stbir__min(int a, int b)\n{\n    return a < b ? a : b;\n}\n\nstatic stbir__inline float stbir__saturate(float x)\n{\n    if (x < 0)\n        return 0;\n\n    if (x > 1)\n        return 1;\n\n    return x;\n}\n\n#ifdef STBIR_SATURATE_INT\nstatic stbir__inline stbir_uint8 stbir__saturate8(int x)\n{\n    if ((unsigned int) x <= 255)\n        return x;\n\n    if (x < 0)\n        return 0;\n\n    return 255;\n}\n\nstatic stbir__inline stbir_uint16 stbir__saturate16(int x)\n{\n    if ((unsigned int) x <= 65535)\n        return x;\n\n    if (x < 0)\n        return 0;\n\n    return 65535;\n}\n#endif\n\nstatic float stbir__srgb_uchar_to_linear_float[256] = {\n    0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f,\n    0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f,\n    0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f,\n    0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f,\n    0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f,\n    0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f,\n    0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f,\n    0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f,\n    0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f,\n    0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f,\n    0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f,\n    0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f,\n    0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f,\n    0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f,\n    0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f,\n    0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f,\n    0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f,\n    0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f,\n    0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f,\n    0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f,\n    0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f,\n    0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f,\n    0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f,\n    0.982251f, 0.991102f, 1.0f\n};\n\nstatic float stbir__srgb_to_linear(float f)\n{\n    if (f <= 0.04045f)\n        return f / 12.92f;\n    else\n        return (float)pow((f + 0.055f) / 1.055f, 2.4f);\n}\n\nstatic float stbir__linear_to_srgb(float f)\n{\n    if (f <= 0.0031308f)\n        return f * 12.92f;\n    else\n        return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f;\n}\n\n#ifndef STBIR_NON_IEEE_FLOAT\n// From https://gist.github.com/rygorous/2203834\n\ntypedef union\n{\n    stbir_uint32 u;\n    float f;\n} stbir__FP32;\n\nstatic const stbir_uint32 fp32_to_srgb8_tab4[104] = {\n    0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d,\n    0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a,\n    0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033,\n    0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067,\n    0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5,\n    0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2,\n    0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143,\n    0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af,\n    0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240,\n    0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300,\n    0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401,\n    0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559,\n    0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723,\n};\n\nstatic stbir_uint8 stbir__linear_to_srgb_uchar(float in)\n{\n    static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps\n    static const stbir__FP32 minval = { (127-13) << 23 };\n    stbir_uint32 tab,bias,scale,t;\n    stbir__FP32 f;\n\n    // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively.\n    // The tests are carefully written so that NaNs map to 0, same as in the reference\n    // implementation.\n    if (!(in > minval.f)) // written this way to catch NaNs\n        in = minval.f;\n    if (in > almostone.f)\n        in = almostone.f;\n\n    // Do the table lookup and unpack bias, scale\n    f.f = in;\n    tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20];\n    bias = (tab >> 16) << 9;\n    scale = tab & 0xffff;\n\n    // Grab next-highest mantissa bits and perform linear interpolation\n    t = (f.u >> 12) & 0xff;\n    return (unsigned char) ((bias + scale*t) >> 16);\n}\n\n#else\n// sRGB transition values, scaled by 1<<28\nstatic int stbir__srgb_offset_to_linear_scaled[256] =\n{\n            0,     40738,    122216,    203693,    285170,    366648,    448125,    529603,\n       611080,    692557,    774035,    855852,    942009,   1033024,   1128971,   1229926,\n      1335959,   1447142,   1563542,   1685229,   1812268,   1944725,   2082664,   2226148,\n      2375238,   2529996,   2690481,   2856753,   3028870,   3206888,   3390865,   3580856,\n      3776916,   3979100,   4187460,   4402049,   4622919,   4850123,   5083710,   5323731,\n      5570236,   5823273,   6082892,   6349140,   6622065,   6901714,   7188133,   7481369,\n      7781466,   8088471,   8402427,   8723380,   9051372,   9386448,   9728650,  10078021,\n     10434603,  10798439,  11169569,  11548036,  11933879,  12327139,  12727857,  13136073,\n     13551826,  13975156,  14406100,  14844697,  15290987,  15745007,  16206795,  16676389,\n     17153826,  17639142,  18132374,  18633560,  19142734,  19659934,  20185196,  20718552,\n     21260042,  21809696,  22367554,  22933648,  23508010,  24090680,  24681686,  25281066,\n     25888850,  26505076,  27129772,  27762974,  28404716,  29055026,  29713942,  30381490,\n     31057708,  31742624,  32436272,  33138682,  33849884,  34569912,  35298800,  36036568,\n     36783260,  37538896,  38303512,  39077136,  39859796,  40651528,  41452360,  42262316,\n     43081432,  43909732,  44747252,  45594016,  46450052,  47315392,  48190064,  49074096,\n     49967516,  50870356,  51782636,  52704392,  53635648,  54576432,  55526772,  56486700,\n     57456236,  58435408,  59424248,  60422780,  61431036,  62449032,  63476804,  64514376,\n     65561776,  66619028,  67686160,  68763192,  69850160,  70947088,  72053992,  73170912,\n     74297864,  75434880,  76581976,  77739184,  78906536,  80084040,  81271736,  82469648,\n     83677792,  84896192,  86124888,  87363888,  88613232,  89872928,  91143016,  92423512,\n     93714432,  95015816,  96327688,  97650056,  98982952, 100326408, 101680440, 103045072,\n    104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544,\n    115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832,\n    127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528,\n    140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968,\n    154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184,\n    168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992,\n    183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968,\n    199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480,\n    215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656,\n    232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464,\n    250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664,\n};\n\nstatic stbir_uint8 stbir__linear_to_srgb_uchar(float f)\n{\n    int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp\n    int v = 0;\n    int i;\n\n    // Refine the guess with a short binary search.\n    i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +  64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +  32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +  16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n\n    return (stbir_uint8) v;\n}\n#endif\n\nstatic float stbir__filter_trapezoid(float x, float scale)\n{\n    float halfscale = scale / 2;\n    float t = 0.5f + halfscale;\n    STBIR_ASSERT(scale <= 1);\n\n    x = (float)fabs(x);\n\n    if (x >= t)\n        return 0;\n    else\n    {\n        float r = 0.5f - halfscale;\n        if (x <= r)\n            return 1;\n        else\n            return (t - x) / scale;\n    }\n}\n\nstatic float stbir__support_trapezoid(float scale)\n{\n    STBIR_ASSERT(scale <= 1);\n    return 0.5f + scale / 2;\n}\n\nstatic float stbir__filter_triangle(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x <= 1.0f)\n        return 1 - x;\n    else\n        return 0;\n}\n\nstatic float stbir__filter_cubic(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x < 1.0f)\n        return (4 + x*x*(3*x - 6))/6;\n    else if (x < 2.0f)\n        return (8 + x*(-12 + x*(6 - x)))/6;\n\n    return (0.0f);\n}\n\nstatic float stbir__filter_catmullrom(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x < 1.0f)\n        return 1 - x*x*(2.5f - 1.5f*x);\n    else if (x < 2.0f)\n        return 2 - x*(4 + x*(0.5f*x - 2.5f));\n\n    return (0.0f);\n}\n\nstatic float stbir__filter_mitchell(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x < 1.0f)\n        return (16 + x*x*(21 * x - 36))/18;\n    else if (x < 2.0f)\n        return (32 + x*(-60 + x*(36 - 7*x)))/18;\n\n    return (0.0f);\n}\n\nstatic float stbir__support_zero(float s)\n{\n    STBIR__UNUSED_PARAM(s);\n    return 0;\n}\n\nstatic float stbir__support_one(float s)\n{\n    STBIR__UNUSED_PARAM(s);\n    return 1;\n}\n\nstatic float stbir__support_two(float s)\n{\n    STBIR__UNUSED_PARAM(s);\n    return 2;\n}\n\nstatic stbir__filter_info stbir__filter_info_table[] = {\n        { NULL,                     stbir__support_zero },\n        { stbir__filter_trapezoid,  stbir__support_trapezoid },\n        { stbir__filter_triangle,   stbir__support_one },\n        { stbir__filter_cubic,      stbir__support_two },\n        { stbir__filter_catmullrom, stbir__support_two },\n        { stbir__filter_mitchell,   stbir__support_two },\n};\n\nstbir__inline static int stbir__use_upsampling(float ratio)\n{\n    return ratio > 1;\n}\n\nstbir__inline static int stbir__use_width_upsampling(stbir__info* stbir_info)\n{\n    return stbir__use_upsampling(stbir_info->horizontal_scale);\n}\n\nstbir__inline static int stbir__use_height_upsampling(stbir__info* stbir_info)\n{\n    return stbir__use_upsampling(stbir_info->vertical_scale);\n}\n\n// This is the maximum number of input samples that can affect an output sample\n// with the given filter\nstatic int stbir__get_filter_pixel_width(stbir_filter filter, float scale)\n{\n    STBIR_ASSERT(filter != 0);\n    STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));\n\n    if (stbir__use_upsampling(scale))\n        return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2);\n    else\n        return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale);\n}\n\n// This is how much to expand buffers to account for filters seeking outside\n// the image boundaries.\nstatic int stbir__get_filter_pixel_margin(stbir_filter filter, float scale)\n{\n    return stbir__get_filter_pixel_width(filter, scale) / 2;\n}\n\nstatic int stbir__get_coefficient_width(stbir_filter filter, float scale)\n{\n    if (stbir__use_upsampling(scale))\n        return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2);\n    else\n        return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2);\n}\n\nstatic int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size)\n{\n    if (stbir__use_upsampling(scale))\n        return output_size;\n    else\n        return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2);\n}\n\nstatic int stbir__get_total_horizontal_coefficients(stbir__info* info)\n{\n    return info->horizontal_num_contributors\n         * stbir__get_coefficient_width      (info->horizontal_filter, info->horizontal_scale);\n}\n\nstatic int stbir__get_total_vertical_coefficients(stbir__info* info)\n{\n    return info->vertical_num_contributors\n         * stbir__get_coefficient_width      (info->vertical_filter, info->vertical_scale);\n}\n\nstatic stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n)\n{\n    return &contributors[n];\n}\n\n// For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample,\n// if you change it here change it there too.\nstatic float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c)\n{\n    int width = stbir__get_coefficient_width(filter, scale);\n    return &coefficients[width*n + c];\n}\n\nstatic int stbir__edge_wrap_slow(stbir_edge edge, int n, int max)\n{\n    switch (edge)\n    {\n    case STBIR_EDGE_ZERO:\n        return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later\n\n    case STBIR_EDGE_CLAMP:\n        if (n < 0)\n            return 0;\n\n        if (n >= max)\n            return max - 1;\n\n        return n; // NOTREACHED\n\n    case STBIR_EDGE_REFLECT:\n    {\n        if (n < 0)\n        {\n            if (n < max)\n                return -n;\n            else\n                return max - 1;\n        }\n\n        if (n >= max)\n        {\n            int max2 = max * 2;\n            if (n >= max2)\n                return 0;\n            else\n                return max2 - n - 1;\n        }\n\n        return n; // NOTREACHED\n    }\n\n    case STBIR_EDGE_WRAP:\n        if (n >= 0)\n            return (n % max);\n        else\n        {\n            int m = (-n) % max;\n\n            if (m != 0)\n                m = max - m;\n\n            return (m);\n        }\n        // NOTREACHED\n\n    default:\n        STBIR_ASSERT(!\"Unimplemented edge type\");\n        return 0;\n    }\n}\n\nstbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max)\n{\n    // avoid per-pixel switch\n    if (n >= 0 && n < max)\n        return n;\n    return stbir__edge_wrap_slow(edge, n, max);\n}\n\n// What input pixels contribute to this output pixel?\nstatic void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out)\n{\n    float out_pixel_center = (float)n + 0.5f;\n    float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius;\n    float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius;\n\n    float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio;\n    float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio;\n\n    *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio;\n    *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5));\n    *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5));\n}\n\n// What output pixels does this input pixel contribute to?\nstatic void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in)\n{\n    float in_pixel_center = (float)n + 0.5f;\n    float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius;\n    float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius;\n\n    float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift;\n    float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift;\n\n    *out_center_of_in = in_pixel_center * scale_ratio - out_shift;\n    *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5));\n    *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5));\n}\n\nstatic void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group)\n{\n    int i;\n    float total_filter = 0;\n    float filter_scale;\n\n    STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.\n\n    contributor->n0 = in_first_pixel;\n    contributor->n1 = in_last_pixel;\n\n    STBIR_ASSERT(contributor->n1 >= contributor->n0);\n\n    for (i = 0; i <= in_last_pixel - in_first_pixel; i++)\n    {\n        float in_pixel_center = (float)(i + in_first_pixel) + 0.5f;\n        coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale);\n\n        // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.)\n        if (i == 0 && !coefficient_group[i])\n        {\n            contributor->n0 = ++in_first_pixel;\n            i--;\n            continue;\n        }\n\n        total_filter += coefficient_group[i];\n    }\n\n    // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be.\n    // It would be true in exact math but is at best approximately true in floating-point math,\n    // and it would not make sense to try and put actual bounds on this here because it depends\n    // on the image aspect ratio which can get pretty extreme.\n    //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0);\n\n    STBIR_ASSERT(total_filter > 0.9);\n    STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off.\n\n    // Make sure the sum of all coefficients is 1.\n    filter_scale = 1 / total_filter;\n\n    for (i = 0; i <= in_last_pixel - in_first_pixel; i++)\n        coefficient_group[i] *= filter_scale;\n\n    for (i = in_last_pixel - in_first_pixel; i >= 0; i--)\n    {\n        if (coefficient_group[i])\n            break;\n\n        // This line has no weight. We can skip it.\n        contributor->n1 = contributor->n0 + i - 1;\n    }\n}\n\nstatic void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group)\n{\n    int i;\n\n    STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.\n\n    contributor->n0 = out_first_pixel;\n    contributor->n1 = out_last_pixel;\n\n    STBIR_ASSERT(contributor->n1 >= contributor->n0);\n\n    for (i = 0; i <= out_last_pixel - out_first_pixel; i++)\n    {\n        float out_pixel_center = (float)(i + out_first_pixel) + 0.5f;\n        float x = out_pixel_center - out_center_of_in;\n        coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio;\n    }\n\n    // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be.\n    // It would be true in exact math but is at best approximately true in floating-point math,\n    // and it would not make sense to try and put actual bounds on this here because it depends\n    // on the image aspect ratio which can get pretty extreme.\n    //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0);\n\n    for (i = out_last_pixel - out_first_pixel; i >= 0; i--)\n    {\n        if (coefficient_group[i])\n            break;\n\n        // This line has no weight. We can skip it.\n        contributor->n1 = contributor->n0 + i - 1;\n    }\n}\n\nstatic void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size)\n{\n    int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);\n    int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio);\n    int i, j;\n    int skip;\n\n    for (i = 0; i < output_size; i++)\n    {\n        float scale;\n        float total = 0;\n\n        for (j = 0; j < num_contributors; j++)\n        {\n            if (i >= contributors[j].n0 && i <= contributors[j].n1)\n            {\n                float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0);\n                total += coefficient;\n            }\n            else if (i < contributors[j].n0)\n                break;\n        }\n\n        STBIR_ASSERT(total > 0.9f);\n        STBIR_ASSERT(total < 1.1f);\n\n        scale = 1 / total;\n\n        for (j = 0; j < num_contributors; j++)\n        {\n            if (i >= contributors[j].n0 && i <= contributors[j].n1)\n                *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale;\n            else if (i < contributors[j].n0)\n                break;\n        }\n    }\n\n    // Optimize: Skip zero coefficients and contributions outside of image bounds.\n    // Do this after normalizing because normalization depends on the n0/n1 values.\n    for (j = 0; j < num_contributors; j++)\n    {\n        int range, max, width;\n\n        skip = 0;\n        while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0)\n            skip++;\n\n        contributors[j].n0 += skip;\n\n        while (contributors[j].n0 < 0)\n        {\n            contributors[j].n0++;\n            skip++;\n        }\n\n        range = contributors[j].n1 - contributors[j].n0 + 1;\n        max = stbir__min(num_coefficients, range);\n\n        width = stbir__get_coefficient_width(filter, scale_ratio);\n        for (i = 0; i < max; i++)\n        {\n            if (i + skip >= width)\n                break;\n\n            *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip);\n        }\n\n        continue;\n    }\n\n    // Using min to avoid writing into invalid pixels.\n    for (i = 0; i < num_contributors; i++)\n        contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1);\n}\n\n// Each scan line uses the same kernel values so we should calculate the kernel\n// values once and then we can use them for every scan line.\nstatic void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size)\n{\n    int n;\n    int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);\n\n    if (stbir__use_upsampling(scale_ratio))\n    {\n        float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio;\n\n        // Looping through out pixels\n        for (n = 0; n < total_contributors; n++)\n        {\n            float in_center_of_out; // Center of the current out pixel in the in pixel space\n            int in_first_pixel, in_last_pixel;\n\n            stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out);\n\n            stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));\n        }\n    }\n    else\n    {\n        float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio;\n\n        // Looping through in pixels\n        for (n = 0; n < total_contributors; n++)\n        {\n            float out_center_of_in; // Center of the current out pixel in the in pixel space\n            int out_first_pixel, out_last_pixel;\n            int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio);\n\n            stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in);\n\n            stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));\n        }\n\n        stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size);\n    }\n}\n\nstatic float* stbir__get_decode_buffer(stbir__info* stbir_info)\n{\n    // The 0 index of the decode buffer starts after the margin. This makes\n    // it okay to use negative indexes on the decode buffer.\n    return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels];\n}\n\n#define STBIR__DECODE(type, colorspace) ((int)(type) * (STBIR_MAX_COLORSPACES) + (int)(colorspace))\n\nstatic void stbir__decode_scanline(stbir__info* stbir_info, int n)\n{\n    int c;\n    int channels = stbir_info->channels;\n    int alpha_channel = stbir_info->alpha_channel;\n    int type = stbir_info->type;\n    int colorspace = stbir_info->colorspace;\n    int input_w = stbir_info->input_w;\n    size_t input_stride_bytes = stbir_info->input_stride_bytes;\n    float* decode_buffer = stbir__get_decode_buffer(stbir_info);\n    stbir_edge edge_horizontal = stbir_info->edge_horizontal;\n    stbir_edge edge_vertical = stbir_info->edge_vertical;\n    size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes;\n    const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset;\n    int max_x = input_w + stbir_info->horizontal_filter_pixel_margin;\n    int decode = STBIR__DECODE(type, colorspace);\n\n    int x = -stbir_info->horizontal_filter_pixel_margin;\n\n    // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input,\n    // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO\n    if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h))\n    {\n        for (; x < max_x; x++)\n            for (c = 0; c < channels; c++)\n                decode_buffer[x*channels + c] = 0;\n        return;\n    }\n\n    switch (decode)\n    {\n    case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]];\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float);\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float);\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float));\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float);\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c];\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]);\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel];\n        }\n\n        break;\n\n    default:\n        STBIR_ASSERT(!\"Unknown type/colorspace/channels combination.\");\n        break;\n    }\n\n    if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED))\n    {\n        for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n\n            // If the alpha value is 0 it will clobber the color values. Make sure it's not.\n            float alpha = decode_buffer[decode_pixel_index + alpha_channel];\n#ifndef STBIR_NO_ALPHA_EPSILON\n            if (stbir_info->type != STBIR_TYPE_FLOAT) {\n                alpha += STBIR_ALPHA_EPSILON;\n                decode_buffer[decode_pixel_index + alpha_channel] = alpha;\n            }\n#endif\n            for (c = 0; c < channels; c++)\n            {\n                if (c == alpha_channel)\n                    continue;\n\n                decode_buffer[decode_pixel_index + c] *= alpha;\n            }\n        }\n    }\n\n    if (edge_horizontal == STBIR_EDGE_ZERO)\n    {\n        for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++)\n        {\n            for (c = 0; c < channels; c++)\n                decode_buffer[x*channels + c] = 0;\n        }\n        for (x = input_w; x < max_x; x++)\n        {\n            for (c = 0; c < channels; c++)\n                decode_buffer[x*channels + c] = 0;\n        }\n    }\n}\n\nstatic float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length)\n{\n    return &ring_buffer[index * ring_buffer_length];\n}\n\nstatic float* stbir__add_empty_ring_buffer_entry(stbir__info* stbir_info, int n)\n{\n    int ring_buffer_index;\n    float* ring_buffer;\n\n    stbir_info->ring_buffer_last_scanline = n;\n\n    if (stbir_info->ring_buffer_begin_index < 0)\n    {\n        ring_buffer_index = stbir_info->ring_buffer_begin_index = 0;\n        stbir_info->ring_buffer_first_scanline = n;\n    }\n    else\n    {\n        ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries;\n        STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index);\n    }\n\n    ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float));\n    memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes);\n\n    return ring_buffer;\n}\n\n\nstatic void stbir__resample_horizontal_upsample(stbir__info* stbir_info, float* output_buffer)\n{\n    int x, k;\n    int output_w = stbir_info->output_w;\n    int channels = stbir_info->channels;\n    float* decode_buffer = stbir__get_decode_buffer(stbir_info);\n    stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;\n    float* horizontal_coefficients = stbir_info->horizontal_coefficients;\n    int coefficient_width = stbir_info->horizontal_coefficient_width;\n\n    for (x = 0; x < output_w; x++)\n    {\n        int n0 = horizontal_contributors[x].n0;\n        int n1 = horizontal_contributors[x].n1;\n\n        int out_pixel_index = x * channels;\n        int coefficient_group = coefficient_width * x;\n        int coefficient_counter = 0;\n\n        STBIR_ASSERT(n1 >= n0);\n        STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin);\n        STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin);\n        STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);\n        STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);\n\n        switch (channels) {\n            case 1:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 1;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                }\n                break;\n            case 2:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 2;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                }\n                break;\n            case 3:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 3;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                }\n                break;\n            case 4:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 4;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                    output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;\n                }\n                break;\n            default:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * channels;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    int c;\n                    STBIR_ASSERT(coefficient != 0);\n                    for (c = 0; c < channels; c++)\n                        output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;\n                }\n                break;\n        }\n    }\n}\n\nstatic void stbir__resample_horizontal_downsample(stbir__info* stbir_info, float* output_buffer)\n{\n    int x, k;\n    int input_w = stbir_info->input_w;\n    int channels = stbir_info->channels;\n    float* decode_buffer = stbir__get_decode_buffer(stbir_info);\n    stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;\n    float* horizontal_coefficients = stbir_info->horizontal_coefficients;\n    int coefficient_width = stbir_info->horizontal_coefficient_width;\n    int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin;\n    int max_x = input_w + filter_pixel_margin * 2;\n\n    STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info));\n\n    switch (channels) {\n        case 1:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 1;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 1;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                }\n            }\n            break;\n\n        case 2:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 2;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 2;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                }\n            }\n            break;\n\n        case 3:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 3;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 3;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                }\n            }\n            break;\n\n        case 4:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 4;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 4;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                    output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;\n                }\n            }\n            break;\n\n        default:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * channels;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int c;\n                    int out_pixel_index = k * channels;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    for (c = 0; c < channels; c++)\n                        output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;\n                }\n            }\n            break;\n    }\n}\n\nstatic void stbir__decode_and_resample_upsample(stbir__info* stbir_info, int n)\n{\n    // Decode the nth scanline from the source image into the decode buffer.\n    stbir__decode_scanline(stbir_info, n);\n\n    // Now resample it into the ring buffer.\n    if (stbir__use_width_upsampling(stbir_info))\n        stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));\n    else\n        stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));\n\n    // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling.\n}\n\nstatic void stbir__decode_and_resample_downsample(stbir__info* stbir_info, int n)\n{\n    // Decode the nth scanline from the source image into the decode buffer.\n    stbir__decode_scanline(stbir_info, n);\n\n    memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float));\n\n    // Now resample it into the horizontal buffer.\n    if (stbir__use_width_upsampling(stbir_info))\n        stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer);\n    else\n        stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer);\n\n    // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers.\n}\n\n// Get the specified scan line from the ring buffer.\nstatic float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length)\n{\n    int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries;\n    return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length);\n}\n\n\nstatic void stbir__encode_scanline(stbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode)\n{\n    int x;\n    int n;\n    int num_nonalpha;\n    stbir_uint16 nonalpha[STBIR_MAX_CHANNELS];\n\n    if (!(stbir_info->flags&STBIR_FLAG_ALPHA_PREMULTIPLIED))\n    {\n        for (x=0; x < num_pixels; ++x)\n        {\n            int pixel_index = x*channels;\n\n            float alpha = encode_buffer[pixel_index + alpha_channel];\n            float reciprocal_alpha = alpha ? 1.0f / alpha : 0;\n\n            // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb\n            for (n = 0; n < channels; n++)\n                if (n != alpha_channel)\n                    encode_buffer[pixel_index + n] *= reciprocal_alpha;\n\n            // We added in a small epsilon to prevent the color channel from being deleted with zero alpha.\n            // Because we only add it for integer types, it will automatically be discarded on integer\n            // conversion, so we don't need to subtract it back out (which would be problematic for\n            // numeric precision reasons).\n        }\n    }\n\n    // build a table of all channels that need colorspace correction, so\n    // we don't perform colorspace correction on channels that don't need it.\n    for (x = 0, num_nonalpha = 0; x < channels; ++x)\n    {\n        if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))\n        {\n            nonalpha[num_nonalpha++] = (stbir_uint16)x;\n        }\n    }\n\n    #define STBIR__ROUND_INT(f)    ((int)          ((f)+0.5))\n    #define STBIR__ROUND_UINT(f)   ((stbir_uint32) ((f)+0.5))\n\n    #ifdef STBIR__SATURATE_INT\n    #define STBIR__ENCODE_LINEAR8(f)   stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float ))\n    #define STBIR__ENCODE_LINEAR16(f)  stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float))\n    #else\n    #define STBIR__ENCODE_LINEAR8(f)   (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float )\n    #define STBIR__ENCODE_LINEAR16(f)  (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float)\n    #endif\n\n    switch (decode)\n    {\n        case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]);\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]);\n                }\n\n                if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]);\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]);\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float);\n                }\n\n                if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]);\n            }\n\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float);\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float);\n                }\n\n                if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float);\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((float*)output_buffer)[index] = encode_buffer[index];\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((float*)output_buffer)[index] = stbir__linear_to_srgb(encode_buffer[index]);\n                }\n\n                if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((float*)output_buffer)[pixel_index + alpha_channel] = encode_buffer[pixel_index + alpha_channel];\n            }\n            break;\n\n        default:\n            STBIR_ASSERT(!\"Unknown type/colorspace/channels combination.\");\n            break;\n    }\n}\n\nstatic void stbir__resample_vertical_upsample(stbir__info* stbir_info, int n)\n{\n    int x, k;\n    int output_w = stbir_info->output_w;\n    stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;\n    float* vertical_coefficients = stbir_info->vertical_coefficients;\n    int channels = stbir_info->channels;\n    int alpha_channel = stbir_info->alpha_channel;\n    int type = stbir_info->type;\n    int colorspace = stbir_info->colorspace;\n    int ring_buffer_entries = stbir_info->ring_buffer_num_entries;\n    void* output_data = stbir_info->output_data;\n    float* encode_buffer = stbir_info->encode_buffer;\n    int decode = STBIR__DECODE(type, colorspace);\n    int coefficient_width = stbir_info->vertical_coefficient_width;\n    int coefficient_counter;\n    int contributor = n;\n\n    float* ring_buffer = stbir_info->ring_buffer;\n    int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;\n    int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;\n    int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);\n\n    int n0,n1, output_row_start;\n    int coefficient_group = coefficient_width * contributor;\n\n    n0 = vertical_contributors[contributor].n0;\n    n1 = vertical_contributors[contributor].n1;\n\n    output_row_start = n * stbir_info->output_stride_bytes;\n\n    STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));\n\n    memset(encode_buffer, 0, output_w * sizeof(float) * channels);\n\n    // I tried reblocking this for better cache usage of encode_buffer\n    // (using x_outer, k, x_inner), but it lost speed. -- stb\n\n    coefficient_counter = 0;\n    switch (channels) {\n        case 1:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 1;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                }\n            }\n            break;\n        case 2:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 2;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                    encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;\n                }\n            }\n            break;\n        case 3:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 3;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                    encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;\n                    encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;\n                }\n            }\n            break;\n        case 4:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 4;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                    encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;\n                    encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;\n                    encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient;\n                }\n            }\n            break;\n        default:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * channels;\n                    int c;\n                    for (c = 0; c < channels; c++)\n                        encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient;\n                }\n            }\n            break;\n    }\n    stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode);\n}\n\nstatic void stbir__resample_vertical_downsample(stbir__info* stbir_info, int n)\n{\n    int x, k;\n    int output_w = stbir_info->output_w;\n    stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;\n    float* vertical_coefficients = stbir_info->vertical_coefficients;\n    int channels = stbir_info->channels;\n    int ring_buffer_entries = stbir_info->ring_buffer_num_entries;\n    float* horizontal_buffer = stbir_info->horizontal_buffer;\n    int coefficient_width = stbir_info->vertical_coefficient_width;\n    int contributor = n + stbir_info->vertical_filter_pixel_margin;\n\n    float* ring_buffer = stbir_info->ring_buffer;\n    int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;\n    int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;\n    int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);\n    int n0,n1;\n\n    n0 = vertical_contributors[contributor].n0;\n    n1 = vertical_contributors[contributor].n1;\n\n    STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));\n\n    for (k = n0; k <= n1; k++)\n    {\n        int coefficient_index = k - n0;\n        int coefficient_group = coefficient_width * contributor;\n        float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n\n        float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n\n        switch (channels) {\n            case 1:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 1;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                }\n                break;\n            case 2:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 2;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;\n                }\n                break;\n            case 3:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 3;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;\n                }\n                break;\n            case 4:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 4;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient;\n                }\n                break;\n            default:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * channels;\n\n                    int c;\n                    for (c = 0; c < channels; c++)\n                        ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient;\n                }\n                break;\n        }\n    }\n}\n\nstatic void stbir__buffer_loop_upsample(stbir__info* stbir_info)\n{\n    int y;\n    float scale_ratio = stbir_info->vertical_scale;\n    float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio;\n\n    STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));\n\n    for (y = 0; y < stbir_info->output_h; y++)\n    {\n        float in_center_of_out = 0; // Center of the current out scanline in the in scanline space\n        int in_first_scanline = 0, in_last_scanline = 0;\n\n        stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out);\n\n        STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);\n\n        if (stbir_info->ring_buffer_begin_index >= 0)\n        {\n            // Get rid of whatever we don't need anymore.\n            while (in_first_scanline > stbir_info->ring_buffer_first_scanline)\n            {\n                if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)\n                {\n                    // We just popped the last scanline off the ring buffer.\n                    // Reset it to the empty state.\n                    stbir_info->ring_buffer_begin_index = -1;\n                    stbir_info->ring_buffer_first_scanline = 0;\n                    stbir_info->ring_buffer_last_scanline = 0;\n                    break;\n                }\n                else\n                {\n                    stbir_info->ring_buffer_first_scanline++;\n                    stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;\n                }\n            }\n        }\n\n        // Load in new ones.\n        if (stbir_info->ring_buffer_begin_index < 0)\n            stbir__decode_and_resample_upsample(stbir_info, in_first_scanline);\n\n        while (in_last_scanline > stbir_info->ring_buffer_last_scanline)\n            stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1);\n\n        // Now all buffers should be ready to write a row of vertical sampling.\n        stbir__resample_vertical_upsample(stbir_info, y);\n\n        STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h);\n    }\n}\n\nstatic void stbir__empty_ring_buffer(stbir__info* stbir_info, int first_necessary_scanline)\n{\n    int output_stride_bytes = stbir_info->output_stride_bytes;\n    int channels = stbir_info->channels;\n    int alpha_channel = stbir_info->alpha_channel;\n    int type = stbir_info->type;\n    int colorspace = stbir_info->colorspace;\n    int output_w = stbir_info->output_w;\n    void* output_data = stbir_info->output_data;\n    int decode = STBIR__DECODE(type, colorspace);\n\n    float* ring_buffer = stbir_info->ring_buffer;\n    int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);\n\n    if (stbir_info->ring_buffer_begin_index >= 0)\n    {\n        // Get rid of whatever we don't need anymore.\n        while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline)\n        {\n            if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h)\n            {\n                int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes;\n                float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length);\n                stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode);\n                STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h);\n            }\n\n            if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)\n            {\n                // We just popped the last scanline off the ring buffer.\n                // Reset it to the empty state.\n                stbir_info->ring_buffer_begin_index = -1;\n                stbir_info->ring_buffer_first_scanline = 0;\n                stbir_info->ring_buffer_last_scanline = 0;\n                break;\n            }\n            else\n            {\n                stbir_info->ring_buffer_first_scanline++;\n                stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;\n            }\n        }\n    }\n}\n\nstatic void stbir__buffer_loop_downsample(stbir__info* stbir_info)\n{\n    int y;\n    float scale_ratio = stbir_info->vertical_scale;\n    int output_h = stbir_info->output_h;\n    float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio;\n    int pixel_margin = stbir_info->vertical_filter_pixel_margin;\n    int max_y = stbir_info->input_h + pixel_margin;\n\n    STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));\n\n    for (y = -pixel_margin; y < max_y; y++)\n    {\n        float out_center_of_in; // Center of the current out scanline in the in scanline space\n        int out_first_scanline, out_last_scanline;\n\n        stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in);\n\n        STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);\n\n        if (out_last_scanline < 0 || out_first_scanline >= output_h)\n            continue;\n\n        stbir__empty_ring_buffer(stbir_info, out_first_scanline);\n\n        stbir__decode_and_resample_downsample(stbir_info, y);\n\n        // Load in new ones.\n        if (stbir_info->ring_buffer_begin_index < 0)\n            stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline);\n\n        while (out_last_scanline > stbir_info->ring_buffer_last_scanline)\n            stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1);\n\n        // Now the horizontal buffer is ready to write to all ring buffer rows.\n        stbir__resample_vertical_downsample(stbir_info, y);\n    }\n\n    stbir__empty_ring_buffer(stbir_info, stbir_info->output_h);\n}\n\nstatic void stbir__setup(stbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels)\n{\n    info->input_w = input_w;\n    info->input_h = input_h;\n    info->output_w = output_w;\n    info->output_h = output_h;\n    info->channels = channels;\n}\n\nstatic void stbir__calculate_transform(stbir__info *info, float s0, float t0, float s1, float t1, float *transform)\n{\n    info->s0 = s0;\n    info->t0 = t0;\n    info->s1 = s1;\n    info->t1 = t1;\n\n    if (transform)\n    {\n        info->horizontal_scale = transform[0];\n        info->vertical_scale   = transform[1];\n        info->horizontal_shift = transform[2];\n        info->vertical_shift   = transform[3];\n    }\n    else\n    {\n        info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0);\n        info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0);\n\n        info->horizontal_shift = s0 * info->output_w / (s1 - s0);\n        info->vertical_shift = t0 * info->output_h / (t1 - t0);\n    }\n}\n\nstatic void stbir__choose_filter(stbir__info *info, stbir_filter h_filter, stbir_filter v_filter)\n{\n    if (h_filter == 0)\n        h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;\n    if (v_filter == 0)\n        v_filter = stbir__use_upsampling(info->vertical_scale)   ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;\n    info->horizontal_filter = h_filter;\n    info->vertical_filter = v_filter;\n}\n\nstatic stbir_uint32 stbir__calculate_memory(stbir__info *info)\n{\n    int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);\n    int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale);\n\n    info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w);\n    info->vertical_num_contributors   = stbir__get_contributors(info->vertical_scale  , info->vertical_filter  , info->input_h, info->output_h);\n\n    // One extra entry because floating point precision problems sometimes cause an extra to be necessary.\n    info->ring_buffer_num_entries = filter_height + 1;\n\n    info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors);\n    info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float);\n    info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors);\n    info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float);\n    info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float);\n    info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float);\n    info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float);\n    info->encode_buffer_size = info->output_w * info->channels * sizeof(float);\n\n    STBIR_ASSERT(info->horizontal_filter != 0);\n    STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late\n    STBIR_ASSERT(info->vertical_filter != 0);\n    STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late\n\n    if (stbir__use_height_upsampling(info))\n        // The horizontal buffer is for when we're downsampling the height and we\n        // can't output the result of sampling the decode buffer directly into the\n        // ring buffers.\n        info->horizontal_buffer_size = 0;\n    else\n        // The encode buffer is to retain precision in the height upsampling method\n        // and isn't used when height downsampling.\n        info->encode_buffer_size = 0;\n\n    return info->horizontal_contributors_size + info->horizontal_coefficients_size\n        + info->vertical_contributors_size + info->vertical_coefficients_size\n        + info->decode_buffer_size + info->horizontal_buffer_size\n        + info->ring_buffer_size + info->encode_buffer_size;\n}\n\nstatic int stbir__resize_allocated(stbir__info *info,\n    const void* input_data, int input_stride_in_bytes,\n    void* output_data, int output_stride_in_bytes,\n    int alpha_channel, stbir_uint32 flags, stbir_datatype type,\n    stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace,\n    void* tempmem, size_t tempmem_size_in_bytes)\n{\n    size_t memory_required = stbir__calculate_memory(info);\n\n    int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type];\n    int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type];\n\n#ifdef STBIR_DEBUG_OVERWRITE_TEST\n#define OVERWRITE_ARRAY_SIZE 8\n    unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE];\n    unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE];\n    unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE];\n    unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE];\n\n    size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type];\n    memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);\n    memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE);\n    memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);\n    memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE);\n#endif\n\n    STBIR_ASSERT(info->channels >= 0);\n    STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS);\n\n    if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS)\n        return 0;\n\n    STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));\n    STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));\n\n    if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))\n        return 0;\n    if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))\n        return 0;\n\n    if (alpha_channel < 0)\n        flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED;\n\n    if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) {\n        STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels);\n    }\n\n    if (alpha_channel >= info->channels)\n        return 0;\n\n    STBIR_ASSERT(tempmem);\n\n    if (!tempmem)\n        return 0;\n\n    STBIR_ASSERT(tempmem_size_in_bytes >= memory_required);\n\n    if (tempmem_size_in_bytes < memory_required)\n        return 0;\n\n    memset(tempmem, 0, tempmem_size_in_bytes);\n\n    info->input_data = input_data;\n    info->input_stride_bytes = width_stride_input;\n\n    info->output_data = output_data;\n    info->output_stride_bytes = width_stride_output;\n\n    info->alpha_channel = alpha_channel;\n    info->flags = flags;\n    info->type = type;\n    info->edge_horizontal = edge_horizontal;\n    info->edge_vertical = edge_vertical;\n    info->colorspace = colorspace;\n\n    info->horizontal_coefficient_width   = stbir__get_coefficient_width  (info->horizontal_filter, info->horizontal_scale);\n    info->vertical_coefficient_width     = stbir__get_coefficient_width  (info->vertical_filter  , info->vertical_scale  );\n    info->horizontal_filter_pixel_width  = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale);\n    info->vertical_filter_pixel_width    = stbir__get_filter_pixel_width (info->vertical_filter  , info->vertical_scale  );\n    info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);\n    info->vertical_filter_pixel_margin   = stbir__get_filter_pixel_margin(info->vertical_filter  , info->vertical_scale  );\n\n    info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float);\n    info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2;\n\n#define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size)\n\n    info->horizontal_contributors = (stbir__contributors *) tempmem;\n    info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float);\n    info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors);\n    info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float);\n    info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float);\n\n    if (stbir__use_height_upsampling(info))\n    {\n        info->horizontal_buffer = NULL;\n        info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);\n        info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float);\n\n        STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);\n    }\n    else\n    {\n        info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);\n        info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float);\n        info->encode_buffer = NULL;\n\n        STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);\n    }\n\n#undef STBIR__NEXT_MEMPTR\n\n    // This signals that the ring buffer is empty\n    info->ring_buffer_begin_index = -1;\n\n    stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w);\n    stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h);\n\n    STBIR_PROGRESS_REPORT(0);\n\n    if (stbir__use_height_upsampling(info))\n        stbir__buffer_loop_upsample(info);\n    else\n        stbir__buffer_loop_downsample(info);\n\n    STBIR_PROGRESS_REPORT(1);\n\n#ifdef STBIR_DEBUG_OVERWRITE_TEST\n    STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);\n    STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0);\n    STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);\n    STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0);\n#endif\n\n    return 1;\n}\n\n\nstatic int stbir__resize_arbitrary(\n    void *alloc_context,\n    const void* input_data, int input_w, int input_h, int input_stride_in_bytes,\n    void* output_data, int output_w, int output_h, int output_stride_in_bytes,\n    float s0, float t0, float s1, float t1, float *transform,\n    int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type,\n    stbir_filter h_filter, stbir_filter v_filter,\n    stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace)\n{\n    stbir__info info;\n    int result;\n    size_t memory_required;\n    void* extra_memory;\n\n    stbir__setup(&info, input_w, input_h, output_w, output_h, channels);\n    stbir__calculate_transform(&info, s0,t0,s1,t1,transform);\n    stbir__choose_filter(&info, h_filter, v_filter);\n    memory_required = stbir__calculate_memory(&info);\n    extra_memory = STBIR_MALLOC(memory_required, alloc_context);\n\n    if (!extra_memory)\n        return 0;\n\n    result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes,\n                                            output_data, output_stride_in_bytes,\n                                            alpha_channel, flags, type,\n                                            edge_horizontal, edge_vertical,\n                                            colorspace, extra_memory, memory_required);\n\n    STBIR_FREE(extra_memory, alloc_context);\n\n    return result;\n}\n\nSTBIRDEF int stbir_resize_uint8(     const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);\n}\n\nSTBIRDEF int stbir_resize_float(     const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);\n}\n\nSTBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels, int alpha_channel, int flags)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB);\n}\n\nSTBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                                    unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                              int num_channels, int alpha_channel, int flags,\n                                              stbir_edge edge_wrap_mode)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB);\n}\n\nSTBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                               unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,\n                                         void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter,\n        edge_wrap_mode, edge_wrap_mode, space);\n}\n\nSTBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels  , int input_w , int input_h , int input_stride_in_bytes,\n                                               stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,\n                                         void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter,\n        edge_wrap_mode, edge_wrap_mode, space);\n}\n\n\nSTBIRDEF int stbir_resize_float_generic( const float *input_pixels         , int input_w , int input_h , int input_stride_in_bytes,\n                                               float *output_pixels        , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,\n                                         void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter,\n        edge_wrap_mode, edge_wrap_mode, space);\n}\n\n\nSTBIRDEF int stbir_resize(         const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,\n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,\n        edge_mode_horizontal, edge_mode_vertical, space);\n}\n\n\nSTBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,\n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float x_scale, float y_scale,\n                                   float x_offset, float y_offset)\n{\n    float transform[4];\n    transform[0] = x_scale;\n    transform[1] = y_scale;\n    transform[2] = x_offset;\n    transform[3] = y_offset;\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,\n        edge_mode_horizontal, edge_mode_vertical, space);\n}\n\nSTBIRDEF int stbir_resize_region(  const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,\n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float s0, float t0, float s1, float t1)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,\n        edge_mode_horizontal, edge_mode_vertical, space);\n}\n\n#endif // STB_IMAGE_RESIZE_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "deprecated/stretch_test.c",
    "content": "// check that stb_truetype compiles with no stb_rect_pack.h\n#define STB_TRUETYPE_IMPLEMENTATION\n#include \"stb_truetype.h\"\n\n#define STB_DS_IMPLEMENTATION\n#include \"stb_ds.h\"\n#include <assert.h>\n\nint main(int arg, char **argv)\n{\n   int i;\n   int *arr = NULL;\n\n   for (i=0; i < 1000000; ++i)\n      arrput(arr, i);\n\n   assert(arrlen(arr) == 1000000);\n   for (i=0; i < 1000000; ++i)\n      assert(arr[i] == i);\n\n   arrfree(arr);\n   arr = NULL;\n\n   for (i=0; i < 1000; ++i)\n      arrput(arr, 1000);\n   assert(arrlen(arr) == 1000000);\n\n   return 0;\n}"
  },
  {
    "path": "deprecated/stretchy_buffer.h",
    "content": "// stretchy_buffer.h - v1.04 - public domain - nothings.org/stb\n// a vector<>-like dynamic array for C\n//\n// version history:\n//      1.04 -  fix warning\n//      1.03 -  compile as C++ maybe\n//      1.02 -  tweaks to syntax for no good reason\n//      1.01 -  added a \"common uses\" documentation section\n//      1.0  -  fixed bug in the version I posted prematurely\n//      0.9  -  rewrite to try to avoid strict-aliasing optimization\n//              issues, but won't compile as C++\n//\n// Will probably not work correctly with strict-aliasing optimizations.\n//\n// The idea:\n//\n//    This implements an approximation to C++ vector<> for C, in that it\n//    provides a generic definition for dynamic arrays which you can\n//    still access in a typesafe way using arr[i] or *(arr+i). However,\n//    it is simply a convenience wrapper around the common idiom of\n//    of keeping a set of variables (in a struct or globals) which store\n//        - pointer to array\n//        - the length of the \"in-use\" part of the array\n//        - the current size of the allocated array\n//\n//    I find it to be the single most useful non-built-in-structure when\n//    programming in C (hash tables a close second), but to be clear\n//    it lacks many of the capabilities of C++ vector<>: there is no\n//    range checking, the object address isn't stable (see next section\n//    for details), the set of methods available is small (although\n//    the file stb.h has another implementation of stretchy buffers\n//    called 'stb_arr' which provides more methods, e.g. for insertion\n//    and deletion).\n//\n// How to use:\n//\n//    Unlike other stb header file libraries, there is no need to\n//    define an _IMPLEMENTATION symbol. Every #include creates as\n//    much implementation is needed.\n//\n//    stretchy_buffer.h does not define any types, so you do not\n//    need to #include it to before defining data types that are\n//    stretchy buffers, only in files that *manipulate* stretchy\n//    buffers.\n//\n//    If you want a stretchy buffer aka dynamic array containing\n//    objects of TYPE, declare such an array as:\n//\n//       TYPE *myarray = NULL;\n//\n//    (There is no typesafe way to distinguish between stretchy\n//    buffers and regular arrays/pointers; this is necessary to\n//    make ordinary array indexing work on these objects.)\n//\n//    Unlike C++ vector<>, the stretchy_buffer has the same\n//    semantics as an object that you manually malloc and realloc.\n//    The pointer may relocate every time you add a new object\n//    to it, so you:\n//\n//         1. can't take long-term pointers to elements of the array\n//         2. have to return the pointer from functions which might expand it\n//            (either as a return value or by storing it to a ptr-to-ptr)\n//\n//    Now you can do the following things with this array:\n//\n//         sb_free(TYPE *a)           free the array\n//         sb_count(TYPE *a)          the number of elements in the array\n//         sb_push(TYPE *a, TYPE v)   adds v on the end of the array, a la push_back\n//         sb_add(TYPE *a, int n)     adds n uninitialized elements at end of array & returns pointer to first added\n//         sb_last(TYPE *a)           returns an lvalue of the last item in the array\n//         a[n]                       access the nth (counting from 0) element of the array\n//\n//     #define STRETCHY_BUFFER_NO_SHORT_NAMES to only export\n//     names of the form 'stb_sb_' if you have a name that would\n//     otherwise collide.\n//\n//     Note that these are all macros and many of them evaluate\n//     their arguments more than once, so the arguments should\n//     be side-effect-free.\n//\n//     Note that 'TYPE *a' in sb_push and sb_add must be lvalues\n//     so that the library can overwrite the existing pointer if\n//     the object has to be reallocated.\n//\n//     In an out-of-memory condition, the code will try to\n//     set up a null-pointer or otherwise-invalid-pointer\n//     exception to happen later. It's possible optimizing\n//     compilers could detect this write-to-null statically\n//     and optimize away some of the code, but it should only\n//     be along the failure path. Nevertheless, for more security\n//     in the face of such compilers, #define STRETCHY_BUFFER_OUT_OF_MEMORY\n//     to a statement such as assert(0) or exit(1) or something\n//     to force a failure when out-of-memory occurs.\n//\n// Common use:\n//\n//    The main application for this is when building a list of\n//    things with an unknown quantity, either due to loading from\n//    a file or through a process which produces an unpredictable\n//    number.\n//\n//    My most common idiom is something like:\n//\n//       SomeStruct *arr = NULL;\n//       while (something)\n//       {\n//          SomeStruct new_one;\n//          new_one.whatever = whatever;\n//          new_one.whatup   = whatup;\n//          new_one.foobar   = barfoo;\n//          sb_push(arr, new_one);\n//       }\n//\n//    and various closely-related factorings of that. For example,\n//    you might have several functions to create/init new SomeStructs,\n//    and if you use the above idiom, you might prefer to make them\n//    return structs rather than take non-const-pointers-to-structs,\n//    so you can do things like:\n//\n//       SomeStruct *arr = NULL;\n//       while (something)\n//       {\n//          if (case_A) {\n//             sb_push(arr, some_func1());\n//          } else if (case_B) {\n//             sb_push(arr, some_func2());\n//          } else {\n//             sb_push(arr, some_func3());\n//          }\n//       }\n//\n//    Note that the above relies on the fact that sb_push doesn't\n//    evaluate its second argument more than once. The macros do\n//    evaluate the *array* argument multiple times, and numeric\n//    arguments may be evaluated multiple times, but you can rely\n//    on the second argument of sb_push being evaluated only once.\n//\n//    Of course, you don't have to store bare objects in the array;\n//    if you need the objects to have stable pointers, store an array\n//    of pointers instead:\n//\n//       SomeStruct **arr = NULL;\n//       while (something)\n//       {\n//          SomeStruct *new_one = malloc(sizeof(*new_one));\n//          new_one->whatever = whatever;\n//          new_one->whatup   = whatup;\n//          new_one->foobar   = barfoo;\n//          sb_push(arr, new_one);\n//       }\n//\n// How it works:\n//\n//    A long-standing tradition in things like malloc implementations\n//    is to store extra data before the beginning of the block returned\n//    to the user. The stretchy buffer implementation here uses the\n//    same trick; the current-count and current-allocation-size are\n//    stored before the beginning of the array returned to the user.\n//    (This means you can't directly free() the pointer, because the\n//    allocated pointer is different from the type-safe pointer provided\n//    to the user.)\n//\n//    The details are trivial and implementation is straightforward;\n//    the main trick is in realizing in the first place that it's\n//    possible to do this in a generic, type-safe way in C.\n//\n// Contributors:\n//\n// Timothy Wright (github:ZenToad)\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n#ifndef STB_STRETCHY_BUFFER_H_INCLUDED\n#define STB_STRETCHY_BUFFER_H_INCLUDED\n\n#ifndef NO_STRETCHY_BUFFER_SHORT_NAMES\n#define sb_free   stb_sb_free\n#define sb_push   stb_sb_push\n#define sb_count  stb_sb_count\n#define sb_add    stb_sb_add\n#define sb_last   stb_sb_last\n#endif\n\n#define stb_sb_free(a)         ((a) ? free(stb__sbraw(a)),0 : 0)\n#define stb_sb_push(a,v)       (stb__sbmaybegrow(a,1), (a)[stb__sbn(a)++] = (v))\n#define stb_sb_count(a)        ((a) ? stb__sbn(a) : 0)\n#define stb_sb_add(a,n)        (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])\n#define stb_sb_last(a)         ((a)[stb__sbn(a)-1])\n\n#define stb__sbraw(a) ((int *) (void *) (a) - 2)\n#define stb__sbm(a)   stb__sbraw(a)[0]\n#define stb__sbn(a)   stb__sbraw(a)[1]\n\n#define stb__sbneedgrow(a,n)  ((a)==0 || stb__sbn(a)+(n) >= stb__sbm(a))\n#define stb__sbmaybegrow(a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(a,n) : 0)\n#define stb__sbgrow(a,n)      (*((void **)&(a)) = stb__sbgrowf((a), (n), sizeof(*(a))))\n\n#include <stdlib.h>\n\nstatic void * stb__sbgrowf(void *arr, int increment, int itemsize)\n{\n   int dbl_cur = arr ? 2*stb__sbm(arr) : 0;\n   int min_needed = stb_sb_count(arr) + increment;\n   int m = dbl_cur > min_needed ? dbl_cur : min_needed;\n   int *p = (int *) realloc(arr ? stb__sbraw(arr) : 0, itemsize * m + sizeof(int)*2);\n   if (p) {\n      if (!arr)\n         p[1] = 0;\n      p[0] = m;\n      return p+2;\n   } else {\n      #ifdef STRETCHY_BUFFER_OUT_OF_MEMORY\n      STRETCHY_BUFFER_OUT_OF_MEMORY ;\n      #endif\n      return (void *) (2*sizeof(int)); // try to force a NULL pointer exception later\n   }\n}\n#endif // STB_STRETCHY_BUFFER_H_INCLUDED\n\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "deprecated/stretchy_buffer.txt",
    "content": "// stretchy buffer // init: NULL // free: sbfree() // push_back: sbpush() // size: sbcount() //\n#define sbfree(a)         ((a) ? free(stb__sbraw(a)),0 : 0)\n#define sbpush(a,v)       (stb__sbmaybegrow(a,1), (a)[stb__sbn(a)++] = (v))\n#define sbcount(a)        ((a) ? stb__sbn(a) : 0)\n#define sbadd(a,n)        (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])\n#define sblast(a)         ((a)[stb__sbn(a)-1])\n\n#include <stdlib.h>\n#define stb__sbraw(a) ((int *) (a) - 2)\n#define stb__sbm(a)   stb__sbraw(a)[0]\n#define stb__sbn(a)   stb__sbraw(a)[1]\n\n#define stb__sbneedgrow(a,n)  ((a)==0 || stb__sbn(a)+n >= stb__sbm(a))\n#define stb__sbmaybegrow(a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(a,n) : 0)\n#define stb__sbgrow(a,n)  stb__sbgrowf((void **) &(a), (n), sizeof(*(a)))\n\nstatic void stb__sbgrowf(void **arr, int increment, int itemsize)\n{\n   int m = *arr ? 2*stb__sbm(*arr)+increment : increment+1;\n   void *p = realloc(*arr ? stb__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);\n   assert(p);\n   if (p) {\n      if (!*arr) ((int *) p)[1] = 0;\n      *arr = (void *) ((int *) p + 2);\n      stb__sbm(*arr) = m;\n   }\n}\n\n"
  },
  {
    "path": "docs/other_libs.md",
    "content": "Moved to https://github.com/nothings/single_file_libs"
  },
  {
    "path": "docs/stb_howto.txt",
    "content": "Lessons learned about how to make a header-file library\nV1.0\nSeptember 2013 Sean Barrett\n\nThings to do in an stb-style header-file library,\nand rationales:\n\n\n1. #define LIBRARYNAME_IMPLEMENTATION\n\nUse a symbol like the above to control creating\nthe implementation. (I used a far-less-clear name\nin my first header-file library; it became\nclear that was a mistake once I had multiple\nlibraries.)\n\nInclude a \"header-file\" section with header-file\nguards and declarations for all the functions,\nbut only guard the implementation with LIBRARYNAME_IMPLEMENTATION,\nnot the header-file guard. That way, if client's\nheader file X includes your header file for\ndeclarations, they can still include header file X\nin the source file that creates the implementation;\nif you guard the implementation too, then the first\ninclude (before the #define) creates the declarations,\nand the second one (after the #define) does nothing.\n\n\n2. AVOID DEPENDENCIES\n\nDon't rely on anything other than the C standard libraries.\n\n(If you're creating a library specifically to leverage/wrap\nsome other library, then obviously you can rely on that\nlibrary. But if that library is public domain, you might\nbe better off directly embedding the source, to reduce\ndependencies for your clients. But of course now you have\nto update whenever that library updates.)\n\nIf you use stdlib, consider wrapping all stdlib calls in\nmacros, and then conditionally define those macros to the\nstdlib function, allowing the user to replace them.\n\nFor functions with side effects, like memory allocations,\nconsider letting the user pass in a context and pass\nthat in to the macros. (The stdlib versions will ignore\nthe parameter.) Otherwise, users may have to use global\nor thread-local variables to achieve the same effect.\n\n\n3. AVOID MALLOC\n\nYou can't always do this, but when you can, embedded developers\nwill appreciate it. I almost never bother avoiding, as it's\ntoo much work (and in some cases is pretty infeasible;\nsee http://nothings.org/gamedev/font_rendering_malloc.txt ).\nBut it's definitely something one of the things I've gotten\nthe most pushback on from potential users.\n\n\n4. ALLOW STATIC IMPLEMENTATION\n\nHave a #define which makes function declarations and\nfunction definitions static. This makes the implementation\nprivate to the source file that creates it. This allows\npeople to use your library multiple times in their project\nwithout collision. (This is only necessary if your library\nhas configuration macros or global state, or if your\nlibrary has multiple versions that are not backwards\ncompatible. I've run into both of those cases.)\n\n\n5. MAKE ACCESSIBLE FROM C\n\nMaking your code accessible from C instead of C++ (i.e.\neither coding in C, or using extern \"C\") makes it more\nstraightforward to be used in C and in other languages,\nwhich often only have support for C bindings, not C++.\n(One of the earliest results I found in googling for\nstb_image was a Haskell wrapper.) Otherwise, people\nhave to wrap it in another set of function calls, and\nthe whole point here is to make it convenient for people\nto use, isn't it? (See below.)\n\nI prefer to code entirely in C, so the source file that\ninstantiates the implementation can be C itself, for\nthose crazy people out there who are programming in C.\nBut it's probably not a big hardship for a C programmer\nto create a single C++ source file to instantiate your\nlibrary.\n\n\n6. NAMESPACE PRIVATE FUNCTIONS\n\nTry to avoid having names in your source code that\nwill cause conflicts with identical names in client\ncode. You can do this either by namespacing in C++,\nor prefixing with your library name in C.\n\nIn C, generally, I use the same prefix for API\nfunctions and private symbols, such as \"stbtt_\"\nfor stb_truetype; but private functions (and\nstatic globals) use a second underscore as\nin \"stbtt__\" to further minimize the chance of\nadditional collisions in the unlikely but not\nimpossible event that users write wrapper\nfunctions that have names of the form \"stbtt_\".\n(Consider the user that has used \"stbtt_foo\"\n*successfully*, and then upgrades to a new\nversion of your library which has a new private\nfunction named either \"stbtt_foo\" or \"stbtt__foo\".)\n\nNote that the double-underscore is reserved for\nuse by the compiler, but (1) there is nothing\nreserved for \"middleware\", i.e. libraries\ndesiring to avoid conflicts with user symbols\nhave no other good options, and (2) in practice\nno compilers use double-underscore in the middle\nrather than the beginning/end. (Unfortunately,\nthere is at least one videogame-console compiler that\nwill warn about double-underscores by default.)\n\n\n7. EASY-TO-COMPLY LICENSE\n\nI make my libraries public domain. You don't have to.\nBut my goal in releasing stb-style libraries is to\nreduce friction for potential users as much as\npossible. That means:\n\n    a. easy to build (what this file is mostly about)\n    b. easy to invoke (which requires good API design)\n    c. easy to deploy (which is about licensing)\n\nI choose to place all my libraries in the public\ndomain, abjuring copyright, rather than license\nthe libraries. This has some benefits and some\ndrawbacks.\n\nAny license which is \"viral\" to modifications\ncauses worries for lawyers, even if their programmers\naren't modifying it.\n\nAny license which requires crediting in documentation\nadds friction which can add up. Valve used to have\na page with a list of all of these on their web site,\nand it was insane, and obviously nobody ever looked\nat it so why would you care whether your credit appeared\nthere?\n\nPermissive licenses like zlib and BSD license are\nperfectly reasonable, but they are very wordy and\nhave only two benefits over public domain: legally-mandated\nattribution and liability-control. I do not believe these\nare worth the excessive verbosity and user-unfriendliness\nthese licenses induce, especially in the single-file\ncase where those licenses tend to be at the top of\nthe file, the first thing you see. (To the specific\npoints, I have had no trouble receiving attribution\nfor my libraries; liability in the face of no explicit\ndisclaimer of liability is an open question.)\n\nHowever, public domain has frictions of its own, because\npublic domain declarations aren't necessary recognized\nin the USA and some other locations. For that reason,\nI recommend a declaration along these lines:\n\n// This software is dual-licensed to the public domain and under the following\n// license: you are granted a perpetual, irrevocable license to copy, modify,\n// publish, and distribute this file as you see fit.\n\nI typically place this declaration at the end of the initial\ncomment block of the file and just say 'public domain'\nat the top.\n\nI have had people say they couldn't use one of my\nlibraries because it was only \"public domain\" and didn't\nhave the additional fallback clause, who asked if\nI could dual-license it under a traditional license.\n\nMy answer: they can create a derivative work by\nmodifying one character, and then license that however\nthey like. (Indeed, *adding* the zlib or BSD license\nwould be such a modification!) Unfortunately, their\nlawyers reportedly didn't like that answer. :(\n"
  },
  {
    "path": "docs/stb_voxel_render_interview.md",
    "content": "# An interview with STB about stb_voxel_render.h\n\n**Q:**\nI suppose you really like Minecraft?\n\n**A:**\nNot really. I mean, I do own it and play it some, and\nI do watch YouTube videos of other people playing it\nonce in a while, but I'm not saying it's that great.\n\nBut I do love voxels. I've been playing with voxel rendering\nsince the mid-late 90's when we were still doing software\nrendering and thinking maybe polygons weren't the answer.\nOnce GPUs came along that kind of died off, at least until\nMinecraft brought it back to attention.\n\n**Q:**\nDo you expect people will make a lot of Minecraft clones\nwith this?\n\n**A:**\nI hope not!\n\nFor one thing, it's a terrible idea for the\ndeveloper. Remember before Minecraft was on the Xbox 360,\nthere were a ton of \"indie\" clones (some maybe making\ndecent money even), but then the real Minecraft came out\nand just crushed them (as far as I know). It's just not\nsomething you really want to compete with.\n\nThe reason I made this library is because I'd like\nto see more games with Minecraft's *art style*, not\nnecessary its *gameplay*.\n\nI can understand the urge to clone the gameplay. When\nyou have a world made of voxels/blocks, there are a\nfew things that become incredibly easy to do that would\notherwise be very hard (at least for an indie) to do in 3D.\nOne thing is that procedural generation becomes much easier.\nAnother is that destructible environments are easy. Another\nis that you have a world where your average user can build\nstuff that they find satisfactory.\n\nMinecraft is at a sort of local maximum, a sweet spot, where\nit leverages all of those easy-to-dos. And so I'm sure it's\nhard to look at the space of 'games using voxels' and move\naway from that local maximum, to give up some of that.\nBut I think that's what people should do.\n\n**Q:**\nSo what else can people do with stb_voxel_render?\n\n**A:**\nAll of those benefits I mentioned above are still valid even\nif you stay away from the sweet spot. You can make a 3D roguelike\nwithout player-creation/destruction that uses procedural generation.\nYou could make a shooter with pre-designed maps but destructible\nenvironments.\n\nAnd I'm sure there are other possible benefits to using voxels/blocks.\nHopefully this will make it easier for people to explore the space.\n\nThe library has a pretty wide range of features to allow\npeople to come up with some distinctive looks. For example,\nthe art style of Continue?9876543210 was one of the inspirations\nfor trying to make the multitexturing capabilities flexible.\nI'm terrible at art, so this isn't really something I can\ncome up with myself, but I tried to put in flexible\ntechnology that could be used multiple ways.\n\nOne thing I did intentionally was try to make it possible to\nmake nicer looking ground terrain, using the half-height\nslopes and \"weird slopes\". There are Minecraft mods with\ndrivable cars and they just go up these blocky slopes and,\nlike, what? So I wanted you to be able to make smoother\nterrain, either just for the look, or for vehicles etc.\nAlso, you can spatially cross-fade between two ground textures for\nthat classic bad dirt/grass transition that has shipped\nin plenty of professional games. Of course, you could\njust use a separate non-voxel ground renderer for all of\nthis. But this way, you can seamlessly integrate everything\nelse with it. E.g. in your authoring tool (or procedural\ngeneration) you can make smooth ground and then cut a\nsharp-edged hole in it for a building's basement or whatever.\n\nAnother thing you can do is work at a very different scale.\nIn Minecraft, a person is just under 2 blocks tall. In\nAce of Spades, a person is just under 3 blocks tall. Why\nnot 4 or 6? Well, partly because you just need a lot more\nvoxels; if a meter is 2 voxels in Mineraft and 4 voxels in\nyour game, and you draw the same number of voxels due to\nhardware limits, then your game has half the view distance\nof Minecraft. Since stb_voxel_render is designed to keep\nthe meshes small and render efficiently, you can push the\nview distance out further than Minecraft--or use a similar\nview distance and a higher voxel resolution. You could also\nstop making infinite worlds and work at entirely different\nscales; where Minecraft is 1 voxel per meter, you could\nhave 20 voxels per meter and make a small arena that's\n50 meters wide and 5 meters tall.\n\nBack when the voxel game Voxatron was announced, the weekend\nafter the trailer came out I wrote my own little GPU-accelerated\nversion of the engine and thought that was pretty cool. I've\nbeen tempted many times to extract that and release it\nas a library, but\nI don't want to steal Voxatron's thunder so I've avoided\nit. You could use this engine to do the same kind of thing,\nalthough it won't be as efficient as an engine dedicated to\nthat style of thing would be.\n\n**Q:**\nWhat one thing would you really like to see somebody do?\n\n**A:**\nBefore Unity, 3D has seemed deeply problematic in the indie\nspace. Software like GameMaker has tried to support 3D but\nit seems like little of note has been done with it.\n\nMinecraft has shown that people can build worlds with the\nMinecraft toolset far more easily than we've ever seen from those\nother tools. Obviously people have done great things with\nUnity, but those people are much closer to professional\ndevelopers; typically they still need real 3D modelling\nand all of that stuff.\n\nSo what I'd really like to see is someone build some kind\nof voxel-game-construction-set. Start with stb_voxel_render,\nmaybe expose all the flexibility of stb_voxel_render (so\npeople can do different things). Thrown in lua or something\nelse for scripting, make some kind of editor that feels\nat least as good as Minecraft and Infinifactory, and see\nwhere that gets you.\n\n**Q:**\nWhy'd you make this library?\n\n**A:**\nMainly as a way of releasing this technology I've been working\non since 2011 and seemed unlikely to ever ship myself. In 2011\nI was playing the voxel shooter Ace of Spades. One of the maps\nthat we played on was a partial port of Broville (which is the\nfirst Minecraft map in stb_voxel_render release trailer). I'd\nmade a bunch of procedural level generators for the game, and\nI started trying to make a city generator inspired by Broville.\n\nBut I realized it would be a lot of work, and of very little\nvalue (most of my maps didn't get much play because people\npreferred to play on maps where they could charge straight\nat the enemies and shoot them as fast as possible). So I\nwrote my own voxel engine and started working on a procedural\ncity game. But I got bogged down after I finally got the road\ngenerator working and never got anywhere with building\ngeneration or gameplay.\n\nstb_voxel_render is actually a complete rewrite from scratch,\nbut it's based a lot on what I learned from that previous work.\n\n**Q:**\nAbout the release video... how long did that take to edit?\n\n**A:**\nAbout seven or eight hours. I had the first version done in\nmaybe six or seven hours, but then I realized I'd left out\none clip, and when I went back to add it I also gussied up\na couple other moments in the video. But there was something\nbasically identical to it that was done in around six.\n\n**Q:** \nOk, that's it. Thanks, me.\n\n**A:**\nThanks *me!*\n"
  },
  {
    "path": "docs/why_public_domain.md",
    "content": "My collected rationales for placing these libraries\nin the public domain:\n\n1. Public domain vs. viral licenses\n\n  Why is this library public domain?\n  Because more people will use it. Because it's not viral, people are\n  not obligated to give back, so you could argue that it hurts the\n  development of it, and then because it doesn't develop as well it's\n  not as good, and then because it's not as good, in the long run\n  maybe fewer people will use it. I have total respect for that\n  opinion, but I just don't believe it myself for most software.\n\n2. Public domain vs. attribution-required licenses\n\n  The primary difference between public domain and, say, a Creative Commons\n  commercial / non-share-alike / attribution license is solely the\n  requirement for attribution. (Similarly the BSD license and such.)\n  While I would *appreciate* acknowledgement and attribution, I believe\n  that it is foolish to place a legal encumberment (i.e. a license) on\n  the software *solely* to get attribution.\n\n  In other words, I'm arguing that PD is superior to the BSD license and\n  the Creative Commons 'Attribution' license. If the license offers\n  anything besides attribution -- as does, e.g., CC NonCommercial-ShareAlike,\n  or the GPL -- that's a separate discussion.\n\n3. Other aspects of BSD-style licenses besides attribution\n\n  Permissive licenses like zlib and BSD license are perfectly reasonable\n  in their requirements, but they are very wordy and\n  have only two benefits over public domain: legally-mandated\n  attribution and liability-control. I do not believe these\n  are worth the excessive verbosity and user-unfriendliness\n  these licenses induce, especially in the single-file\n  case where those licenses tend to be at the top of\n  the file, the first thing you see.\n\n  To the specific points, I have had no trouble receiving\n  attribution for my libraries; liability in the face of\n  no explicit disclaimer of liability is an open question,\n  but one I have a lot of difficulty imagining there being\n  any actual doubt about in court. Sometimes I explicitly\n  note in my libraries that I make no guarantees about them\n  being fit for purpose, but it's pretty absurd to do this;\n  as a whole, it comes across as \"here is a library to decode\n  vorbis audio files, but it may not actually work and if\n  you have problems it's not my fault, but also please\n  report bugs so I can fix them\"--so dumb!\n\n4. full discussion from stb_howto.txt on what YOU should do for YOUR libs\n\n```\nEASY-TO-COMPLY LICENSE\n\nI make my libraries public domain. You don't have to.\nBut my goal in releasing stb-style libraries is to\nreduce friction for potential users as much as\npossible. That means:\n\n  a. easy to build (what this file is mostly about)\n  b. easy to invoke (which requires good API design)\n  c. easy to deploy (which is about licensing)\n\nI choose to place all my libraries in the public\ndomain, abjuring copyright, rather than license\nthe libraries. This has some benefits and some\ndrawbacks.\n\nAny license which is \"viral\" to modifications\ncauses worries for lawyers, even if their programmers\naren't modifying it.\n\nAny license which requires crediting in documentation\nadds friction which can add up. Valve has a huge list\n(http://nothings.org/remote/ThirdPartyLegalNotices_steam_2019.html)\nof all of these included in each game they ship,\nand it's insane, and obviously nobody ever looks\nat it so why would you care whether your credit\nappeared there?\n\nPermissive licenses like zlib and BSD license are\nperfectly reasonable, but they are very wordy and\nhave only two benefits over public domain: legally-mandated\nattribution and liability-control. I do not believe these\nare worth the excessive verbosity and user-unfriendliness\nthese licenses induce, especially in the single-file\ncase where those licenses tend to be at the top of\nthe file, the first thing you see. (To the specific\npoints, I have had no trouble receiving attribution\nfor my libraries; liability in the face of no explicit\ndisclaimer of liability is an open question.)\n\nHowever, public domain has frictions of its own, because\npublic domain declarations aren't necessary recognized\nin the USA and some other locations. For that reason,\nI recommend a declaration along these lines:\n\n// This software is dual-licensed to the public domain and under the following\n// license: you are granted a perpetual, irrevocable license to copy, modify,\n// publish, and distribute this file as you see fit.\n\nI typically place this declaration at the end of the initial\ncomment block of the file and just say 'public domain'\nat the top.\n\nI have had people say they couldn't use one of my\nlibraries because it was only \"public domain\" and didn't\nhave the additional fallback clause, who asked if\nI could dual-license it under a traditional license.\n\nMy answer: they can create a derivative work by\nmodifying one character, and then license that however\nthey like. (Indeed, *adding* the zlib or BSD license\nwould be such a modification!) Unfortunately, their\nlawyers reportedly didn't like that answer. :(\n```\n"
  },
  {
    "path": "stb_c_lexer.h",
    "content": "// stb_c_lexer.h - v0.12 - public domain Sean Barrett 2013\n// lexer for making little C-like languages with recursive-descent parsers\n//\n// This file provides both the interface and the implementation.\n// To instantiate the implementation,\n//      #define STB_C_LEXER_IMPLEMENTATION\n// in *ONE* source file, before #including this file.\n//\n// The default configuration is fairly close to a C lexer, although\n// suffixes on integer constants are not handled (you can override this).\n//\n// History:\n//     0.12 fix compilation bug for NUL support; better support separate inclusion\n//     0.11 fix clang static analysis warning\n//     0.10 fix warnings\n//     0.09 hex floats, no-stdlib fixes\n//     0.08 fix bad pointer comparison\n//     0.07 fix mishandling of hexadecimal constants parsed by strtol\n//     0.06 fix missing next character after ending quote mark (Andreas Fredriksson)\n//     0.05 refixed get_location because github version had lost the fix\n//     0.04 fix octal parsing bug\n//     0.03 added STB_C_LEX_DISCARD_PREPROCESSOR option\n//          refactor API to simplify (only one struct instead of two)\n//          change literal enum names to have 'lit' at the end\n//     0.02 first public release\n//\n// Status:\n//     - haven't tested compiling as C++\n//     - haven't tested the float parsing path\n//     - haven't tested the non-default-config paths (e.g. non-stdlib)\n//     - only tested default-config paths by eyeballing output of self-parse\n//\n//     - haven't implemented multiline strings\n//     - haven't implemented octal/hex character constants\n//     - haven't implemented support for unicode CLEX_char\n//     - need to expand error reporting so you don't just get \"CLEX_parse_error\"\n//\n// Contributors:\n//   Arpad Goretity (bugfix)\n//   Alan Hickman (hex floats)\n//   github:mundusnine (bugfix)\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n#ifdef STB_C_LEXER_IMPLEMENTATION\n#ifndef STB_C_LEXER_DEFINITIONS\n// to change the default parsing rules, copy the following lines\n// into your C/C++ file *before* including this, and then replace\n// the Y's with N's for the ones you don't want. This needs to be\n// set to the same values for every place in your program where\n// stb_c_lexer.h is included.\n// --BEGIN--\n\n#if defined(Y) || defined(N)\n#error \"Can only use stb_c_lexer in contexts where the preprocessor symbols 'Y' and 'N' are not defined\"\n#endif\n\n#define STB_C_LEX_C_DECIMAL_INTS    Y   //  \"0|[1-9][0-9]*\"                        CLEX_intlit\n#define STB_C_LEX_C_HEX_INTS        Y   //  \"0x[0-9a-fA-F]+\"                       CLEX_intlit\n#define STB_C_LEX_C_OCTAL_INTS      Y   //  \"[0-7]+\"                               CLEX_intlit\n#define STB_C_LEX_C_DECIMAL_FLOATS  Y   //  \"[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?)     CLEX_floatlit\n#define STB_C_LEX_C99_HEX_FLOATS    N   //  \"0x{hex}+(.{hex}*)?[pP][-+]?{hex}+     CLEX_floatlit\n#define STB_C_LEX_C_IDENTIFIERS     Y   //  \"[_a-zA-Z][_a-zA-Z0-9]*\"               CLEX_id\n#define STB_C_LEX_C_DQ_STRINGS      Y   //  double-quote-delimited strings with escapes  CLEX_dqstring\n#define STB_C_LEX_C_SQ_STRINGS      N   //  single-quote-delimited strings with escapes  CLEX_ssstring\n#define STB_C_LEX_C_CHARS           Y   //  single-quote-delimited character with escape CLEX_charlits\n#define STB_C_LEX_C_COMMENTS        Y   //  \"/* comment */\"\n#define STB_C_LEX_CPP_COMMENTS      Y   //  \"// comment to end of line\\n\"\n#define STB_C_LEX_C_COMPARISONS     Y   //  \"==\" CLEX_eq  \"!=\" CLEX_noteq   \"<=\" CLEX_lesseq  \">=\" CLEX_greatereq\n#define STB_C_LEX_C_LOGICAL         Y   //  \"&&\"  CLEX_andand   \"||\"  CLEX_oror\n#define STB_C_LEX_C_SHIFTS          Y   //  \"<<\"  CLEX_shl      \">>\"  CLEX_shr\n#define STB_C_LEX_C_INCREMENTS      Y   //  \"++\"  CLEX_plusplus \"--\"  CLEX_minusminus\n#define STB_C_LEX_C_ARROW           Y   //  \"->\"  CLEX_arrow\n#define STB_C_LEX_EQUAL_ARROW       N   //  \"=>\"  CLEX_eqarrow\n#define STB_C_LEX_C_BITWISEEQ       Y   //  \"&=\"  CLEX_andeq    \"|=\"  CLEX_oreq     \"^=\"  CLEX_xoreq\n#define STB_C_LEX_C_ARITHEQ         Y   //  \"+=\"  CLEX_pluseq   \"-=\"  CLEX_minuseq\n                                        //  \"*=\"  CLEX_muleq    \"/=\"  CLEX_diveq    \"%=\" CLEX_modeq\n                                        //  if both STB_C_LEX_SHIFTS & STB_C_LEX_ARITHEQ:\n                                        //                      \"<<=\" CLEX_shleq    \">>=\" CLEX_shreq\n\n#define STB_C_LEX_PARSE_SUFFIXES    N   // letters after numbers are parsed as part of those numbers, and must be in suffix list below\n#define STB_C_LEX_DECIMAL_SUFFIXES  \"\"  // decimal integer suffixes e.g. \"uUlL\" -- these are returned as-is in string storage\n#define STB_C_LEX_HEX_SUFFIXES      \"\"  // e.g. \"uUlL\"\n#define STB_C_LEX_OCTAL_SUFFIXES    \"\"  // e.g. \"uUlL\"\n#define STB_C_LEX_FLOAT_SUFFIXES    \"\"  //\n\n#define STB_C_LEX_0_IS_EOF             N  // if Y, ends parsing at '\\0'; if N, returns '\\0' as token\n#define STB_C_LEX_INTEGERS_AS_DOUBLES  N  // parses integers as doubles so they can be larger than 'int', but only if STB_C_LEX_STDLIB==N\n#define STB_C_LEX_MULTILINE_DSTRINGS   N  // allow newlines in double-quoted strings\n#define STB_C_LEX_MULTILINE_SSTRINGS   N  // allow newlines in single-quoted strings\n#define STB_C_LEX_USE_STDLIB           Y  // use strtod,strtol for parsing #s; otherwise inaccurate hack\n#define STB_C_LEX_DOLLAR_IDENTIFIER    Y  // allow $ as an identifier character\n#define STB_C_LEX_FLOAT_NO_DECIMAL     Y  // allow floats that have no decimal point if they have an exponent\n\n#define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES  N   // if Y, all CLEX_ token names are defined, even if never returned\n                                              // leaving it as N should help you catch config bugs\n\n#define STB_C_LEX_DISCARD_PREPROCESSOR    Y   // discard C-preprocessor directives (e.g. after prepocess\n                                              // still have #line, #pragma, etc)\n\n//#define STB_C_LEX_ISWHITE(str)    ... // return length in bytes of whitespace characters if first char is whitespace\n\n#define STB_C_LEXER_DEFINITIONS         // This line prevents the header file from replacing your definitions\n// --END--\n#endif\n#endif\n\n#ifndef INCLUDE_STB_C_LEXER_H\n#define INCLUDE_STB_C_LEXER_H\n\ntypedef struct\n{\n   // lexer variables\n   char *input_stream;\n   char *eof;\n   char *parse_point;\n   char *string_storage;\n   int   string_storage_len;\n\n   // lexer parse location for error messages\n   char *where_firstchar;\n   char *where_lastchar;\n\n   // lexer token variables\n   long token;\n   double real_number;\n   long   int_number;\n   char *string;\n   int string_len;\n} stb_lexer;\n\ntypedef struct\n{\n   int line_number;\n   int line_offset;\n} stb_lex_location;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nextern void stb_c_lexer_init(stb_lexer *lexer, const char *input_stream, const char *input_stream_end, char *string_store, int store_length);\n// this function initialize the 'lexer' structure\n//   Input:\n//   - input_stream points to the file to parse, loaded into memory\n//   - input_stream_end points to the end of the file, or NULL if you use 0-for-EOF\n//   - string_store is storage the lexer can use for storing parsed strings and identifiers\n//   - store_length is the length of that storage\n\nextern int stb_c_lexer_get_token(stb_lexer *lexer);\n// this function returns non-zero if a token is parsed, or 0 if at EOF\n//   Output:\n//   - lexer->token is the token ID, which is unicode code point for a single-char token, < 0 for a multichar or eof or error\n//   - lexer->real_number is a double constant value for CLEX_floatlit, or CLEX_intlit if STB_C_LEX_INTEGERS_AS_DOUBLES\n//   - lexer->int_number is an integer constant for CLEX_intlit if !STB_C_LEX_INTEGERS_AS_DOUBLES, or character for CLEX_charlit\n//   - lexer->string is a 0-terminated string for CLEX_dqstring or CLEX_sqstring or CLEX_identifier\n//   - lexer->string_len is the byte length of lexer->string\n\nextern void stb_c_lexer_get_location(const stb_lexer *lexer, const char *where, stb_lex_location *loc);\n// this inefficient function returns the line number and character offset of a\n// given location in the file as returned by stb_lex_token. Because it's inefficient,\n// you should only call it for errors, not for every token.\n// For error messages of invalid tokens, you typically want the location of the start\n// of the token (which caused the token to be invalid). For bugs involving legit\n// tokens, you can report the first or the range.\n//    Output:\n//    - loc->line_number is the line number in the file, counting from 1, of the location\n//    - loc->line_offset is the char-offset in the line, counting from 0, of the location\n\n\n#ifdef __cplusplus\n}\n#endif\n\nenum\n{\n   CLEX_eof = 256,\n   CLEX_parse_error,\n   CLEX_intlit        ,\n   CLEX_floatlit      ,\n   CLEX_id            ,\n   CLEX_dqstring      ,\n   CLEX_sqstring      ,\n   CLEX_charlit       ,\n   CLEX_eq            ,\n   CLEX_noteq         ,\n   CLEX_lesseq        ,\n   CLEX_greatereq     ,\n   CLEX_andand        ,\n   CLEX_oror          ,\n   CLEX_shl           ,\n   CLEX_shr           ,\n   CLEX_plusplus      ,\n   CLEX_minusminus    ,\n   CLEX_pluseq        ,\n   CLEX_minuseq       ,\n   CLEX_muleq         ,\n   CLEX_diveq         ,\n   CLEX_modeq         ,\n   CLEX_andeq         ,\n   CLEX_oreq          ,\n   CLEX_xoreq         ,\n   CLEX_arrow         ,\n   CLEX_eqarrow       ,\n   CLEX_shleq, CLEX_shreq,\n\n   CLEX_first_unused_token\n\n};\n#endif // INCLUDE_STB_C_LEXER_H\n\n#ifdef STB_C_LEXER_IMPLEMENTATION\n\n// Hacky definitions so we can easily #if on them\n#define Y(x) 1\n#define N(x) 0\n\n#if STB_C_LEX_INTEGERS_AS_DOUBLES(x)\ntypedef double     stb__clex_int;\n#define intfield   real_number\n#define STB__clex_int_as_double\n#else\ntypedef long       stb__clex_int;\n#define intfield   int_number\n#endif\n\n// Convert these config options to simple conditional #defines so we can more\n// easily test them once we've change the meaning of Y/N\n\n#if STB_C_LEX_PARSE_SUFFIXES(x)\n#define STB__clex_parse_suffixes\n#endif\n\n#if STB_C_LEX_C99_HEX_FLOATS(x)\n#define STB__clex_hex_floats\n#endif\n\n#if STB_C_LEX_C_HEX_INTS(x)\n#define STB__clex_hex_ints\n#endif\n\n#if STB_C_LEX_C_DECIMAL_INTS(x)\n#define STB__clex_decimal_ints\n#endif\n\n#if STB_C_LEX_C_OCTAL_INTS(x)\n#define STB__clex_octal_ints\n#endif\n\n#if STB_C_LEX_C_DECIMAL_FLOATS(x)\n#define STB__clex_decimal_floats\n#endif\n\n#if STB_C_LEX_DISCARD_PREPROCESSOR(x)\n#define STB__clex_discard_preprocessor\n#endif\n\n#if STB_C_LEX_USE_STDLIB(x) && (!defined(STB__clex_hex_floats) || __STDC_VERSION__ >= 199901L)\n#define STB__CLEX_use_stdlib\n#include <stdlib.h>\n#endif\n\n// Now for the rest of the file we'll use the basic definition where\n// where Y expands to its contents and N expands to nothing\n#undef  Y\n#define Y(a) a\n#undef N\n#define N(a)\n\n// API function\nvoid stb_c_lexer_init(stb_lexer *lexer, const char *input_stream, const char *input_stream_end, char *string_store, int store_length)\n{\n   lexer->input_stream = (char *) input_stream;\n   lexer->eof = (char *) input_stream_end;\n   lexer->parse_point = (char *) input_stream;\n   lexer->string_storage = string_store;\n   lexer->string_storage_len = store_length;\n}\n\n// API function\nvoid stb_c_lexer_get_location(const stb_lexer *lexer, const char *where, stb_lex_location *loc)\n{\n   char *p = lexer->input_stream;\n   int line_number = 1;\n   int char_offset = 0;\n   while (*p && p < where) {\n      if (*p == '\\n' || *p == '\\r') {\n         p += (p[0]+p[1] == '\\r'+'\\n' ? 2 : 1); // skip newline\n         line_number += 1;\n         char_offset = 0;\n      } else {\n         ++p;\n         ++char_offset;\n      }\n   }\n   loc->line_number = line_number;\n   loc->line_offset = char_offset;\n}\n\n// main helper function for returning a parsed token\nstatic int stb__clex_token(stb_lexer *lexer, int token, char *start, char *end)\n{\n   lexer->token = token;\n   lexer->where_firstchar = start;\n   lexer->where_lastchar = end;\n   lexer->parse_point = end+1;\n   return 1;\n}\n\n// helper function for returning eof\nstatic int stb__clex_eof(stb_lexer *lexer)\n{\n   lexer->token = CLEX_eof;\n   return 0;\n}\n\nstatic int stb__clex_iswhite(int x)\n{\n   return x == ' ' || x == '\\t' || x == '\\r' || x == '\\n' || x == '\\f';\n}\n\nstatic const char *stb__strchr(const char *str, int ch)\n{\n   for (; *str; ++str)\n      if (*str == ch)\n         return str;\n   return 0;\n}\n\n// parse suffixes at the end of a number\nstatic int stb__clex_parse_suffixes(stb_lexer *lexer, long tokenid, char *start, char *cur, const char *suffixes)\n{\n   #ifdef STB__clex_parse_suffixes\n   lexer->string = lexer->string_storage;\n   lexer->string_len = 0;\n\n   while ((*cur >= 'a' && *cur <= 'z') || (*cur >= 'A' && *cur <= 'Z')) {\n      if (stb__strchr(suffixes, *cur) == 0)\n         return stb__clex_token(lexer, CLEX_parse_error, start, cur);\n      if (lexer->string_len+1 >= lexer->string_storage_len)\n         return stb__clex_token(lexer, CLEX_parse_error, start, cur);\n      lexer->string[lexer->string_len++] = *cur++;\n   }\n   #else\n   suffixes = suffixes; // attempt to suppress warnings\n   #endif\n   return stb__clex_token(lexer, tokenid, start, cur-1);\n}\n\n#ifndef STB__CLEX_use_stdlib\nstatic double stb__clex_pow(double base, unsigned int exponent)\n{\n   double value=1;\n   for ( ; exponent; exponent >>= 1) {\n      if (exponent & 1)\n         value *= base;\n      base *= base;\n   }\n   return value;\n}\n\nstatic double stb__clex_parse_float(char *p, char **q)\n{\n   char *s = p;\n   double value=0;\n   int base=10;\n   int exponent=0;\n\n#ifdef STB__clex_hex_floats\n   if (*p == '0') {\n      if (p[1] == 'x' || p[1] == 'X') {\n         base=16;\n         p += 2;\n      }\n   }\n#endif\n\n   for (;;) {\n      if (*p >= '0' && *p <= '9')\n         value = value*base + (*p++ - '0');\n#ifdef STB__clex_hex_floats\n      else if (base == 16 && *p >= 'a' && *p <= 'f')\n         value = value*base + 10 + (*p++ - 'a');\n      else if (base == 16 && *p >= 'A' && *p <= 'F')\n         value = value*base + 10 + (*p++ - 'A');\n#endif\n      else\n         break;\n   }\n\n   if (*p == '.') {\n      double pow, addend = 0;\n      ++p;\n      for (pow=1; ; pow*=base) {\n         if (*p >= '0' && *p <= '9')\n            addend = addend*base + (*p++ - '0');\n#ifdef STB__clex_hex_floats\n         else if (base == 16 && *p >= 'a' && *p <= 'f')\n            addend = addend*base + 10 + (*p++ - 'a');\n         else if (base == 16 && *p >= 'A' && *p <= 'F')\n            addend = addend*base + 10 + (*p++ - 'A');\n#endif\n         else\n            break;\n      }\n      value += addend / pow;\n   }\n#ifdef STB__clex_hex_floats\n   if (base == 16) {\n      // exponent required for hex float literal\n      if (*p != 'p' && *p != 'P') {\n         *q = s;\n         return 0;\n      }\n      exponent = 1;\n   } else\n#endif\n      exponent = (*p == 'e' || *p == 'E');\n\n   if (exponent) {\n      int sign = p[1] == '-';\n      unsigned int exponent=0;\n      double power=1;\n      ++p;\n      if (*p == '-' || *p == '+')\n         ++p;\n      while (*p >= '0' && *p <= '9')\n         exponent = exponent*10 + (*p++ - '0');\n\n#ifdef STB__clex_hex_floats\n      if (base == 16)\n         power = stb__clex_pow(2, exponent);\n      else\n#endif\n         power = stb__clex_pow(10, exponent);\n      if (sign)\n         value /= power;\n      else\n         value *= power;\n   }\n   *q = p;\n   return value;\n}\n#endif\n\nstatic int stb__clex_parse_char(char *p, char **q)\n{\n   if (*p == '\\\\') {\n      *q = p+2; // tentatively guess we'll parse two characters\n      switch(p[1]) {\n         case '\\\\': return '\\\\';\n         case '\\'': return '\\'';\n         case '\"': return '\"';\n         case 't': return '\\t';\n         case 'f': return '\\f';\n         case 'n': return '\\n';\n         case 'r': return '\\r';\n         case '0': return '\\0'; // @TODO ocatal constants\n         case 'x': case 'X': return -1; // @TODO hex constants\n         case 'u': return -1; // @TODO unicode constants\n      }\n   }\n   *q = p+1;\n   return (unsigned char) *p;\n}\n\nstatic int stb__clex_parse_string(stb_lexer *lexer, char *p, int type)\n{\n   char *start = p;\n   char delim = *p++; // grab the \" or ' for later matching\n   char *out = lexer->string_storage;\n   char *outend = lexer->string_storage + lexer->string_storage_len;\n   while (*p != delim) {\n      int n;\n      if (*p == '\\\\') {\n         char *q;\n         n = stb__clex_parse_char(p, &q);\n         if (n < 0)\n            return stb__clex_token(lexer, CLEX_parse_error, start, q);\n         p = q;\n      } else {\n         // @OPTIMIZE: could speed this up by looping-while-not-backslash\n         n = (unsigned char) *p++;\n      }\n      if (out+1 > outend)\n         return stb__clex_token(lexer, CLEX_parse_error, start, p);\n      // @TODO expand unicode escapes to UTF8\n      *out++ = (char) n;\n   }\n   *out = 0;\n   lexer->string = lexer->string_storage;\n   lexer->string_len = (int) (out - lexer->string_storage);\n   return stb__clex_token(lexer, type, start, p);\n}\n\nint stb_c_lexer_get_token(stb_lexer *lexer)\n{\n   char *p = lexer->parse_point;\n\n   // skip whitespace and comments\n   for (;;) {\n      #ifdef STB_C_LEX_ISWHITE\n      while (p != lexer->stream_end) {\n         int n;\n         n = STB_C_LEX_ISWHITE(p);\n         if (n == 0) break;\n         if (lexer->eof && lexer->eof - lexer->parse_point < n)\n            return stb__clex_token(tok, CLEX_parse_error, p,lexer->eof-1);\n         p += n;\n      }\n      #else\n      while (p != lexer->eof && stb__clex_iswhite(*p))\n         ++p;\n      #endif\n\n      STB_C_LEX_CPP_COMMENTS(\n         if (p != lexer->eof && p[0] == '/' && p[1] == '/') {\n            while (p != lexer->eof && *p != '\\r' && *p != '\\n')\n               ++p;\n            continue;\n         }\n      )\n\n      STB_C_LEX_C_COMMENTS(\n         if (p != lexer->eof && p[0] == '/' && p[1] == '*') {\n            char *start = p;\n            p += 2;\n            while (p != lexer->eof && (p[0] != '*' || p[1] != '/'))\n               ++p;\n            if (p == lexer->eof)\n               return stb__clex_token(lexer, CLEX_parse_error, start, p-1);\n            p += 2;\n            continue;\n         }\n      )\n\n      #ifdef STB__clex_discard_preprocessor\n         // @TODO this discards everything after a '#', regardless\n         // of where in the line the # is, rather than requiring it\n         // be at the start. (because this parser doesn't otherwise\n         // check for line breaks!)\n         if (p != lexer->eof && p[0] == '#') {\n            while (p != lexer->eof && *p != '\\r' && *p != '\\n')\n               ++p;\n            continue;\n         }\n      #endif\n\n      break;\n   }\n\n   if (p == lexer->eof)\n      return stb__clex_eof(lexer);\n\n   switch (*p) {\n      default:\n         if (   (*p >= 'a' && *p <= 'z')\n             || (*p >= 'A' && *p <= 'Z')\n             || *p == '_' || (unsigned char) *p >= 128    // >= 128 is UTF8 char\n             STB_C_LEX_DOLLAR_IDENTIFIER( || *p == '$' ) )\n         {\n            int n = 0;\n            lexer->string = lexer->string_storage;\n            do {\n               if (n+1 >= lexer->string_storage_len)\n                  return stb__clex_token(lexer, CLEX_parse_error, p, p+n);\n               lexer->string[n] = p[n];\n               ++n;\n            } while (\n                  (p[n] >= 'a' && p[n] <= 'z')\n               || (p[n] >= 'A' && p[n] <= 'Z')\n               || (p[n] >= '0' && p[n] <= '9') // allow digits in middle of identifier\n               || p[n] == '_' || (unsigned char) p[n] >= 128\n                STB_C_LEX_DOLLAR_IDENTIFIER( || p[n] == '$' )\n            );\n            lexer->string[n] = 0;\n            lexer->string_len = n;\n            return stb__clex_token(lexer, CLEX_id, p, p+n-1);\n         }\n\n         // check for EOF\n         STB_C_LEX_0_IS_EOF(\n            if (*p == 0)\n               return stb__clex_eof(lexer);\n         )\n\n      single_char:\n         // not an identifier, return the character as itself\n         return stb__clex_token(lexer, *p, p, p);\n\n      case '+':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_INCREMENTS(if (p[1] == '+') return stb__clex_token(lexer, CLEX_plusplus, p,p+1);)\n            STB_C_LEX_C_ARITHEQ(   if (p[1] == '=') return stb__clex_token(lexer, CLEX_pluseq  , p,p+1);)\n         }\n         goto single_char;\n      case '-':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_INCREMENTS(if (p[1] == '-') return stb__clex_token(lexer, CLEX_minusminus, p,p+1);)\n            STB_C_LEX_C_ARITHEQ(   if (p[1] == '=') return stb__clex_token(lexer, CLEX_minuseq   , p,p+1);)\n            STB_C_LEX_C_ARROW(     if (p[1] == '>') return stb__clex_token(lexer, CLEX_arrow     , p,p+1);)\n         }\n         goto single_char;\n      case '&':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_LOGICAL(  if (p[1] == '&') return stb__clex_token(lexer, CLEX_andand, p,p+1);)\n            STB_C_LEX_C_BITWISEEQ(if (p[1] == '=') return stb__clex_token(lexer, CLEX_andeq , p,p+1);)\n         }\n         goto single_char;\n      case '|':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_LOGICAL(  if (p[1] == '|') return stb__clex_token(lexer, CLEX_oror, p,p+1);)\n            STB_C_LEX_C_BITWISEEQ(if (p[1] == '=') return stb__clex_token(lexer, CLEX_oreq, p,p+1);)\n         }\n         goto single_char;\n      case '=':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_eq, p,p+1);)\n            STB_C_LEX_EQUAL_ARROW(  if (p[1] == '>') return stb__clex_token(lexer, CLEX_eqarrow, p,p+1);)\n         }\n         goto single_char;\n      case '!':\n         STB_C_LEX_C_COMPARISONS(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_noteq, p,p+1);)\n         goto single_char;\n      case '^':\n         STB_C_LEX_C_BITWISEEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_xoreq, p,p+1));\n         goto single_char;\n      case '%':\n         STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_modeq, p,p+1));\n         goto single_char;\n      case '*':\n         STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_muleq, p,p+1));\n         goto single_char;\n      case '/':\n         STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_diveq, p,p+1));\n         goto single_char;\n      case '<':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_lesseq, p,p+1);)\n            STB_C_LEX_C_SHIFTS(     if (p[1] == '<') {\n                                       STB_C_LEX_C_ARITHEQ(if (p+2 != lexer->eof && p[2] == '=')\n                                                              return stb__clex_token(lexer, CLEX_shleq, p,p+2);)\n                                       return stb__clex_token(lexer, CLEX_shl, p,p+1);\n                                    }\n                              )\n         }\n         goto single_char;\n      case '>':\n         if (p+1 != lexer->eof) {\n            STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_greatereq, p,p+1);)\n            STB_C_LEX_C_SHIFTS(     if (p[1] == '>') {\n                                       STB_C_LEX_C_ARITHEQ(if (p+2 != lexer->eof && p[2] == '=')\n                                                              return stb__clex_token(lexer, CLEX_shreq, p,p+2);)\n                                       return stb__clex_token(lexer, CLEX_shr, p,p+1);\n                                    }\n                              )\n         }\n         goto single_char;\n\n      case '\"':\n         STB_C_LEX_C_DQ_STRINGS(return stb__clex_parse_string(lexer, p, CLEX_dqstring);)\n         goto single_char;\n      case '\\'':\n         STB_C_LEX_C_SQ_STRINGS(return stb__clex_parse_string(lexer, p, CLEX_sqstring);)\n         STB_C_LEX_C_CHARS(\n         {\n            char *start = p;\n            lexer->int_number = stb__clex_parse_char(p+1, &p);\n            if (lexer->int_number < 0)\n               return stb__clex_token(lexer, CLEX_parse_error, start,start);\n            if (p == lexer->eof || *p != '\\'')\n               return stb__clex_token(lexer, CLEX_parse_error, start,p);\n            return stb__clex_token(lexer, CLEX_charlit, start, p+1);\n         })\n         goto single_char;\n\n      case '0':\n         #if defined(STB__clex_hex_ints) || defined(STB__clex_hex_floats)\n            if (p+1 != lexer->eof) {\n               if (p[1] == 'x' || p[1] == 'X') {\n                  char *q;\n\n                  #ifdef STB__clex_hex_floats\n                  for (q=p+2;\n                       q != lexer->eof && ((*q >= '0' && *q <= '9') || (*q >= 'a' && *q <= 'f') || (*q >= 'A' && *q <= 'F'));\n                       ++q);\n                  if (q != lexer->eof) {\n                     if (*q == '.' STB_C_LEX_FLOAT_NO_DECIMAL(|| *q == 'p' || *q == 'P')) {\n                        #ifdef STB__CLEX_use_stdlib\n                        lexer->real_number = strtod((char *) p, (char**) &q);\n                        #else\n                        lexer->real_number = stb__clex_parse_float(p, &q);\n                        #endif\n\n                        if (p == q)\n                           return stb__clex_token(lexer, CLEX_parse_error, p,q);\n                        return stb__clex_parse_suffixes(lexer, CLEX_floatlit, p,q, STB_C_LEX_FLOAT_SUFFIXES);\n\n                     }\n                  }\n                  #endif   // STB__CLEX_hex_floats\n\n                  #ifdef STB__clex_hex_ints\n                  #ifdef STB__CLEX_use_stdlib\n                  lexer->int_number = strtol((char *) p, (char **) &q, 16);\n                  #else\n                  {\n                     stb__clex_int n=0;\n                     for (q=p+2; q != lexer->eof; ++q) {\n                        if (*q >= '0' && *q <= '9')\n                           n = n*16 + (*q - '0');\n                        else if (*q >= 'a' && *q <= 'f')\n                           n = n*16 + (*q - 'a') + 10;\n                        else if (*q >= 'A' && *q <= 'F')\n                           n = n*16 + (*q - 'A') + 10;\n                        else\n                           break;\n                     }\n                     lexer->int_number = n;\n                  }\n                  #endif\n                  if (q == p+2)\n                     return stb__clex_token(lexer, CLEX_parse_error, p-2,p-1);\n                  return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_HEX_SUFFIXES);\n                  #endif\n               }\n            }\n         #endif // defined(STB__clex_hex_ints) || defined(STB__clex_hex_floats)\n         // can't test for octal because we might parse '0.0' as float or as '0' '.' '0',\n         // so have to do float first\n\n         /* FALL THROUGH */\n      case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':\n\n         #ifdef STB__clex_decimal_floats\n         {\n            char *q = p;\n            while (q != lexer->eof && (*q >= '0' && *q <= '9'))\n               ++q;\n            if (q != lexer->eof) {\n               if (*q == '.' STB_C_LEX_FLOAT_NO_DECIMAL(|| *q == 'e' || *q == 'E')) {\n                  #ifdef STB__CLEX_use_stdlib\n                  lexer->real_number = strtod((char *) p, (char**) &q);\n                  #else\n                  lexer->real_number = stb__clex_parse_float(p, &q);\n                  #endif\n\n                  return stb__clex_parse_suffixes(lexer, CLEX_floatlit, p,q, STB_C_LEX_FLOAT_SUFFIXES);\n\n               }\n            }\n         }\n         #endif // STB__clex_decimal_floats\n\n         #ifdef STB__clex_octal_ints\n         if (p[0] == '0') {\n            char *q = p;\n            #ifdef STB__CLEX_use_stdlib\n            lexer->int_number = strtol((char *) p, (char **) &q, 8);\n            #else\n            stb__clex_int n=0;\n            while (q != lexer->eof) {\n               if (*q >= '0' && *q <= '7')\n                  n = n*8 + (*q - '0');\n               else\n                  break;\n               ++q;\n            }\n            if (q != lexer->eof && (*q == '8' || *q=='9'))\n               return stb__clex_token(lexer, CLEX_parse_error, p, q);\n            lexer->int_number = n;\n            #endif\n            return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_OCTAL_SUFFIXES);\n         }\n         #endif // STB__clex_octal_ints\n\n         #ifdef STB__clex_decimal_ints\n         {\n            char *q = p;\n            #ifdef STB__CLEX_use_stdlib\n            lexer->int_number = strtol((char *) p, (char **) &q, 10);\n            #else\n            stb__clex_int n=0;\n            while (q != lexer->eof) {\n               if (*q >= '0' && *q <= '9')\n                  n = n*10 + (*q - '0');\n               else\n                  break;\n               ++q;\n            }\n            lexer->int_number = n;\n            #endif\n            return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_OCTAL_SUFFIXES);\n         }\n         #endif // STB__clex_decimal_ints\n         goto single_char;\n   }\n}\n#endif // STB_C_LEXER_IMPLEMENTATION\n\n#ifdef STB_C_LEXER_SELF_TEST\n#define _CRT_SECURE_NO_WARNINGS\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic void print_token(stb_lexer *lexer)\n{\n   switch (lexer->token) {\n      case CLEX_id        : printf(\"_%s\", lexer->string); break;\n      case CLEX_eq        : printf(\"==\"); break;\n      case CLEX_noteq     : printf(\"!=\"); break;\n      case CLEX_lesseq    : printf(\"<=\"); break;\n      case CLEX_greatereq : printf(\">=\"); break;\n      case CLEX_andand    : printf(\"&&\"); break;\n      case CLEX_oror      : printf(\"||\"); break;\n      case CLEX_shl       : printf(\"<<\"); break;\n      case CLEX_shr       : printf(\">>\"); break;\n      case CLEX_plusplus  : printf(\"++\"); break;\n      case CLEX_minusminus: printf(\"--\"); break;\n      case CLEX_arrow     : printf(\"->\"); break;\n      case CLEX_andeq     : printf(\"&=\"); break;\n      case CLEX_oreq      : printf(\"|=\"); break;\n      case CLEX_xoreq     : printf(\"^=\"); break;\n      case CLEX_pluseq    : printf(\"+=\"); break;\n      case CLEX_minuseq   : printf(\"-=\"); break;\n      case CLEX_muleq     : printf(\"*=\"); break;\n      case CLEX_diveq     : printf(\"/=\"); break;\n      case CLEX_modeq     : printf(\"%%=\"); break;\n      case CLEX_shleq     : printf(\"<<=\"); break;\n      case CLEX_shreq     : printf(\">>=\"); break;\n      case CLEX_eqarrow   : printf(\"=>\"); break;\n      case CLEX_dqstring  : printf(\"\\\"%s\\\"\", lexer->string); break;\n      case CLEX_sqstring  : printf(\"'\\\"%s\\\"'\", lexer->string); break;\n      case CLEX_charlit   : printf(\"'%s'\", lexer->string); break;\n      #if defined(STB__clex_int_as_double) && !defined(STB__CLEX_use_stdlib)\n      case CLEX_intlit    : printf(\"#%g\", lexer->real_number); break;\n      #else\n      case CLEX_intlit    : printf(\"#%ld\", lexer->int_number); break;\n      #endif\n      case CLEX_floatlit  : printf(\"%g\", lexer->real_number); break;\n      default:\n         if (lexer->token >= 0 && lexer->token < 256)\n            printf(\"%c\", (int) lexer->token);\n         else {\n            printf(\"<<<UNKNOWN TOKEN %ld >>>\\n\", lexer->token);\n         }\n         break;\n   }\n}\n\n/* Force a test\nof parsing\nmultiline comments */\n\n/*/ comment /*/\n/**/ extern /**/\n\nvoid dummy(void)\n{\n   double some_floats[] = {\n      1.0501, -10.4e12, 5E+10,\n#if 0   // not supported in C++ or C-pre-99, so don't try to compile it, but let our parser test it\n      0x1.0p+24, 0xff.FP-8, 0x1p-23,\n#endif\n      4.\n   };\n   (void) sizeof(some_floats);\n   (void) some_floats[1];\n\n   printf(\"test %d\",1); // https://github.com/nothings/stb/issues/13\n}\n\nint main(int argc, char **argv)\n{\n   FILE *f = fopen(\"stb_c_lexer.h\",\"rb\");\n   char *text = (char *) malloc(1 << 20);\n   int len = f ? (int) fread(text, 1, 1<<20, f) : -1;\n   stb_lexer lex;\n   if (len < 0) {\n      fprintf(stderr, \"Error opening file\\n\");\n      free(text);\n      fclose(f);\n      return 1;\n   }\n   fclose(f);\n\n   stb_c_lexer_init(&lex, text, text+len, (char *) malloc(0x10000), 0x10000);\n   while (stb_c_lexer_get_token(&lex)) {\n      if (lex.token == CLEX_parse_error) {\n         printf(\"\\n<<<PARSE ERROR>>>\\n\");\n         break;\n      }\n      print_token(&lex);\n      printf(\"  \");\n   }\n   return 0;\n}\n#endif\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_connected_components.h",
    "content": "// stb_connected_components - v0.96 - public domain connected components on grids\n//                                                 http://github.com/nothings/stb\n//\n// Finds connected components on 2D grids for testing reachability between\n// two points, with fast updates when changing reachability (e.g. on one machine\n// it was typically 0.2ms w/ 1024x1024 grid). Each grid square must be \"open\" or\n// \"closed\" (traversable or untraversable), and grid squares are only connected\n// to their orthogonal neighbors, not diagonally.\n//\n// In one source file, create the implementation by doing something like this:\n//\n//   #define STBCC_GRID_COUNT_X_LOG2    10\n//   #define STBCC_GRID_COUNT_Y_LOG2    10\n//   #define STB_CONNECTED_COMPONENTS_IMPLEMENTATION\n//   #include \"stb_connected_components.h\"\n//\n// The above creates an implementation that can run on maps up to 1024x1024.\n// Map sizes must be a multiple of (1<<(LOG2/2)) on each axis (e.g. 32 if LOG2=10,\n// 16 if LOG2=8, etc.) (You can just pad your map with untraversable space.)\n//\n// MEMORY USAGE\n//\n//   Uses about 6-7 bytes per grid square (e.g. 7MB for a 1024x1024 grid).\n//   Uses a single worst-case allocation which you pass in.\n//\n// PERFORMANCE\n//\n//   On a core i7-2700K at 3.5 Ghz, for a particular 1024x1024 map (map_03.png):\n//\n//       Creating map                   : 44.85 ms\n//       Making one square   traversable:  0.27 ms    (average over 29,448 calls)\n//       Making one square untraversable:  0.23 ms    (average over 30,123 calls)\n//       Reachability query:               0.00001 ms (average over 4,000,000 calls)\n//\n//   On non-degenerate maps update time is O(N^0.5), but on degenerate maps like\n//   checkerboards or 50% random, update time is O(N^0.75) (~2ms on above machine).\n//\n// CHANGELOG\n//\n//    0.96  (2019-03-04)  Fix warnings\n//    0.95  (2016-10-16)  Bugfix if multiple clumps in one cluster connect to same clump in another\n//    0.94  (2016-04-17)  Bugfix & optimize worst case (checkerboard & random)\n//    0.93  (2016-04-16)  Reduce memory by 10x for 1Kx1K map; small speedup\n//    0.92  (2016-04-16)  Compute sqrt(N) cluster size by default\n//    0.91  (2016-04-15)  Initial release\n//\n// TODO:\n//    - better API documentation\n//    - more comments\n//    - try re-integrating naive algorithm & compare performance\n//    - more optimized batching (current approach still recomputes local clumps many times)\n//    - function for setting a grid of squares at once (just use batching)\n//\n// LICENSE\n//\n//   See end of file for license information.\n//\n// ALGORITHM\n//\n//   The NxN grid map is split into sqrt(N) x sqrt(N) blocks called\n//  \"clusters\". Each cluster independently computes a set of connected\n//   components within that cluster (ignoring all connectivity out of\n//   that cluster) using a union-find disjoint set forest. This produces a bunch\n//   of locally connected components called \"clumps\". Each clump is (a) connected\n//   within its cluster, (b) does not directly connect to any other clumps in the\n//   cluster (though it may connect to them by paths that lead outside the cluster,\n//   but those are ignored at this step), and (c) maintains an adjacency list of\n//   all clumps in adjacent clusters that it _is_ connected to. Then a second\n//   union-find disjoint set forest is used to compute connected clumps\n//   globally, across the whole map. Reachability is then computed by\n//   finding which clump each input point belongs to, and checking whether\n//   those clumps are in the same \"global\" connected component.\n//\n//   The above data structure can be updated efficiently; on a change\n//   of a single grid square on the map, only one cluster changes its\n//   purely-local state, so only one cluster needs its clumps fully\n//   recomputed. Clumps in adjacent clusters need their adjacency lists\n//   updated: first to remove all references to the old clumps in the\n//   rebuilt cluster, then to add new references to the new clumps. Both\n//   of these operations can use the existing \"find which clump each input\n//   point belongs to\" query to compute that adjacency information rapidly.\n\n#ifndef INCLUDE_STB_CONNECTED_COMPONENTS_H\n#define INCLUDE_STB_CONNECTED_COMPONENTS_H\n\n#include <stdlib.h>\n\ntypedef struct st_stbcc_grid stbcc_grid;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n//////////////////////////////////////////////////////////////////////////////////////////\n//\n//  initialization\n//\n\n// you allocate the grid data structure to this size (note that it will be very big!!!)\nextern size_t stbcc_grid_sizeof(void);\n\n// initialize the grid, value of map[] is 0 = traversable, non-0 is solid\nextern void stbcc_init_grid(stbcc_grid *g, unsigned char *map, int w, int h);\n\n\n//////////////////////////////////////////////////////////////////////////////////////////\n//\n//  main functionality\n//\n\n// update a grid square state, 0 = traversable, non-0 is solid\n// i can add a batch-update if it's needed\nextern void stbcc_update_grid(stbcc_grid *g, int x, int y, int solid);\n\n// query if two grid squares are reachable from each other\nextern int stbcc_query_grid_node_connection(stbcc_grid *g, int x1, int y1, int x2, int y2);\n\n\n//////////////////////////////////////////////////////////////////////////////////////////\n//\n//  bonus functions\n//\n\n// wrap multiple stbcc_update_grid calls in these function to compute\n// multiple updates more efficiently; cannot make queries inside batch\nextern void stbcc_update_batch_begin(stbcc_grid *g);\nextern void stbcc_update_batch_end(stbcc_grid *g);\n\n// query the grid data structure for whether a given square is open or not\nextern int stbcc_query_grid_open(stbcc_grid *g, int x, int y);\n\n// get a unique id for the connected component this is in; it's not necessarily\n// small, you'll need a hash table or something to remap it (or just use\nextern unsigned int stbcc_get_unique_id(stbcc_grid *g, int x, int y);\n#define STBCC_NULL_UNIQUE_ID 0xffffffff // returned for closed map squares\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // INCLUDE_STB_CONNECTED_COMPONENTS_H\n\n#ifdef STB_CONNECTED_COMPONENTS_IMPLEMENTATION\n\n#include <assert.h>\n#include <string.h> // memset\n\n#if !defined(STBCC_GRID_COUNT_X_LOG2) || !defined(STBCC_GRID_COUNT_Y_LOG2)\n   #error \"You must define STBCC_GRID_COUNT_X_LOG2 and STBCC_GRID_COUNT_Y_LOG2 to define the max grid supported.\"\n#endif\n\n#define STBCC__GRID_COUNT_X (1 << STBCC_GRID_COUNT_X_LOG2)\n#define STBCC__GRID_COUNT_Y (1 << STBCC_GRID_COUNT_Y_LOG2)\n\n#define STBCC__MAP_STRIDE   (1 << (STBCC_GRID_COUNT_X_LOG2-3))\n\n#ifndef STBCC_CLUSTER_SIZE_X_LOG2\n   #define STBCC_CLUSTER_SIZE_X_LOG2   (STBCC_GRID_COUNT_X_LOG2/2) // log2(sqrt(2^N)) = 1/2 * log2(2^N)) = 1/2 * N\n   #if STBCC_CLUSTER_SIZE_X_LOG2 > 6\n   #undef STBCC_CLUSTER_SIZE_X_LOG2\n   #define STBCC_CLUSTER_SIZE_X_LOG2 6\n   #endif\n#endif\n\n#ifndef STBCC_CLUSTER_SIZE_Y_LOG2\n   #define STBCC_CLUSTER_SIZE_Y_LOG2   (STBCC_GRID_COUNT_Y_LOG2/2)\n   #if STBCC_CLUSTER_SIZE_Y_LOG2 > 6\n   #undef STBCC_CLUSTER_SIZE_Y_LOG2\n   #define STBCC_CLUSTER_SIZE_Y_LOG2 6\n   #endif\n#endif\n\n#define STBCC__CLUSTER_SIZE_X   (1 << STBCC_CLUSTER_SIZE_X_LOG2)\n#define STBCC__CLUSTER_SIZE_Y   (1 << STBCC_CLUSTER_SIZE_Y_LOG2)\n\n#define STBCC__CLUSTER_COUNT_X_LOG2   (STBCC_GRID_COUNT_X_LOG2 - STBCC_CLUSTER_SIZE_X_LOG2)\n#define STBCC__CLUSTER_COUNT_Y_LOG2   (STBCC_GRID_COUNT_Y_LOG2 - STBCC_CLUSTER_SIZE_Y_LOG2)\n\n#define STBCC__CLUSTER_COUNT_X  (1 << STBCC__CLUSTER_COUNT_X_LOG2)\n#define STBCC__CLUSTER_COUNT_Y  (1 << STBCC__CLUSTER_COUNT_Y_LOG2)\n\n#if STBCC__CLUSTER_SIZE_X >= STBCC__GRID_COUNT_X || STBCC__CLUSTER_SIZE_Y >= STBCC__GRID_COUNT_Y\n   #error \"STBCC_CLUSTER_SIZE_X/Y_LOG2 must be smaller than STBCC_GRID_COUNT_X/Y_LOG2\"\n#endif\n\n// worst case # of clumps per cluster\n#define STBCC__MAX_CLUMPS_PER_CLUSTER_LOG2   (STBCC_CLUSTER_SIZE_X_LOG2 + STBCC_CLUSTER_SIZE_Y_LOG2-1)\n#define STBCC__MAX_CLUMPS_PER_CLUSTER        (1 << STBCC__MAX_CLUMPS_PER_CLUSTER_LOG2)\n#define STBCC__MAX_CLUMPS                    (STBCC__MAX_CLUMPS_PER_CLUSTER * STBCC__CLUSTER_COUNT_X * STBCC__CLUSTER_COUNT_Y)\n#define STBCC__NULL_CLUMPID                  STBCC__MAX_CLUMPS_PER_CLUSTER\n\n#define STBCC__CLUSTER_X_FOR_COORD_X(x)  ((x) >> STBCC_CLUSTER_SIZE_X_LOG2)\n#define STBCC__CLUSTER_Y_FOR_COORD_Y(y)  ((y) >> STBCC_CLUSTER_SIZE_Y_LOG2)\n\n#define STBCC__MAP_BYTE_MASK(x,y)       (1 << ((x) & 7))\n#define STBCC__MAP_BYTE(g,x,y)          ((g)->map[y][(x) >> 3])\n#define STBCC__MAP_OPEN(g,x,y)          (STBCC__MAP_BYTE(g,x,y) & STBCC__MAP_BYTE_MASK(x,y))\n\ntypedef unsigned short stbcc__clumpid;\ntypedef unsigned char stbcc__verify_max_clumps[STBCC__MAX_CLUMPS_PER_CLUSTER < (1 << (8*sizeof(stbcc__clumpid))) ? 1 : -1];\n\n#define STBCC__MAX_EXITS_PER_CLUSTER   (STBCC__CLUSTER_SIZE_X + STBCC__CLUSTER_SIZE_Y)   // 64 for 32x32\n#define STBCC__MAX_EXITS_PER_CLUMP     (STBCC__CLUSTER_SIZE_X + STBCC__CLUSTER_SIZE_Y)   // 64 for 32x32\n#define STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER  (STBCC__MAX_EXITS_PER_CLUMP)\n\n// 2^19 * 2^6 => 2^25 exits => 2^26  => 64MB for 1024x1024\n\n// Logic for above on 4x4 grid:\n//\n// Many clumps:      One clump:\n//   + +               +  +\n//  +X.X.             +XX.X+\n//   .X.X+             .XXX\n//  +X.X.              XXX.\n//   .X.X+            +X.XX+\n//    + +              +  +\n//\n// 8 exits either way\n\ntypedef unsigned char stbcc__verify_max_exits[STBCC__MAX_EXITS_PER_CLUMP <= 256];\n\ntypedef struct\n{\n   unsigned short clump_index:12;\n     signed short cluster_dx:2;\n     signed short cluster_dy:2;\n} stbcc__relative_clumpid;\n\ntypedef union\n{\n   struct {\n      unsigned int clump_index:12;\n      unsigned int cluster_x:10;\n      unsigned int cluster_y:10;\n   } f;\n   unsigned int c;\n} stbcc__global_clumpid;\n\n// rebuilt cluster 3,4\n\n// what changes in cluster 2,4\n\ntypedef struct\n{\n   stbcc__global_clumpid global_label;        // 4\n   unsigned char num_adjacent;                // 1\n   unsigned char max_adjacent;                // 1\n   unsigned char adjacent_clump_list_index;   // 1\n   unsigned char reserved;\n} stbcc__clump; // 8\n\n#define STBCC__CLUSTER_ADJACENCY_COUNT   (STBCC__MAX_EXITS_PER_CLUSTER*2)\ntypedef struct\n{\n   short num_clumps;\n   unsigned char num_edge_clumps;\n   unsigned char rebuild_adjacency;\n   stbcc__clump clump[STBCC__MAX_CLUMPS_PER_CLUSTER];       // 8 * 2^9 = 4KB\n   stbcc__relative_clumpid adjacency_storage[STBCC__CLUSTER_ADJACENCY_COUNT]; // 256 bytes\n} stbcc__cluster;\n\nstruct st_stbcc_grid\n{\n   int w,h,cw,ch;\n   int in_batched_update;\n   //unsigned char cluster_dirty[STBCC__CLUSTER_COUNT_Y][STBCC__CLUSTER_COUNT_X]; // could bitpack, but: 1K x 1K => 1KB\n   unsigned char map[STBCC__GRID_COUNT_Y][STBCC__MAP_STRIDE]; // 1K x 1K => 1K x 128 => 128KB\n   stbcc__clumpid clump_for_node[STBCC__GRID_COUNT_Y][STBCC__GRID_COUNT_X];  // 1K x 1K x 2 = 2MB\n   stbcc__cluster cluster[STBCC__CLUSTER_COUNT_Y][STBCC__CLUSTER_COUNT_X]; //  1K x 4.5KB = 4.5MB\n};\n\nint stbcc_query_grid_node_connection(stbcc_grid *g, int x1, int y1, int x2, int y2)\n{\n   stbcc__global_clumpid label1, label2;\n   stbcc__clumpid c1 = g->clump_for_node[y1][x1];\n   stbcc__clumpid c2 = g->clump_for_node[y2][x2];\n   int cx1 = STBCC__CLUSTER_X_FOR_COORD_X(x1);\n   int cy1 = STBCC__CLUSTER_Y_FOR_COORD_Y(y1);\n   int cx2 = STBCC__CLUSTER_X_FOR_COORD_X(x2);\n   int cy2 = STBCC__CLUSTER_Y_FOR_COORD_Y(y2);\n   assert(!g->in_batched_update);\n   if (c1 == STBCC__NULL_CLUMPID || c2 == STBCC__NULL_CLUMPID)\n      return 0;\n   label1 = g->cluster[cy1][cx1].clump[c1].global_label;\n   label2 = g->cluster[cy2][cx2].clump[c2].global_label;\n   if (label1.c == label2.c)\n      return 1;\n   return 0;\n}\n\nint stbcc_query_grid_open(stbcc_grid *g, int x, int y)\n{\n   return STBCC__MAP_OPEN(g, x, y) != 0;\n}\n\nunsigned int stbcc_get_unique_id(stbcc_grid *g, int x, int y)\n{\n   stbcc__clumpid c = g->clump_for_node[y][x];\n   int cx = STBCC__CLUSTER_X_FOR_COORD_X(x);\n   int cy = STBCC__CLUSTER_Y_FOR_COORD_Y(y);\n   assert(!g->in_batched_update);\n   if (c == STBCC__NULL_CLUMPID) return STBCC_NULL_UNIQUE_ID;\n   return g->cluster[cy][cx].clump[c].global_label.c;\n}\n\ntypedef struct\n{\n   unsigned char x,y;\n} stbcc__tinypoint;\n\ntypedef struct\n{\n   stbcc__tinypoint parent[STBCC__CLUSTER_SIZE_Y][STBCC__CLUSTER_SIZE_X]; // 32x32 => 2KB\n   stbcc__clumpid   label[STBCC__CLUSTER_SIZE_Y][STBCC__CLUSTER_SIZE_X];\n} stbcc__cluster_build_info;\n\nstatic void stbcc__build_clumps_for_cluster(stbcc_grid *g, int cx, int cy);\nstatic void stbcc__remove_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy);\nstatic void stbcc__add_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy);\n\nstatic stbcc__global_clumpid stbcc__clump_find(stbcc_grid *g, stbcc__global_clumpid n)\n{\n   stbcc__global_clumpid q;\n   stbcc__clump *c = &g->cluster[n.f.cluster_y][n.f.cluster_x].clump[n.f.clump_index];\n\n   if (c->global_label.c == n.c)\n      return n;\n\n   q = stbcc__clump_find(g, c->global_label);\n   c->global_label = q;\n   return q;\n}\n\ntypedef struct\n{\n   unsigned int cluster_x;\n   unsigned int cluster_y;\n   unsigned int clump_index;\n} stbcc__unpacked_clumpid;\n\nstatic void stbcc__clump_union(stbcc_grid *g, stbcc__unpacked_clumpid m, int x, int y, int idx)\n{\n   stbcc__clump *mc = &g->cluster[m.cluster_y][m.cluster_x].clump[m.clump_index];\n   stbcc__clump *nc = &g->cluster[y][x].clump[idx];\n   stbcc__global_clumpid mp = stbcc__clump_find(g, mc->global_label);\n   stbcc__global_clumpid np = stbcc__clump_find(g, nc->global_label);\n\n   if (mp.c == np.c)\n      return;\n\n   g->cluster[mp.f.cluster_y][mp.f.cluster_x].clump[mp.f.clump_index].global_label = np;\n}\n\nstatic void stbcc__build_connected_components_for_clumps(stbcc_grid *g)\n{\n   int i,j,k,h;\n\n   for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j) {\n      for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i) {\n         stbcc__cluster *cluster = &g->cluster[j][i];\n         for (k=0; k < (int) cluster->num_edge_clumps; ++k) {\n            stbcc__global_clumpid m;\n            m.f.clump_index = k;\n            m.f.cluster_x = i;\n            m.f.cluster_y = j;\n            assert((int) m.f.clump_index == k && (int) m.f.cluster_x == i && (int) m.f.cluster_y == j);\n            cluster->clump[k].global_label = m;\n         }\n      }\n   }\n\n   for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j) {\n      for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i) {\n         stbcc__cluster *cluster = &g->cluster[j][i];\n         for (k=0; k < (int) cluster->num_edge_clumps; ++k) {\n            stbcc__clump *clump = &cluster->clump[k];\n            stbcc__unpacked_clumpid m;\n            stbcc__relative_clumpid *adj;\n            m.clump_index = k;\n            m.cluster_x = i;\n            m.cluster_y = j;\n            adj = &cluster->adjacency_storage[clump->adjacent_clump_list_index];\n            for (h=0; h < clump->num_adjacent; ++h) {\n               unsigned int clump_index = adj[h].clump_index;\n               unsigned int x = adj[h].cluster_dx + i;\n               unsigned int y = adj[h].cluster_dy + j;\n               stbcc__clump_union(g, m, x, y, clump_index);\n            }\n         }\n      }\n   }\n\n   for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j) {\n      for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i) {\n         stbcc__cluster *cluster = &g->cluster[j][i];\n         for (k=0; k < (int) cluster->num_edge_clumps; ++k) {\n            stbcc__global_clumpid m;\n            m.f.clump_index = k;\n            m.f.cluster_x = i;\n            m.f.cluster_y = j;\n            stbcc__clump_find(g, m);\n         }\n      }\n   }\n}\n\nstatic void stbcc__build_all_connections_for_cluster(stbcc_grid *g, int cx, int cy)\n{\n   // in this particular case, we are fully non-incremental. that means we\n   // can discover the correct sizes for the arrays, but requires we build\n   // the data into temporary data structures, or just count the sizes, so\n   // for simplicity we do the latter\n   stbcc__cluster *cluster = &g->cluster[cy][cx];\n   unsigned char connected[STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER][STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER/8]; // 64 x 8 => 1KB\n   unsigned char num_adj[STBCC__MAX_CLUMPS_PER_CLUSTER] = { 0 };\n   int x = cx * STBCC__CLUSTER_SIZE_X;\n   int y = cy * STBCC__CLUSTER_SIZE_Y;\n   int step_x, step_y=0, i, j, k, n, m, dx, dy, total;\n   int extra;\n\n   g->cluster[cy][cx].rebuild_adjacency = 0;\n\n   total = 0;\n   for (m=0; m < 4; ++m) {\n      switch (m) {\n         case 0:\n            dx = 1, dy = 0;\n            step_x = 0, step_y = 1;\n            i = STBCC__CLUSTER_SIZE_X-1;\n            j = 0;\n            n = STBCC__CLUSTER_SIZE_Y;\n            break;\n         case 1:\n            dx = -1, dy = 0;\n            i = 0;\n            j = 0;\n            step_x = 0;\n            step_y = 1;\n            n = STBCC__CLUSTER_SIZE_Y;\n            break;\n         case 2:\n            dy = -1, dx = 0;\n            i = 0;\n            j = 0;\n            step_x = 1;\n            step_y = 0;\n            n = STBCC__CLUSTER_SIZE_X;\n            break;\n         case 3:\n            dy = 1, dx = 0;\n            i = 0;\n            j = STBCC__CLUSTER_SIZE_Y-1;\n            step_x = 1;\n            step_y = 0;\n            n = STBCC__CLUSTER_SIZE_X;\n            break;\n      }\n\n      if (cx+dx < 0 || cx+dx >= g->cw || cy+dy < 0 || cy+dy >= g->ch)\n         continue;\n\n      memset(connected, 0, sizeof(connected));\n      for (k=0; k < n; ++k) {\n         if (STBCC__MAP_OPEN(g, x+i, y+j) && STBCC__MAP_OPEN(g, x+i+dx, y+j+dy)) {\n            stbcc__clumpid src = g->clump_for_node[y+j][x+i];\n            stbcc__clumpid dest = g->clump_for_node[y+j+dy][x+i+dx];\n            if (0 == (connected[src][dest>>3] & (1 << (dest & 7)))) {\n               connected[src][dest>>3] |= 1 << (dest & 7);\n               ++num_adj[src];\n               ++total;\n            }\n         }\n         i += step_x;\n         j += step_y;\n      }\n   }\n\n   assert(total <= STBCC__CLUSTER_ADJACENCY_COUNT);\n\n   // decide how to apportion unused adjacency slots; only clumps that lie\n   // on the edges of the cluster need adjacency slots, so divide them up\n   // evenly between those clumps\n\n   // we want:\n   //    extra = (STBCC__CLUSTER_ADJACENCY_COUNT - total) / cluster->num_edge_clumps;\n   // but we efficiently approximate this without a divide, because\n   // ignoring edge-vs-non-edge with 'num_adj[i]*2' was faster than\n   // 'num_adj[i]+extra' with the divide\n   if      (total + (cluster->num_edge_clumps<<2) <= STBCC__CLUSTER_ADJACENCY_COUNT)\n      extra = 4;\n   else if (total + (cluster->num_edge_clumps<<1) <= STBCC__CLUSTER_ADJACENCY_COUNT)\n      extra = 2;\n   else if (total + (cluster->num_edge_clumps<<0) <= STBCC__CLUSTER_ADJACENCY_COUNT)\n      extra = 1;\n   else\n      extra = 0;\n\n   total = 0;\n   for (i=0; i < (int) cluster->num_edge_clumps; ++i) {\n      int alloc = num_adj[i]+extra;\n      if (alloc > STBCC__MAX_EXITS_PER_CLUSTER)\n         alloc = STBCC__MAX_EXITS_PER_CLUSTER;\n      assert(total < 256); // must fit in byte\n      cluster->clump[i].adjacent_clump_list_index = (unsigned char) total;\n      cluster->clump[i].max_adjacent = alloc;\n      cluster->clump[i].num_adjacent = 0;\n      total += alloc;\n   }\n   assert(total <= STBCC__CLUSTER_ADJACENCY_COUNT);\n\n   stbcc__add_connections_to_adjacent_cluster(g, cx, cy, -1, 0);\n   stbcc__add_connections_to_adjacent_cluster(g, cx, cy,  1, 0);\n   stbcc__add_connections_to_adjacent_cluster(g, cx, cy,  0,-1);\n   stbcc__add_connections_to_adjacent_cluster(g, cx, cy,  0, 1);\n   // make sure all of the above succeeded.\n   assert(g->cluster[cy][cx].rebuild_adjacency == 0);\n}\n\nstatic void stbcc__add_connections_to_adjacent_cluster_with_rebuild(stbcc_grid *g, int cx, int cy, int dx, int dy)\n{\n   if (cx >= 0 && cx < g->cw && cy >= 0 && cy < g->ch) {\n      stbcc__add_connections_to_adjacent_cluster(g, cx, cy, dx, dy);\n      if (g->cluster[cy][cx].rebuild_adjacency)\n         stbcc__build_all_connections_for_cluster(g, cx, cy);\n   }\n}\n\nvoid stbcc_update_grid(stbcc_grid *g, int x, int y, int solid)\n{\n   int cx,cy;\n\n   if (!solid) {\n      if (STBCC__MAP_OPEN(g,x,y))\n         return;\n   } else {\n      if (!STBCC__MAP_OPEN(g,x,y))\n         return;\n   }\n\n   cx = STBCC__CLUSTER_X_FOR_COORD_X(x);\n   cy = STBCC__CLUSTER_Y_FOR_COORD_Y(y);\n\n   stbcc__remove_connections_to_adjacent_cluster(g, cx-1, cy,  1, 0);\n   stbcc__remove_connections_to_adjacent_cluster(g, cx+1, cy, -1, 0);\n   stbcc__remove_connections_to_adjacent_cluster(g, cx, cy-1,  0, 1);\n   stbcc__remove_connections_to_adjacent_cluster(g, cx, cy+1,  0,-1);\n\n   if (!solid)\n      STBCC__MAP_BYTE(g,x,y) |= STBCC__MAP_BYTE_MASK(x,y);\n   else\n      STBCC__MAP_BYTE(g,x,y) &= ~STBCC__MAP_BYTE_MASK(x,y);\n\n   stbcc__build_clumps_for_cluster(g, cx, cy);\n   stbcc__build_all_connections_for_cluster(g, cx, cy);\n\n   stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx-1, cy,  1, 0);\n   stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx+1, cy, -1, 0);\n   stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx, cy-1,  0, 1);\n   stbcc__add_connections_to_adjacent_cluster_with_rebuild(g, cx, cy+1,  0,-1);\n\n   if (!g->in_batched_update)\n      stbcc__build_connected_components_for_clumps(g);\n   #if 0\n   else\n      g->cluster_dirty[cy][cx] = 1;\n   #endif\n}\n\nvoid stbcc_update_batch_begin(stbcc_grid *g)\n{\n   assert(!g->in_batched_update);\n   g->in_batched_update = 1;\n}\n\nvoid stbcc_update_batch_end(stbcc_grid *g)\n{\n   assert(g->in_batched_update);\n   g->in_batched_update =  0;\n   stbcc__build_connected_components_for_clumps(g); // @OPTIMIZE: only do this if update was non-empty\n}\n\nsize_t stbcc_grid_sizeof(void)\n{\n   return sizeof(stbcc_grid);\n}\n\nvoid stbcc_init_grid(stbcc_grid *g, unsigned char *map, int w, int h)\n{\n   int i,j,k;\n   assert(w % STBCC__CLUSTER_SIZE_X == 0);\n   assert(h % STBCC__CLUSTER_SIZE_Y == 0);\n   assert(w % 8 == 0);\n\n   g->w = w;\n   g->h = h;\n   g->cw = w >> STBCC_CLUSTER_SIZE_X_LOG2;\n   g->ch = h >> STBCC_CLUSTER_SIZE_Y_LOG2;\n   g->in_batched_update = 0;\n\n   #if 0\n   for (j=0; j < STBCC__CLUSTER_COUNT_Y; ++j)\n      for (i=0; i < STBCC__CLUSTER_COUNT_X; ++i)\n         g->cluster_dirty[j][i] = 0;\n   #endif\n\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; i += 8) {\n         unsigned char c = 0;\n         for (k=0; k < 8; ++k)\n            if (map[j*w + (i+k)] == 0)\n               c |= (1 << k);\n         g->map[j][i>>3] = c;\n      }\n   }\n\n   for (j=0; j < g->ch; ++j)\n      for (i=0; i < g->cw; ++i)\n         stbcc__build_clumps_for_cluster(g, i, j);\n\n   for (j=0; j < g->ch; ++j)\n      for (i=0; i < g->cw; ++i)\n         stbcc__build_all_connections_for_cluster(g, i, j);\n\n   stbcc__build_connected_components_for_clumps(g);\n\n   for (j=0; j < g->h; ++j)\n      for (i=0; i < g->w; ++i)\n         assert(g->clump_for_node[j][i] <= STBCC__NULL_CLUMPID);\n}\n\n\nstatic void stbcc__add_clump_connection(stbcc_grid *g, int x1, int y1, int x2, int y2)\n{\n   stbcc__cluster *cluster;\n   stbcc__clump *clump;\n\n   int cx1 = STBCC__CLUSTER_X_FOR_COORD_X(x1);\n   int cy1 = STBCC__CLUSTER_Y_FOR_COORD_Y(y1);\n   int cx2 = STBCC__CLUSTER_X_FOR_COORD_X(x2);\n   int cy2 = STBCC__CLUSTER_Y_FOR_COORD_Y(y2);\n\n   stbcc__clumpid c1 = g->clump_for_node[y1][x1];\n   stbcc__clumpid c2 = g->clump_for_node[y2][x2];\n\n   stbcc__relative_clumpid rc;\n\n   assert(cx1 != cx2 || cy1 != cy2);\n   assert(abs(cx1-cx2) + abs(cy1-cy2) == 1);\n\n   // add connection to c2 in c1\n\n   rc.clump_index = c2;\n   rc.cluster_dx = x2-x1;\n   rc.cluster_dy = y2-y1;\n\n   cluster = &g->cluster[cy1][cx1];\n   clump = &cluster->clump[c1];\n   assert(clump->num_adjacent <= clump->max_adjacent);\n   if (clump->num_adjacent == clump->max_adjacent)\n      g->cluster[cy1][cx1].rebuild_adjacency = 1;\n   else {\n      stbcc__relative_clumpid *adj = &cluster->adjacency_storage[clump->adjacent_clump_list_index];\n      assert(clump->num_adjacent < STBCC__MAX_EXITS_PER_CLUMP);\n      assert(clump->adjacent_clump_list_index + clump->num_adjacent <= STBCC__CLUSTER_ADJACENCY_COUNT);\n      adj[clump->num_adjacent++] = rc;\n   }\n}\n\nstatic void stbcc__remove_clump_connection(stbcc_grid *g, int x1, int y1, int x2, int y2)\n{\n   stbcc__cluster *cluster;\n   stbcc__clump *clump;\n   stbcc__relative_clumpid *adj;\n   int i;\n\n   int cx1 = STBCC__CLUSTER_X_FOR_COORD_X(x1);\n   int cy1 = STBCC__CLUSTER_Y_FOR_COORD_Y(y1);\n   int cx2 = STBCC__CLUSTER_X_FOR_COORD_X(x2);\n   int cy2 = STBCC__CLUSTER_Y_FOR_COORD_Y(y2);\n\n   stbcc__clumpid c1 = g->clump_for_node[y1][x1];\n   stbcc__clumpid c2 = g->clump_for_node[y2][x2];\n\n   stbcc__relative_clumpid rc;\n\n   assert(cx1 != cx2 || cy1 != cy2);\n   assert(abs(cx1-cx2) + abs(cy1-cy2) == 1);\n\n   // add connection to c2 in c1\n\n   rc.clump_index = c2;\n   rc.cluster_dx = x2-x1;\n   rc.cluster_dy = y2-y1;\n\n   cluster = &g->cluster[cy1][cx1];\n   clump = &cluster->clump[c1];\n   adj = &cluster->adjacency_storage[clump->adjacent_clump_list_index];\n\n   for (i=0; i < clump->num_adjacent; ++i)\n      if (rc.clump_index == adj[i].clump_index &&\n          rc.cluster_dx  == adj[i].cluster_dx  &&\n          rc.cluster_dy  == adj[i].cluster_dy)\n         break;\n\n   if (i < clump->num_adjacent)\n      adj[i] = adj[--clump->num_adjacent];\n   else\n      assert(0);\n}\n\nstatic void stbcc__add_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy)\n{\n   unsigned char connected[STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER][STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER/8] = { { 0 } };\n   int x = cx * STBCC__CLUSTER_SIZE_X;\n   int y = cy * STBCC__CLUSTER_SIZE_Y;\n   int step_x, step_y=0, i, j, k, n;\n\n   if (cx < 0 || cx >= g->cw || cy < 0 || cy >= g->ch)\n      return;\n\n   if (cx+dx < 0 || cx+dx >= g->cw || cy+dy < 0 || cy+dy >= g->ch)\n      return;\n\n   if (g->cluster[cy][cx].rebuild_adjacency)\n      return;\n\n   assert(abs(dx) + abs(dy) == 1);\n\n   if (dx == 1) {\n      i = STBCC__CLUSTER_SIZE_X-1;\n      j = 0;\n      step_x = 0;\n      step_y = 1;\n      n = STBCC__CLUSTER_SIZE_Y;\n   } else if (dx == -1) {\n      i = 0;\n      j = 0;\n      step_x = 0;\n      step_y = 1;\n      n = STBCC__CLUSTER_SIZE_Y;\n   } else if (dy == -1) {\n      i = 0;\n      j = 0;\n      step_x = 1;\n      step_y = 0;\n      n = STBCC__CLUSTER_SIZE_X;\n   } else if (dy == 1) {\n      i = 0;\n      j = STBCC__CLUSTER_SIZE_Y-1;\n      step_x = 1;\n      step_y = 0;\n      n = STBCC__CLUSTER_SIZE_X;\n   } else {\n      assert(0);\n      return;\n   }\n\n   for (k=0; k < n; ++k) {\n      if (STBCC__MAP_OPEN(g, x+i, y+j) && STBCC__MAP_OPEN(g, x+i+dx, y+j+dy)) {\n         stbcc__clumpid src = g->clump_for_node[y+j][x+i];\n         stbcc__clumpid dest = g->clump_for_node[y+j+dy][x+i+dx];\n         if (0 == (connected[src][dest>>3] & (1 << (dest & 7)))) {\n            assert((dest>>3) < sizeof(connected));\n            connected[src][dest>>3] |= 1 << (dest & 7);\n            stbcc__add_clump_connection(g, x+i, y+j, x+i+dx, y+j+dy);\n            if (g->cluster[cy][cx].rebuild_adjacency)\n               break;\n         }\n      }\n      i += step_x;\n      j += step_y;\n   }\n}\n\nstatic void stbcc__remove_connections_to_adjacent_cluster(stbcc_grid *g, int cx, int cy, int dx, int dy)\n{\n   unsigned char disconnected[STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER][STBCC__MAX_EDGE_CLUMPS_PER_CLUSTER/8] = { { 0 } };\n   int x = cx * STBCC__CLUSTER_SIZE_X;\n   int y = cy * STBCC__CLUSTER_SIZE_Y;\n   int step_x, step_y=0, i, j, k, n;\n\n   if (cx < 0 || cx >= g->cw || cy < 0 || cy >= g->ch)\n      return;\n\n   if (cx+dx < 0 || cx+dx >= g->cw || cy+dy < 0 || cy+dy >= g->ch)\n      return;\n\n   assert(abs(dx) + abs(dy) == 1);\n\n   if (dx == 1) {\n      i = STBCC__CLUSTER_SIZE_X-1;\n      j = 0;\n      step_x = 0;\n      step_y = 1;\n      n = STBCC__CLUSTER_SIZE_Y;\n   } else if (dx == -1) {\n      i = 0;\n      j = 0;\n      step_x = 0;\n      step_y = 1;\n      n = STBCC__CLUSTER_SIZE_Y;\n   } else if (dy == -1) {\n      i = 0;\n      j = 0;\n      step_x = 1;\n      step_y = 0;\n      n = STBCC__CLUSTER_SIZE_X;\n   } else if (dy == 1) {\n      i = 0;\n      j = STBCC__CLUSTER_SIZE_Y-1;\n      step_x = 1;\n      step_y = 0;\n      n = STBCC__CLUSTER_SIZE_X;\n   } else {\n      assert(0);\n      return;\n   }\n\n   for (k=0; k < n; ++k) {\n      if (STBCC__MAP_OPEN(g, x+i, y+j) && STBCC__MAP_OPEN(g, x+i+dx, y+j+dy)) {\n         stbcc__clumpid src = g->clump_for_node[y+j][x+i];\n         stbcc__clumpid dest = g->clump_for_node[y+j+dy][x+i+dx];\n         if (0 == (disconnected[src][dest>>3] & (1 << (dest & 7)))) {\n            disconnected[src][dest>>3] |= 1 << (dest & 7);\n            stbcc__remove_clump_connection(g, x+i, y+j, x+i+dx, y+j+dy);\n         }\n      }\n      i += step_x;\n      j += step_y;\n   }\n}\n\nstatic stbcc__tinypoint stbcc__incluster_find(stbcc__cluster_build_info *cbi, int x, int y)\n{\n   stbcc__tinypoint p,q;\n   p = cbi->parent[y][x];\n   if (p.x == x && p.y == y)\n      return p;\n   q = stbcc__incluster_find(cbi, p.x, p.y);\n   cbi->parent[y][x] = q;\n   return q;\n}\n\nstatic void stbcc__incluster_union(stbcc__cluster_build_info *cbi, int x1, int y1, int x2, int y2)\n{\n   stbcc__tinypoint p = stbcc__incluster_find(cbi, x1,y1);\n   stbcc__tinypoint q = stbcc__incluster_find(cbi, x2,y2);\n\n   if (p.x == q.x && p.y == q.y)\n      return;\n\n   cbi->parent[p.y][p.x] = q;\n}\n\nstatic void stbcc__switch_root(stbcc__cluster_build_info *cbi, int x, int y, stbcc__tinypoint p)\n{\n   cbi->parent[p.y][p.x].x = x;\n   cbi->parent[p.y][p.x].y = y;\n   cbi->parent[y][x].x = x;\n   cbi->parent[y][x].y = y;\n}\n\nstatic void stbcc__build_clumps_for_cluster(stbcc_grid *g, int cx, int cy)\n{\n   stbcc__cluster *c;\n   stbcc__cluster_build_info cbi;\n   int label=0;\n   int i,j;\n   int x = cx * STBCC__CLUSTER_SIZE_X;\n   int y = cy * STBCC__CLUSTER_SIZE_Y;\n\n   // set initial disjoint set forest state\n   for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {\n      for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i) {\n         cbi.parent[j][i].x = i;\n         cbi.parent[j][i].y = j;\n      }\n   }\n\n   // join all sets that are connected\n   for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {\n      // check down only if not on bottom row\n      if (j < STBCC__CLUSTER_SIZE_Y-1)\n         for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i)\n            if (STBCC__MAP_OPEN(g,x+i,y+j) && STBCC__MAP_OPEN(g,x+i  ,y+j+1))\n               stbcc__incluster_union(&cbi, i,j, i,j+1);\n      // check right for everything but rightmost column\n      for (i=0; i < STBCC__CLUSTER_SIZE_X-1; ++i)\n         if (STBCC__MAP_OPEN(g,x+i,y+j) && STBCC__MAP_OPEN(g,x+i+1,y+j  ))\n            stbcc__incluster_union(&cbi, i,j, i+1,j);\n   }\n\n   // label all non-empty clumps along edges so that all edge clumps are first\n   // in list; this means in degenerate case we can skip traversing non-edge clumps.\n   // because in the first pass we only label leaders, we swap the leader to the\n   // edge first\n\n   // first put solid labels on all the edges; these will get overwritten if they're open\n   for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j)\n      cbi.label[j][0] = cbi.label[j][STBCC__CLUSTER_SIZE_X-1] = STBCC__NULL_CLUMPID;\n   for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i)\n      cbi.label[0][i] = cbi.label[STBCC__CLUSTER_SIZE_Y-1][i] = STBCC__NULL_CLUMPID;\n\n   for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {\n      i = 0;\n      if (STBCC__MAP_OPEN(g, x+i, y+j)) {\n         stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);\n         if (p.x == i && p.y == j)\n            // if this is the leader, give it a label\n            cbi.label[j][i] = label++;\n         else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {\n            // if leader is in interior, promote this edge node to leader and label\n            stbcc__switch_root(&cbi, i, j, p);\n            cbi.label[j][i] = label++;\n         }\n         // else if leader is on edge, do nothing (it'll get labelled when we reach it)\n      }\n      i = STBCC__CLUSTER_SIZE_X-1;\n      if (STBCC__MAP_OPEN(g, x+i, y+j)) {\n         stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);\n         if (p.x == i && p.y == j)\n            cbi.label[j][i] = label++;\n         else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {\n            stbcc__switch_root(&cbi, i, j, p);\n            cbi.label[j][i] = label++;\n         }\n      }\n   }\n\n   for (i=1; i < STBCC__CLUSTER_SIZE_Y-1; ++i) {\n      j = 0;\n      if (STBCC__MAP_OPEN(g, x+i, y+j)) {\n         stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);\n         if (p.x == i && p.y == j)\n            cbi.label[j][i] = label++;\n         else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {\n            stbcc__switch_root(&cbi, i, j, p);\n            cbi.label[j][i] = label++;\n         }\n      }\n      j = STBCC__CLUSTER_SIZE_Y-1;\n      if (STBCC__MAP_OPEN(g, x+i, y+j)) {\n         stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);\n         if (p.x == i && p.y == j)\n            cbi.label[j][i] = label++;\n         else if (!(p.x == 0 || p.x == STBCC__CLUSTER_SIZE_X-1 || p.y == 0 || p.y == STBCC__CLUSTER_SIZE_Y-1)) {\n            stbcc__switch_root(&cbi, i, j, p);\n            cbi.label[j][i] = label++;\n         }\n      }\n   }\n\n   c = &g->cluster[cy][cx];\n   c->num_edge_clumps = label;\n\n   // label any internal clusters\n   for (j=1; j < STBCC__CLUSTER_SIZE_Y-1; ++j) {\n      for (i=1; i < STBCC__CLUSTER_SIZE_X-1; ++i) {\n         stbcc__tinypoint p = cbi.parent[j][i];\n         if (p.x == i && p.y == j) {\n            if (STBCC__MAP_OPEN(g,x+i,y+j))\n               cbi.label[j][i] = label++;\n            else\n               cbi.label[j][i] = STBCC__NULL_CLUMPID;\n         }\n      }\n   }\n\n   // label all other nodes\n   for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j) {\n      for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i) {\n         stbcc__tinypoint p = stbcc__incluster_find(&cbi, i,j);\n         if (p.x != i || p.y != j) {\n            if (STBCC__MAP_OPEN(g,x+i,y+j))\n               cbi.label[j][i] = cbi.label[p.y][p.x];\n         }\n         if (STBCC__MAP_OPEN(g,x+i,y+j))\n            assert(cbi.label[j][i] != STBCC__NULL_CLUMPID);\n      }\n   }\n\n   c->num_clumps = label;\n\n   for (i=0; i < label; ++i) {\n      c->clump[i].num_adjacent = 0;\n      c->clump[i].max_adjacent = 0;\n   }\n\n   for (j=0; j < STBCC__CLUSTER_SIZE_Y; ++j)\n      for (i=0; i < STBCC__CLUSTER_SIZE_X; ++i) {\n         g->clump_for_node[y+j][x+i] = cbi.label[j][i]; // @OPTIMIZE: remove cbi.label entirely\n         assert(g->clump_for_node[y+j][x+i] <= STBCC__NULL_CLUMPID);\n      }\n\n   // set the global label for all interior clumps since they can't have connections,\n   // so we don't have to do this on the global pass (brings from O(N) to O(N^0.75))\n   for (i=(int) c->num_edge_clumps; i < (int) c->num_clumps; ++i) {\n      stbcc__global_clumpid gc;\n      gc.f.cluster_x = cx;\n      gc.f.cluster_y = cy;\n      gc.f.clump_index = i;\n      c->clump[i].global_label = gc;\n   }\n\n   c->rebuild_adjacency = 1; // flag that it has no valid adjacency data\n}\n\n#endif // STB_CONNECTED_COMPONENTS_IMPLEMENTATION\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_divide.h",
    "content": "// stb_divide.h - v0.94 - public domain - Sean Barrett, Feb 2010\n// Three kinds of divide/modulus of signed integers.\n//\n// HISTORY\n//\n//   v0.94              Fix integer overflow issues\n//   v0.93  2020-02-02  Write useful exit() value from main()\n//   v0.92  2019-02-25  Fix warning\n//   v0.91  2010-02-27  Fix euclidean division by INT_MIN for non-truncating C\n//                      Check result with 64-bit math to catch such cases\n//   v0.90  2010-02-24  First public release\n//\n// USAGE\n//\n// In *ONE* source file, put:\n//\n//    #define STB_DIVIDE_IMPLEMENTATION\n//    // #define C_INTEGER_DIVISION_TRUNCATES  // see Note 1\n//    // #define C_INTEGER_DIVISION_FLOORS     // see Note 2\n//    #include \"stb_divide.h\"\n//\n// Other source files should just include stb_divide.h\n//\n// Note 1: On platforms/compilers that you know signed C division\n// truncates, you can #define C_INTEGER_DIVISION_TRUNCATES.\n//\n// Note 2: On platforms/compilers that you know signed C division\n// floors (rounds to negative infinity), you can #define\n// C_INTEGER_DIVISION_FLOORS.\n//\n// You can #define STB_DIVIDE_TEST in which case the implementation\n// will generate a main() and compiling the result will create a\n// program that tests the implementation. Run it with no arguments\n// and any output indicates an error; run it with any argument and\n// it will also print the test results. Define STB_DIVIDE_TEST_64\n// to a 64-bit integer type to avoid overflows in the result-checking\n// which give false negatives.\n//\n// ABOUT\n//\n// This file provides three different consistent divide/mod pairs\n// implemented on top of arbitrary C/C++ division, including correct\n// handling of overflow of intermediate calculations:\n//\n//     trunc:   a/b truncates to 0,           a%b has same sign as a\n//     floor:   a/b truncates to -inf,        a%b has same sign as b\n//     eucl:    a/b truncates to sign(b)*inf, a%b is non-negative\n//\n// Not necessarily optimal; I tried to keep it generally efficient,\n// but there may be better ways.\n//\n// Briefly, for those who are not familiar with the problem, we note\n// the reason these divides exist and are interesting:\n//\n//     'trunc' is easy to implement in hardware (strip the signs,\n//          compute, reapply the signs), thus is commonly defined\n//          by many languages (including C99)\n//\n//     'floor' is simple to define and better behaved than trunc;\n//          for example it divides integers into fixed-size buckets\n//          without an extra-wide bucket at 0, and for a fixed\n//          divisor N there are only |N| possible moduli.\n//\n//     'eucl' guarantees fixed-sized buckets *and* a non-negative\n//          modulus and defines division to be whatever is needed\n//          to achieve that result.\n//\n// See \"The Euclidean definition of the functions div and mod\"\n// by Raymond Boute (1992), or \"Division and Modulus for Computer\n// Scientists\" by Daan Leijen (2001)\n//\n// We assume of the built-in C division:\n//     (a) modulus is the remainder for the corresponding division\n//     (b) a/b truncates if a and b are the same sign\n//\n// Property (a) requires (a/b)*b + (a%b)==a, and is required by C.\n// Property (b) seems to be true of all hardware but is *not* satisfied\n// by the euclidean division operator we define, so it's possibly not\n// always true. If any such platform turns up, we can add more cases.\n// (Possibly only stb_div_trunc currently relies on property (b).)\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n\n#ifndef INCLUDE_STB_DIVIDE_H\n#define INCLUDE_STB_DIVIDE_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nextern int stb_div_trunc(int value_to_be_divided, int value_to_divide_by);\nextern int stb_div_floor(int value_to_be_divided, int value_to_divide_by);\nextern int stb_div_eucl (int value_to_be_divided, int value_to_divide_by);\nextern int stb_mod_trunc(int value_to_be_divided, int value_to_divide_by);\nextern int stb_mod_floor(int value_to_be_divided, int value_to_divide_by);\nextern int stb_mod_eucl (int value_to_be_divided, int value_to_divide_by);\n\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef STB_DIVIDE_IMPLEMENTATION\n\n#if defined(__STDC_VERSION) && __STDC_VERSION__ >= 19901\n   #ifndef C_INTEGER_DIVISION_TRUNCATES\n      #define C_INTEGER_DIVISION_TRUNCATES\n   #endif\n#endif\n\n#ifndef INT_MIN\n#include <limits.h> // if you have no limits.h, #define INT_MIN yourself\n#endif\n\n// the following macros are designed to allow testing\n// other platforms by simulating them\n#ifndef STB_DIVIDE_TEST_FLOOR\n   #define stb__div(a,b)  ((a)/(b))\n   #define stb__mod(a,b)  ((a)%(b))\n#else\n   // implement floor-style divide on trunc platform\n   #ifndef C_INTEGER_DIVISION_TRUNCATES\n   #error \"floor test requires truncating division\"\n   #endif\n   #undef C_INTEGER_DIVISION_TRUNCATES\n   int stb__div(int v1, int v2)\n   {\n      int q = v1/v2, r = v1%v2;\n      if ((r > 0 && v2 < 0) || (r < 0 && v2 > 0))\n         return q-1;\n      else\n         return q;\n   }\n\n   int stb__mod(int v1, int v2)\n   {\n      int r = v1%v2;\n      if ((r > 0 && v2 < 0) || (r < 0 && v2 > 0))\n         return r+v2;\n      else\n         return r;\n   }\n#endif\n\nint stb_div_trunc(int v1, int v2)\n{\n   #ifdef C_INTEGER_DIVISION_TRUNCATES\n   return v1/v2;\n   #else\n   if (v1 >= 0 && v2 <= 0)\n      return -stb__div(-v1,v2);  // both negative to avoid overflow\n   if (v1 <= 0 && v2 >= 0)\n      if (v1 != INT_MIN)\n         return -stb__div(v1,-v2);    // both negative to avoid overflow\n      else\n         return -stb__div(v1+v2,-v2)-1; // push v1 away from wrap point\n   else\n      return v1/v2;            // same sign, so expect truncation\n   #endif\n}\n\nint stb_div_floor(int v1, int v2)\n{\n   #ifdef C_INTEGER_DIVISION_FLOORS\n   return v1/v2;\n   #else\n   if (v1 >= 0 && v2 < 0) {\n      if (v2 + 1 >= INT_MIN + v1) // check if increasing v1's magnitude overflows\n         return -stb__div((v2+1)-v1,v2); // nope, so just compute it\n      else\n         return -stb__div(-v1,v2) + ((-v1)%v2 ? -1 : 0);\n   }\n   if (v1 < 0 && v2 >= 0) {\n      if (v1 != INT_MIN) {\n         if (v1 + 1 >= INT_MIN + v2) // check if increasing v1's magnitude overflows\n            return -stb__div((v1+1)-v2,-v2); // nope, so just compute it\n         else\n            return -stb__div(-v1,v2) + (stb__mod(v1,-v2) ? -1 : 0);\n      } else // it must be possible to compute -(v1+v2) without overflowing\n         return -stb__div(-(v1+v2),v2) + (stb__mod(-(v1+v2),v2) ? -2 : -1);\n   } else\n      return v1/v2;           // same sign, so expect truncation\n   #endif\n}\n\nint stb_div_eucl(int v1, int v2)\n{\n   int q,r;\n   #ifdef C_INTEGER_DIVISION_TRUNCATES\n   q = v1/v2;\n   r = v1%v2;\n   #else\n   // handle every quadrant separately, since we can't rely on q and r flor\n   if (v1 >= 0)\n      if (v2 >= 0)\n         return stb__div(v1,v2);\n      else if (v2 != INT_MIN)\n         q = -stb__div(v1,-v2), r = stb__mod(v1,-v2);\n      else\n         q = 0, r = v1;\n   else if (v1 != INT_MIN)\n      if (v2 >= 0)\n         q = -stb__div(-v1,v2), r = -stb__mod(-v1,v2);\n      else if (v2 != INT_MIN)\n         q = stb__div(-v1,-v2), r = -stb__mod(-v1,-v2);\n      else // if v2 is INT_MIN, then we can't use -v2, but we can't divide by v2\n         q = 1, r = v1-q*v2;\n   else // if v1 is INT_MIN, we have to move away from overflow place\n      if (v2 >= 0)\n         q = -stb__div(-(v1+v2),v2)-1, r = -stb__mod(-(v1+v2),v2);\n      else if (v2 != INT_MIN)\n         q = stb__div(-(v1-v2),-v2)+1, r = -stb__mod(-(v1-v2),-v2);\n      else // for INT_MIN / INT_MIN, we need to be extra-careful to avoid overflow\n         q = 1, r = 0;\n   #endif\n   if (r >= 0)\n      return q;\n   else\n      return q + (v2 > 0 ? -1 : 1);\n}\n\nint stb_mod_trunc(int v1, int v2)\n{\n   #ifdef C_INTEGER_DIVISION_TRUNCATES\n   return v1%v2;\n   #else\n   if (v1 >= 0) { // modulus result should always be positive\n      int r = stb__mod(v1,v2);\n      if (r >= 0)\n         return r;\n      else\n         return r - (v2 < 0 ? v2 : -v2);\n   } else {    // modulus result should always be negative\n      int r = stb__mod(v1,v2);\n      if (r <= 0)\n         return r;\n      else\n         return r + (v2 < 0 ? v2 : -v2);\n   }\n   #endif\n}\n\nint stb_mod_floor(int v1, int v2)\n{\n   #ifdef C_INTEGER_DIVISION_FLOORS\n   return v1%v2;\n   #else\n   if (v2 >= 0) { // result should always be positive\n      int r = stb__mod(v1,v2);\n      if (r >= 0)\n         return r;\n      else\n         return r + v2;\n   } else { // result should always be negative\n      int r = stb__mod(v1,v2);\n      if (r <= 0)\n         return r;\n      else\n         return r + v2;\n   }\n   #endif\n}\n\nint stb_mod_eucl(int v1, int v2)\n{\n   int r = stb__mod(v1,v2);\n\n   if (r >= 0)\n      return r;\n   else\n      return r - (v2 < 0 ? v2 : -v2); // negative abs() [to avoid overflow]\n}\n\n#ifdef STB_DIVIDE_TEST\n#include <stdio.h>\n#include <math.h>\n#include <limits.h>\n\nint show=0;\nint err=0;\n\nvoid stbdiv_check(int q, int r, int a, int b, char *type, int dir)\n{\n   if ((dir > 0 && r < 0) || (dir < 0 && r > 0)) {\n      fprintf(stderr, \"FAILED: %s(%d,%d) remainder %d in wrong direction\\n\", type,a,b,r);\n      err++;\n   } else\n      if (b != INT_MIN) // can't compute abs(), but if b==INT_MIN all remainders are valid\n         if (r <= -abs(b) || r >= abs(b)) {\n            fprintf(stderr, \"FAILED: %s(%d,%d) remainder %d out of range\\n\", type,a,b,r);\n            err++;\n         }\n   #ifdef STB_DIVIDE_TEST_64\n   {\n      STB_DIVIDE_TEST_64 q64 = q, r64=r, a64=a, b64=b;\n      if (q64*b64+r64 != a64) {\n         fprintf(stderr, \"FAILED: %s(%d,%d) remainder %d doesn't match quotient %d\\n\", type,a,b,r,q);\n         err++;\n      }\n   }\n   #else\n   if (q*b+r != a) {\n      fprintf(stderr, \"FAILED: %s(%d,%d) remainder %d doesn't match quotient %d\\n\", type,a,b,r,q);\n      err++;\n   }\n   #endif\n}\n\nvoid test(int a, int b)\n{\n   int q,r;\n   if (show) printf(\"(%+11d,%+d) |  \", a,b);\n   q = stb_div_trunc(a,b), r = stb_mod_trunc(a,b);\n   if (show) printf(\"(%+11d,%+2d)  \", q,r); stbdiv_check(q,r,a,b, \"trunc\",a);\n   q = stb_div_floor(a,b), r = stb_mod_floor(a,b);\n   if (show) printf(\"(%+11d,%+2d)  \", q,r); stbdiv_check(q,r,a,b, \"floor\",b);\n   q = stb_div_eucl (a,b), r = stb_mod_eucl (a,b);\n   if (show) printf(\"(%+11d,%+2d)\\n\", q,r); stbdiv_check(q,r,a,b, \"euclidean\",1);\n}\n\nvoid testh(int a, int b)\n{\n   int q,r;\n   if (show) printf(\"(%08x,%08x) |\\n\", a,b);\n   q = stb_div_trunc(a,b), r = stb_mod_trunc(a,b); stbdiv_check(q,r,a,b, \"trunc\",a);\n   if (show) printf(\"             (%08x,%08x)\", q,r);\n   q = stb_div_floor(a,b), r = stb_mod_floor(a,b); stbdiv_check(q,r,a,b, \"floor\",b);\n   if (show) printf(\"   (%08x,%08x)\", q,r);\n   q = stb_div_eucl (a,b), r = stb_mod_eucl (a,b); stbdiv_check(q,r,a,b, \"euclidean\",1);\n   if (show) printf(\"   (%08x,%08x)\\n \", q,r);\n}\n\nint main(int argc, char **argv)\n{\n   if (argc > 1) show=1;\n\n   test(8,3);\n   test(8,-3);\n   test(-8,3);\n   test(-8,-3);\n   test(1,2);\n   test(1,-2);\n   test(-1,2);\n   test(-1,-2);\n   test(8,4);\n   test(8,-4);\n   test(-8,4);\n   test(-8,-4);\n\n   test(INT_MAX,1);\n   test(INT_MIN,1);\n   test(INT_MIN+1,1);\n   test(INT_MAX,-1);\n   //test(INT_MIN,-1); // this traps in MSVC, so we leave it untested\n   test(INT_MIN+1,-1);\n   test(INT_MIN,-2);\n   test(INT_MIN+1,2);\n   test(INT_MIN+1,-2);\n   test(INT_MAX,2);\n   test(INT_MAX,-2);\n   test(INT_MIN+1,2);\n   test(INT_MIN+1,-2);\n   test(INT_MIN,2);\n   test(INT_MIN,-2);\n   test(INT_MIN,7);\n   test(INT_MIN,-7);\n   test(INT_MIN+1,4);\n   test(INT_MIN+1,-4);\n\n   testh(-7, INT_MIN);\n   testh(-1, INT_MIN);\n   testh(1, INT_MIN);\n   testh(7, INT_MIN);\n\n   testh(INT_MAX-1, INT_MIN);\n   testh(INT_MAX,   INT_MIN);\n   testh(INT_MIN,   INT_MIN);\n   testh(INT_MIN+1, INT_MIN);\n\n   testh(INT_MAX-1, INT_MAX);\n   testh(INT_MAX  , INT_MAX);\n   testh(INT_MIN  , INT_MAX);\n   testh(INT_MIN+1, INT_MAX);\n\n   return err > 0 ? 1 : 0;\n}\n#endif // STB_DIVIDE_TEST\n#endif // STB_DIVIDE_IMPLEMENTATION\n#endif // INCLUDE_STB_DIVIDE_H\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_ds.h",
    "content": "/* stb_ds.h - v0.67 - public domain data structures - Sean Barrett 2019\n\n   This is a single-header-file library that provides easy-to-use\n   dynamic arrays and hash tables for C (also works in C++).\n\n   For a gentle introduction:\n      http://nothings.org/stb_ds\n\n   To use this library, do this in *one* C or C++ file:\n      #define STB_DS_IMPLEMENTATION\n      #include \"stb_ds.h\"\n\nTABLE OF CONTENTS\n\n  Table of Contents\n  Compile-time options\n  License\n  Documentation\n  Notes\n  Notes - Dynamic arrays\n  Notes - Hash maps\n  Credits\n\nCOMPILE-TIME OPTIONS\n\n  #define STBDS_NO_SHORT_NAMES\n\n     This flag needs to be set globally.\n\n     By default stb_ds exposes shorter function names that are not qualified\n     with the \"stbds_\" prefix. If these names conflict with the names in your\n     code, define this flag.\n\n  #define STBDS_SIPHASH_2_4\n\n     This flag only needs to be set in the file containing #define STB_DS_IMPLEMENTATION.\n\n     By default stb_ds.h hashes using a weaker variant of SipHash and a custom hash for\n     4- and 8-byte keys. On 64-bit platforms, you can define the above flag to force\n     stb_ds.h to use specification-compliant SipHash-2-4 for all keys. Doing so makes\n     hash table insertion about 20% slower on 4- and 8-byte keys, 5% slower on\n     64-byte keys, and 10% slower on 256-byte keys on my test computer.\n\n  #define STBDS_REALLOC(context,ptr,size) better_realloc\n  #define STBDS_FREE(context,ptr)         better_free\n\n     These defines only need to be set in the file containing #define STB_DS_IMPLEMENTATION.\n\n     By default stb_ds uses stdlib realloc() and free() for memory management. You can\n     substitute your own functions instead by defining these symbols. You must either\n     define both, or neither. Note that at the moment, 'context' will always be NULL.\n     @TODO add an array/hash initialization function that takes a memory context pointer.\n\n  #define STBDS_UNIT_TESTS\n\n     Defines a function stbds_unit_tests() that checks the functioning of the data structures.\n\n  Note that on older versions of gcc (e.g. 5.x.x) you may need to build with '-std=c++0x'\n     (or equivalentally '-std=c++11') when using anonymous structures as seen on the web\n     page or in STBDS_UNIT_TESTS.\n\nLICENSE\n\n  Placed in the public domain and also MIT licensed.\n  See end of file for detailed license information.\n\nDOCUMENTATION\n\n  Dynamic Arrays\n\n    Non-function interface:\n\n      Declare an empty dynamic array of type T\n        T* foo = NULL;\n\n      Access the i'th item of a dynamic array 'foo' of type T, T* foo:\n        foo[i]\n\n    Functions (actually macros)\n\n      arrfree:\n        void arrfree(T*);\n          Frees the array.\n\n      arrlen:\n        ptrdiff_t arrlen(T*);\n          Returns the number of elements in the array.\n\n      arrlenu:\n        size_t arrlenu(T*);\n          Returns the number of elements in the array as an unsigned type.\n\n      arrpop:\n        T arrpop(T* a)\n          Removes the final element of the array and returns it.\n\n      arrput:\n        T arrput(T* a, T b);\n          Appends the item b to the end of array a. Returns b.\n\n      arrins:\n        T arrins(T* a, int p, T b);\n          Inserts the item b into the middle of array a, into a[p],\n          moving the rest of the array over. Returns b.\n\n      arrinsn:\n        void arrinsn(T* a, int p, int n);\n          Inserts n uninitialized items into array a starting at a[p],\n          moving the rest of the array over.\n\n      arraddnptr:\n        T* arraddnptr(T* a, int n)\n          Appends n uninitialized items onto array at the end.\n          Returns a pointer to the first uninitialized item added.\n\n      arraddnindex:\n        size_t arraddnindex(T* a, int n)\n          Appends n uninitialized items onto array at the end.\n          Returns the index of the first uninitialized item added.\n\n      arrdel:\n        void arrdel(T* a, int p);\n          Deletes the element at a[p], moving the rest of the array over.\n\n      arrdeln:\n        void arrdeln(T* a, int p, int n);\n          Deletes n elements starting at a[p], moving the rest of the array over.\n\n      arrdelswap:\n        void arrdelswap(T* a, int p);\n          Deletes the element at a[p], replacing it with the element from\n          the end of the array. O(1) performance.\n\n      arrsetlen:\n        void arrsetlen(T* a, int n);\n          Changes the length of the array to n. Allocates uninitialized\n          slots at the end if necessary.\n\n      arrsetcap:\n        size_t arrsetcap(T* a, int n);\n          Sets the length of allocated storage to at least n. It will not\n          change the length of the array.\n\n      arrcap:\n        size_t arrcap(T* a);\n          Returns the number of total elements the array can contain without\n          needing to be reallocated.\n\n  Hash maps & String hash maps\n\n    Given T is a structure type: struct { TK key; TV value; }. Note that some\n    functions do not require TV value and can have other fields. For string\n    hash maps, TK must be 'char *'.\n\n    Special interface:\n\n      stbds_rand_seed:\n        void stbds_rand_seed(size_t seed);\n          For security against adversarially chosen data, you should seed the\n          library with a strong random number. Or at least seed it with time().\n\n      stbds_hash_string:\n        size_t stbds_hash_string(char *str, size_t seed);\n          Returns a hash value for a string.\n\n      stbds_hash_bytes:\n        size_t stbds_hash_bytes(void *p, size_t len, size_t seed);\n          These functions hash an arbitrary number of bytes. The function\n          uses a custom hash for 4- and 8-byte data, and a weakened version\n          of SipHash for everything else. On 64-bit platforms you can get\n          specification-compliant SipHash-2-4 on all data by defining\n          STBDS_SIPHASH_2_4, at a significant cost in speed.\n\n    Non-function interface:\n\n      Declare an empty hash map of type T\n        T* foo = NULL;\n\n      Access the i'th entry in a hash table T* foo:\n        foo[i]\n\n    Function interface (actually macros):\n\n      hmfree\n      shfree\n        void hmfree(T*);\n        void shfree(T*);\n          Frees the hashmap and sets the pointer to NULL.\n\n      hmlen\n      shlen\n        ptrdiff_t hmlen(T*)\n        ptrdiff_t shlen(T*)\n          Returns the number of elements in the hashmap.\n\n      hmlenu\n      shlenu\n        size_t hmlenu(T*)\n        size_t shlenu(T*)\n          Returns the number of elements in the hashmap.\n\n      hmgeti\n      shgeti\n      hmgeti_ts\n        ptrdiff_t hmgeti(T*, TK key)\n        ptrdiff_t shgeti(T*, char* key)\n        ptrdiff_t hmgeti_ts(T*, TK key, ptrdiff_t tempvar)\n          Returns the index in the hashmap which has the key 'key', or -1\n          if the key is not present.\n\n      hmget\n      hmget_ts\n      shget\n        TV hmget(T*, TK key)\n        TV shget(T*, char* key)\n        TV hmget_ts(T*, TK key, ptrdiff_t tempvar)\n          Returns the value corresponding to 'key' in the hashmap.\n          The structure must have a 'value' field\n\n      hmgets\n      shgets\n        T hmgets(T*, TK key)\n        T shgets(T*, char* key)\n          Returns the structure corresponding to 'key' in the hashmap.\n\n      hmgetp\n      shgetp\n      hmgetp_ts\n      hmgetp_null\n      shgetp_null\n        T* hmgetp(T*, TK key)\n        T* shgetp(T*, char* key)\n        T* hmgetp_ts(T*, TK key, ptrdiff_t tempvar)\n        T* hmgetp_null(T*, TK key)\n        T* shgetp_null(T*, char *key)\n          Returns a pointer to the structure corresponding to 'key' in\n          the hashmap. Functions ending in \"_null\" return NULL if the key\n          is not present in the hashmap; the others return a pointer to a\n          structure holding the default value (but not the searched-for key).\n\n      hmdefault\n      shdefault\n        TV hmdefault(T*, TV value)\n        TV shdefault(T*, TV value)\n          Sets the default value for the hashmap, the value which will be\n          returned by hmget/shget if the key is not present.\n\n      hmdefaults\n      shdefaults\n        TV hmdefaults(T*, T item)\n        TV shdefaults(T*, T item)\n          Sets the default struct for the hashmap, the contents which will be\n          returned by hmgets/shgets if the key is not present.\n\n      hmput\n      shput\n        TV hmput(T*, TK key, TV value)\n        TV shput(T*, char* key, TV value)\n          Inserts a <key,value> pair into the hashmap. If the key is already\n          present in the hashmap, updates its value.\n\n      hmputs\n      shputs\n        T hmputs(T*, T item)\n        T shputs(T*, T item)\n          Inserts a struct with T.key into the hashmap. If the struct is already\n          present in the hashmap, updates it.\n\n      hmdel\n      shdel\n        int hmdel(T*, TK key)\n        int shdel(T*, char* key)\n          If 'key' is in the hashmap, deletes its entry and returns 1.\n          Otherwise returns 0.\n\n    Function interface (actually macros) for strings only:\n\n      sh_new_strdup\n        void sh_new_strdup(T*);\n          Overwrites the existing pointer with a newly allocated\n          string hashmap which will automatically allocate and free\n          each string key using realloc/free\n\n      sh_new_arena\n        void sh_new_arena(T*);\n          Overwrites the existing pointer with a newly allocated\n          string hashmap which will automatically allocate each string\n          key to a string arena. Every string key ever used by this\n          hash table remains in the arena until the arena is freed.\n          Additionally, any key which is deleted and reinserted will\n          be allocated multiple times in the string arena.\n\nNOTES\n\n  * These data structures are realloc'd when they grow, and the macro\n    \"functions\" write to the provided pointer. This means: (a) the pointer\n    must be an lvalue, and (b) the pointer to the data structure is not\n    stable, and you must maintain it the same as you would a realloc'd\n    pointer. For example, if you pass a pointer to a dynamic array to a\n    function which updates it, the function must return back the new\n    pointer to the caller. This is the price of trying to do this in C.\n\n  * The following are the only functions that are thread-safe on a single data\n    structure, i.e. can be run in multiple threads simultaneously on the same\n    data structure\n        hmlen        shlen\n        hmlenu       shlenu\n        hmget_ts     shget_ts\n        hmgeti_ts    shgeti_ts\n        hmgets_ts    shgets_ts\n\n  * You iterate over the contents of a dynamic array and a hashmap in exactly\n    the same way, using arrlen/hmlen/shlen:\n\n      for (i=0; i < arrlen(foo); ++i)\n         ... foo[i] ...\n\n  * All operations except arrins/arrdel are O(1) amortized, but individual\n    operations can be slow, so these data structures may not be suitable\n    for real time use. Dynamic arrays double in capacity as needed, so\n    elements are copied an average of once. Hash tables double/halve\n    their size as needed, with appropriate hysteresis to maintain O(1)\n    performance.\n\nNOTES - DYNAMIC ARRAY\n\n  * If you know how long a dynamic array is going to be in advance, you can avoid\n    extra memory allocations by using arrsetlen to allocate it to that length in\n    advance and use foo[n] while filling it out, or arrsetcap to allocate the memory\n    for that length and use arrput/arrpush as normal.\n\n  * Unlike some other versions of the dynamic array, this version should\n    be safe to use with strict-aliasing optimizations.\n\nNOTES - HASH MAP\n\n  * For compilers other than GCC and clang (e.g. Visual Studio), for hmput/hmget/hmdel\n    and variants, the key must be an lvalue (so the macro can take the address of it).\n    Extensions are used that eliminate this requirement if you're using C99 and later\n    in GCC or clang, or if you're using C++ in GCC. But note that this can make your\n    code less portable.\n\n  * To test for presence of a key in a hashmap, just do 'hmgeti(foo,key) >= 0'.\n\n  * The iteration order of your data in the hashmap is determined solely by the\n    order of insertions and deletions. In particular, if you never delete, new\n    keys are always added at the end of the array. This will be consistent\n    across all platforms and versions of the library. However, you should not\n    attempt to serialize the internal hash table, as the hash is not consistent\n    between different platforms, and may change with future versions of the library.\n\n  * Use sh_new_arena() for string hashmaps that you never delete from. Initialize\n    with NULL if you're managing the memory for your strings, or your strings are\n    never freed (at least until the hashmap is freed). Otherwise, use sh_new_strdup().\n    @TODO: make an arena variant that garbage collects the strings with a trivial\n    copy collector into a new arena whenever the table shrinks / rebuilds. Since\n    current arena recommendation is to only use arena if it never deletes, then\n    this can just replace current arena implementation.\n\n  * If adversarial input is a serious concern and you're on a 64-bit platform,\n    enable STBDS_SIPHASH_2_4 (see the 'Compile-time options' section), and pass\n    a strong random number to stbds_rand_seed.\n\n  * The default value for the hash table is stored in foo[-1], so if you\n    use code like 'hmget(T,k)->value = 5' you can accidentally overwrite\n    the value stored by hmdefault if 'k' is not present.\n\nCREDITS\n\n  Sean Barrett -- library, idea for dynamic array API/implementation\n  Per Vognsen  -- idea for hash table API/implementation\n  Rafael Sachetto -- arrpop()\n  github:HeroicKatora -- arraddn() reworking\n\n  Bugfixes:\n    Andy Durdin\n    Shane Liesegang\n    Vinh Truong\n    Andreas Molzer\n    github:hashitaku\n    github:srdjanstipic\n    Macoy Madson\n    Andreas Vennstrom\n    Tobias Mansfield-Williams\n*/\n\n#ifdef STBDS_UNIT_TESTS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#ifndef INCLUDE_STB_DS_H\n#define INCLUDE_STB_DS_H\n\n#include <stddef.h>\n#include <string.h>\n\n#ifndef STBDS_NO_SHORT_NAMES\n#define arrlen      stbds_arrlen\n#define arrlenu     stbds_arrlenu\n#define arrput      stbds_arrput\n#define arrpush     stbds_arrput\n#define arrpop      stbds_arrpop\n#define arrfree     stbds_arrfree\n#define arraddn     stbds_arraddn // deprecated, use one of the following instead:\n#define arraddnptr  stbds_arraddnptr\n#define arraddnindex stbds_arraddnindex\n#define arrsetlen   stbds_arrsetlen\n#define arrlast     stbds_arrlast\n#define arrins      stbds_arrins\n#define arrinsn     stbds_arrinsn\n#define arrdel      stbds_arrdel\n#define arrdeln     stbds_arrdeln\n#define arrdelswap  stbds_arrdelswap\n#define arrcap      stbds_arrcap\n#define arrsetcap   stbds_arrsetcap\n\n#define hmput       stbds_hmput\n#define hmputs      stbds_hmputs\n#define hmget       stbds_hmget\n#define hmget_ts    stbds_hmget_ts\n#define hmgets      stbds_hmgets\n#define hmgetp      stbds_hmgetp\n#define hmgetp_ts   stbds_hmgetp_ts\n#define hmgetp_null stbds_hmgetp_null\n#define hmgeti      stbds_hmgeti\n#define hmgeti_ts   stbds_hmgeti_ts\n#define hmdel       stbds_hmdel\n#define hmlen       stbds_hmlen\n#define hmlenu      stbds_hmlenu\n#define hmfree      stbds_hmfree\n#define hmdefault   stbds_hmdefault\n#define hmdefaults  stbds_hmdefaults\n\n#define shput       stbds_shput\n#define shputi      stbds_shputi\n#define shputs      stbds_shputs\n#define shget       stbds_shget\n#define shgeti      stbds_shgeti\n#define shgets      stbds_shgets\n#define shgetp      stbds_shgetp\n#define shgetp_null stbds_shgetp_null\n#define shdel       stbds_shdel\n#define shlen       stbds_shlen\n#define shlenu      stbds_shlenu\n#define shfree      stbds_shfree\n#define shdefault   stbds_shdefault\n#define shdefaults  stbds_shdefaults\n#define sh_new_arena  stbds_sh_new_arena\n#define sh_new_strdup stbds_sh_new_strdup\n\n#define stralloc    stbds_stralloc\n#define strreset    stbds_strreset\n#endif\n\n#if defined(STBDS_REALLOC) && !defined(STBDS_FREE) || !defined(STBDS_REALLOC) && defined(STBDS_FREE)\n#error \"You must define both STBDS_REALLOC and STBDS_FREE, or neither.\"\n#endif\n#if !defined(STBDS_REALLOC) && !defined(STBDS_FREE)\n#include <stdlib.h>\n#define STBDS_REALLOC(c,p,s) realloc(p,s)\n#define STBDS_FREE(c,p)      free(p)\n#endif\n\n#ifdef _MSC_VER\n#define STBDS_NOTUSED(v)  (void)(v)\n#else\n#define STBDS_NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// for security against attackers, seed the library with a random number, at least time() but stronger is better\nextern void stbds_rand_seed(size_t seed);\n\n// these are the hash functions used internally if you want to test them or use them for other purposes\nextern size_t stbds_hash_bytes(void *p, size_t len, size_t seed);\nextern size_t stbds_hash_string(char *str, size_t seed);\n\n// this is a simple string arena allocator, initialize with e.g. 'stbds_string_arena my_arena={0}'.\ntypedef struct stbds_string_arena stbds_string_arena;\nextern char * stbds_stralloc(stbds_string_arena *a, char *str);\nextern void   stbds_strreset(stbds_string_arena *a);\n\n// have to #define STBDS_UNIT_TESTS to call this\nextern void stbds_unit_tests(void);\n\n///////////////\n//\n// Everything below here is implementation details\n//\n\nextern void * stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap);\nextern void   stbds_arrfreef(void *a);\nextern void   stbds_hmfree_func(void *p, size_t elemsize);\nextern void * stbds_hmget_key(void *a, size_t elemsize, void *key, size_t keysize, int mode);\nextern void * stbds_hmget_key_ts(void *a, size_t elemsize, void *key, size_t keysize, ptrdiff_t *temp, int mode);\nextern void * stbds_hmput_default(void *a, size_t elemsize);\nextern void * stbds_hmput_key(void *a, size_t elemsize, void *key, size_t keysize, int mode);\nextern void * stbds_hmdel_key(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode);\nextern void * stbds_shmode_func(size_t elemsize, int mode);\n\n#ifdef __cplusplus\n}\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n#define STBDS_HAS_TYPEOF\n#ifdef __cplusplus\n//#define STBDS_HAS_LITERAL_ARRAY  // this is currently broken for clang\n#endif\n#endif\n\n#if !defined(__cplusplus)\n#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L\n#define STBDS_HAS_LITERAL_ARRAY\n#endif\n#endif\n\n// this macro takes the address of the argument, but on gcc/clang can accept rvalues\n#if defined(STBDS_HAS_LITERAL_ARRAY) && defined(STBDS_HAS_TYPEOF)\n  #if __clang__\n  #define STBDS_ADDRESSOF(typevar, value)     ((__typeof__(typevar)[1]){value}) // literal array decays to pointer to value\n  #else\n  #define STBDS_ADDRESSOF(typevar, value)     ((typeof(typevar)[1]){value}) // literal array decays to pointer to value\n  #endif\n#else\n#define STBDS_ADDRESSOF(typevar, value)     &(value)\n#endif\n\n#define STBDS_OFFSETOF(var,field)           ((char *) &(var)->field - (char *) (var))\n\n#define stbds_header(t)  ((stbds_array_header *) (t) - 1)\n#define stbds_temp(t)    stbds_header(t)->temp\n#define stbds_temp_key(t) (*(char **) stbds_header(t)->hash_table)\n\n#define stbds_arrsetcap(a,n)   (stbds_arrgrow(a,0,n))\n#define stbds_arrsetlen(a,n)   ((stbds_arrcap(a) < (size_t) (n) ? stbds_arrsetcap((a),(size_t)(n)),0 : 0), (a) ? stbds_header(a)->length = (size_t) (n) : 0)\n#define stbds_arrcap(a)        ((a) ? stbds_header(a)->capacity : 0)\n#define stbds_arrlen(a)        ((a) ? (ptrdiff_t) stbds_header(a)->length : 0)\n#define stbds_arrlenu(a)       ((a) ?             stbds_header(a)->length : 0)\n#define stbds_arrput(a,v)      (stbds_arrmaybegrow(a,1), (a)[stbds_header(a)->length++] = (v))\n#define stbds_arrpush          stbds_arrput  // synonym\n#define stbds_arrpop(a)        (stbds_header(a)->length--, (a)[stbds_header(a)->length])\n#define stbds_arraddn(a,n)     ((void)(stbds_arraddnindex(a, n)))    // deprecated, use one of the following instead:\n#define stbds_arraddnptr(a,n)  (stbds_arrmaybegrow(a,n), (n) ? (stbds_header(a)->length += (n), &(a)[stbds_header(a)->length-(n)]) : (a))\n#define stbds_arraddnindex(a,n)(stbds_arrmaybegrow(a,n), (n) ? (stbds_header(a)->length += (n), stbds_header(a)->length-(n)) : stbds_arrlen(a))\n#define stbds_arraddnoff       stbds_arraddnindex\n#define stbds_arrlast(a)       ((a)[stbds_header(a)->length-1])\n#define stbds_arrfree(a)       ((void) ((a) ? STBDS_FREE(NULL,stbds_header(a)) : (void)0), (a)=NULL)\n#define stbds_arrdel(a,i)      stbds_arrdeln(a,i,1)\n#define stbds_arrdeln(a,i,n)   (memmove(&(a)[i], &(a)[(i)+(n)], sizeof *(a) * (stbds_header(a)->length-(n)-(i))), stbds_header(a)->length -= (n))\n#define stbds_arrdelswap(a,i)  ((a)[i] = stbds_arrlast(a), stbds_header(a)->length -= 1)\n#define stbds_arrinsn(a,i,n)   (stbds_arraddn((a),(n)), memmove(&(a)[(i)+(n)], &(a)[i], sizeof *(a) * (stbds_header(a)->length-(n)-(i))))\n#define stbds_arrins(a,i,v)    (stbds_arrinsn((a),(i),1), (a)[i]=(v))\n\n#define stbds_arrmaybegrow(a,n)  ((!(a) || stbds_header(a)->length + (n) > stbds_header(a)->capacity) \\\n                                  ? (stbds_arrgrow(a,n,0),0) : 0)\n\n#define stbds_arrgrow(a,b,c)   ((a) = stbds_arrgrowf_wrapper((a), sizeof *(a), (b), (c)))\n\n#define stbds_hmput(t, k, v) \\\n    ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, 0),   \\\n     (t)[stbds_temp((t)-1)].key = (k),    \\\n     (t)[stbds_temp((t)-1)].value = (v))\n\n#define stbds_hmputs(t, s) \\\n    ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), &(s).key, sizeof (s).key, STBDS_HM_BINARY), \\\n     (t)[stbds_temp((t)-1)] = (s))\n\n#define stbds_hmgeti(t,k) \\\n    ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, STBDS_HM_BINARY), \\\n      stbds_temp((t)-1))\n\n#define stbds_hmgeti_ts(t,k,temp) \\\n    ((t) = stbds_hmget_key_ts_wrapper((t), sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, &(temp), STBDS_HM_BINARY), \\\n      (temp))\n\n#define stbds_hmgetp(t, k) \\\n    ((void) stbds_hmgeti(t,k), &(t)[stbds_temp((t)-1)])\n\n#define stbds_hmgetp_ts(t, k, temp) \\\n    ((void) stbds_hmgeti_ts(t,k,temp), &(t)[temp])\n\n#define stbds_hmdel(t,k) \\\n    (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, STBDS_OFFSETOF((t),key), STBDS_HM_BINARY)),(t)?stbds_temp((t)-1):0)\n\n#define stbds_hmdefault(t, v) \\\n    ((t) = stbds_hmput_default_wrapper((t), sizeof *(t)), (t)[-1].value = (v))\n\n#define stbds_hmdefaults(t, s) \\\n    ((t) = stbds_hmput_default_wrapper((t), sizeof *(t)), (t)[-1] = (s))\n\n#define stbds_hmfree(p)        \\\n    ((void) ((p) != NULL ? stbds_hmfree_func((p)-1,sizeof*(p)),0 : 0),(p)=NULL)\n\n#define stbds_hmgets(t, k)    (*stbds_hmgetp(t,k))\n#define stbds_hmget(t, k)     (stbds_hmgetp(t,k)->value)\n#define stbds_hmget_ts(t, k, temp)  (stbds_hmgetp_ts(t,k,temp)->value)\n#define stbds_hmlen(t)        ((t) ? (ptrdiff_t) stbds_header((t)-1)->length-1 : 0)\n#define stbds_hmlenu(t)       ((t) ?             stbds_header((t)-1)->length-1 : 0)\n#define stbds_hmgetp_null(t,k)  (stbds_hmgeti(t,k) == -1 ? NULL : &(t)[stbds_temp((t)-1)])\n\n#define stbds_shput(t, k, v) \\\n    ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_HM_STRING),   \\\n     (t)[stbds_temp((t)-1)].value = (v))\n\n#define stbds_shputi(t, k, v) \\\n    ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_HM_STRING),   \\\n     (t)[stbds_temp((t)-1)].value = (v), stbds_temp((t)-1))\n\n#define stbds_shputs(t, s) \\\n    ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (s).key, sizeof (s).key, STBDS_HM_STRING), \\\n     (t)[stbds_temp((t)-1)] = (s), \\\n     (t)[stbds_temp((t)-1)].key = stbds_temp_key((t)-1)) // above line overwrites whole structure, so must rewrite key here if it was allocated internally\n\n#define stbds_pshput(t, p) \\\n    ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (p)->key, sizeof (p)->key, STBDS_HM_PTR_TO_STRING), \\\n     (t)[stbds_temp((t)-1)] = (p))\n\n#define stbds_shgeti(t,k) \\\n     ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_HM_STRING), \\\n      stbds_temp((t)-1))\n\n#define stbds_pshgeti(t,k) \\\n     ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (*(t))->key, STBDS_HM_PTR_TO_STRING), \\\n      stbds_temp((t)-1))\n\n#define stbds_shgetp(t, k) \\\n    ((void) stbds_shgeti(t,k), &(t)[stbds_temp((t)-1)])\n\n#define stbds_pshget(t, k) \\\n    ((void) stbds_pshgeti(t,k), (t)[stbds_temp((t)-1)])\n\n#define stbds_shdel(t,k) \\\n    (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_OFFSETOF((t),key), STBDS_HM_STRING)),(t)?stbds_temp((t)-1):0)\n#define stbds_pshdel(t,k) \\\n    (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), (void*) (k), sizeof (*(t))->key, STBDS_OFFSETOF(*(t),key), STBDS_HM_PTR_TO_STRING)),(t)?stbds_temp((t)-1):0)\n\n#define stbds_sh_new_arena(t)  \\\n    ((t) = stbds_shmode_func_wrapper(t, sizeof *(t), STBDS_SH_ARENA))\n#define stbds_sh_new_strdup(t) \\\n    ((t) = stbds_shmode_func_wrapper(t, sizeof *(t), STBDS_SH_STRDUP))\n\n#define stbds_shdefault(t, v)  stbds_hmdefault(t,v)\n#define stbds_shdefaults(t, s) stbds_hmdefaults(t,s)\n\n#define stbds_shfree       stbds_hmfree\n#define stbds_shlenu       stbds_hmlenu\n\n#define stbds_shgets(t, k) (*stbds_shgetp(t,k))\n#define stbds_shget(t, k)  (stbds_shgetp(t,k)->value)\n#define stbds_shgetp_null(t,k)  (stbds_shgeti(t,k) == -1 ? NULL : &(t)[stbds_temp((t)-1)])\n#define stbds_shlen        stbds_hmlen\n\ntypedef struct\n{\n  size_t      length;\n  size_t      capacity;\n  void      * hash_table;\n  ptrdiff_t   temp;\n} stbds_array_header;\n\ntypedef struct stbds_string_block\n{\n  struct stbds_string_block *next;\n  char storage[8];\n} stbds_string_block;\n\nstruct stbds_string_arena\n{\n  stbds_string_block *storage;\n  size_t remaining;\n  unsigned char block;\n  unsigned char mode;  // this isn't used by the string arena itself\n};\n\n#define STBDS_HM_BINARY         0\n#define STBDS_HM_STRING         1\n\nenum\n{\n   STBDS_SH_NONE,\n   STBDS_SH_DEFAULT,\n   STBDS_SH_STRDUP,\n   STBDS_SH_ARENA\n};\n\n#ifdef __cplusplus\n// in C we use implicit assignment from these void*-returning functions to T*.\n// in C++ these templates make the same code work\ntemplate<class T> static T * stbds_arrgrowf_wrapper(T *a, size_t elemsize, size_t addlen, size_t min_cap) {\n  return (T*)stbds_arrgrowf((void *)a, elemsize, addlen, min_cap);\n}\ntemplate<class T> static T * stbds_hmget_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, int mode) {\n  return (T*)stbds_hmget_key((void*)a, elemsize, key, keysize, mode);\n}\ntemplate<class T> static T * stbds_hmget_key_ts_wrapper(T *a, size_t elemsize, void *key, size_t keysize, ptrdiff_t *temp, int mode) {\n  return (T*)stbds_hmget_key_ts((void*)a, elemsize, key, keysize, temp, mode);\n}\ntemplate<class T> static T * stbds_hmput_default_wrapper(T *a, size_t elemsize) {\n  return (T*)stbds_hmput_default((void *)a, elemsize);\n}\ntemplate<class T> static T * stbds_hmput_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, int mode) {\n  return (T*)stbds_hmput_key((void*)a, elemsize, key, keysize, mode);\n}\ntemplate<class T> static T * stbds_hmdel_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode){\n  return (T*)stbds_hmdel_key((void*)a, elemsize, key, keysize, keyoffset, mode);\n}\ntemplate<class T> static T * stbds_shmode_func_wrapper(T *, size_t elemsize, int mode) {\n  return (T*)stbds_shmode_func(elemsize, mode);\n}\n#else\n#define stbds_arrgrowf_wrapper            stbds_arrgrowf\n#define stbds_hmget_key_wrapper           stbds_hmget_key\n#define stbds_hmget_key_ts_wrapper        stbds_hmget_key_ts\n#define stbds_hmput_default_wrapper       stbds_hmput_default\n#define stbds_hmput_key_wrapper           stbds_hmput_key\n#define stbds_hmdel_key_wrapper           stbds_hmdel_key\n#define stbds_shmode_func_wrapper(t,e,m)  stbds_shmode_func(e,m)\n#endif\n\n#endif // INCLUDE_STB_DS_H\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//   IMPLEMENTATION\n//\n\n#ifdef STB_DS_IMPLEMENTATION\n#include <assert.h>\n#include <string.h>\n\n#ifndef STBDS_ASSERT\n#define STBDS_ASSERT_WAS_UNDEFINED\n#define STBDS_ASSERT(x)   ((void) 0)\n#endif\n\n#ifdef STBDS_STATISTICS\n#define STBDS_STATS(x)   x\nsize_t stbds_array_grow;\nsize_t stbds_hash_grow;\nsize_t stbds_hash_shrink;\nsize_t stbds_hash_rebuild;\nsize_t stbds_hash_probes;\nsize_t stbds_hash_alloc;\nsize_t stbds_rehash_probes;\nsize_t stbds_rehash_items;\n#else\n#define STBDS_STATS(x)\n#endif\n\n//\n// stbds_arr implementation\n//\n\n//int *prev_allocs[65536];\n//int num_prev;\n\nvoid *stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap)\n{\n  stbds_array_header temp={0}; // force debugging\n  void *b;\n  size_t min_len = stbds_arrlen(a) + addlen;\n  (void) sizeof(temp);\n\n  // compute the minimum capacity needed\n  if (min_len > min_cap)\n    min_cap = min_len;\n\n  if (min_cap <= stbds_arrcap(a))\n    return a;\n\n  // increase needed capacity to guarantee O(1) amortized\n  if (min_cap < 2 * stbds_arrcap(a))\n    min_cap = 2 * stbds_arrcap(a);\n  else if (min_cap < 4)\n    min_cap = 4;\n\n  //if (num_prev < 65536) if (a) prev_allocs[num_prev++] = (int *) ((char *) a+1);\n  //if (num_prev == 2201)\n  //  num_prev = num_prev;\n  b = STBDS_REALLOC(NULL, (a) ? stbds_header(a) : 0, elemsize * min_cap + sizeof(stbds_array_header));\n  //if (num_prev < 65536) prev_allocs[num_prev++] = (int *) (char *) b;\n  b = (char *) b + sizeof(stbds_array_header);\n  if (a == NULL) {\n    stbds_header(b)->length = 0;\n    stbds_header(b)->hash_table = 0;\n    stbds_header(b)->temp = 0;\n  } else {\n    STBDS_STATS(++stbds_array_grow);\n  }\n  stbds_header(b)->capacity = min_cap;\n\n  return b;\n}\n\nvoid stbds_arrfreef(void *a)\n{\n  STBDS_FREE(NULL, stbds_header(a));\n}\n\n//\n// stbds_hm hash table implementation\n//\n\n#ifdef STBDS_INTERNAL_SMALL_BUCKET\n#define STBDS_BUCKET_LENGTH      4\n#else\n#define STBDS_BUCKET_LENGTH      8\n#endif\n\n#define STBDS_BUCKET_SHIFT      (STBDS_BUCKET_LENGTH == 8 ? 3 : 2)\n#define STBDS_BUCKET_MASK       (STBDS_BUCKET_LENGTH-1)\n#define STBDS_CACHE_LINE_SIZE   64\n\n#define STBDS_ALIGN_FWD(n,a)   (((n) + (a) - 1) & ~((a)-1))\n\ntypedef struct\n{\n   size_t    hash [STBDS_BUCKET_LENGTH];\n   ptrdiff_t index[STBDS_BUCKET_LENGTH];\n} stbds_hash_bucket; // in 32-bit, this is one 64-byte cache line; in 64-bit, each array is one 64-byte cache line\n\ntypedef struct\n{\n  char * temp_key; // this MUST be the first field of the hash table\n  size_t slot_count;\n  size_t used_count;\n  size_t used_count_threshold;\n  size_t used_count_shrink_threshold;\n  size_t tombstone_count;\n  size_t tombstone_count_threshold;\n  size_t seed;\n  size_t slot_count_log2;\n  stbds_string_arena string;\n  stbds_hash_bucket *storage; // not a separate allocation, just 64-byte aligned storage after this struct\n} stbds_hash_index;\n\n#define STBDS_INDEX_EMPTY    -1\n#define STBDS_INDEX_DELETED  -2\n#define STBDS_INDEX_IN_USE(x)  ((x) >= 0)\n\n#define STBDS_HASH_EMPTY      0\n#define STBDS_HASH_DELETED    1\n\nstatic size_t stbds_hash_seed=0x31415926;\n\nvoid stbds_rand_seed(size_t seed)\n{\n  stbds_hash_seed = seed;\n}\n\n#define stbds_load_32_or_64(var, temp, v32, v64_hi, v64_lo)                                          \\\n  temp = v64_lo ^ v32, temp <<= 16, temp <<= 16, temp >>= 16, temp >>= 16, /* discard if 32-bit */   \\\n  var = v64_hi, var <<= 16, var <<= 16,                                    /* discard if 32-bit */   \\\n  var ^= temp ^ v32\n\n#define STBDS_SIZE_T_BITS           ((sizeof (size_t)) * 8)\n\nstatic size_t stbds_probe_position(size_t hash, size_t slot_count, size_t slot_log2)\n{\n  size_t pos;\n  STBDS_NOTUSED(slot_log2);\n  pos = hash & (slot_count-1);\n  #ifdef STBDS_INTERNAL_BUCKET_START\n  pos &= ~STBDS_BUCKET_MASK;\n  #endif\n  return pos;\n}\n\nstatic size_t stbds_log2(size_t slot_count)\n{\n  size_t n=0;\n  while (slot_count > 1) {\n    slot_count >>= 1;\n    ++n;\n  }\n  return n;\n}\n\nstatic stbds_hash_index *stbds_make_hash_index(size_t slot_count, stbds_hash_index *ot)\n{\n  stbds_hash_index *t;\n  t = (stbds_hash_index *) STBDS_REALLOC(NULL,0,(slot_count >> STBDS_BUCKET_SHIFT) * sizeof(stbds_hash_bucket) + sizeof(stbds_hash_index) + STBDS_CACHE_LINE_SIZE-1);\n  t->storage = (stbds_hash_bucket *) STBDS_ALIGN_FWD((size_t) (t+1), STBDS_CACHE_LINE_SIZE);\n  t->slot_count = slot_count;\n  t->slot_count_log2 = stbds_log2(slot_count);\n  t->tombstone_count = 0;\n  t->used_count = 0;\n\n  #if 0 // A1\n  t->used_count_threshold        = slot_count*12/16; // if 12/16th of table is occupied, grow\n  t->tombstone_count_threshold   = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild\n  t->used_count_shrink_threshold = slot_count* 4/16; // if table is only 4/16th full, shrink\n  #elif 1 // A2\n  //t->used_count_threshold        = slot_count*12/16; // if 12/16th of table is occupied, grow\n  //t->tombstone_count_threshold   = slot_count* 3/16; // if tombstones are 3/16th of table, rebuild\n  //t->used_count_shrink_threshold = slot_count* 4/16; // if table is only 4/16th full, shrink\n\n  // compute without overflowing\n  t->used_count_threshold        = slot_count - (slot_count>>2);\n  t->tombstone_count_threshold   = (slot_count>>3) + (slot_count>>4);\n  t->used_count_shrink_threshold = slot_count >> 2;\n\n  #elif 0 // B1\n  t->used_count_threshold        = slot_count*13/16; // if 13/16th of table is occupied, grow\n  t->tombstone_count_threshold   = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild\n  t->used_count_shrink_threshold = slot_count* 5/16; // if table is only 5/16th full, shrink\n  #else // C1\n  t->used_count_threshold        = slot_count*14/16; // if 14/16th of table is occupied, grow\n  t->tombstone_count_threshold   = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild\n  t->used_count_shrink_threshold = slot_count* 6/16; // if table is only 6/16th full, shrink\n  #endif\n  // Following statistics were measured on a Core i7-6700 @ 4.00Ghz, compiled with clang 7.0.1 -O2\n    // Note that the larger tables have high variance as they were run fewer times\n  //     A1            A2          B1           C1\n  //    0.10ms :     0.10ms :     0.10ms :     0.11ms :      2,000 inserts creating 2K table\n  //    0.96ms :     0.95ms :     0.97ms :     1.04ms :     20,000 inserts creating 20K table\n  //   14.48ms :    14.46ms :    10.63ms :    11.00ms :    200,000 inserts creating 200K table\n  //  195.74ms :   196.35ms :   203.69ms :   214.92ms :  2,000,000 inserts creating 2M table\n  // 2193.88ms :  2209.22ms :  2285.54ms :  2437.17ms : 20,000,000 inserts creating 20M table\n  //   65.27ms :    53.77ms :    65.33ms :    65.47ms : 500,000 inserts & deletes in 2K table\n  //   72.78ms :    62.45ms :    71.95ms :    72.85ms : 500,000 inserts & deletes in 20K table\n  //   89.47ms :    77.72ms :    96.49ms :    96.75ms : 500,000 inserts & deletes in 200K table\n  //   97.58ms :    98.14ms :    97.18ms :    97.53ms : 500,000 inserts & deletes in 2M table\n  //  118.61ms :   119.62ms :   120.16ms :   118.86ms : 500,000 inserts & deletes in 20M table\n  //  192.11ms :   194.39ms :   196.38ms :   195.73ms : 500,000 inserts & deletes in 200M table\n\n  if (slot_count <= STBDS_BUCKET_LENGTH)\n    t->used_count_shrink_threshold = 0;\n  // to avoid infinite loop, we need to guarantee that at least one slot is empty and will terminate probes\n  STBDS_ASSERT(t->used_count_threshold + t->tombstone_count_threshold < t->slot_count);\n  STBDS_STATS(++stbds_hash_alloc);\n  if (ot) {\n    t->string = ot->string;\n    // reuse old seed so we can reuse old hashes so below \"copy out old data\" doesn't do any hashing\n    t->seed = ot->seed;\n  } else {\n    size_t a,b,temp;\n    memset(&t->string, 0, sizeof(t->string));\n    t->seed = stbds_hash_seed;\n    // LCG\n    // in 32-bit, a =          2147001325   b =  715136305\n    // in 64-bit, a = 2862933555777941757   b = 3037000493\n    stbds_load_32_or_64(a,temp, 2147001325, 0x27bb2ee6, 0x87b0b0fd);\n    stbds_load_32_or_64(b,temp,  715136305,          0, 0xb504f32d);\n    stbds_hash_seed = stbds_hash_seed  * a + b;\n  }\n\n  {\n    size_t i,j;\n    for (i=0; i < slot_count >> STBDS_BUCKET_SHIFT; ++i) {\n      stbds_hash_bucket *b = &t->storage[i];\n      for (j=0; j < STBDS_BUCKET_LENGTH; ++j)\n        b->hash[j] = STBDS_HASH_EMPTY;\n      for (j=0; j < STBDS_BUCKET_LENGTH; ++j)\n        b->index[j] = STBDS_INDEX_EMPTY;\n    }\n  }\n\n  // copy out the old data, if any\n  if (ot) {\n    size_t i,j;\n    t->used_count = ot->used_count;\n    for (i=0; i < ot->slot_count >> STBDS_BUCKET_SHIFT; ++i) {\n      stbds_hash_bucket *ob = &ot->storage[i];\n      for (j=0; j < STBDS_BUCKET_LENGTH; ++j) {\n        if (STBDS_INDEX_IN_USE(ob->index[j])) {\n          size_t hash = ob->hash[j];\n          size_t pos = stbds_probe_position(hash, t->slot_count, t->slot_count_log2);\n          size_t step = STBDS_BUCKET_LENGTH;\n          STBDS_STATS(++stbds_rehash_items);\n          for (;;) {\n            size_t limit,z;\n            stbds_hash_bucket *bucket;\n            bucket = &t->storage[pos >> STBDS_BUCKET_SHIFT];\n            STBDS_STATS(++stbds_rehash_probes);\n\n            for (z=pos & STBDS_BUCKET_MASK; z < STBDS_BUCKET_LENGTH; ++z) {\n              if (bucket->hash[z] == 0) {\n                bucket->hash[z] = hash;\n                bucket->index[z] = ob->index[j];\n                goto done;\n              }\n            }\n\n            limit = pos & STBDS_BUCKET_MASK;\n            for (z = 0; z < limit; ++z) {\n              if (bucket->hash[z] == 0) {\n                bucket->hash[z] = hash;\n                bucket->index[z] = ob->index[j];\n                goto done;\n              }\n            }\n\n            pos += step;                  // quadratic probing\n            step += STBDS_BUCKET_LENGTH;\n            pos &= (t->slot_count-1);\n          }\n        }\n       done:\n        ;\n      }\n    }\n  }\n\n  return t;\n}\n\n#define STBDS_ROTATE_LEFT(val, n)   (((val) << (n)) | ((val) >> (STBDS_SIZE_T_BITS - (n))))\n#define STBDS_ROTATE_RIGHT(val, n)  (((val) >> (n)) | ((val) << (STBDS_SIZE_T_BITS - (n))))\n\nsize_t stbds_hash_string(char *str, size_t seed)\n{\n  size_t hash = seed;\n  while (*str)\n     hash = STBDS_ROTATE_LEFT(hash, 9) + (unsigned char) *str++;\n\n  // Thomas Wang 64-to-32 bit mix function, hopefully also works in 32 bits\n  hash ^= seed;\n  hash = (~hash) + (hash << 18);\n  hash ^= hash ^ STBDS_ROTATE_RIGHT(hash,31);\n  hash = hash * 21;\n  hash ^= hash ^ STBDS_ROTATE_RIGHT(hash,11);\n  hash += (hash << 6);\n  hash ^= STBDS_ROTATE_RIGHT(hash,22);\n  return hash+seed;\n}\n\n#ifdef STBDS_SIPHASH_2_4\n#define STBDS_SIPHASH_C_ROUNDS 2\n#define STBDS_SIPHASH_D_ROUNDS 4\ntypedef int STBDS_SIPHASH_2_4_can_only_be_used_in_64_bit_builds[sizeof(size_t) == 8 ? 1 : -1];\n#endif\n\n#ifndef STBDS_SIPHASH_C_ROUNDS\n#define STBDS_SIPHASH_C_ROUNDS 1\n#endif\n#ifndef STBDS_SIPHASH_D_ROUNDS\n#define STBDS_SIPHASH_D_ROUNDS 1\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4127) // conditional expression is constant, for do..while(0) and sizeof()==\n#endif\n\nstatic size_t stbds_siphash_bytes(void *p, size_t len, size_t seed)\n{\n  unsigned char *d = (unsigned char *) p;\n  size_t i,j;\n  size_t v0,v1,v2,v3, data;\n\n  // hash that works on 32- or 64-bit registers without knowing which we have\n  // (computes different results on 32-bit and 64-bit platform)\n  // derived from siphash, but on 32-bit platforms very different as it uses 4 32-bit state not 4 64-bit\n  v0 = ((((size_t) 0x736f6d65 << 16) << 16) + 0x70736575) ^  seed;\n  v1 = ((((size_t) 0x646f7261 << 16) << 16) + 0x6e646f6d) ^ ~seed;\n  v2 = ((((size_t) 0x6c796765 << 16) << 16) + 0x6e657261) ^  seed;\n  v3 = ((((size_t) 0x74656462 << 16) << 16) + 0x79746573) ^ ~seed;\n\n  #ifdef STBDS_TEST_SIPHASH_2_4\n  // hardcoded with key material in the siphash test vectors\n  v0 ^= 0x0706050403020100ull ^  seed;\n  v1 ^= 0x0f0e0d0c0b0a0908ull ^ ~seed;\n  v2 ^= 0x0706050403020100ull ^  seed;\n  v3 ^= 0x0f0e0d0c0b0a0908ull ^ ~seed;\n  #endif\n\n  #define STBDS_SIPROUND() \\\n    do {                   \\\n      v0 += v1; v1 = STBDS_ROTATE_LEFT(v1, 13);  v1 ^= v0; v0 = STBDS_ROTATE_LEFT(v0,STBDS_SIZE_T_BITS/2); \\\n      v2 += v3; v3 = STBDS_ROTATE_LEFT(v3, 16);  v3 ^= v2;                                                 \\\n      v2 += v1; v1 = STBDS_ROTATE_LEFT(v1, 17);  v1 ^= v2; v2 = STBDS_ROTATE_LEFT(v2,STBDS_SIZE_T_BITS/2); \\\n      v0 += v3; v3 = STBDS_ROTATE_LEFT(v3, 21);  v3 ^= v0;                                                 \\\n    } while (0)\n\n  for (i=0; i+sizeof(size_t) <= len; i += sizeof(size_t), d += sizeof(size_t)) {\n    data = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);\n    data |= (size_t) (d[4] | (d[5] << 8) | (d[6] << 16) | (d[7] << 24)) << 16 << 16; // discarded if size_t == 4\n\n    v3 ^= data;\n    for (j=0; j < STBDS_SIPHASH_C_ROUNDS; ++j)\n      STBDS_SIPROUND();\n    v0 ^= data;\n  }\n  data = len << (STBDS_SIZE_T_BITS-8);\n  switch (len - i) {\n    case 7: data |= ((size_t) d[6] << 24) << 24; // fall through\n    case 6: data |= ((size_t) d[5] << 20) << 20; // fall through\n    case 5: data |= ((size_t) d[4] << 16) << 16; // fall through\n    case 4: data |= (d[3] << 24); // fall through\n    case 3: data |= (d[2] << 16); // fall through\n    case 2: data |= (d[1] << 8); // fall through\n    case 1: data |= d[0]; // fall through\n    case 0: break;\n  }\n  v3 ^= data;\n  for (j=0; j < STBDS_SIPHASH_C_ROUNDS; ++j)\n    STBDS_SIPROUND();\n  v0 ^= data;\n  v2 ^= 0xff;\n  for (j=0; j < STBDS_SIPHASH_D_ROUNDS; ++j)\n    STBDS_SIPROUND();\n\n#ifdef STBDS_SIPHASH_2_4\n  return v0^v1^v2^v3;\n#else\n  return v1^v2^v3; // slightly stronger since v0^v3 in above cancels out final round operation? I tweeted at the authors of SipHash about this but they didn't reply\n#endif\n}\n\nsize_t stbds_hash_bytes(void *p, size_t len, size_t seed)\n{\n#ifdef STBDS_SIPHASH_2_4\n  return stbds_siphash_bytes(p,len,seed);\n#else\n  unsigned char *d = (unsigned char *) p;\n\n  if (len == 4) {\n    unsigned int hash = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);\n    #if 0\n    // HASH32-A  Bob Jenkin's hash function w/o large constants\n    hash ^= seed;\n    hash -= (hash<<6);\n    hash ^= (hash>>17);\n    hash -= (hash<<9);\n    hash ^= seed;\n    hash ^= (hash<<4);\n    hash -= (hash<<3);\n    hash ^= (hash<<10);\n    hash ^= (hash>>15);\n    #elif 1\n    // HASH32-BB  Bob Jenkin's presumably-accidental version of Thomas Wang hash with rotates turned into shifts.\n    // Note that converting these back to rotates makes it run a lot slower, presumably due to collisions, so I'm\n    // not really sure what's going on.\n    hash ^= seed;\n    hash = (hash ^ 61) ^ (hash >> 16);\n    hash = hash + (hash << 3);\n    hash = hash ^ (hash >> 4);\n    hash = hash * 0x27d4eb2d;\n    hash ^= seed;\n    hash = hash ^ (hash >> 15);\n    #else  // HASH32-C   -  Murmur3\n    hash ^= seed;\n    hash *= 0xcc9e2d51;\n    hash = (hash << 17) | (hash >> 15);\n    hash *= 0x1b873593;\n    hash ^= seed;\n    hash = (hash << 19) | (hash >> 13);\n    hash = hash*5 + 0xe6546b64;\n    hash ^= hash >> 16;\n    hash *= 0x85ebca6b;\n    hash ^= seed;\n    hash ^= hash >> 13;\n    hash *= 0xc2b2ae35;\n    hash ^= hash >> 16;\n    #endif\n    // Following statistics were measured on a Core i7-6700 @ 4.00Ghz, compiled with clang 7.0.1 -O2\n    // Note that the larger tables have high variance as they were run fewer times\n    //  HASH32-A   //  HASH32-BB  //  HASH32-C\n    //    0.10ms   //    0.10ms   //    0.10ms :      2,000 inserts creating 2K table\n    //    0.96ms   //    0.95ms   //    0.99ms :     20,000 inserts creating 20K table\n    //   14.69ms   //   14.43ms   //   14.97ms :    200,000 inserts creating 200K table\n    //  199.99ms   //  195.36ms   //  202.05ms :  2,000,000 inserts creating 2M table\n    // 2234.84ms   // 2187.74ms   // 2240.38ms : 20,000,000 inserts creating 20M table\n    //   55.68ms   //   53.72ms   //   57.31ms : 500,000 inserts & deletes in 2K table\n    //   63.43ms   //   61.99ms   //   65.73ms : 500,000 inserts & deletes in 20K table\n    //   80.04ms   //   77.96ms   //   81.83ms : 500,000 inserts & deletes in 200K table\n    //  100.42ms   //   97.40ms   //  102.39ms : 500,000 inserts & deletes in 2M table\n    //  119.71ms   //  120.59ms   //  121.63ms : 500,000 inserts & deletes in 20M table\n    //  185.28ms   //  195.15ms   //  187.74ms : 500,000 inserts & deletes in 200M table\n    //   15.58ms   //   14.79ms   //   15.52ms : 200,000 inserts creating 200K table with varying key spacing\n\n    return (((size_t) hash << 16 << 16) | hash) ^ seed;\n  } else if (len == 8 && sizeof(size_t) == 8) {\n    size_t hash = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);\n    hash |= (size_t) (d[4] | (d[5] << 8) | (d[6] << 16) | (d[7] << 24)) << 16 << 16; // avoid warning if size_t == 4\n    hash ^= seed;\n    hash = (~hash) + (hash << 21);\n    hash ^= STBDS_ROTATE_RIGHT(hash,24);\n    hash *= 265;\n    hash ^= STBDS_ROTATE_RIGHT(hash,14);\n    hash ^= seed;\n    hash *= 21;\n    hash ^= STBDS_ROTATE_RIGHT(hash,28);\n    hash += (hash << 31);\n    hash = (~hash) + (hash << 18);\n    return hash;\n  } else {\n    return stbds_siphash_bytes(p,len,seed);\n  }\n#endif\n}\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n\nstatic int stbds_is_key_equal(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode, size_t i)\n{\n  if (mode >= STBDS_HM_STRING)\n    return 0==strcmp((char *) key, * (char **) ((char *) a + elemsize*i + keyoffset));\n  else\n    return 0==memcmp(key, (char *) a + elemsize*i + keyoffset, keysize);\n}\n\n#define STBDS_HASH_TO_ARR(x,elemsize) ((char*) (x) - (elemsize))\n#define STBDS_ARR_TO_HASH(x,elemsize) ((char*) (x) + (elemsize))\n\n#define stbds_hash_table(a)  ((stbds_hash_index *) stbds_header(a)->hash_table)\n\nvoid stbds_hmfree_func(void *a, size_t elemsize)\n{\n  if (a == NULL) return;\n  if (stbds_hash_table(a) != NULL) {\n    if (stbds_hash_table(a)->string.mode == STBDS_SH_STRDUP) {\n      size_t i;\n      // skip 0th element, which is default\n      for (i=1; i < stbds_header(a)->length; ++i)\n        STBDS_FREE(NULL, *(char**) ((char *) a + elemsize*i));\n    }\n    stbds_strreset(&stbds_hash_table(a)->string);\n  }\n  STBDS_FREE(NULL, stbds_header(a)->hash_table);\n  STBDS_FREE(NULL, stbds_header(a));\n}\n\nstatic ptrdiff_t stbds_hm_find_slot(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode)\n{\n  void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);\n  stbds_hash_index *table = stbds_hash_table(raw_a);\n  size_t hash = mode >= STBDS_HM_STRING ? stbds_hash_string((char*)key,table->seed) : stbds_hash_bytes(key, keysize,table->seed);\n  size_t step = STBDS_BUCKET_LENGTH;\n  size_t limit,i;\n  size_t pos;\n  stbds_hash_bucket *bucket;\n\n  if (hash < 2) hash += 2; // stored hash values are forbidden from being 0, so we can detect empty slots\n\n  pos = stbds_probe_position(hash, table->slot_count, table->slot_count_log2);\n\n  for (;;) {\n    STBDS_STATS(++stbds_hash_probes);\n    bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];\n\n    // start searching from pos to end of bucket, this should help performance on small hash tables that fit in cache\n    for (i=pos & STBDS_BUCKET_MASK; i < STBDS_BUCKET_LENGTH; ++i) {\n      if (bucket->hash[i] == hash) {\n        if (stbds_is_key_equal(a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {\n          return (pos & ~STBDS_BUCKET_MASK)+i;\n        }\n      } else if (bucket->hash[i] == STBDS_HASH_EMPTY) {\n        return -1;\n      }\n    }\n\n    // search from beginning of bucket to pos\n    limit = pos & STBDS_BUCKET_MASK;\n    for (i = 0; i < limit; ++i) {\n      if (bucket->hash[i] == hash) {\n        if (stbds_is_key_equal(a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {\n          return (pos & ~STBDS_BUCKET_MASK)+i;\n        }\n      } else if (bucket->hash[i] == STBDS_HASH_EMPTY) {\n        return -1;\n      }\n    }\n\n    // quadratic probing\n    pos += step;\n    step += STBDS_BUCKET_LENGTH;\n    pos &= (table->slot_count-1);\n  }\n  /* NOTREACHED */\n}\n\nvoid * stbds_hmget_key_ts(void *a, size_t elemsize, void *key, size_t keysize, ptrdiff_t *temp, int mode)\n{\n  size_t keyoffset = 0;\n  if (a == NULL) {\n    // make it non-empty so we can return a temp\n    a = stbds_arrgrowf(0, elemsize, 0, 1);\n    stbds_header(a)->length += 1;\n    memset(a, 0, elemsize);\n    *temp = STBDS_INDEX_EMPTY;\n    // adjust a to point after the default element\n    return STBDS_ARR_TO_HASH(a,elemsize);\n  } else {\n    stbds_hash_index *table;\n    void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);\n    // adjust a to point to the default element\n    table = (stbds_hash_index *) stbds_header(raw_a)->hash_table;\n    if (table == 0) {\n      *temp = -1;\n    } else {\n      ptrdiff_t slot = stbds_hm_find_slot(a, elemsize, key, keysize, keyoffset, mode);\n      if (slot < 0) {\n        *temp = STBDS_INDEX_EMPTY;\n      } else {\n        stbds_hash_bucket *b = &table->storage[slot >> STBDS_BUCKET_SHIFT];\n        *temp = b->index[slot & STBDS_BUCKET_MASK];\n      }\n    }\n    return a;\n  }\n}\n\nvoid * stbds_hmget_key(void *a, size_t elemsize, void *key, size_t keysize, int mode)\n{\n  ptrdiff_t temp;\n  void *p = stbds_hmget_key_ts(a, elemsize, key, keysize, &temp, mode);\n  stbds_temp(STBDS_HASH_TO_ARR(p,elemsize)) = temp;\n  return p;\n}\n\nvoid * stbds_hmput_default(void *a, size_t elemsize)\n{\n  // three cases:\n  //   a is NULL <- allocate\n  //   a has a hash table but no entries, because of shmode <- grow\n  //   a has entries <- do nothing\n  if (a == NULL || stbds_header(STBDS_HASH_TO_ARR(a,elemsize))->length == 0) {\n    a = stbds_arrgrowf(a ? STBDS_HASH_TO_ARR(a,elemsize) : NULL, elemsize, 0, 1);\n    stbds_header(a)->length += 1;\n    memset(a, 0, elemsize);\n    a=STBDS_ARR_TO_HASH(a,elemsize);\n  }\n  return a;\n}\n\nstatic char *stbds_strdup(char *str);\n\nvoid *stbds_hmput_key(void *a, size_t elemsize, void *key, size_t keysize, int mode)\n{\n  size_t keyoffset=0;\n  void *raw_a;\n  stbds_hash_index *table;\n\n  if (a == NULL) {\n    a = stbds_arrgrowf(0, elemsize, 0, 1);\n    memset(a, 0, elemsize);\n    stbds_header(a)->length += 1;\n    // adjust a to point AFTER the default element\n    a = STBDS_ARR_TO_HASH(a,elemsize);\n  }\n\n  // adjust a to point to the default element\n  raw_a = a;\n  a = STBDS_HASH_TO_ARR(a,elemsize);\n\n  table = (stbds_hash_index *) stbds_header(a)->hash_table;\n\n  if (table == NULL || table->used_count >= table->used_count_threshold) {\n    stbds_hash_index *nt;\n    size_t slot_count;\n\n    slot_count = (table == NULL) ? STBDS_BUCKET_LENGTH : table->slot_count*2;\n    nt = stbds_make_hash_index(slot_count, table);\n    if (table)\n      STBDS_FREE(NULL, table);\n    else\n      nt->string.mode = mode >= STBDS_HM_STRING ? STBDS_SH_DEFAULT : 0;\n    stbds_header(a)->hash_table = table = nt;\n    STBDS_STATS(++stbds_hash_grow);\n  }\n\n  // we iterate hash table explicitly because we want to track if we saw a tombstone\n  {\n    size_t hash = mode >= STBDS_HM_STRING ? stbds_hash_string((char*)key,table->seed) : stbds_hash_bytes(key, keysize,table->seed);\n    size_t step = STBDS_BUCKET_LENGTH;\n    size_t pos;\n    ptrdiff_t tombstone = -1;\n    stbds_hash_bucket *bucket;\n\n    // stored hash values are forbidden from being 0, so we can detect empty slots to early out quickly\n    if (hash < 2) hash += 2;\n\n    pos = stbds_probe_position(hash, table->slot_count, table->slot_count_log2);\n\n    for (;;) {\n      size_t limit, i;\n      STBDS_STATS(++stbds_hash_probes);\n      bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];\n\n      // start searching from pos to end of bucket\n      for (i=pos & STBDS_BUCKET_MASK; i < STBDS_BUCKET_LENGTH; ++i) {\n        if (bucket->hash[i] == hash) {\n          if (stbds_is_key_equal(raw_a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {\n            stbds_temp(a) = bucket->index[i];\n            if (mode >= STBDS_HM_STRING)\n              stbds_temp_key(a) = * (char **) ((char *) raw_a + elemsize*bucket->index[i] + keyoffset);\n            return STBDS_ARR_TO_HASH(a,elemsize);\n          }\n        } else if (bucket->hash[i] == 0) {\n          pos = (pos & ~STBDS_BUCKET_MASK) + i;\n          goto found_empty_slot;\n        } else if (tombstone < 0) {\n          if (bucket->index[i] == STBDS_INDEX_DELETED)\n            tombstone = (ptrdiff_t) ((pos & ~STBDS_BUCKET_MASK) + i);\n        }\n      }\n\n      // search from beginning of bucket to pos\n      limit = pos & STBDS_BUCKET_MASK;\n      for (i = 0; i < limit; ++i) {\n        if (bucket->hash[i] == hash) {\n          if (stbds_is_key_equal(raw_a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {\n            stbds_temp(a) = bucket->index[i];\n            return STBDS_ARR_TO_HASH(a,elemsize);\n          }\n        } else if (bucket->hash[i] == 0) {\n          pos = (pos & ~STBDS_BUCKET_MASK) + i;\n          goto found_empty_slot;\n        } else if (tombstone < 0) {\n          if (bucket->index[i] == STBDS_INDEX_DELETED)\n            tombstone = (ptrdiff_t) ((pos & ~STBDS_BUCKET_MASK) + i);\n        }\n      }\n\n      // quadratic probing\n      pos += step;\n      step += STBDS_BUCKET_LENGTH;\n      pos &= (table->slot_count-1);\n    }\n   found_empty_slot:\n    if (tombstone >= 0) {\n      pos = tombstone;\n      --table->tombstone_count;\n    }\n    ++table->used_count;\n\n    {\n      ptrdiff_t i = (ptrdiff_t) stbds_arrlen(a);\n      // we want to do stbds_arraddn(1), but we can't use the macros since we don't have something of the right type\n      if ((size_t) i+1 > stbds_arrcap(a))\n        *(void **) &a = stbds_arrgrowf(a, elemsize, 1, 0);\n      raw_a = STBDS_ARR_TO_HASH(a,elemsize);\n\n      STBDS_ASSERT((size_t) i+1 <= stbds_arrcap(a));\n      stbds_header(a)->length = i+1;\n      bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];\n      bucket->hash[pos & STBDS_BUCKET_MASK] = hash;\n      bucket->index[pos & STBDS_BUCKET_MASK] = i-1;\n      stbds_temp(a) = i-1;\n\n      switch (table->string.mode) {\n         case STBDS_SH_STRDUP:  stbds_temp_key(a) = *(char **) ((char *) a + elemsize*i) = stbds_strdup((char*) key); break;\n         case STBDS_SH_ARENA:   stbds_temp_key(a) = *(char **) ((char *) a + elemsize*i) = stbds_stralloc(&table->string, (char*)key); break;\n         case STBDS_SH_DEFAULT: stbds_temp_key(a) = *(char **) ((char *) a + elemsize*i) = (char *) key; break;\n         default:                memcpy((char *) a + elemsize*i, key, keysize); break;\n      }\n    }\n    return STBDS_ARR_TO_HASH(a,elemsize);\n  }\n}\n\nvoid * stbds_shmode_func(size_t elemsize, int mode)\n{\n  void *a = stbds_arrgrowf(0, elemsize, 0, 1);\n  stbds_hash_index *h;\n  memset(a, 0, elemsize);\n  stbds_header(a)->length = 1;\n  stbds_header(a)->hash_table = h = (stbds_hash_index *) stbds_make_hash_index(STBDS_BUCKET_LENGTH, NULL);\n  h->string.mode = (unsigned char) mode;\n  return STBDS_ARR_TO_HASH(a,elemsize);\n}\n\nvoid * stbds_hmdel_key(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode)\n{\n  if (a == NULL) {\n    return 0;\n  } else {\n    stbds_hash_index *table;\n    void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);\n    table = (stbds_hash_index *) stbds_header(raw_a)->hash_table;\n    stbds_temp(raw_a) = 0;\n    if (table == 0) {\n      return a;\n    } else {\n      ptrdiff_t slot;\n      slot = stbds_hm_find_slot(a, elemsize, key, keysize, keyoffset, mode);\n      if (slot < 0)\n        return a;\n      else {\n        stbds_hash_bucket *b = &table->storage[slot >> STBDS_BUCKET_SHIFT];\n        int i = slot & STBDS_BUCKET_MASK;\n        ptrdiff_t old_index = b->index[i];\n        ptrdiff_t final_index = (ptrdiff_t) stbds_arrlen(raw_a)-1-1; // minus one for the raw_a vs a, and minus one for 'last'\n        STBDS_ASSERT(slot < (ptrdiff_t) table->slot_count);\n        --table->used_count;\n        ++table->tombstone_count;\n        stbds_temp(raw_a) = 1;\n        STBDS_ASSERT(table->used_count >= 0);\n        //STBDS_ASSERT(table->tombstone_count < table->slot_count/4);\n        b->hash[i] = STBDS_HASH_DELETED;\n        b->index[i] = STBDS_INDEX_DELETED;\n\n        if (mode == STBDS_HM_STRING && table->string.mode == STBDS_SH_STRDUP)\n          STBDS_FREE(NULL, *(char**) ((char *) a+elemsize*old_index));\n\n        // if indices are the same, memcpy is a no-op, but back-pointer-fixup will fail, so skip\n        if (old_index != final_index) {\n          // swap delete\n          memmove((char*) a + elemsize*old_index, (char*) a + elemsize*final_index, elemsize);\n\n          // now find the slot for the last element\n          if (mode == STBDS_HM_STRING)\n            slot = stbds_hm_find_slot(a, elemsize, *(char**) ((char *) a+elemsize*old_index + keyoffset), keysize, keyoffset, mode);\n          else\n            slot = stbds_hm_find_slot(a, elemsize,  (char* ) a+elemsize*old_index + keyoffset, keysize, keyoffset, mode);\n          STBDS_ASSERT(slot >= 0);\n          b = &table->storage[slot >> STBDS_BUCKET_SHIFT];\n          i = slot & STBDS_BUCKET_MASK;\n          STBDS_ASSERT(b->index[i] == final_index);\n          b->index[i] = old_index;\n        }\n        stbds_header(raw_a)->length -= 1;\n\n        if (table->used_count < table->used_count_shrink_threshold && table->slot_count > STBDS_BUCKET_LENGTH) {\n          stbds_header(raw_a)->hash_table = stbds_make_hash_index(table->slot_count>>1, table);\n          STBDS_FREE(NULL, table);\n          STBDS_STATS(++stbds_hash_shrink);\n        } else if (table->tombstone_count > table->tombstone_count_threshold) {\n          stbds_header(raw_a)->hash_table = stbds_make_hash_index(table->slot_count   , table);\n          STBDS_FREE(NULL, table);\n          STBDS_STATS(++stbds_hash_rebuild);\n        }\n\n        return a;\n      }\n    }\n  }\n  /* NOTREACHED */\n}\n\nstatic char *stbds_strdup(char *str)\n{\n  // to keep replaceable allocator simple, we don't want to use strdup.\n  // rolling our own also avoids problem of strdup vs _strdup\n  size_t len = strlen(str)+1;\n  char *p = (char*) STBDS_REALLOC(NULL, 0, len);\n  memmove(p, str, len);\n  return p;\n}\n\n#ifndef STBDS_STRING_ARENA_BLOCKSIZE_MIN\n#define STBDS_STRING_ARENA_BLOCKSIZE_MIN  512u\n#endif\n#ifndef STBDS_STRING_ARENA_BLOCKSIZE_MAX\n#define STBDS_STRING_ARENA_BLOCKSIZE_MAX  (1u<<20)\n#endif\n\nchar *stbds_stralloc(stbds_string_arena *a, char *str)\n{\n  char *p;\n  size_t len = strlen(str)+1;\n  if (len > a->remaining) {\n    // compute the next blocksize\n    size_t blocksize = a->block;\n\n    // size is 512, 512, 1024, 1024, 2048, 2048, 4096, 4096, etc., so that\n    // there are log(SIZE) allocations to free when we destroy the table\n    blocksize = (size_t) (STBDS_STRING_ARENA_BLOCKSIZE_MIN) << (blocksize>>1);\n\n    // if size is under 1M, advance to next blocktype\n    if (blocksize < (size_t)(STBDS_STRING_ARENA_BLOCKSIZE_MAX))\n      ++a->block;\n\n    if (len > blocksize) {\n      // if string is larger than blocksize, then just allocate the full size.\n      // note that we still advance string_block so block size will continue\n      // increasing, so e.g. if somebody only calls this with 1000-long strings,\n      // eventually the arena will start doubling and handling those as well\n      stbds_string_block *sb = (stbds_string_block *) STBDS_REALLOC(NULL, 0, sizeof(*sb)-8 + len);\n      memmove(sb->storage, str, len);\n      if (a->storage) {\n        // insert it after the first element, so that we don't waste the space there\n        sb->next = a->storage->next;\n        a->storage->next = sb;\n      } else {\n        sb->next = 0;\n        a->storage = sb;\n        a->remaining = 0; // this is redundant, but good for clarity\n      }\n      return sb->storage;\n    } else {\n      stbds_string_block *sb = (stbds_string_block *) STBDS_REALLOC(NULL, 0, sizeof(*sb)-8 + blocksize);\n      sb->next = a->storage;\n      a->storage = sb;\n      a->remaining = blocksize;\n    }\n  }\n\n  STBDS_ASSERT(len <= a->remaining);\n  p = a->storage->storage + a->remaining - len;\n  a->remaining -= len;\n  memmove(p, str, len);\n  return p;\n}\n\nvoid stbds_strreset(stbds_string_arena *a)\n{\n  stbds_string_block *x,*y;\n  x = a->storage;\n  while (x) {\n    y = x->next;\n    STBDS_FREE(NULL, x);\n    x = y;\n  }\n  memset(a, 0, sizeof(*a));\n}\n\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//   UNIT TESTS\n//\n\n#ifdef STBDS_UNIT_TESTS\n#include <stdio.h>\n#ifdef STBDS_ASSERT_WAS_UNDEFINED\n#undef STBDS_ASSERT\n#endif\n#ifndef STBDS_ASSERT\n#define STBDS_ASSERT assert\n#include <assert.h>\n#endif\n\ntypedef struct { int key,b,c,d; } stbds_struct;\ntypedef struct { int key[2],b,c,d; } stbds_struct2;\n\nstatic char buffer[256];\nchar *strkey(int n)\n{\n#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)\n   sprintf_s(buffer, sizeof(buffer), \"test_%d\", n);\n#else\n   sprintf(buffer, \"test_%d\", n);\n#endif\n   return buffer;\n}\n\nvoid stbds_unit_tests(void)\n{\n#if defined(_MSC_VER) && _MSC_VER <= 1200 && defined(__cplusplus)\n  // VC6 C++ doesn't like the template<> trick on unnamed structures, so do nothing!\n  STBDS_ASSERT(0);\n#else\n  const int testsize = 100000;\n  const int testsize2 = testsize/20;\n  int *arr=NULL;\n  struct { int   key;        int value; }  *intmap  = NULL;\n  struct { char *key;        int value; }  *strmap  = NULL, s;\n  struct { stbds_struct key; int value; }  *map     = NULL;\n  stbds_struct                             *map2    = NULL;\n  stbds_struct2                            *map3    = NULL;\n  stbds_string_arena                        sa      = { 0 };\n  int key3[2] = { 1,2 };\n  ptrdiff_t temp;\n\n  int i,j;\n\n  STBDS_ASSERT(arrlen(arr)==0);\n  for (i=0; i < 20000; i += 50) {\n    for (j=0; j < i; ++j)\n      arrpush(arr,j);\n    arrfree(arr);\n  }\n\n  for (i=0; i < 4; ++i) {\n    arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);\n    arrdel(arr,i);\n    arrfree(arr);\n    arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);\n    arrdelswap(arr,i);\n    arrfree(arr);\n  }\n\n  for (i=0; i < 5; ++i) {\n    arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);\n    stbds_arrins(arr,i,5);\n    STBDS_ASSERT(arr[i] == 5);\n    if (i < 4)\n      STBDS_ASSERT(arr[4] == 4);\n    arrfree(arr);\n  }\n\n  i = 1;\n  STBDS_ASSERT(hmgeti(intmap,i) == -1);\n  hmdefault(intmap, -2);\n  STBDS_ASSERT(hmgeti(intmap, i) == -1);\n  STBDS_ASSERT(hmget (intmap, i) == -2);\n  for (i=0; i < testsize; i+=2)\n    hmput(intmap, i, i*5);\n  for (i=0; i < testsize; i+=1) {\n    if (i & 1) STBDS_ASSERT(hmget(intmap, i) == -2 );\n    else       STBDS_ASSERT(hmget(intmap, i) == i*5);\n    if (i & 1) STBDS_ASSERT(hmget_ts(intmap, i, temp) == -2 );\n    else       STBDS_ASSERT(hmget_ts(intmap, i, temp) == i*5);\n  }\n  for (i=0; i < testsize; i+=2)\n    hmput(intmap, i, i*3);\n  for (i=0; i < testsize; i+=1)\n    if (i & 1) STBDS_ASSERT(hmget(intmap, i) == -2 );\n    else       STBDS_ASSERT(hmget(intmap, i) == i*3);\n  for (i=2; i < testsize; i+=4)\n    hmdel(intmap, i); // delete half the entries\n  for (i=0; i < testsize; i+=1)\n    if (i & 3) STBDS_ASSERT(hmget(intmap, i) == -2 );\n    else       STBDS_ASSERT(hmget(intmap, i) == i*3);\n  for (i=0; i < testsize; i+=1)\n    hmdel(intmap, i); // delete the rest of the entries\n  for (i=0; i < testsize; i+=1)\n    STBDS_ASSERT(hmget(intmap, i) == -2 );\n  hmfree(intmap);\n  for (i=0; i < testsize; i+=2)\n    hmput(intmap, i, i*3);\n  hmfree(intmap);\n\n  #if defined(__clang__) || defined(__GNUC__)\n  #ifndef __cplusplus\n  intmap = NULL;\n  hmput(intmap, 15, 7);\n  hmput(intmap, 11, 3);\n  hmput(intmap,  9, 5);\n  STBDS_ASSERT(hmget(intmap, 9) == 5);\n  STBDS_ASSERT(hmget(intmap, 11) == 3);\n  STBDS_ASSERT(hmget(intmap, 15) == 7);\n  #endif\n  #endif\n\n  for (i=0; i < testsize; ++i)\n    stralloc(&sa, strkey(i));\n  strreset(&sa);\n\n  {\n    s.key = \"a\", s.value = 1;\n    shputs(strmap, s);\n    STBDS_ASSERT(*strmap[0].key == 'a');\n    STBDS_ASSERT(strmap[0].key == s.key);\n    STBDS_ASSERT(strmap[0].value == s.value);\n    shfree(strmap);\n  }\n\n  {\n    s.key = \"a\", s.value = 1;\n    sh_new_strdup(strmap);\n    shputs(strmap, s);\n    STBDS_ASSERT(*strmap[0].key == 'a');\n    STBDS_ASSERT(strmap[0].key != s.key);\n    STBDS_ASSERT(strmap[0].value == s.value);\n    shfree(strmap);\n  }\n\n  {\n    s.key = \"a\", s.value = 1;\n    sh_new_arena(strmap);\n    shputs(strmap, s);\n    STBDS_ASSERT(*strmap[0].key == 'a');\n    STBDS_ASSERT(strmap[0].key != s.key);\n    STBDS_ASSERT(strmap[0].value == s.value);\n    shfree(strmap);\n  }\n\n  for (j=0; j < 2; ++j) {\n    STBDS_ASSERT(shgeti(strmap,\"foo\") == -1);\n    if (j == 0)\n      sh_new_strdup(strmap);\n    else\n      sh_new_arena(strmap);\n    STBDS_ASSERT(shgeti(strmap,\"foo\") == -1);\n    shdefault(strmap, -2);\n    STBDS_ASSERT(shgeti(strmap,\"foo\") == -1);\n    for (i=0; i < testsize; i+=2)\n      shput(strmap, strkey(i), i*3);\n    for (i=0; i < testsize; i+=1)\n      if (i & 1) STBDS_ASSERT(shget(strmap, strkey(i)) == -2 );\n      else       STBDS_ASSERT(shget(strmap, strkey(i)) == i*3);\n    for (i=2; i < testsize; i+=4)\n      shdel(strmap, strkey(i)); // delete half the entries\n    for (i=0; i < testsize; i+=1)\n      if (i & 3) STBDS_ASSERT(shget(strmap, strkey(i)) == -2 );\n      else       STBDS_ASSERT(shget(strmap, strkey(i)) == i*3);\n    for (i=0; i < testsize; i+=1)\n      shdel(strmap, strkey(i)); // delete the rest of the entries\n    for (i=0; i < testsize; i+=1)\n      STBDS_ASSERT(shget(strmap, strkey(i)) == -2 );\n    shfree(strmap);\n  }\n\n  {\n    struct { char *key; char value; } *hash = NULL;\n    char name[4] = \"jen\";\n    shput(hash, \"bob\"   , 'h');\n    shput(hash, \"sally\" , 'e');\n    shput(hash, \"fred\"  , 'l');\n    shput(hash, \"jen\"   , 'x');\n    shput(hash, \"doug\"  , 'o');\n\n    shput(hash, name    , 'l');\n    shfree(hash);\n  }\n\n  for (i=0; i < testsize; i += 2) {\n    stbds_struct s = { i,i*2,i*3,i*4 };\n    hmput(map, s, i*5);\n  }\n\n  for (i=0; i < testsize; i += 1) {\n    stbds_struct s = { i,i*2,i*3  ,i*4 };\n    stbds_struct t = { i,i*2,i*3+1,i*4 };\n    if (i & 1) STBDS_ASSERT(hmget(map, s) == 0);\n    else       STBDS_ASSERT(hmget(map, s) == i*5);\n    if (i & 1) STBDS_ASSERT(hmget_ts(map, s, temp) == 0);\n    else       STBDS_ASSERT(hmget_ts(map, s, temp) == i*5);\n    //STBDS_ASSERT(hmget(map, t.key) == 0);\n  }\n\n  for (i=0; i < testsize; i += 2) {\n    stbds_struct s = { i,i*2,i*3,i*4 };\n    hmputs(map2, s);\n  }\n  hmfree(map);\n\n  for (i=0; i < testsize; i += 1) {\n    stbds_struct s = { i,i*2,i*3,i*4 };\n    stbds_struct t = { i,i*2,i*3+1,i*4 };\n    if (i & 1) STBDS_ASSERT(hmgets(map2, s.key).d == 0);\n    else       STBDS_ASSERT(hmgets(map2, s.key).d == i*4);\n    //STBDS_ASSERT(hmgetp(map2, t.key) == 0);\n  }\n  hmfree(map2);\n\n  for (i=0; i < testsize; i += 2) {\n    stbds_struct2 s = { { i,i*2 }, i*3,i*4, i*5 };\n    hmputs(map3, s);\n  }\n  for (i=0; i < testsize; i += 1) {\n    stbds_struct2 s = { { i,i*2}, i*3, i*4, i*5 };\n    stbds_struct2 t = { { i,i*2}, i*3+1, i*4, i*5 };\n    if (i & 1) STBDS_ASSERT(hmgets(map3, s.key).d == 0);\n    else       STBDS_ASSERT(hmgets(map3, s.key).d == i*5);\n    //STBDS_ASSERT(hmgetp(map3, t.key) == 0);\n  }\n#endif\n}\n#endif\n\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2019 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_dxt.h",
    "content": "// stb_dxt.h - v1.12 - DXT1/DXT5 compressor - public domain\n// original by fabian \"ryg\" giesen - ported to C by stb\n// use '#define STB_DXT_IMPLEMENTATION' before including to create the implementation\n//\n// USAGE:\n//   call stb_compress_dxt_block() for every block (you must pad)\n//     source should be a 4x4 block of RGBA data in row-major order;\n//     Alpha channel is not stored if you specify alpha=0 (but you\n//     must supply some constant alpha in the alpha channel).\n//     You can turn on dithering and \"high quality\" using mode.\n//\n// version history:\n//   v1.12  - (ryg) fix bug in single-color table generator\n//   v1.11  - (ryg) avoid racy global init, better single-color tables, remove dither\n//   v1.10  - (i.c) various small quality improvements\n//   v1.09  - (stb) update documentation re: surprising alpha channel requirement\n//   v1.08  - (stb) fix bug in dxt-with-alpha block\n//   v1.07  - (stb) bc4; allow not using libc; add STB_DXT_STATIC\n//   v1.06  - (stb) fix to known-broken 1.05\n//   v1.05  - (stb) support bc5/3dc (Arvids Kokins), use extern \"C\" in C++ (Pavel Krajcevski)\n//   v1.04  - (ryg) default to no rounding bias for lerped colors (as per S3TC/DX10 spec);\n//            single color match fix (allow for inexact color interpolation);\n//            optimal DXT5 index finder; \"high quality\" mode that runs multiple refinement steps.\n//   v1.03  - (stb) endianness support\n//   v1.02  - (stb) fix alpha encoding bug\n//   v1.01  - (stb) fix bug converting to RGB that messed up quality, thanks ryg & cbloom\n//   v1.00  - (stb) first release\n//\n// contributors:\n//   Rich Geldreich (more accurate index selection)\n//   Kevin Schmidt (#defines for \"freestanding\" compilation)\n//   github:ppiastucki (BC4 support)\n//   Ignacio Castano - improve DXT endpoint quantization\n//   Alan Hickman - static table initialization\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n#ifndef STB_INCLUDE_STB_DXT_H\n#define STB_INCLUDE_STB_DXT_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifdef STB_DXT_STATIC\n#define STBDDEF static\n#else\n#define STBDDEF extern\n#endif\n\n// compression mode (bitflags)\n#define STB_DXT_NORMAL    0\n#define STB_DXT_DITHER    1   // use dithering. was always dubious, now deprecated. does nothing!\n#define STB_DXT_HIGHQUAL  2   // high quality mode, does two refinement steps instead of 1. ~30-40% slower.\n\nSTBDDEF void stb_compress_dxt_block(unsigned char *dest, const unsigned char *src_rgba_four_bytes_per_pixel, int alpha, int mode);\nSTBDDEF void stb_compress_bc4_block(unsigned char *dest, const unsigned char *src_r_one_byte_per_pixel);\nSTBDDEF void stb_compress_bc5_block(unsigned char *dest, const unsigned char *src_rg_two_byte_per_pixel);\n\n#define STB_COMPRESS_DXT_BLOCK\n\n#ifdef __cplusplus\n}\n#endif\n#endif // STB_INCLUDE_STB_DXT_H\n\n#ifdef STB_DXT_IMPLEMENTATION\n\n// configuration options for DXT encoder. set them in the project/makefile or just define\n// them at the top.\n\n// STB_DXT_USE_ROUNDING_BIAS\n//     use a rounding bias during color interpolation. this is closer to what \"ideal\"\n//     interpolation would do but doesn't match the S3TC/DX10 spec. old versions (pre-1.03)\n//     implicitly had this turned on.\n//\n//     in case you're targeting a specific type of hardware (e.g. console programmers):\n//     NVidia and Intel GPUs (as of 2010) as well as DX9 ref use DXT decoders that are closer\n//     to STB_DXT_USE_ROUNDING_BIAS. AMD/ATI, S3 and DX10 ref are closer to rounding with no bias.\n//     you also see \"(a*5 + b*3) / 8\" on some old GPU designs.\n// #define STB_DXT_USE_ROUNDING_BIAS\n\n#include <stdlib.h>\n\n#if !defined(STBD_FABS)\n#include <math.h>\n#endif\n\n#ifndef STBD_FABS\n#define STBD_FABS(x)          fabs(x)\n#endif\n\nstatic const unsigned char stb__OMatch5[256][2] = {\n   {  0,  0 }, {  0,  0 }, {  0,  1 }, {  0,  1 }, {  1,  0 }, {  1,  0 }, {  1,  0 }, {  1,  1 },\n   {  1,  1 }, {  1,  1 }, {  1,  2 }, {  0,  4 }, {  2,  1 }, {  2,  1 }, {  2,  1 }, {  2,  2 },\n   {  2,  2 }, {  2,  2 }, {  2,  3 }, {  1,  5 }, {  3,  2 }, {  3,  2 }, {  4,  0 }, {  3,  3 },\n   {  3,  3 }, {  3,  3 }, {  3,  4 }, {  3,  4 }, {  3,  4 }, {  3,  5 }, {  4,  3 }, {  4,  3 },\n   {  5,  2 }, {  4,  4 }, {  4,  4 }, {  4,  5 }, {  4,  5 }, {  5,  4 }, {  5,  4 }, {  5,  4 },\n   {  6,  3 }, {  5,  5 }, {  5,  5 }, {  5,  6 }, {  4,  8 }, {  6,  5 }, {  6,  5 }, {  6,  5 },\n   {  6,  6 }, {  6,  6 }, {  6,  6 }, {  6,  7 }, {  5,  9 }, {  7,  6 }, {  7,  6 }, {  8,  4 },\n   {  7,  7 }, {  7,  7 }, {  7,  7 }, {  7,  8 }, {  7,  8 }, {  7,  8 }, {  7,  9 }, {  8,  7 },\n   {  8,  7 }, {  9,  6 }, {  8,  8 }, {  8,  8 }, {  8,  9 }, {  8,  9 }, {  9,  8 }, {  9,  8 },\n   {  9,  8 }, { 10,  7 }, {  9,  9 }, {  9,  9 }, {  9, 10 }, {  8, 12 }, { 10,  9 }, { 10,  9 },\n   { 10,  9 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 11 }, {  9, 13 }, { 11, 10 }, { 11, 10 },\n   { 12,  8 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 12 }, { 11, 12 }, { 11, 12 }, { 11, 13 },\n   { 12, 11 }, { 12, 11 }, { 13, 10 }, { 12, 12 }, { 12, 12 }, { 12, 13 }, { 12, 13 }, { 13, 12 },\n   { 13, 12 }, { 13, 12 }, { 14, 11 }, { 13, 13 }, { 13, 13 }, { 13, 14 }, { 12, 16 }, { 14, 13 },\n   { 14, 13 }, { 14, 13 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 15 }, { 13, 17 }, { 15, 14 },\n   { 15, 14 }, { 16, 12 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 16 }, { 15, 16 }, { 15, 16 },\n   { 15, 17 }, { 16, 15 }, { 16, 15 }, { 17, 14 }, { 16, 16 }, { 16, 16 }, { 16, 17 }, { 16, 17 },\n   { 17, 16 }, { 17, 16 }, { 17, 16 }, { 18, 15 }, { 17, 17 }, { 17, 17 }, { 17, 18 }, { 16, 20 },\n   { 18, 17 }, { 18, 17 }, { 18, 17 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 19 }, { 17, 21 },\n   { 19, 18 }, { 19, 18 }, { 20, 16 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 20 }, { 19, 20 },\n   { 19, 20 }, { 19, 21 }, { 20, 19 }, { 20, 19 }, { 21, 18 }, { 20, 20 }, { 20, 20 }, { 20, 21 },\n   { 20, 21 }, { 21, 20 }, { 21, 20 }, { 21, 20 }, { 22, 19 }, { 21, 21 }, { 21, 21 }, { 21, 22 },\n   { 20, 24 }, { 22, 21 }, { 22, 21 }, { 22, 21 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 23 },\n   { 21, 25 }, { 23, 22 }, { 23, 22 }, { 24, 20 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 24 },\n   { 23, 24 }, { 23, 24 }, { 23, 25 }, { 24, 23 }, { 24, 23 }, { 25, 22 }, { 24, 24 }, { 24, 24 },\n   { 24, 25 }, { 24, 25 }, { 25, 24 }, { 25, 24 }, { 25, 24 }, { 26, 23 }, { 25, 25 }, { 25, 25 },\n   { 25, 26 }, { 24, 28 }, { 26, 25 }, { 26, 25 }, { 26, 25 }, { 26, 26 }, { 26, 26 }, { 26, 26 },\n   { 26, 27 }, { 25, 29 }, { 27, 26 }, { 27, 26 }, { 28, 24 }, { 27, 27 }, { 27, 27 }, { 27, 27 },\n   { 27, 28 }, { 27, 28 }, { 27, 28 }, { 27, 29 }, { 28, 27 }, { 28, 27 }, { 29, 26 }, { 28, 28 },\n   { 28, 28 }, { 28, 29 }, { 28, 29 }, { 29, 28 }, { 29, 28 }, { 29, 28 }, { 30, 27 }, { 29, 29 },\n   { 29, 29 }, { 29, 30 }, { 29, 30 }, { 30, 29 }, { 30, 29 }, { 30, 29 }, { 30, 30 }, { 30, 30 },\n   { 30, 30 }, { 30, 31 }, { 30, 31 }, { 31, 30 }, { 31, 30 }, { 31, 30 }, { 31, 31 }, { 31, 31 },\n};\nstatic const unsigned char stb__OMatch6[256][2] = {\n   {  0,  0 }, {  0,  1 }, {  1,  0 }, {  1,  1 }, {  1,  1 }, {  1,  2 }, {  2,  1 }, {  2,  2 },\n   {  2,  2 }, {  2,  3 }, {  3,  2 }, {  3,  3 }, {  3,  3 }, {  3,  4 }, {  4,  3 }, {  4,  4 },\n   {  4,  4 }, {  4,  5 }, {  5,  4 }, {  5,  5 }, {  5,  5 }, {  5,  6 }, {  6,  5 }, {  6,  6 },\n   {  6,  6 }, {  6,  7 }, {  7,  6 }, {  7,  7 }, {  7,  7 }, {  7,  8 }, {  8,  7 }, {  8,  8 },\n   {  8,  8 }, {  8,  9 }, {  9,  8 }, {  9,  9 }, {  9,  9 }, {  9, 10 }, { 10,  9 }, { 10, 10 },\n   { 10, 10 }, { 10, 11 }, { 11, 10 }, {  8, 16 }, { 11, 11 }, { 11, 12 }, { 12, 11 }, {  9, 17 },\n   { 12, 12 }, { 12, 13 }, { 13, 12 }, { 11, 16 }, { 13, 13 }, { 13, 14 }, { 14, 13 }, { 12, 17 },\n   { 14, 14 }, { 14, 15 }, { 15, 14 }, { 14, 16 }, { 15, 15 }, { 15, 16 }, { 16, 14 }, { 16, 15 },\n   { 17, 14 }, { 16, 16 }, { 16, 17 }, { 17, 16 }, { 18, 15 }, { 17, 17 }, { 17, 18 }, { 18, 17 },\n   { 20, 14 }, { 18, 18 }, { 18, 19 }, { 19, 18 }, { 21, 15 }, { 19, 19 }, { 19, 20 }, { 20, 19 },\n   { 20, 20 }, { 20, 20 }, { 20, 21 }, { 21, 20 }, { 21, 21 }, { 21, 21 }, { 21, 22 }, { 22, 21 },\n   { 22, 22 }, { 22, 22 }, { 22, 23 }, { 23, 22 }, { 23, 23 }, { 23, 23 }, { 23, 24 }, { 24, 23 },\n   { 24, 24 }, { 24, 24 }, { 24, 25 }, { 25, 24 }, { 25, 25 }, { 25, 25 }, { 25, 26 }, { 26, 25 },\n   { 26, 26 }, { 26, 26 }, { 26, 27 }, { 27, 26 }, { 24, 32 }, { 27, 27 }, { 27, 28 }, { 28, 27 },\n   { 25, 33 }, { 28, 28 }, { 28, 29 }, { 29, 28 }, { 27, 32 }, { 29, 29 }, { 29, 30 }, { 30, 29 },\n   { 28, 33 }, { 30, 30 }, { 30, 31 }, { 31, 30 }, { 30, 32 }, { 31, 31 }, { 31, 32 }, { 32, 30 },\n   { 32, 31 }, { 33, 30 }, { 32, 32 }, { 32, 33 }, { 33, 32 }, { 34, 31 }, { 33, 33 }, { 33, 34 },\n   { 34, 33 }, { 36, 30 }, { 34, 34 }, { 34, 35 }, { 35, 34 }, { 37, 31 }, { 35, 35 }, { 35, 36 },\n   { 36, 35 }, { 36, 36 }, { 36, 36 }, { 36, 37 }, { 37, 36 }, { 37, 37 }, { 37, 37 }, { 37, 38 },\n   { 38, 37 }, { 38, 38 }, { 38, 38 }, { 38, 39 }, { 39, 38 }, { 39, 39 }, { 39, 39 }, { 39, 40 },\n   { 40, 39 }, { 40, 40 }, { 40, 40 }, { 40, 41 }, { 41, 40 }, { 41, 41 }, { 41, 41 }, { 41, 42 },\n   { 42, 41 }, { 42, 42 }, { 42, 42 }, { 42, 43 }, { 43, 42 }, { 40, 48 }, { 43, 43 }, { 43, 44 },\n   { 44, 43 }, { 41, 49 }, { 44, 44 }, { 44, 45 }, { 45, 44 }, { 43, 48 }, { 45, 45 }, { 45, 46 },\n   { 46, 45 }, { 44, 49 }, { 46, 46 }, { 46, 47 }, { 47, 46 }, { 46, 48 }, { 47, 47 }, { 47, 48 },\n   { 48, 46 }, { 48, 47 }, { 49, 46 }, { 48, 48 }, { 48, 49 }, { 49, 48 }, { 50, 47 }, { 49, 49 },\n   { 49, 50 }, { 50, 49 }, { 52, 46 }, { 50, 50 }, { 50, 51 }, { 51, 50 }, { 53, 47 }, { 51, 51 },\n   { 51, 52 }, { 52, 51 }, { 52, 52 }, { 52, 52 }, { 52, 53 }, { 53, 52 }, { 53, 53 }, { 53, 53 },\n   { 53, 54 }, { 54, 53 }, { 54, 54 }, { 54, 54 }, { 54, 55 }, { 55, 54 }, { 55, 55 }, { 55, 55 },\n   { 55, 56 }, { 56, 55 }, { 56, 56 }, { 56, 56 }, { 56, 57 }, { 57, 56 }, { 57, 57 }, { 57, 57 },\n   { 57, 58 }, { 58, 57 }, { 58, 58 }, { 58, 58 }, { 58, 59 }, { 59, 58 }, { 59, 59 }, { 59, 59 },\n   { 59, 60 }, { 60, 59 }, { 60, 60 }, { 60, 60 }, { 60, 61 }, { 61, 60 }, { 61, 61 }, { 61, 61 },\n   { 61, 62 }, { 62, 61 }, { 62, 62 }, { 62, 62 }, { 62, 63 }, { 63, 62 }, { 63, 63 }, { 63, 63 },\n};\n\nstatic int stb__Mul8Bit(int a, int b)\n{\n  int t = a*b + 128;\n  return (t + (t >> 8)) >> 8;\n}\n\nstatic void stb__From16Bit(unsigned char *out, unsigned short v)\n{\n   int rv = (v & 0xf800) >> 11;\n   int gv = (v & 0x07e0) >>  5;\n   int bv = (v & 0x001f) >>  0;\n\n   // expand to 8 bits via bit replication\n   out[0] = (rv * 33) >> 2;\n   out[1] = (gv * 65) >> 4;\n   out[2] = (bv * 33) >> 2;\n   out[3] = 0;\n}\n\nstatic unsigned short stb__As16Bit(int r, int g, int b)\n{\n   return (unsigned short)((stb__Mul8Bit(r,31) << 11) + (stb__Mul8Bit(g,63) << 5) + stb__Mul8Bit(b,31));\n}\n\n// linear interpolation at 1/3 point between a and b, using desired rounding type\nstatic int stb__Lerp13(int a, int b)\n{\n#ifdef STB_DXT_USE_ROUNDING_BIAS\n   // with rounding bias\n   return a + stb__Mul8Bit(b-a, 0x55);\n#else\n   // without rounding bias\n   // replace \"/ 3\" by \"* 0xaaab) >> 17\" if your compiler sucks or you really need every ounce of speed.\n   return (2*a + b) / 3;\n#endif\n}\n\n// lerp RGB color\nstatic void stb__Lerp13RGB(unsigned char *out, unsigned char *p1, unsigned char *p2)\n{\n   out[0] = (unsigned char)stb__Lerp13(p1[0], p2[0]);\n   out[1] = (unsigned char)stb__Lerp13(p1[1], p2[1]);\n   out[2] = (unsigned char)stb__Lerp13(p1[2], p2[2]);\n}\n\n/****************************************************************************/\n\nstatic void stb__EvalColors(unsigned char *color,unsigned short c0,unsigned short c1)\n{\n   stb__From16Bit(color+ 0, c0);\n   stb__From16Bit(color+ 4, c1);\n   stb__Lerp13RGB(color+ 8, color+0, color+4);\n   stb__Lerp13RGB(color+12, color+4, color+0);\n}\n\n// The color matching function\nstatic unsigned int stb__MatchColorsBlock(unsigned char *block, unsigned char *color)\n{\n   unsigned int mask = 0;\n   int dirr = color[0*4+0] - color[1*4+0];\n   int dirg = color[0*4+1] - color[1*4+1];\n   int dirb = color[0*4+2] - color[1*4+2];\n   int dots[16];\n   int stops[4];\n   int i;\n   int c0Point, halfPoint, c3Point;\n\n   for(i=0;i<16;i++)\n      dots[i] = block[i*4+0]*dirr + block[i*4+1]*dirg + block[i*4+2]*dirb;\n\n   for(i=0;i<4;i++)\n      stops[i] = color[i*4+0]*dirr + color[i*4+1]*dirg + color[i*4+2]*dirb;\n\n   // think of the colors as arranged on a line; project point onto that line, then choose\n   // next color out of available ones. we compute the crossover points for \"best color in top\n   // half\"/\"best in bottom half\" and then the same inside that subinterval.\n   //\n   // relying on this 1d approximation isn't always optimal in terms of euclidean distance,\n   // but it's very close and a lot faster.\n   // http://cbloomrants.blogspot.com/2008/12/12-08-08-dxtc-summary.html\n\n   c0Point   = (stops[1] + stops[3]);\n   halfPoint = (stops[3] + stops[2]);\n   c3Point   = (stops[2] + stops[0]);\n\n   for (i=15;i>=0;i--) {\n      int dot = dots[i]*2;\n      mask <<= 2;\n\n      if(dot < halfPoint)\n         mask |= (dot < c0Point) ? 1 : 3;\n      else\n         mask |= (dot < c3Point) ? 2 : 0;\n   }\n\n   return mask;\n}\n\n// The color optimization function. (Clever code, part 1)\nstatic void stb__OptimizeColorsBlock(unsigned char *block, unsigned short *pmax16, unsigned short *pmin16)\n{\n  int mind,maxd;\n  unsigned char *minp, *maxp;\n  double magn;\n  int v_r,v_g,v_b;\n  static const int nIterPower = 4;\n  float covf[6],vfr,vfg,vfb;\n\n  // determine color distribution\n  int cov[6];\n  int mu[3],min[3],max[3];\n  int ch,i,iter;\n\n  for(ch=0;ch<3;ch++)\n  {\n    const unsigned char *bp = ((const unsigned char *) block) + ch;\n    int muv,minv,maxv;\n\n    muv = minv = maxv = bp[0];\n    for(i=4;i<64;i+=4)\n    {\n      muv += bp[i];\n      if (bp[i] < minv) minv = bp[i];\n      else if (bp[i] > maxv) maxv = bp[i];\n    }\n\n    mu[ch] = (muv + 8) >> 4;\n    min[ch] = minv;\n    max[ch] = maxv;\n  }\n\n  // determine covariance matrix\n  for (i=0;i<6;i++)\n     cov[i] = 0;\n\n  for (i=0;i<16;i++)\n  {\n    int r = block[i*4+0] - mu[0];\n    int g = block[i*4+1] - mu[1];\n    int b = block[i*4+2] - mu[2];\n\n    cov[0] += r*r;\n    cov[1] += r*g;\n    cov[2] += r*b;\n    cov[3] += g*g;\n    cov[4] += g*b;\n    cov[5] += b*b;\n  }\n\n  // convert covariance matrix to float, find principal axis via power iter\n  for(i=0;i<6;i++)\n    covf[i] = cov[i] / 255.0f;\n\n  vfr = (float) (max[0] - min[0]);\n  vfg = (float) (max[1] - min[1]);\n  vfb = (float) (max[2] - min[2]);\n\n  for(iter=0;iter<nIterPower;iter++)\n  {\n    float r = vfr*covf[0] + vfg*covf[1] + vfb*covf[2];\n    float g = vfr*covf[1] + vfg*covf[3] + vfb*covf[4];\n    float b = vfr*covf[2] + vfg*covf[4] + vfb*covf[5];\n\n    vfr = r;\n    vfg = g;\n    vfb = b;\n  }\n\n  magn = STBD_FABS(vfr);\n  if (STBD_FABS(vfg) > magn) magn = STBD_FABS(vfg);\n  if (STBD_FABS(vfb) > magn) magn = STBD_FABS(vfb);\n\n   if(magn < 4.0f) { // too small, default to luminance\n      v_r = 299; // JPEG YCbCr luma coefs, scaled by 1000.\n      v_g = 587;\n      v_b = 114;\n   } else {\n      magn = 512.0 / magn;\n      v_r = (int) (vfr * magn);\n      v_g = (int) (vfg * magn);\n      v_b = (int) (vfb * magn);\n   }\n\n   minp = maxp = block;\n   mind = maxd = block[0]*v_r + block[1]*v_g + block[2]*v_b;\n   // Pick colors at extreme points\n   for(i=1;i<16;i++)\n   {\n      int dot = block[i*4+0]*v_r + block[i*4+1]*v_g + block[i*4+2]*v_b;\n\n      if (dot < mind) {\n         mind = dot;\n         minp = block+i*4;\n      }\n\n      if (dot > maxd) {\n         maxd = dot;\n         maxp = block+i*4;\n      }\n   }\n\n   *pmax16 = stb__As16Bit(maxp[0],maxp[1],maxp[2]);\n   *pmin16 = stb__As16Bit(minp[0],minp[1],minp[2]);\n}\n\nstatic const float stb__midpoints5[32] = {\n   0.015686f, 0.047059f, 0.078431f, 0.111765f, 0.145098f, 0.176471f, 0.207843f, 0.241176f, 0.274510f, 0.305882f, 0.337255f, 0.370588f, 0.403922f, 0.435294f, 0.466667f, 0.5f,\n   0.533333f, 0.564706f, 0.596078f, 0.629412f, 0.662745f, 0.694118f, 0.725490f, 0.758824f, 0.792157f, 0.823529f, 0.854902f, 0.888235f, 0.921569f, 0.952941f, 0.984314f, 1.0f\n};\n\nstatic const float stb__midpoints6[64] = {\n   0.007843f, 0.023529f, 0.039216f, 0.054902f, 0.070588f, 0.086275f, 0.101961f, 0.117647f, 0.133333f, 0.149020f, 0.164706f, 0.180392f, 0.196078f, 0.211765f, 0.227451f, 0.245098f,\n   0.262745f, 0.278431f, 0.294118f, 0.309804f, 0.325490f, 0.341176f, 0.356863f, 0.372549f, 0.388235f, 0.403922f, 0.419608f, 0.435294f, 0.450980f, 0.466667f, 0.482353f, 0.500000f,\n   0.517647f, 0.533333f, 0.549020f, 0.564706f, 0.580392f, 0.596078f, 0.611765f, 0.627451f, 0.643137f, 0.658824f, 0.674510f, 0.690196f, 0.705882f, 0.721569f, 0.737255f, 0.754902f,\n   0.772549f, 0.788235f, 0.803922f, 0.819608f, 0.835294f, 0.850980f, 0.866667f, 0.882353f, 0.898039f, 0.913725f, 0.929412f, 0.945098f, 0.960784f, 0.976471f, 0.992157f, 1.0f\n};\n\nstatic unsigned short stb__Quantize5(float x)\n{\n   unsigned short q;\n   x = x < 0 ? 0 : x > 1 ? 1 : x;  // saturate\n   q = (unsigned short)(x * 31);\n   q += (x > stb__midpoints5[q]);\n   return q;\n}\n\nstatic unsigned short stb__Quantize6(float x)\n{\n   unsigned short q;\n   x = x < 0 ? 0 : x > 1 ? 1 : x;  // saturate\n   q = (unsigned short)(x * 63);\n   q += (x > stb__midpoints6[q]);\n   return q;\n}\n\n// The refinement function. (Clever code, part 2)\n// Tries to optimize colors to suit block contents better.\n// (By solving a least squares system via normal equations+Cramer's rule)\nstatic int stb__RefineBlock(unsigned char *block, unsigned short *pmax16, unsigned short *pmin16, unsigned int mask)\n{\n   static const int w1Tab[4] = { 3,0,2,1 };\n   static const int prods[4] = { 0x090000,0x000900,0x040102,0x010402 };\n   // ^some magic to save a lot of multiplies in the accumulating loop...\n   // (precomputed products of weights for least squares system, accumulated inside one 32-bit register)\n\n   float f;\n   unsigned short oldMin, oldMax, min16, max16;\n   int i, akku = 0, xx,xy,yy;\n   int At1_r,At1_g,At1_b;\n   int At2_r,At2_g,At2_b;\n   unsigned int cm = mask;\n\n   oldMin = *pmin16;\n   oldMax = *pmax16;\n\n   if((mask ^ (mask<<2)) < 4) // all pixels have the same index?\n   {\n      // yes, linear system would be singular; solve using optimal\n      // single-color match on average color\n      int r = 8, g = 8, b = 8;\n      for (i=0;i<16;++i) {\n         r += block[i*4+0];\n         g += block[i*4+1];\n         b += block[i*4+2];\n      }\n\n      r >>= 4; g >>= 4; b >>= 4;\n\n      max16 = (stb__OMatch5[r][0]<<11) | (stb__OMatch6[g][0]<<5) | stb__OMatch5[b][0];\n      min16 = (stb__OMatch5[r][1]<<11) | (stb__OMatch6[g][1]<<5) | stb__OMatch5[b][1];\n   } else {\n      At1_r = At1_g = At1_b = 0;\n      At2_r = At2_g = At2_b = 0;\n      for (i=0;i<16;++i,cm>>=2) {\n         int step = cm&3;\n         int w1 = w1Tab[step];\n         int r = block[i*4+0];\n         int g = block[i*4+1];\n         int b = block[i*4+2];\n\n         akku    += prods[step];\n         At1_r   += w1*r;\n         At1_g   += w1*g;\n         At1_b   += w1*b;\n         At2_r   += r;\n         At2_g   += g;\n         At2_b   += b;\n      }\n\n      At2_r = 3*At2_r - At1_r;\n      At2_g = 3*At2_g - At1_g;\n      At2_b = 3*At2_b - At1_b;\n\n      // extract solutions and decide solvability\n      xx = akku >> 16;\n      yy = (akku >> 8) & 0xff;\n      xy = (akku >> 0) & 0xff;\n\n      f = 3.0f / 255.0f / (xx*yy - xy*xy);\n\n      max16 =  stb__Quantize5((At1_r*yy - At2_r * xy) * f) << 11;\n      max16 |= stb__Quantize6((At1_g*yy - At2_g * xy) * f) << 5;\n      max16 |= stb__Quantize5((At1_b*yy - At2_b * xy) * f) << 0;\n\n      min16 =  stb__Quantize5((At2_r*xx - At1_r * xy) * f) << 11;\n      min16 |= stb__Quantize6((At2_g*xx - At1_g * xy) * f) << 5;\n      min16 |= stb__Quantize5((At2_b*xx - At1_b * xy) * f) << 0;\n   }\n\n   *pmin16 = min16;\n   *pmax16 = max16;\n   return oldMin != min16 || oldMax != max16;\n}\n\n// Color block compression\nstatic void stb__CompressColorBlock(unsigned char *dest, unsigned char *block, int mode)\n{\n   unsigned int mask;\n   int i;\n   int refinecount;\n   unsigned short max16, min16;\n   unsigned char color[4*4];\n\n   refinecount = (mode & STB_DXT_HIGHQUAL) ? 2 : 1;\n\n   // check if block is constant\n   for (i=1;i<16;i++)\n      if (((unsigned int *) block)[i] != ((unsigned int *) block)[0])\n         break;\n\n   if(i == 16) { // constant color\n      int r = block[0], g = block[1], b = block[2];\n      mask  = 0xaaaaaaaa;\n      max16 = (stb__OMatch5[r][0]<<11) | (stb__OMatch6[g][0]<<5) | stb__OMatch5[b][0];\n      min16 = (stb__OMatch5[r][1]<<11) | (stb__OMatch6[g][1]<<5) | stb__OMatch5[b][1];\n   } else {\n      // first step: PCA+map along principal axis\n      stb__OptimizeColorsBlock(block,&max16,&min16);\n      if (max16 != min16) {\n         stb__EvalColors(color,max16,min16);\n         mask = stb__MatchColorsBlock(block,color);\n      } else\n         mask = 0;\n\n      // third step: refine (multiple times if requested)\n      for (i=0;i<refinecount;i++) {\n         unsigned int lastmask = mask;\n\n         if (stb__RefineBlock(block,&max16,&min16,mask)) {\n            if (max16 != min16) {\n               stb__EvalColors(color,max16,min16);\n               mask = stb__MatchColorsBlock(block,color);\n            } else {\n               mask = 0;\n               break;\n            }\n         }\n\n         if(mask == lastmask)\n            break;\n      }\n  }\n\n  // write the color block\n  if(max16 < min16)\n  {\n     unsigned short t = min16;\n     min16 = max16;\n     max16 = t;\n     mask ^= 0x55555555;\n  }\n\n  dest[0] = (unsigned char) (max16);\n  dest[1] = (unsigned char) (max16 >> 8);\n  dest[2] = (unsigned char) (min16);\n  dest[3] = (unsigned char) (min16 >> 8);\n  dest[4] = (unsigned char) (mask);\n  dest[5] = (unsigned char) (mask >> 8);\n  dest[6] = (unsigned char) (mask >> 16);\n  dest[7] = (unsigned char) (mask >> 24);\n}\n\n// Alpha block compression (this is easy for a change)\nstatic void stb__CompressAlphaBlock(unsigned char *dest,unsigned char *src, int stride)\n{\n   int i,dist,bias,dist4,dist2,bits,mask;\n\n   // find min/max color\n   int mn,mx;\n   mn = mx = src[0];\n\n   for (i=1;i<16;i++)\n   {\n      if (src[i*stride] < mn) mn = src[i*stride];\n      else if (src[i*stride] > mx) mx = src[i*stride];\n   }\n\n   // encode them\n   dest[0] = (unsigned char)mx;\n   dest[1] = (unsigned char)mn;\n   dest += 2;\n\n   // determine bias and emit color indices\n   // given the choice of mx/mn, these indices are optimal:\n   // http://fgiesen.wordpress.com/2009/12/15/dxt5-alpha-block-index-determination/\n   dist = mx-mn;\n   dist4 = dist*4;\n   dist2 = dist*2;\n   bias = (dist < 8) ? (dist - 1) : (dist/2 + 2);\n   bias -= mn * 7;\n   bits = 0,mask=0;\n\n   for (i=0;i<16;i++) {\n      int a = src[i*stride]*7 + bias;\n      int ind,t;\n\n      // select index. this is a \"linear scale\" lerp factor between 0 (val=min) and 7 (val=max).\n      t = (a >= dist4) ? -1 : 0; ind =  t & 4; a -= dist4 & t;\n      t = (a >= dist2) ? -1 : 0; ind += t & 2; a -= dist2 & t;\n      ind += (a >= dist);\n\n      // turn linear scale into DXT index (0/1 are extremal pts)\n      ind = -ind & 7;\n      ind ^= (2 > ind);\n\n      // write index\n      mask |= ind << bits;\n      if((bits += 3) >= 8) {\n         *dest++ = (unsigned char)mask;\n         mask >>= 8;\n         bits -= 8;\n      }\n   }\n}\n\nvoid stb_compress_dxt_block(unsigned char *dest, const unsigned char *src, int alpha, int mode)\n{\n   unsigned char data[16][4];\n   if (alpha) {\n      int i;\n      stb__CompressAlphaBlock(dest,(unsigned char*) src+3, 4);\n      dest += 8;\n      // make a new copy of the data in which alpha is opaque,\n      // because code uses a fast test for color constancy\n      memcpy(data, src, 4*16);\n      for (i=0; i < 16; ++i)\n         data[i][3] = 255;\n      src = &data[0][0];\n   }\n\n   stb__CompressColorBlock(dest,(unsigned char*) src,mode);\n}\n\nvoid stb_compress_bc4_block(unsigned char *dest, const unsigned char *src)\n{\n   stb__CompressAlphaBlock(dest,(unsigned char*) src, 1);\n}\n\nvoid stb_compress_bc5_block(unsigned char *dest, const unsigned char *src)\n{\n   stb__CompressAlphaBlock(dest,(unsigned char*) src,2);\n   stb__CompressAlphaBlock(dest + 8,(unsigned char*) src+1,2);\n}\n#endif // STB_DXT_IMPLEMENTATION\n\n// Compile with STB_DXT_IMPLEMENTATION and STB_DXT_GENERATE_TABLES\n// defined to generate the tables above.\n#ifdef STB_DXT_GENERATE_TABLES\n#include <stdio.h>\n\nint main()\n{\n   int i, j;\n   const char *omatch_names[] = { \"stb__OMatch5\", \"stb__OMatch6\" };\n   int dequant_mults[2] = { 33*4, 65 }; // .4 fixed-point dequant multipliers\n\n   // optimal endpoint tables\n   for (i = 0; i < 2; ++i) {\n      int dequant = dequant_mults[i];\n      int size = i ? 64 : 32;\n      printf(\"static const unsigned char %s[256][2] = {\\n\", omatch_names[i]);\n      for (int j = 0; j < 256; ++j) {\n         int mn, mx;\n         int best_mn = 0, best_mx = 0;\n         int best_err = 256 * 100;\n         for (mn=0;mn<size;mn++) {\n            for (mx=0;mx<size;mx++) {\n               int mine = (mn * dequant) >> 4;\n               int maxe = (mx * dequant) >> 4;\n               int err = abs(stb__Lerp13(maxe, mine) - j) * 100;\n\n               // DX10 spec says that interpolation must be within 3% of \"correct\" result,\n               // add this as error term. Normally we'd expect a random distribution of\n               // +-1.5% error, but nowhere in the spec does it say that the error has to be\n               // unbiased - better safe than sorry.\n               err += abs(maxe - mine) * 3;\n\n               if(err < best_err) {\n                  best_mn = mn;\n                  best_mx = mx;\n                  best_err = err;\n               }\n            }\n         }\n         if ((j % 8) == 0) printf(\"  \"); // 2 spaces, third is done below\n         printf(\" { %2d, %2d },\", best_mx, best_mn);\n         if ((j % 8) == 7) printf(\"\\n\");\n      }\n      printf(\"};\\n\");\n   }\n\n   return 0;\n}\n#endif\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_easy_font.h",
    "content": "// stb_easy_font.h - v1.1 - bitmap font for 3D rendering - public domain\n// Sean Barrett, Feb 2015\n//\n//    Easy-to-deploy,\n//    reasonably compact,\n//    extremely inefficient performance-wise,\n//    crappy-looking,\n//    ASCII-only,\n//    bitmap font for use in 3D APIs.\n//\n// Intended for when you just want to get some text displaying\n// in a 3D app as quickly as possible.\n//\n// Doesn't use any textures, instead builds characters out of quads.\n//\n// DOCUMENTATION:\n//\n//   int stb_easy_font_width(char *text)\n//   int stb_easy_font_height(char *text)\n//\n//      Takes a string and returns the horizontal size and the\n//      vertical size (which can vary if 'text' has newlines).\n//\n//   int stb_easy_font_print(float x, float y,\n//                           char *text, unsigned char color[4],\n//                           void *vertex_buffer, int vbuf_size)\n//\n//      Takes a string (which can contain '\\n') and fills out a\n//      vertex buffer with renderable data to draw the string.\n//      Output data assumes increasing x is rightwards, increasing y\n//      is downwards.\n//\n//      The vertex data is divided into quads, i.e. there are four\n//      vertices in the vertex buffer for each quad.\n//\n//      The vertices are stored in an interleaved format:\n//\n//         x:float\n//         y:float\n//         z:float\n//         color:uint8[4]\n//\n//      You can ignore z and color if you get them from elsewhere\n//      This format was chosen in the hopes it would make it\n//      easier for you to reuse existing vertex-buffer-drawing code.\n//\n//      If you pass in NULL for color, it becomes 255,255,255,255.\n//\n//      Returns the number of quads.\n//\n//      If the buffer isn't large enough, it will truncate.\n//      Expect it to use an average of ~270 bytes per character.\n//\n//      If your API doesn't draw quads, build a reusable index\n//      list that allows you to render quads as indexed triangles.\n//\n//   void stb_easy_font_spacing(float spacing)\n//\n//      Use positive values to expand the space between characters,\n//      and small negative values (no smaller than -1.5) to contract\n//      the space between characters.\n//\n//      E.g. spacing = 1 adds one \"pixel\" of spacing between the\n//      characters. spacing = -1 is reasonable but feels a bit too\n//      compact to me; -0.5 is a reasonable compromise as long as\n//      you're scaling the font up.\n//\n// LICENSE\n//\n//   See end of file for license information.\n//\n// VERSION HISTORY\n//\n//   (2020-02-02)  1.1   make everything static so can compile it in more than one src file\n//   (2017-01-15)  1.0   space character takes same space as numbers; fix bad spacing of 'f'\n//   (2016-01-22)  0.7   width() supports multiline text; add height()\n//   (2015-09-13)  0.6   #include <math.h>; updated license\n//   (2015-02-01)  0.5   First release\n//\n// CONTRIBUTORS\n//\n//   github:vassvik    --  bug report\n//   github:podsvirov  --  fix multiple definition errors\n\n#if 0\n// SAMPLE CODE:\n//\n//    Here's sample code for old OpenGL; it's a lot more complicated\n//    to make work on modern APIs, and that's your problem.\n//\nvoid print_string(float x, float y, char *text, float r, float g, float b)\n{\n  static char buffer[99999]; // ~500 chars\n  int num_quads;\n\n  num_quads = stb_easy_font_print(x, y, text, NULL, buffer, sizeof(buffer));\n\n  glColor3f(r,g,b);\n  glEnableClientState(GL_VERTEX_ARRAY);\n  glVertexPointer(2, GL_FLOAT, 16, buffer);\n  glDrawArrays(GL_QUADS, 0, num_quads*4);\n  glDisableClientState(GL_VERTEX_ARRAY);\n}\n#endif\n\n#ifndef INCLUDE_STB_EASY_FONT_H\n#define INCLUDE_STB_EASY_FONT_H\n\n#include <stdlib.h>\n#include <math.h>\n\nstatic struct stb_easy_font_info_struct {\n    unsigned char advance;\n    unsigned char h_seg;\n    unsigned char v_seg;\n} stb_easy_font_charinfo[96] = {\n    {  6,  0,  0 },  {  3,  0,  0 },  {  5,  1,  1 },  {  7,  1,  4 },\n    {  7,  3,  7 },  {  7,  6, 12 },  {  7,  8, 19 },  {  4, 16, 21 },\n    {  4, 17, 22 },  {  4, 19, 23 },  { 23, 21, 24 },  { 23, 22, 31 },\n    { 20, 23, 34 },  { 22, 23, 36 },  { 19, 24, 36 },  { 21, 25, 36 },\n    {  6, 25, 39 },  {  6, 27, 43 },  {  6, 28, 45 },  {  6, 30, 49 },\n    {  6, 33, 53 },  {  6, 34, 57 },  {  6, 40, 58 },  {  6, 46, 59 },\n    {  6, 47, 62 },  {  6, 55, 64 },  { 19, 57, 68 },  { 20, 59, 68 },\n    { 21, 61, 69 },  { 22, 66, 69 },  { 21, 68, 69 },  {  7, 73, 69 },\n    {  9, 75, 74 },  {  6, 78, 81 },  {  6, 80, 85 },  {  6, 83, 90 },\n    {  6, 85, 91 },  {  6, 87, 95 },  {  6, 90, 96 },  {  7, 92, 97 },\n    {  6, 96,102 },  {  5, 97,106 },  {  6, 99,107 },  {  6,100,110 },\n    {  6,100,115 },  {  7,101,116 },  {  6,101,121 },  {  6,101,125 },\n    {  6,102,129 },  {  7,103,133 },  {  6,104,140 },  {  6,105,145 },\n    {  7,107,149 },  {  6,108,151 },  {  7,109,155 },  {  7,109,160 },\n    {  7,109,165 },  {  7,118,167 },  {  6,118,172 },  {  4,120,176 },\n    {  6,122,177 },  {  4,122,181 },  { 23,124,182 },  { 22,129,182 },\n    {  4,130,182 },  { 22,131,183 },  {  6,133,187 },  { 22,135,191 },\n    {  6,137,192 },  { 22,139,196 },  {  6,144,197 },  { 22,147,198 },\n    {  6,150,202 },  { 19,151,206 },  { 21,152,207 },  {  6,155,209 },\n    {  3,160,210 },  { 23,160,211 },  { 22,164,216 },  { 22,165,220 },\n    { 22,167,224 },  { 22,169,228 },  { 21,171,232 },  { 21,173,233 },\n    {  5,178,233 },  { 22,179,234 },  { 23,180,238 },  { 23,180,243 },\n    { 23,180,248 },  { 22,189,248 },  { 22,191,252 },  {  5,196,252 },\n    {  3,203,252 },  {  5,203,253 },  { 22,210,253 },  {  0,214,253 },\n};\n\nstatic unsigned char stb_easy_font_hseg[214] = {\n   97,37,69,84,28,51,2,18,10,49,98,41,65,25,81,105,33,9,97,1,97,37,37,36,\n    81,10,98,107,3,100,3,99,58,51,4,99,58,8,73,81,10,50,98,8,73,81,4,10,50,\n    98,8,25,33,65,81,10,50,17,65,97,25,33,25,49,9,65,20,68,1,65,25,49,41,\n    11,105,13,101,76,10,50,10,50,98,11,99,10,98,11,50,99,11,50,11,99,8,57,\n    58,3,99,99,107,10,10,11,10,99,11,5,100,41,65,57,41,65,9,17,81,97,3,107,\n    9,97,1,97,33,25,9,25,41,100,41,26,82,42,98,27,83,42,98,26,51,82,8,41,\n    35,8,10,26,82,114,42,1,114,8,9,73,57,81,41,97,18,8,8,25,26,26,82,26,82,\n    26,82,41,25,33,82,26,49,73,35,90,17,81,41,65,57,41,65,25,81,90,114,20,\n    84,73,57,41,49,25,33,65,81,9,97,1,97,25,33,65,81,57,33,25,41,25,\n};\n\nstatic unsigned char stb_easy_font_vseg[253] = {\n   4,2,8,10,15,8,15,33,8,15,8,73,82,73,57,41,82,10,82,18,66,10,21,29,1,65,\n    27,8,27,9,65,8,10,50,97,74,66,42,10,21,57,41,29,25,14,81,73,57,26,8,8,\n    26,66,3,8,8,15,19,21,90,58,26,18,66,18,105,89,28,74,17,8,73,57,26,21,\n    8,42,41,42,8,28,22,8,8,30,7,8,8,26,66,21,7,8,8,29,7,7,21,8,8,8,59,7,8,\n    8,15,29,8,8,14,7,57,43,10,82,7,7,25,42,25,15,7,25,41,15,21,105,105,29,\n    7,57,57,26,21,105,73,97,89,28,97,7,57,58,26,82,18,57,57,74,8,30,6,8,8,\n    14,3,58,90,58,11,7,74,43,74,15,2,82,2,42,75,42,10,67,57,41,10,7,2,42,\n    74,106,15,2,35,8,8,29,7,8,8,59,35,51,8,8,15,35,30,35,8,8,30,7,8,8,60,\n    36,8,45,7,7,36,8,43,8,44,21,8,8,44,35,8,8,43,23,8,8,43,35,8,8,31,21,15,\n    20,8,8,28,18,58,89,58,26,21,89,73,89,29,20,8,8,30,7,\n};\n\ntypedef struct\n{\n   unsigned char c[4];\n} stb_easy_font_color;\n\nstatic int stb_easy_font_draw_segs(float x, float y, unsigned char *segs, int num_segs, int vertical, stb_easy_font_color c, char *vbuf, int vbuf_size, int offset)\n{\n    int i,j;\n    for (i=0; i < num_segs; ++i) {\n        int len = segs[i] & 7;\n        x += (float) ((segs[i] >> 3) & 1);\n        if (len && offset+64 <= vbuf_size) {\n            float y0 = y + (float) (segs[i]>>4);\n            for (j=0; j < 4; ++j) {\n                * (float *) (vbuf+offset+0) = x  + (j==1 || j==2 ? (vertical ? 1 : len) : 0);\n                * (float *) (vbuf+offset+4) = y0 + (    j >= 2   ? (vertical ? len : 1) : 0);\n                * (float *) (vbuf+offset+8) = 0.f;\n                * (stb_easy_font_color *) (vbuf+offset+12) = c;\n                offset += 16;\n            }\n        }\n    }\n    return offset;\n}\n\nstatic float stb_easy_font_spacing_val = 0;\nstatic void stb_easy_font_spacing(float spacing)\n{\n   stb_easy_font_spacing_val = spacing;\n}\n\nstatic int stb_easy_font_print(float x, float y, char *text, unsigned char color[4], void *vertex_buffer, int vbuf_size)\n{\n    char *vbuf = (char *) vertex_buffer;\n    float start_x = x;\n    int offset = 0;\n\n    stb_easy_font_color c = { 255,255,255,255 }; // use structure copying to avoid needing depending on memcpy()\n    if (color) { c.c[0] = color[0]; c.c[1] = color[1]; c.c[2] = color[2]; c.c[3] = color[3]; }\n\n    while (*text && offset < vbuf_size) {\n        if (*text == '\\n') {\n            y += 12;\n            x = start_x;\n        } else {\n            unsigned char advance = stb_easy_font_charinfo[*text-32].advance;\n            float y_ch = advance & 16 ? y+1 : y;\n            int h_seg, v_seg, num_h, num_v;\n            h_seg = stb_easy_font_charinfo[*text-32  ].h_seg;\n            v_seg = stb_easy_font_charinfo[*text-32  ].v_seg;\n            num_h = stb_easy_font_charinfo[*text-32+1].h_seg - h_seg;\n            num_v = stb_easy_font_charinfo[*text-32+1].v_seg - v_seg;\n            offset = stb_easy_font_draw_segs(x, y_ch, &stb_easy_font_hseg[h_seg], num_h, 0, c, vbuf, vbuf_size, offset);\n            offset = stb_easy_font_draw_segs(x, y_ch, &stb_easy_font_vseg[v_seg], num_v, 1, c, vbuf, vbuf_size, offset);\n            x += advance & 15;\n            x += stb_easy_font_spacing_val;\n        }\n        ++text;\n    }\n    return (unsigned) offset/64;\n}\n\nstatic int stb_easy_font_width(char *text)\n{\n    float len = 0;\n    float max_len = 0;\n    while (*text) {\n        if (*text == '\\n') {\n            if (len > max_len) max_len = len;\n            len = 0;\n        } else {\n            len += stb_easy_font_charinfo[*text-32].advance & 15;\n            len += stb_easy_font_spacing_val;\n        }\n        ++text;\n    }\n    if (len > max_len) max_len = len;\n    return (int) ceil(max_len);\n}\n\nstatic int stb_easy_font_height(char *text)\n{\n    float y = 0;\n    int nonempty_line=0;\n    while (*text) {\n        if (*text == '\\n') {\n            y += 12;\n            nonempty_line = 0;\n        } else {\n            nonempty_line = 1;\n        }\n        ++text;\n    }\n    return (int) ceil(y + (nonempty_line ? 12 : 0));\n}\n#endif\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_herringbone_wang_tile.h",
    "content": "/* stbhw - v0.7 -  http://nothings.org/gamedev/herringbone\n   Herringbone Wang Tile Generator - Sean Barrett 2014 - public domain\n\n== LICENSE ==============================\n\nThis software is dual-licensed to the public domain and under the following\nlicense: you are granted a perpetual, irrevocable license to copy, modify,\npublish, and distribute this file as you see fit.\n\n== WHAT IT IS ===========================\n\n This library is an SDK for Herringbone Wang Tile generation:\n\n      http://nothings.org/gamedev/herringbone\n\n The core design is that you use this library offline to generate a\n \"template\" of the tiles you'll create. You then edit those tiles, then\n load the created tile image file back into this library and use it at\n runtime to generate \"maps\".\n\n You cannot load arbitrary tile image files with this library; it is\n only designed to load image files made from the template it created.\n It stores a binary description of the tile sizes & constraints in a\n few pixels, and uses those to recover the rules, rather than trying\n to parse the tiles themselves.\n\n You *can* use this library to generate from arbitrary tile sets, but\n only by loading the tile set and specifying the constraints explicitly\n yourself.\n\n== COMPILING ============================\n\n 1. #define STB_HERRINGBONE_WANG_TILE_IMPLEMENTATION before including this\n    header file in *one* source file to create the implementation\n    in that source file.\n\n 2. optionally #define STB_HBWANG_RAND() to be a random number\n    generator. if you don't define it, it will use rand(),\n    and you need to seed srand() yourself.\n\n 3. optionally #define STB_HBWANG_ASSERT(x), otherwise\n    it will use assert()\n\n 4. optionally #define STB_HBWANG_STATIC to force all symbols to be\n    static instead of public, so they are only accesible\n    in the source file that creates the implementation\n\n 5. optionally #define STB_HBWANG_NO_REPITITION_REDUCTION to disable\n    the code that tries to reduce having the same tile appear\n    adjacent to itself in wang-corner-tile mode (e.g. imagine\n    if you were doing something where 90% of things should be\n    the same grass tile, you need to disable this system)\n\n 6. optionally define STB_HBWANG_MAX_X and STB_HBWANG_MAX_Y\n    to be the max dimensions of the generated map in multiples\n    of the wang tile's short side's length (e.g. if you\n    have 20x10 wang tiles, so short_side_len=10, and you\n    have MAX_X is 17, then the largest map you can generate\n    is 170 pixels wide). The defaults are 100x100. This\n    is used to define static arrays which affect memory\n    usage.\n\n== USING ================================\n\n  To use the map generator, you need a tileset. You can download\n  some sample tilesets from http://nothings.org/gamedev/herringbone\n\n  Then see the \"sample application\" below.\n\n  You can also use this file to generate templates for\n  tilesets which you then hand-edit to create the data.\n\n\n== MEMORY MANAGEMENT ====================\n\n  The tileset loader allocates memory with malloc(). The map\n  generator does no memory allocation, so e.g. you can load\n  tilesets at startup and never free them and never do any\n  further allocation.\n\n\n== SAMPLE APPLICATION ===================\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"        // http://nothings.org/stb_image.c\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"  // http://nothings.org/stb/stb_image_write.h\n\n#define STB_HBWANG_IMPLEMENTATION\n#include \"stb_hbwang.h\"\n\nint main(int argc, char **argv)\n{\n   unsigned char *data;\n   int xs,ys, w,h;\n   stbhw_tileset ts;\n\n   if (argc != 4) {\n      fprintf(stderr, \"Usage: mapgen {tile-file} {xsize} {ysize}\\n\"\n                      \"generates file named 'test_map.png'\\n\");\n      exit(1);\n   }\n   data = stbi_load(argv[1], &w, &h, NULL, 3);\n   xs = atoi(argv[2]);\n   ys = atoi(argv[3]);\n   if (data == NULL) {\n      fprintf(stderr, \"Error opening or parsing '%s' as an image file\\n\", argv[1]);\n      exit(1);\n   }\n   if (xs < 1 || xs > 1000) {\n      fprintf(stderr, \"xsize invalid or out of range\\n\");\n      exit(1);\n   }\n   if (ys < 1 || ys > 1000) {\n      fprintf(stderr, \"ysize invalid or out of range\\n\");\n      exit(1);\n   }\n\n   stbhw_build_tileset_from_image(&ts, data, w*3, w, h);\n   free(data);\n\n   // allocate a buffer to create the final image to\n   data = malloc(3 * xs * ys);\n\n   srand(time(NULL));\n   stbhw_generate_image(&ts, NULL, data, xs*3, xs, ys);\n\n   stbi_write_png(\"test_map.png\", xs, ys, 3, data, xs*3);\n\n   stbhw_free_tileset(&ts);\n   free(data);\n\n   return 0;\n}\n\n== VERSION HISTORY ===================\n\n   0.7   2019-03-04   - fix warnings\n\t0.6   2014-08-17   - fix broken map-maker\n\t0.5   2014-07-07   - initial release\n\n*/\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                         HEADER FILE SECTION                              //\n//                                                                          //\n\n#ifndef INCLUDE_STB_HWANG_H\n#define INCLUDE_STB_HWANG_H\n\n#ifdef STB_HBWANG_STATIC\n#define STBHW_EXTERN static\n#else\n#ifdef __cplusplus\n#define STBHW_EXTERN extern \"C\"\n#else\n#define STBHW_EXTERN extern\n#endif\n#endif\n\ntypedef struct stbhw_tileset stbhw_tileset;\n\n// returns description of last error produced by any function (not thread-safe)\nSTBHW_EXTERN const char *stbhw_get_last_error(void);\n\n// build a tileset from an image that conforms to a template created by this\n// library. (you allocate storage for stbhw_tileset and function fills it out;\n// memory for individual tiles are malloc()ed).\n// returns non-zero on success, 0 on error\nSTBHW_EXTERN int stbhw_build_tileset_from_image(stbhw_tileset *ts,\n                     unsigned char *pixels, int stride_in_bytes, int w, int h);\n\n// free a tileset built by stbhw_build_tileset_from_image\nSTBHW_EXTERN void stbhw_free_tileset(stbhw_tileset *ts);\n\n// generate a map that is w * h pixels (3-bytes each)\n// returns non-zero on success, 0 on error\n// not thread-safe (uses a global data structure to avoid memory management)\n// weighting should be NULL, as non-NULL weighting is currently untested\nSTBHW_EXTERN int stbhw_generate_image(stbhw_tileset *ts, int **weighting,\n                     unsigned char *pixels, int stride_in_bytes, int w, int h);\n\n//////////////////////////////////////\n//\n// TILESET DATA STRUCTURE\n//\n// if you use the image-to-tileset system from this file, you\n// don't need to worry about these data structures. but if you\n// want to build/load a tileset yourself, you'll need to fill\n// these out.\n\ntypedef struct\n{\n   // the edge or vertex constraints, according to diagram below\n   signed char a,b,c,d,e,f;\n\n   // The herringbone wang tile data; it is a bitmap which is either\n   // w=2*short_sidelen,h=short_sidelen, or w=short_sidelen,h=2*short_sidelen.\n   // it is always RGB, stored row-major, with no padding between rows.\n   // (allocate stbhw_tile structure to be large enough for the pixel data)\n   unsigned char pixels[1];\n} stbhw_tile;\n\nstruct stbhw_tileset\n{\n   int is_corner;\n   int num_color[6];  // number of colors for each of 6 edge types or 4 corner types\n   int short_side_len;\n   stbhw_tile **h_tiles;\n   stbhw_tile **v_tiles;\n   int num_h_tiles, max_h_tiles;\n   int num_v_tiles, max_v_tiles;\n};\n\n///////////////  TEMPLATE GENERATOR  //////////////////////////\n\n// when requesting a template, you fill out this data\ntypedef struct\n{\n   int is_corner;      // using corner colors or edge colors?\n   int short_side_len; // rectangles is 2n x n, n = short_side_len\n   int num_color[6];   // see below diagram for meaning of the index to this;\n                       // 6 values if edge (!is_corner), 4 values if is_corner\n                       // legal numbers: 1..8 if edge, 1..4 if is_corner\n   int num_vary_x;     // additional number of variations along x axis in the template\n   int num_vary_y;     // additional number of variations along y axis in the template\n   int corner_type_color_template[4][4];\n      // if corner_type_color_template[s][t] is non-zero, then any\n      // corner of type s generated as color t will get a little\n      // corner sample markup in the template image data\n\n} stbhw_config;\n\n// computes the size needed for the template image\nSTBHW_EXTERN void stbhw_get_template_size(stbhw_config *c, int *w, int *h);\n\n// generates a template image, assuming data is 3*w*h bytes long, RGB format\nSTBHW_EXTERN int stbhw_make_template(stbhw_config *c, unsigned char *data, int w, int h, int stride_in_bytes);\n\n#endif//INCLUDE_STB_HWANG_H\n\n\n// TILE CONSTRAINT TYPES\n//\n// there are 4 \"types\" of corners and 6 types of edges.\n// you can configure the tileset to have different numbers\n// of colors for each type of color or edge.\n//\n// corner types:\n//\n//                     0---*---1---*---2---*---3\n//                     |       |               |\n//                     *       *               *\n//                     |       |               |\n//     1---*---2---*---3       0---*---1---*---2\n//     |               |       |\n//     *               *       *\n//     |               |       |\n//     0---*---1---*---2---*---3\n//\n//\n//  edge types:\n//\n//     *---2---*---3---*      *---0---*\n//     |               |      |       |\n//     1               4      5       1\n//     |               |      |       |\n//     *---0---*---2---*      *       *\n//                            |       |\n//                            4       5\n//                            |       |\n//                            *---3---*\n//\n// TILE CONSTRAINTS\n//\n// each corner/edge has a color; this shows the name\n// of the variable containing the color\n//\n// corner constraints:\n//\n//                        a---*---d\n//                        |       |\n//                        *       *\n//                        |       |\n//     a---*---b---*---c  b       e\n//     |               |  |       |\n//     *               *  *       *\n//     |               |  |       |\n//     d---*---e---*---f  c---*---f\n//\n//\n//  edge constraints:\n//\n//     *---a---*---b---*      *---a---*\n//     |               |      |       |\n//     c               d      b       c\n//     |               |      |       |\n//     *---e---*---f---*      *       *\n//                            |       |\n//                            d       e\n//                            |       |\n//                            *---f---*\n//\n\n\n//////////////////////////////////////////////////////////////////////////////\n//                                                                          //\n//                       IMPLEMENTATION SECTION                             //\n//                                                                          //\n\n#ifdef STB_HERRINGBONE_WANG_TILE_IMPLEMENTATION\n\n\n#include <string.h> // memcpy\n#include <stdlib.h> // malloc\n\n#ifndef STB_HBWANG_RAND\n#include <stdlib.h>\n#define STB_HBWANG_RAND()  (rand() >> 4)\n#endif\n\n#ifndef STB_HBWANG_ASSERT\n#include <assert.h>\n#define STB_HBWANG_ASSERT(x)  assert(x)\n#endif\n\n// map size\n#ifndef STB_HBWANG_MAX_X\n#define STB_HBWANG_MAX_X  100\n#endif\n\n#ifndef STB_HBWANG_MAX_Y\n#define STB_HBWANG_MAX_Y  100\n#endif\n\n// global variables for color assignments\n// @MEMORY change these to just store last two/three rows\n//         and keep them on the stack\nstatic signed char c_color[STB_HBWANG_MAX_Y+6][STB_HBWANG_MAX_X+6];\nstatic signed char v_color[STB_HBWANG_MAX_Y+6][STB_HBWANG_MAX_X+5];\nstatic signed char h_color[STB_HBWANG_MAX_Y+5][STB_HBWANG_MAX_X+6];\n\nstatic const char *stbhw_error;\nSTBHW_EXTERN const char *stbhw_get_last_error(void)\n{\n   const char *temp = stbhw_error;\n   stbhw_error = 0;\n   return temp;\n}\n\n\n\n\n/////////////////////////////////////////////////////////////\n//\n//  SHARED TEMPLATE-DESCRIPTION CODE\n//\n//  Used by both template generator and tileset parser; by\n//  using the same code, they are locked in sync and we don't\n//  need to try to do more sophisticated parsing of edge color\n//  markup or something.\n\ntypedef void stbhw__process_rect(struct stbhw__process *p, int xpos, int ypos,\n                                 int a, int b, int c, int d, int e, int f);\n\ntypedef struct stbhw__process\n{\n   stbhw_tileset *ts;\n   stbhw_config *c;\n   stbhw__process_rect *process_h_rect;\n   stbhw__process_rect *process_v_rect;\n   unsigned char *data;\n   int stride,w,h;\n} stbhw__process;\n\nstatic void stbhw__process_h_row(stbhw__process *p,\n                           int xpos, int ypos,\n                           int a0, int a1,\n                           int b0, int b1,\n                           int c0, int c1,\n                           int d0, int d1,\n                           int e0, int e1,\n                           int f0, int f1,\n                           int variants)\n{\n   int a,b,c,d,e,f,v;\n\n   for (v=0; v < variants; ++v)\n      for (f=f0; f <= f1; ++f)\n         for (e=e0; e <= e1; ++e)\n            for (d=d0; d <= d1; ++d)\n               for (c=c0; c <= c1; ++c)\n                  for (b=b0; b <= b1; ++b)\n                     for (a=a0; a <= a1; ++a) {\n                        p->process_h_rect(p, xpos, ypos, a,b,c,d,e,f);\n                        xpos += 2*p->c->short_side_len + 3;\n                     }\n}\n\nstatic void stbhw__process_v_row(stbhw__process *p,\n                           int xpos, int ypos,\n                           int a0, int a1,\n                           int b0, int b1,\n                           int c0, int c1,\n                           int d0, int d1,\n                           int e0, int e1,\n                           int f0, int f1,\n                           int variants)\n{\n   int a,b,c,d,e,f,v;\n\n   for (v=0; v < variants; ++v)\n      for (f=f0; f <= f1; ++f)\n         for (e=e0; e <= e1; ++e)\n            for (d=d0; d <= d1; ++d)\n               for (c=c0; c <= c1; ++c)\n                  for (b=b0; b <= b1; ++b)\n                     for (a=a0; a <= a1; ++a) {\n                        p->process_v_rect(p, xpos, ypos, a,b,c,d,e,f);\n                        xpos += p->c->short_side_len+3;\n                     }\n}\n\nstatic void stbhw__get_template_info(stbhw_config *c, int *w, int *h, int *h_count, int *v_count)\n{\n   int size_x,size_y;\n   int horz_count,vert_count;\n\n   if (c->is_corner) {\n      int horz_w = c->num_color[1] * c->num_color[2] * c->num_color[3] * c->num_vary_x;\n      int horz_h = c->num_color[0] * c->num_color[1] * c->num_color[2] * c->num_vary_y;\n\n      int vert_w = c->num_color[0] * c->num_color[3] * c->num_color[2] * c->num_vary_y;\n      int vert_h = c->num_color[1] * c->num_color[0] * c->num_color[3] * c->num_vary_x;\n\n      int horz_x = horz_w * (2*c->short_side_len + 3);\n      int horz_y = horz_h * (  c->short_side_len + 3);\n\n      int vert_x = vert_w * (  c->short_side_len + 3);\n      int vert_y = vert_h * (2*c->short_side_len + 3);\n\n      horz_count = horz_w * horz_h;\n      vert_count = vert_w * vert_h;\n\n      size_x = horz_x > vert_x ? horz_x : vert_x;\n      size_y = 2 + horz_y + 2 + vert_y;\n   } else {\n      int horz_w = c->num_color[0] * c->num_color[1] * c->num_color[2] * c->num_vary_x;\n      int horz_h = c->num_color[3] * c->num_color[4] * c->num_color[2] * c->num_vary_y;\n\n      int vert_w = c->num_color[0] * c->num_color[5] * c->num_color[1] * c->num_vary_y;\n      int vert_h = c->num_color[3] * c->num_color[4] * c->num_color[5] * c->num_vary_x;\n\n      int horz_x = horz_w * (2*c->short_side_len + 3);\n      int horz_y = horz_h * (  c->short_side_len + 3);\n\n      int vert_x = vert_w * (  c->short_side_len + 3);\n      int vert_y = vert_h * (2*c->short_side_len + 3);\n\n      horz_count = horz_w * horz_h;\n      vert_count = vert_w * vert_h;\n\n      size_x = horz_x > vert_x ? horz_x : vert_x;\n      size_y = 2 + horz_y + 2 + vert_y;\n   }\n   if (w) *w = size_x;\n   if (h) *h = size_y;\n   if (h_count) *h_count = horz_count;\n   if (v_count) *v_count = vert_count;\n}\n\nSTBHW_EXTERN void stbhw_get_template_size(stbhw_config *c, int *w, int *h)\n{\n   stbhw__get_template_info(c, w, h, NULL, NULL);\n}\n\nstatic int stbhw__process_template(stbhw__process *p)\n{\n   int i,j,k,q, ypos;\n   int size_x, size_y;\n   stbhw_config *c = p->c;\n\n   stbhw__get_template_info(c, &size_x, &size_y, NULL, NULL);\n\n   if (p->w < size_x || p->h < size_y) {\n      stbhw_error = \"image too small for configuration\";\n      return 0;\n   }\n\n   if (c->is_corner) {\n      ypos = 2;\n      for (k=0; k < c->num_color[2]; ++k) {\n         for (j=0; j < c->num_color[1]; ++j) {\n            for (i=0; i < c->num_color[0]; ++i) {\n               for (q=0; q < c->num_vary_y; ++q) {\n                  stbhw__process_h_row(p, 0,ypos,\n                     0,c->num_color[1]-1, 0,c->num_color[2]-1, 0,c->num_color[3]-1,\n                     i,i, j,j, k,k,\n                     c->num_vary_x);\n                  ypos += c->short_side_len + 3;\n               }\n            }\n         }\n      }\n      ypos += 2;\n      for (k=0; k < c->num_color[3]; ++k) {\n         for (j=0; j < c->num_color[0]; ++j) {\n            for (i=0; i < c->num_color[1]; ++i) {\n               for (q=0; q < c->num_vary_x; ++q) {\n                  stbhw__process_v_row(p, 0,ypos,\n                     0,c->num_color[0]-1, 0,c->num_color[3]-1, 0,c->num_color[2]-1,\n                     i,i, j,j, k,k,\n                     c->num_vary_y);\n                  ypos += (c->short_side_len*2) + 3;\n               }\n            }\n         }\n      }\n      assert(ypos == size_y);\n   } else {\n      ypos = 2;\n      for (k=0; k < c->num_color[3]; ++k) {\n         for (j=0; j < c->num_color[4]; ++j) {\n            for (i=0; i < c->num_color[2]; ++i) {\n               for (q=0; q < c->num_vary_y; ++q) {\n                  stbhw__process_h_row(p, 0,ypos,\n                     0,c->num_color[2]-1, k,k,\n                     0,c->num_color[1]-1, j,j,\n                     0,c->num_color[0]-1, i,i,\n                     c->num_vary_x);\n                  ypos += c->short_side_len + 3;\n               }\n            }\n         }\n      }\n      ypos += 2;\n      for (k=0; k < c->num_color[3]; ++k) {\n         for (j=0; j < c->num_color[4]; ++j) {\n            for (i=0; i < c->num_color[5]; ++i) {\n               for (q=0; q < c->num_vary_x; ++q) {\n                  stbhw__process_v_row(p, 0,ypos,\n                     0,c->num_color[0]-1, i,i,\n                     0,c->num_color[1]-1, j,j,\n                     0,c->num_color[5]-1, k,k,\n                     c->num_vary_y);\n                  ypos += (c->short_side_len*2) + 3;\n               }\n            }\n         }\n      }\n      assert(ypos == size_y);\n   }\n   return 1;\n}\n\n\n/////////////////////////////////////////////////////////////\n//\n//  MAP GENERATOR\n//\n\nstatic void stbhw__draw_pixel(unsigned char *output, int stride, int x, int y, unsigned char c[3])\n{\n   memcpy(output + y*stride + x*3, c, 3);\n}\n\nstatic void stbhw__draw_h_tile(unsigned char *output, int stride, int xmax, int ymax, int x, int y, stbhw_tile *h, int sz)\n{\n   int i,j;\n   for (j=0; j < sz; ++j)\n      if (y+j >= 0 && y+j < ymax)\n         for (i=0; i < sz*2; ++i)\n            if (x+i >= 0 && x+i < xmax)\n               stbhw__draw_pixel(output,stride, x+i,y+j, &h->pixels[(j*sz*2 + i)*3]);\n}\n\nstatic void stbhw__draw_v_tile(unsigned char *output, int stride, int xmax, int ymax, int x, int y, stbhw_tile *h, int sz)\n{\n   int i,j;\n   for (j=0; j < sz*2; ++j)\n      if (y+j >= 0 && y+j < ymax)\n         for (i=0; i < sz; ++i)\n            if (x+i >= 0 && x+i < xmax)\n               stbhw__draw_pixel(output,stride, x+i,y+j, &h->pixels[(j*sz + i)*3]);\n}\n\n\n// randomly choose a tile that fits constraints for a given spot, and update the constraints\nstatic stbhw_tile * stbhw__choose_tile(stbhw_tile **list, int numlist,\n                                      signed char *a, signed char *b, signed char *c,\n                                      signed char *d, signed char *e, signed char *f,\n                                      int **weighting)\n{\n   int i,n,m = 1<<30,pass;\n   for (pass=0; pass < 2; ++pass) {\n      n=0;\n      // pass #1:\n      //   count number of variants that match this partial set of constraints\n      // pass #2:\n      //   stop on randomly selected match\n      for (i=0; i < numlist; ++i) {\n         stbhw_tile *h = list[i];\n         if ((*a < 0 || *a == h->a) &&\n             (*b < 0 || *b == h->b) &&\n             (*c < 0 || *c == h->c) &&\n             (*d < 0 || *d == h->d) &&\n             (*e < 0 || *e == h->e) &&\n             (*f < 0 || *f == h->f)) {\n            if (weighting)\n               n += weighting[0][i];\n            else\n               n += 1;\n            if (n > m) {\n               // use list[i]\n               // update constraints to reflect what we placed\n               *a = h->a;\n               *b = h->b;\n               *c = h->c;\n               *d = h->d;\n               *e = h->e;\n               *f = h->f;\n               return h;\n            }\n         }\n      }\n      if (n == 0) {\n         stbhw_error = \"couldn't find tile matching constraints\";\n         return NULL;\n      }\n      m = STB_HBWANG_RAND() % n;\n   }\n   STB_HBWANG_ASSERT(0);\n   return NULL;\n}\n\nstatic int stbhw__match(int x, int y)\n{\n   return c_color[y][x] == c_color[y+1][x+1];\n}\n\nstatic int stbhw__weighted(int num_options, int *weights)\n{\n   int k, total, choice;\n   total = 0;\n   for (k=0; k < num_options; ++k)\n      total += weights[k];\n   choice = STB_HBWANG_RAND() % total;\n   total = 0;\n   for (k=0; k < num_options; ++k) {\n      total += weights[k];\n      if (choice < total)\n         break;\n   }\n   STB_HBWANG_ASSERT(k < num_options);\n   return k;\n}\n\nstatic int stbhw__change_color(int old_color, int num_options, int *weights)\n{\n   if (weights) {\n      int k, total, choice;\n      total = 0;\n      for (k=0; k < num_options; ++k)\n         if (k != old_color)\n            total += weights[k];\n      choice = STB_HBWANG_RAND() % total;\n      total = 0;\n      for (k=0; k < num_options; ++k) {\n         if (k != old_color) {\n            total += weights[k];\n            if (choice < total)\n               break;\n         }\n      }\n      STB_HBWANG_ASSERT(k < num_options);\n      return k;\n   } else {\n      int offset = 1+STB_HBWANG_RAND() % (num_options-1);\n      return (old_color+offset) % num_options;\n   }\n}\n\n\n\n// generate a map that is w * h pixels (3-bytes each)\n// returns 1 on success, 0 on error\nSTBHW_EXTERN int stbhw_generate_image(stbhw_tileset *ts, int **weighting, unsigned char *output, int stride, int w, int h)\n{\n   int sidelen = ts->short_side_len;\n   int xmax = (w / sidelen) + 6;\n   int ymax = (h / sidelen) + 6;\n   if (xmax > STB_HBWANG_MAX_X+6 || ymax > STB_HBWANG_MAX_Y+6) {\n      stbhw_error = \"increase STB_HBWANG_MAX_X/Y\";\n      return 0;\n   }\n\n   if (ts->is_corner) {\n      int i,j, ypos;\n      int *cc = ts->num_color;\n\n      for (j=0; j < ymax; ++j) {\n         for (i=0; i < xmax; ++i) {\n            int p = (i-j+1)&3; // corner type\n            if (weighting==NULL || weighting[p]==0 || cc[p] == 1)\n               c_color[j][i] = STB_HBWANG_RAND() % cc[p];\n            else\n               c_color[j][i] = stbhw__weighted(cc[p], weighting[p]);\n         }\n      }\n      #ifndef STB_HBWANG_NO_REPITITION_REDUCTION\n      // now go back through and make sure we don't have adjancent 3x2 vertices that are identical,\n      // to avoid really obvious repetition (which happens easily with extreme weights)\n      for (j=0; j < ymax-3; ++j) {\n         for (i=0; i < xmax-3; ++i) {\n            //int p = (i-j+1) & 3; // corner type   // unused, not sure what the intent was so commenting it out\n            STB_HBWANG_ASSERT(i+3 < STB_HBWANG_MAX_X+6);\n            STB_HBWANG_ASSERT(j+3 < STB_HBWANG_MAX_Y+6);\n            if (stbhw__match(i,j) && stbhw__match(i,j+1) && stbhw__match(i,j+2)\n                && stbhw__match(i+1,j) && stbhw__match(i+1,j+1) && stbhw__match(i+1,j+2)) {\n               int p = ((i+1)-(j+1)+1) & 3;\n               if (cc[p] > 1)\n                  c_color[j+1][i+1] = stbhw__change_color(c_color[j+1][i+1], cc[p], weighting ? weighting[p] : NULL);\n            }\n            if (stbhw__match(i,j) && stbhw__match(i+1,j) && stbhw__match(i+2,j)\n                && stbhw__match(i,j+1) && stbhw__match(i+1,j+1) && stbhw__match(i+2,j+1)) {\n               int p = ((i+2)-(j+1)+1) & 3;\n               if (cc[p] > 1)\n                  c_color[j+1][i+2] = stbhw__change_color(c_color[j+1][i+2], cc[p], weighting ? weighting[p] : NULL);\n            }\n         }\n      }\n      #endif\n\n      ypos = -1 * sidelen;\n      for (j = -1; ypos < h; ++j) {\n         // a general herringbone row consists of:\n         //    horizontal left block, the bottom of a previous vertical, the top of a new vertical\n         int phase = (j & 3);\n         // displace horizontally according to pattern\n         if (phase == 0) {\n            i = 0;\n         } else {\n            i = phase-4;\n         }\n         for (;; i += 4) {\n            int xpos = i * sidelen;\n            if (xpos >= w)\n               break;\n            // horizontal left-block\n            if (xpos + sidelen*2 >= 0 && ypos >= 0) {\n               stbhw_tile *t = stbhw__choose_tile(\n                  ts->h_tiles, ts->num_h_tiles,\n                  &c_color[j+2][i+2], &c_color[j+2][i+3], &c_color[j+2][i+4],\n                  &c_color[j+3][i+2], &c_color[j+3][i+3], &c_color[j+3][i+4],\n                  weighting\n               );\n               if (t == NULL)\n                  return 0;\n               stbhw__draw_h_tile(output,stride,w,h, xpos, ypos, t, sidelen);\n            }\n            xpos += sidelen * 2;\n            // now we're at the end of a previous vertical one\n            xpos += sidelen;\n            // now we're at the start of a new vertical one\n            if (xpos < w) {\n               stbhw_tile *t = stbhw__choose_tile(\n                  ts->v_tiles, ts->num_v_tiles,\n                  &c_color[j+2][i+5], &c_color[j+3][i+5], &c_color[j+4][i+5],\n                  &c_color[j+2][i+6], &c_color[j+3][i+6], &c_color[j+4][i+6],\n                  weighting\n               );\n               if (t == NULL)\n                  return 0;\n               stbhw__draw_v_tile(output,stride,w,h, xpos, ypos,  t, sidelen);\n            }\n         }\n         ypos += sidelen;\n      }\n   } else {\n      // @TODO edge-color repetition reduction\n      int i,j, ypos;\n      memset(v_color, -1, sizeof(v_color));\n      memset(h_color, -1, sizeof(h_color));\n\n      ypos = -1 * sidelen;\n      for (j = -1; ypos<h; ++j) {\n         // a general herringbone row consists of:\n         //    horizontal left block, the bottom of a previous vertical, the top of a new vertical\n         int phase = (j & 3);\n         // displace horizontally according to pattern\n         if (phase == 0) {\n            i = 0;\n         } else {\n            i = phase-4;\n         }\n         for (;; i += 4) {\n            int xpos = i * sidelen;\n            if (xpos >= w)\n               break;\n            // horizontal left-block\n            if (xpos + sidelen*2 >= 0 && ypos >= 0) {\n               stbhw_tile *t = stbhw__choose_tile(\n                  ts->h_tiles, ts->num_h_tiles,\n                  &h_color[j+2][i+2], &h_color[j+2][i+3],\n                  &v_color[j+2][i+2], &v_color[j+2][i+4],\n                  &h_color[j+3][i+2], &h_color[j+3][i+3],\n                  weighting\n               );\n               if (t == NULL) return 0;\n               stbhw__draw_h_tile(output,stride,w,h, xpos, ypos, t, sidelen);\n            }\n            xpos += sidelen * 2;\n            // now we're at the end of a previous vertical one\n            xpos += sidelen;\n            // now we're at the start of a new vertical one\n            if (xpos < w) {\n               stbhw_tile *t = stbhw__choose_tile(\n                  ts->v_tiles, ts->num_v_tiles,\n                  &h_color[j+2][i+5],\n                  &v_color[j+2][i+5], &v_color[j+2][i+6],\n                  &v_color[j+3][i+5], &v_color[j+3][i+6],\n                  &h_color[j+4][i+5],\n                  weighting\n               );\n               if (t == NULL) return 0;\n               stbhw__draw_v_tile(output,stride,w,h, xpos, ypos,  t, sidelen);\n            }\n         }\n         ypos += sidelen;\n      }\n   }\n   return 1;\n}\n\nstatic void stbhw__parse_h_rect(stbhw__process *p, int xpos, int ypos,\n                            int a, int b, int c, int d, int e, int f)\n{\n   int len = p->c->short_side_len;\n   stbhw_tile *h = (stbhw_tile *) malloc(sizeof(*h)-1 + 3 * (len*2) * len);\n   int i,j;\n   ++xpos;\n   ++ypos;\n   h->a = a, h->b = b, h->c = c, h->d = d, h->e = e, h->f = f;\n   for (j=0; j < len; ++j)\n      for (i=0; i < len*2; ++i)\n         memcpy(h->pixels + j*(3*len*2) + i*3, p->data+(ypos+j)*p->stride+(xpos+i)*3, 3);\n   STB_HBWANG_ASSERT(p->ts->num_h_tiles < p->ts->max_h_tiles);\n   p->ts->h_tiles[p->ts->num_h_tiles++] = h;\n}\n\nstatic void stbhw__parse_v_rect(stbhw__process *p, int xpos, int ypos,\n                            int a, int b, int c, int d, int e, int f)\n{\n   int len = p->c->short_side_len;\n   stbhw_tile *h = (stbhw_tile *) malloc(sizeof(*h)-1 + 3 * (len*2) * len);\n   int i,j;\n   ++xpos;\n   ++ypos;\n   h->a = a, h->b = b, h->c = c, h->d = d, h->e = e, h->f = f;\n   for (j=0; j < len*2; ++j)\n      for (i=0; i < len; ++i)\n         memcpy(h->pixels + j*(3*len) + i*3, p->data+(ypos+j)*p->stride+(xpos+i)*3, 3);\n   STB_HBWANG_ASSERT(p->ts->num_v_tiles < p->ts->max_v_tiles);\n   p->ts->v_tiles[p->ts->num_v_tiles++] = h;\n}\n\nSTBHW_EXTERN int stbhw_build_tileset_from_image(stbhw_tileset *ts, unsigned char *data, int stride, int w, int h)\n{\n   int i, h_count, v_count;\n   unsigned char header[9];\n   stbhw_config c = { 0 };\n   stbhw__process p = { 0 };\n\n   // extract binary header\n\n   // remove encoding that makes it more visually obvious it encodes actual data\n   for (i=0; i < 9; ++i)\n      header[i] = data[w*3 - 1 - i] ^ (i*55);\n\n   // extract header info\n   if (header[7] == 0xc0) {\n      // corner-type\n      c.is_corner = 1;\n      for (i=0; i < 4; ++i)\n         c.num_color[i] = header[i];\n      c.num_vary_x = header[4];\n      c.num_vary_y = header[5];\n      c.short_side_len = header[6];\n   } else {\n      c.is_corner = 0;\n      // edge-type\n      for (i=0; i < 6; ++i)\n         c.num_color[i] = header[i];\n      c.num_vary_x = header[6];\n      c.num_vary_y = header[7];\n      c.short_side_len = header[8];\n   }\n\n   if (c.num_vary_x < 0 || c.num_vary_x > 64 || c.num_vary_y < 0 || c.num_vary_y > 64)\n      return 0;\n   if (c.short_side_len == 0)\n      return 0;\n   if (c.num_color[0] > 32 || c.num_color[1] > 32 || c.num_color[2] > 32 || c.num_color[3] > 32)\n      return 0;\n\n   stbhw__get_template_info(&c, NULL, NULL, &h_count, &v_count);\n\n   ts->is_corner = c.is_corner;\n   ts->short_side_len = c.short_side_len;\n   memcpy(ts->num_color, c.num_color, sizeof(ts->num_color));\n\n   ts->max_h_tiles = h_count;\n   ts->max_v_tiles = v_count;\n\n   ts->num_h_tiles = ts->num_v_tiles = 0;\n\n   ts->h_tiles = (stbhw_tile **) malloc(sizeof(*ts->h_tiles) * h_count);\n   ts->v_tiles = (stbhw_tile **) malloc(sizeof(*ts->v_tiles) * v_count);\n\n   p.ts = ts;\n   p.data = data;\n   p.stride = stride;\n   p.process_h_rect = stbhw__parse_h_rect;\n   p.process_v_rect = stbhw__parse_v_rect;\n   p.w = w;\n   p.h = h;\n   p.c = &c;\n\n   // load all the tiles out of the image\n   return stbhw__process_template(&p);\n}\n\nSTBHW_EXTERN void stbhw_free_tileset(stbhw_tileset *ts)\n{\n   int i;\n   for (i=0; i < ts->num_h_tiles; ++i)\n      free(ts->h_tiles[i]);\n   for (i=0; i < ts->num_v_tiles; ++i)\n      free(ts->v_tiles[i]);\n   free(ts->h_tiles);\n   free(ts->v_tiles);\n   ts->h_tiles = NULL;\n   ts->v_tiles = NULL;\n   ts->num_h_tiles = ts->max_h_tiles = 0;\n   ts->num_v_tiles = ts->max_v_tiles = 0;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//               GENERATOR\n//\n//\n\n\n// shared code\n\nstatic void stbhw__set_pixel(unsigned char *data, int stride, int xpos, int ypos, unsigned char color[3])\n{\n   memcpy(data + ypos*stride + xpos*3, color, 3);\n}\n\nstatic void stbhw__stbhw__set_pixel_whiten(unsigned char *data, int stride, int xpos, int ypos, unsigned char color[3])\n{\n   unsigned char c2[3];\n   int i;\n   for (i=0; i < 3; ++i)\n      c2[i] = (color[i]*2 + 255)/3;\n   memcpy(data + ypos*stride + xpos*3, c2, 3);\n}\n\n\nstatic unsigned char stbhw__black[3] = { 0,0,0 };\n\n// each edge set gets its own unique color variants\n// used http://phrogz.net/css/distinct-colors.html to generate this set,\n// but it's not very good and needs to be revised\n\nstatic unsigned char stbhw__color[7][8][3] =\n{\n   { {255,51,51}  , {143,143,29}, {0,199,199}, {159,119,199},     {0,149,199}  , {143, 0,143}, {255,128,0}, {64,255,0},  },\n   { {235,255,30 }, {255,0,255},  {199,139,119},  {29,143, 57},    {143,0,71}   , { 0,143,143}, {0,99,199}, {143,71,0},  },\n   { {0,149,199}  , {143, 0,143}, {255,128,0}, {64,255,0},        {255,191,0}  , {51,255,153}, {0,0,143}, {199,119,159},},\n   { {143,0,71}   , { 0,143,143}, {0,99,199}, {143,71,0},         {255,190,153}, { 0,255,255}, {128,0,255}, {255,51,102},},\n   { {255,191,0}  , {51,255,153}, {0,0,143}, {199,119,159},       {255,51,51}  , {143,143,29}, {0,199,199}, {159,119,199},},\n   { {255,190,153}, { 0,255,255}, {128,0,255}, {255,51,102},      {235,255,30 }, {255,0,255}, {199,139,119},  {29,143, 57}, },\n\n   { {40,40,40 },  { 90,90,90 }, { 150,150,150 }, { 200,200,200 },\n     { 255,90,90 }, { 160,160,80}, { 50,150,150 }, { 200,50,200 } },\n};\n\nstatic void stbhw__draw_hline(unsigned char *data, int stride, int xpos, int ypos, int color, int len, int slot)\n{\n   int i;\n   int j = len * 6 / 16;\n   int k = len * 10 / 16;\n   for (i=0; i < len; ++i)\n      stbhw__set_pixel(data, stride, xpos+i, ypos, stbhw__black);\n   if (k-j < 2) {\n      j = len/2 - 1;\n      k = j+2;\n      if (len & 1)\n         ++k;\n   }\n   for (i=j; i < k; ++i)\n      stbhw__stbhw__set_pixel_whiten(data, stride, xpos+i, ypos, stbhw__color[slot][color]);\n}\n\nstatic void stbhw__draw_vline(unsigned char *data, int stride, int xpos, int ypos, int color, int len, int slot)\n{\n   int i;\n   int j = len * 6 / 16;\n   int k = len * 10 / 16;\n   for (i=0; i < len; ++i)\n      stbhw__set_pixel(data, stride, xpos, ypos+i, stbhw__black);\n   if (k-j < 2) {\n      j = len/2 - 1;\n      k = j+2;\n      if (len & 1)\n         ++k;\n   }\n   for (i=j; i < k; ++i)\n      stbhw__stbhw__set_pixel_whiten(data, stride, xpos, ypos+i, stbhw__color[slot][color]);\n}\n\n//                 0--*--1--*--2--*--3\n//                 |     |           |\n//                 *     *           *\n//                 |     |           |\n//     1--*--2--*--3     0--*--1--*--2\n//     |           |     |\n//     *           *     *\n//     |           |     |\n//     0--*--1--*--2--*--3\n//\n// variables while enumerating (no correspondence between corners\n// of the types is implied by these variables)\n//\n//     a-----b-----c      a-----d\n//     |           |      |     |\n//     |           |      |     |\n//     |           |      |     |\n//     d-----e-----f      b     e\n//                        |     |\n//                        |     |\n//                        |     |\n//                        c-----f\n//\n\nunsigned char stbhw__corner_colors[4][4][3] =\n{\n   { { 255,0,0 }, { 200,200,200 }, { 100,100,200 }, { 255,200,150 }, },\n   { { 0,0,255 }, { 255,255,0 },   { 100,200,100 }, { 150,255,200 }, },\n   { { 255,0,255 }, { 80,80,80 },  { 200,100,100 }, { 200,150,255 }, },\n   { { 0,255,255 }, { 0,255,0 },   { 200,120,200 }, { 255,200,200 }, },\n};\n\nint stbhw__corner_colors_to_edge_color[4][4] =\n{\n   // 0   1   2   3\n   {  0,  1,  4,  9, }, // 0\n   {  2,  3,  5, 10, }, // 1\n   {  6,  7,  8, 11, }, // 2\n   { 12, 13, 14, 15, }, // 3\n};\n\n#define stbhw__c2e stbhw__corner_colors_to_edge_color\n\nstatic void stbhw__draw_clipped_corner(unsigned char *data, int stride, int xpos, int ypos, int w, int h, int x, int y)\n{\n   static unsigned char template_color[3] = { 167,204,204 };\n   int i,j;\n   for (j = -2; j <= 1; ++j) {\n      for (i = -2; i <= 1; ++i) {\n         if ((i == -2 || i == 1) && (j == -2 || j == 1))\n            continue;\n         else {\n            if (x+i < 1 || x+i > w) continue;\n            if (y+j < 1 || y+j > h) continue;\n            stbhw__set_pixel(data, stride, xpos+x+i, ypos+y+j, template_color);\n\n         }\n      }\n   }\n}\n\nstatic void stbhw__edge_process_h_rect(stbhw__process *p, int xpos, int ypos,\n                            int a, int b, int c, int d, int e, int f)\n{\n   int len = p->c->short_side_len;\n   stbhw__draw_hline(p->data, p->stride, xpos+1        , ypos        , a, len, 2);\n   stbhw__draw_hline(p->data, p->stride, xpos+  len+1  , ypos        , b, len, 3);\n   stbhw__draw_vline(p->data, p->stride, xpos          , ypos+1      , c, len, 1);\n   stbhw__draw_vline(p->data, p->stride, xpos+2*len+1  , ypos+1      , d, len, 4);\n   stbhw__draw_hline(p->data, p->stride, xpos+1        , ypos + len+1, e, len, 0);\n   stbhw__draw_hline(p->data, p->stride, xpos + len+1  , ypos + len+1, f, len, 2);\n}\n\nstatic void stbhw__edge_process_v_rect(stbhw__process *p, int xpos, int ypos,\n                            int a, int b, int c, int d, int e, int f)\n{\n   int len = p->c->short_side_len;\n   stbhw__draw_hline(p->data, p->stride, xpos+1      , ypos          , a, len, 0);\n   stbhw__draw_vline(p->data, p->stride, xpos        , ypos+1        , b, len, 5);\n   stbhw__draw_vline(p->data, p->stride, xpos + len+1, ypos+1        , c, len, 1);\n   stbhw__draw_vline(p->data, p->stride, xpos        , ypos +   len+1, d, len, 4);\n   stbhw__draw_vline(p->data, p->stride, xpos + len+1, ypos +   len+1, e, len, 5);\n   stbhw__draw_hline(p->data, p->stride, xpos+1      , ypos + 2*len+1, f, len, 3);\n}\n\nstatic void stbhw__corner_process_h_rect(stbhw__process *p, int xpos, int ypos,\n                            int a, int b, int c, int d, int e, int f)\n{\n   int len = p->c->short_side_len;\n\n   stbhw__draw_hline(p->data, p->stride, xpos+1        , ypos        , stbhw__c2e[a][b], len, 2);\n   stbhw__draw_hline(p->data, p->stride, xpos+  len+1  , ypos        , stbhw__c2e[b][c], len, 3);\n   stbhw__draw_vline(p->data, p->stride, xpos          , ypos+1      , stbhw__c2e[a][d], len, 1);\n   stbhw__draw_vline(p->data, p->stride, xpos+2*len+1  , ypos+1      , stbhw__c2e[c][f], len, 4);\n   stbhw__draw_hline(p->data, p->stride, xpos+1        , ypos + len+1, stbhw__c2e[d][e], len, 0);\n   stbhw__draw_hline(p->data, p->stride, xpos + len+1  , ypos + len+1, stbhw__c2e[e][f], len, 2);\n\n   if (p->c->corner_type_color_template[1][a]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len*2,len, 1,1);\n   if (p->c->corner_type_color_template[2][b]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len*2,len, len+1,1);\n   if (p->c->corner_type_color_template[3][c]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len*2,len, len*2+1,1);\n\n   if (p->c->corner_type_color_template[0][d]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len*2,len, 1,len+1);\n   if (p->c->corner_type_color_template[1][e]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len*2,len, len+1,len+1);\n   if (p->c->corner_type_color_template[2][f]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len*2,len, len*2+1,len+1);\n\n   stbhw__set_pixel(p->data, p->stride, xpos        , ypos, stbhw__corner_colors[1][a]);\n   stbhw__set_pixel(p->data, p->stride, xpos+len    , ypos, stbhw__corner_colors[2][b]);\n   stbhw__set_pixel(p->data, p->stride, xpos+2*len+1, ypos, stbhw__corner_colors[3][c]);\n   stbhw__set_pixel(p->data, p->stride, xpos        , ypos+len+1, stbhw__corner_colors[0][d]);\n   stbhw__set_pixel(p->data, p->stride, xpos+len    , ypos+len+1, stbhw__corner_colors[1][e]);\n   stbhw__set_pixel(p->data, p->stride, xpos+2*len+1, ypos+len+1, stbhw__corner_colors[2][f]);\n}\n\nstatic void stbhw__corner_process_v_rect(stbhw__process *p, int xpos, int ypos,\n                            int a, int b, int c, int d, int e, int f)\n{\n   int len = p->c->short_side_len;\n\n   stbhw__draw_hline(p->data, p->stride, xpos+1      , ypos          , stbhw__c2e[a][d], len, 0);\n   stbhw__draw_vline(p->data, p->stride, xpos        , ypos+1        , stbhw__c2e[a][b], len, 5);\n   stbhw__draw_vline(p->data, p->stride, xpos + len+1, ypos+1        , stbhw__c2e[d][e], len, 1);\n   stbhw__draw_vline(p->data, p->stride, xpos        , ypos +   len+1, stbhw__c2e[b][c], len, 4);\n   stbhw__draw_vline(p->data, p->stride, xpos + len+1, ypos +   len+1, stbhw__c2e[e][f], len, 5);\n   stbhw__draw_hline(p->data, p->stride, xpos+1      , ypos + 2*len+1, stbhw__c2e[c][f], len, 3);\n\n   if (p->c->corner_type_color_template[0][a]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len,len*2, 1,1);\n   if (p->c->corner_type_color_template[3][b]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len,len*2, 1,len+1);\n   if (p->c->corner_type_color_template[2][c]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len,len*2, 1,len*2+1);\n\n   if (p->c->corner_type_color_template[1][d]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len,len*2, len+1,1);\n   if (p->c->corner_type_color_template[0][e]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len,len*2, len+1,len+1);\n   if (p->c->corner_type_color_template[3][f]) stbhw__draw_clipped_corner(p->data,p->stride, xpos,ypos, len,len*2, len+1,len*2+1);\n\n   stbhw__set_pixel(p->data, p->stride, xpos      , ypos        , stbhw__corner_colors[0][a]);\n   stbhw__set_pixel(p->data, p->stride, xpos      , ypos+len    , stbhw__corner_colors[3][b]);\n   stbhw__set_pixel(p->data, p->stride, xpos      , ypos+2*len+1, stbhw__corner_colors[2][c]);\n   stbhw__set_pixel(p->data, p->stride, xpos+len+1, ypos        , stbhw__corner_colors[1][d]);\n   stbhw__set_pixel(p->data, p->stride, xpos+len+1, ypos+len    , stbhw__corner_colors[0][e]);\n   stbhw__set_pixel(p->data, p->stride, xpos+len+1, ypos+2*len+1, stbhw__corner_colors[3][f]);\n}\n\n// generates a template image, assuming data is 3*w*h bytes long, RGB format\nSTBHW_EXTERN int stbhw_make_template(stbhw_config *c, unsigned char *data, int w, int h, int stride_in_bytes)\n{\n   stbhw__process p;\n   int i;\n\n   p.data = data;\n   p.w = w;\n   p.h = h;\n   p.stride = stride_in_bytes;\n   p.ts = 0;\n   p.c = c;\n\n   if (c->is_corner) {\n      p.process_h_rect = stbhw__corner_process_h_rect;\n      p.process_v_rect = stbhw__corner_process_v_rect;\n   } else {\n      p.process_h_rect = stbhw__edge_process_h_rect;\n      p.process_v_rect = stbhw__edge_process_v_rect;\n   }\n\n   for (i=0; i < p.h; ++i)\n      memset(p.data + i*p.stride, 255, 3*p.w);\n\n   if (!stbhw__process_template(&p))\n      return 0;\n\n   if (c->is_corner) {\n      // write out binary information in first line of image\n      for (i=0; i < 4; ++i)\n         data[w*3-1-i] = c->num_color[i];\n      data[w*3-1-i] = c->num_vary_x;\n      data[w*3-2-i] = c->num_vary_y;\n      data[w*3-3-i] = c->short_side_len;\n      data[w*3-4-i] = 0xc0;\n   } else {\n      for (i=0; i < 6; ++i)\n         data[w*3-1-i] = c->num_color[i];\n      data[w*3-1-i] = c->num_vary_x;\n      data[w*3-2-i] = c->num_vary_y;\n      data[w*3-3-i] = c->short_side_len;\n   }\n\n   // make it more obvious it encodes actual data\n   for (i=0; i < 9; ++i)\n      p.data[p.w*3 - 1 - i] ^= i*55;\n\n   return 1;\n}\n#endif // STB_HBWANG_IMPLEMENTATION\n"
  },
  {
    "path": "stb_hexwave.h",
    "content": "// stb_hexwave - v0.5 - public domain, initial release 2021-04-01\n//\n// A flexible anti-aliased (bandlimited) digital audio oscillator.\n//\n// This library generates waveforms of a variety of shapes made of\n// line segments. It does not do envelopes, LFO effects, etc.; it\n// merely tries to solve the problem of generating an artifact-free\n// morphable digital waveform with a variety of spectra, and leaves\n// it to the user to rescale the waveform and mix multiple voices, etc.\n//\n// Compiling:\n//\n//   In one C/C++ file that #includes this file, do\n//\n//      #define STB_HEXWAVE_IMPLEMENTATION\n//      #include \"stb_hexwave.h\"\n//\n//   Optionally, #define STB_HEXWAVE_STATIC before including\n//   the header to cause the definitions to be private to the\n//   implementation file (i.e. to be \"static\" instead of \"extern\").\n//\n// Notes:\n//\n//   Optionally performs memory allocation during initialization,\n//   never allocates otherwise.\n//\n// License:\n//\n//   See end of file for license information.\n//\n// Usage:\n//\n//   Initialization:\n//\n//     hexwave_init(32,16,NULL); // read \"header section\" for alternatives\n//\n//   Create oscillator:\n//\n//     HexWave *osc = malloc(sizeof(*osc)); // or \"new HexWave\", or declare globally or on stack\n//     hexwave_create(osc, reflect_flag, peak_time, half_height, zero_wait);\n//       see \"Waveform shapes\" below for the meaning of these parameters\n//\n//   Generate audio:\n//\n//     hexwave_generate_samples(output, number_of_samples, osc, oscillator_freq)\n//       where:\n//         output is a buffer where the library will store floating point audio samples\n//         number_of_samples is the number of audio samples to generate\n//         osc is a pointer to a Hexwave\n//         oscillator_freq is the frequency of the oscillator divided by the sample rate\n//\n//       The output samples will continue from where the samples generated by the\n//       previous hexwave_generate_samples() on this oscillator ended.\n//\n//   Change oscillator waveform:\n//\n//     hexwave_change(osc, reflect_flag, peak_time, half_height, zero_wait);\n//       can call in between calls to hexwave_generate_samples\n//\n// Waveform shapes:\n//\n//   All waveforms generated by hexwave are constructed from six line segments\n//   characterized by 3 parameters.\n//\n//   See demonstration: https://www.youtube.com/watch?v=hsUCrAsDN-M\n//\n//                 reflect=0                          reflect=1\n//\n//           0-----P---1                        0-----P---1    peak_time = P\n//                 .     1                            .     1\n//                /\\_    :                           /\\_    :\n//               /   \\_  :                          /   \\_  :\n//              /      \\.H                         /      \\.H  half_height = H\n//             /       | :                        /       | :\n//       _____/        |_:___               _____/        | :       _____\n//           .           :   \\        |         .         | :      /\n//           .           :    \\       |         .         | :     /\n//           .           :     \\     _/         .         \\_:    /\n//           .           :      \\  _/           .           :_  /\n//           .          -1       \\/             .          -1 \\/\n//       0 - Z - - - - 1                    0 - Z - - - - 1   zero_wait = Z\n//\n//    Classic waveforms:\n//                               peak    half    zero\n//                     reflect   time   height   wait\n//      Sawtooth          1       0       0       0\n//      Square            1       0       1       0\n//      Triangle          1       0.5     0       0\n//\n//    Some waveforms can be produced in multiple ways, which is useful when morphing\n//    into other waveforms, and there are a few more notable shapes:\n//\n//                               peak    half    zero\n//                     reflect   time   height   wait\n//      Sawtooth          1       1      any      0\n//      Sawtooth (8va)    1       0      -1       0\n//      Triangle          1       0.5     0       0\n//      Square            1       0       1       0\n//      Square            0       0       1       0\n//      Triangle          0       0.5     0       0\n//      Triangle          0       0      -1       0\n//      AlternatingSaw    0       0       0       0\n//      AlternatingSaw    0       1      any      0\n//      Stairs            0       0       1       0.5\n//\n//    The \"Sawtooth (8va)\" waveform is identical to a sawtooth wave with 2x the\n//    frequency, but when morphed with other values, it becomes an overtone of\n//    the base frequency.\n//\n//  Morphing waveforms:\n//\n//    Sweeping peak_time morphs the waveform while producing various spectra.\n//    Sweeping half_height effectively crossfades between two waveforms; useful, but less exciting.\n//    Sweeping zero_wait produces a similar effect no matter the reset of the waveform,\n//        a sort of high-pass/PWM effect where the wave becomes silent at zero_wait=1.\n//\n//    You can trivially morph between any two waveforms from the above table\n//    which only differ in one column.\n//\n//    Crossfade between classic waveforms:\n//                                            peak     half    zero\n//        Start         End         reflect   time    height   wait\n//        -----         ---         -------   ----    ------   ----\n//        Triangle      Square         0       0      -1..1    0\n//        Saw           Square         1       0       0..1    0\n//        Triangle      Saw            1       0.5     0..2    0\n//\n//    The last morph uses uses half-height values larger than 1, which means it will\n//    be louder and the output should be scaled down by half to compensate, or better\n//    by dynamically tracking the morph: volume_scale = 1 - half_height/4\n//\n//    Non-crossfade morph between classic waveforms, most require changing\n//    two parameters at the same time:\n//                                           peak     half    zero\n//      Start         End         reflect    time    height   wait\n//      -----         ---         -------    ----    ------   ----\n//      Square        Triangle      any      0..0.5   1..0     0\n//      Square        Saw            1       0..1     1..any   0\n//      Triangle      Saw            1     0.5..1     0..-1    0\n//\n//    Other noteworthy morphs between simple shapes:\n//                                                            peak     half    zero\n//      Start           Halfway       End          reflect    time    height   wait\n//      -----           ---------     ---          -------    ----    ------   ----\n//      Saw (8va,neg)                Saw (pos)        1       0..1      -1      0\n//      Saw (neg)                    Saw (pos)        1       0..1       0      0\n//      Triangle                     AlternatingSaw   0       0..1      -1      0\n//      AlternatingSaw  Triangle     AlternatingSaw   0       0..1       0      0\n//      Square                       AlternatingSaw   0       0..1       1      0\n//      Triangle        Triangle     AlternatingSaw   0       0..1    -1..1     0\n//      Square                       AlternatingSaw   0       0..1     1..0     0\n//      Saw (8va)       Triangle     Saw              1       0..1    -1..1     0\n//      Saw (neg)                    Saw (pos)        1       0..1     0..1     0\n//      AlternatingSaw               AlternatingSaw   0       0..1     0..any   0\n//\n//   The last entry is noteworthy because the morph from the halfway point to either\n//   endpoint sounds very different. For example, an LFO sweeping back and forth over\n//   the whole range will morph between the middle timbre and the AlternatingSaw\n//   timbre in two different ways, alternating.\n//\n//   Entries with \"any\" for half_height are whole families of morphs, as you can pick\n//   any value you want as the endpoint for half_height.\n//\n//   You can always morph between any two waveforms with the same value of 'reflect'\n//   by just sweeping the parameters simultaneously. There will never be artifacts\n//   and the result will always be useful, if not necessarily what you want.\n//\n//   You can vary the sound of two-parameter morphs by ramping them differently,\n//   e.g. if the morph goes from t=0..1, then square-to-triangle looks like:\n//        peak_time   = lerp(t, 0, 0.5)\n//        half_height = lerp(t, 1, 0  )\n//   but you can also do things like:\n//        peak_time   = lerp(smoothstep(t), 0, 0.5)\n//        half_height = cos(PI/2 * t)\n//\n// How it works:\n//\n//   hexwave use BLEP to bandlimit discontinuities and BLAMP\n//   to bandlimit C1 discontinuities. This is not polyBLEP\n//   (polynomial BLEP), it is table-driven BLEP. It is\n//   also not minBLEP (minimum-phase BLEP), as that complicates\n//   things for little benefit once BLAMP is involved.\n//\n//   The previous oscillator frequency is remembered, and when\n//   the frequency changes, a BLAMP is generated to remove the\n//   C1 discontinuity, which reduces artifacts for sweeps/LFO.\n//\n//   Changes to an oscillator timbre using hexwave_change() actually\n//   wait until the oscillator finishes its current cycle. All\n//   waveforms with non-zero \"zero_wait\" settings pass through 0\n//   and have 0-slope at the start of a cycle, which means changing\n//   the settings is artifact free at that time. (If zero_wait is 0,\n//   the code still treats it as passing through 0 with 0-slope; it'll\n//   apply the necessary fixups to make it artifact free as if it does\n//   transition to 0 with 0-slope vs. the waveform at the end of\n//   the cycle, then adds the fixups for a non-0 and non-0 slope\n//   at the start of the cycle, which cancels out if zero_wait is 0,\n//   and still does the right thing if zero_wait is 0 when the\n//   settings are updated.)\n//\n//   BLEP/BLAMP normally requires overlapping buffers, but this\n//   is hidden from the user by generating the waveform to a\n//   temporary buffer and saving the overlap regions internally\n//   between calls. (It is slightly more complicated; see code.)\n//\n//   By design all shapes have 0 DC offset; this is one reason\n//   hexwave uses zero_wait instead of standard PWM.\n//\n//   The internals of hexwave could support any arbitrary shape\n//   made of line segments, but I chose not to expose this\n//   generality in favor of a simple, easy-to-use API.\n\n#ifndef STB_INCLUDE_STB_HEXWAVE_H\n#define STB_INCLUDE_STB_HEXWAVE_H\n\n#ifndef STB_HEXWAVE_MAX_BLEP_LENGTH\n#define STB_HEXWAVE_MAX_BLEP_LENGTH   64 // good enough for anybody\n#endif\n\n#ifdef STB_HEXWAVE_STATIC\n#define STB_HEXWAVE_DEF static\n#else\n#define STB_HEXWAVE_DEF extern\n#endif\n\ntypedef struct HexWave HexWave;\n\nSTB_HEXWAVE_DEF void hexwave_init(int width, int oversample, float *user_buffer);\n//         width: size of BLEP, from 4..64, larger is slower & more memory but less aliasing\n//    oversample: 2+, number of subsample positions, larger uses more memory but less noise\n//   user_buffer: optional, if provided the library will perform no allocations.\n//                16*width*(oversample+1) bytes, must stay allocated as long as library is used\n//                technically it only needs:   8*( width * (oversample  + 1))\n//                                           + 8*((width *  oversample) + 1)  bytes\n//\n// width can be larger than 64 if you define STB_HEXWAVE_MAX_BLEP_LENGTH to a larger value\n\nSTB_HEXWAVE_DEF void hexwave_shutdown(float *user_buffer);\n//       user_buffer: pass in same parameter as passed to hexwave_init\n\nSTB_HEXWAVE_DEF void hexwave_create(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait);\n// see docs above for description\n//\n//   reflect is tested as 0 or non-zero\n//   peak_time is clamped to 0..1\n//   half_height is not clamped\n//   zero_wait is clamped to 0..1\n\nSTB_HEXWAVE_DEF void hexwave_change(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait);\n// see docs\n\nSTB_HEXWAVE_DEF void hexwave_generate_samples(float *output, int num_samples, HexWave *hex, float freq);\n//            output: buffer where the library will store generated floating point audio samples\n// number_of_samples: the number of audio samples to generate\n//               osc: pointer to a Hexwave initialized with 'hexwave_create'\n//   oscillator_freq: frequency of the oscillator divided by the sample rate\n\n// private:\ntypedef struct\n{\n   int   reflect;\n   float peak_time;\n   float zero_wait;\n   float half_height;\n} HexWaveParameters;\n\nstruct HexWave\n{\n   float t, prev_dt;\n   HexWaveParameters current, pending;\n   int have_pending;\n   float buffer[STB_HEXWAVE_MAX_BLEP_LENGTH];\n}; \n#endif\n\n#ifdef STB_HEXWAVE_IMPLEMENTATION\n\n#ifndef STB_HEXWAVE_NO_ALLOCATION\n#include <stdlib.h> // malloc,free\n#endif\n\n#include <string.h> // memset,memcpy,memmove\n#include <math.h>   // sin,cos,fabs\n\n#define hexwave_clamp(v,a,b)   ((v) < (a) ? (a) : (v) > (b) ? (b) : (v))\n\nSTB_HEXWAVE_DEF void hexwave_change(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait)\n{\n   hex->pending.reflect     = reflect;\n   hex->pending.peak_time   = hexwave_clamp(peak_time,0,1);\n   hex->pending.half_height = half_height;\n   hex->pending.zero_wait   = hexwave_clamp(zero_wait,0,1);\n   // put a barrier here to allow changing from a different thread than the generator\n   hex->have_pending        = 1;\n}\n\nSTB_HEXWAVE_DEF void hexwave_create(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait)\n{\n   memset(hex, 0, sizeof(*hex));\n   hexwave_change(hex, reflect, peak_time, half_height, zero_wait);\n   hex->current = hex->pending;\n   hex->have_pending = 0;\n   hex->t = 0;\n   hex->prev_dt = 0;\n}\n\nstatic struct\n{\n   int width;       // width of fixup in samples\n   int oversample;  // number of oversampled versions (there's actually one more to allow lerpign)\n   float *blep;\n   float *blamp;\n} hexblep;\n\nstatic void hex_add_oversampled_bleplike(float *output, float time_since_transition, float scale, float *data)\n{\n   float *d1,*d2;\n   float lerpweight;\n   int i, bw = hexblep.width;\n\n   int slot = (int) (time_since_transition * hexblep.oversample);\n   if (slot >= hexblep.oversample)\n      slot = hexblep.oversample-1; // clamp in case the floats overshoot\n\n   d1 = &data[ slot   *bw];\n   d2 = &data[(slot+1)*bw];\n\n   lerpweight = time_since_transition * hexblep.oversample - slot;\n   for (i=0; i < bw; ++i)\n      output[i] += scale * (d1[i] + (d2[i]-d1[i])*lerpweight);\n}\n\nstatic void hex_blep (float *output, float time_since_transition, float scale)\n{\n   hex_add_oversampled_bleplike(output, time_since_transition, scale, hexblep.blep);\n}\n\nstatic void hex_blamp(float *output, float time_since_transition, float scale)\n{\n   hex_add_oversampled_bleplike(output, time_since_transition, scale, hexblep.blamp);\n}\n\ntypedef struct\n{\n   float t,v,s; // time, value, slope\n} hexvert;\n\n// each half of the waveform needs 4 vertices to represent 3 line\n// segments, plus 1 more for wraparound\nstatic void hexwave_generate_linesegs(hexvert vert[9], HexWave *hex, float dt)\n{\n   int j;\n   float min_len = dt / 256.0f;\n\n   vert[0].t = 0;\n   vert[0].v = 0;\n   vert[1].t = hex->current.zero_wait*0.5f;\n   vert[1].v = 0;\n   vert[2].t = 0.5f*hex->current.peak_time + vert[1].t*(1-hex->current.peak_time);\n   vert[2].v = 1;\n   vert[3].t = 0.5f;\n   vert[3].v = hex->current.half_height;\n\n   if (hex->current.reflect) {\n      for (j=4; j <= 7; ++j) {\n         vert[j].t = 1 -  vert[7-j].t;\n         vert[j].v =    - vert[7-j].v;\n      }\n   } else {\n      for (j=4; j <= 7; ++j) {\n         vert[j].t =  0.5f +  vert[j-4].t;\n         vert[j].v =        - vert[j-4].v;\n      }\n   }\n   vert[8].t = 1;\n   vert[8].v = 0;\n\n   for (j=0; j < 8; ++j) {\n      if (vert[j+1].t <= vert[j].t + min_len) {\n          // if change takes place over less than a fraction of a sample treat as discontinuity\n          //\n          // otherwise the slope computation can blow up to arbitrarily large and we\n          // try to generate a huge BLAMP and the result is wrong.\n          // \n          // why does this happen if the math is right? i believe if done perfectly,\n          // the two BLAMPs on either side of the slope would cancel out, but our\n          // BLAMPs have only limited sub-sample precision and limited integration\n          // accuracy. or maybe it's just the math blowing up w/ floating point precision\n          // limits as we try to make x * (1/x) cancel out\n          //\n          // min_len verified artifact-free even near nyquist with only oversample=4\n         vert[j+1].t = vert[j].t;\n      }\n   }\n\n   if (vert[8].t != 1.0f) {\n      // if the above fixup moved the endpoint away from 1.0, move it back,\n      // along with any other vertices that got moved to the same time\n      float t = vert[8].t;\n      for (j=5; j <= 8; ++j)\n         if (vert[j].t == t)\n            vert[j].t = 1.0f;\n   }\n\n   // compute the exact slopes from the final fixed-up positions\n   for (j=0; j < 8; ++j)\n      if (vert[j+1].t == vert[j].t)\n         vert[j].s = 0;\n      else\n         vert[j].s = (vert[j+1].v - vert[j].v) / (vert[j+1].t - vert[j].t);\n\n   // wraparound at end\n   vert[8].t = 1;\n   vert[8].v = vert[0].v;\n   vert[8].s = vert[0].s;\n}\n\nSTB_HEXWAVE_DEF void hexwave_generate_samples(float *output, int num_samples, HexWave *hex, float freq)\n{\n   hexvert vert[9];\n   int pass,i,j;\n   float t = hex->t;\n   float temp_output[2*STB_HEXWAVE_MAX_BLEP_LENGTH];\n   int buffered_length = sizeof(float)*hexblep.width;\n   float dt = (float) fabs(freq);\n   float recip_dt = (dt == 0.0f) ? 0.0f : 1.0f / dt;\n\n   int halfw = hexblep.width/2;\n   // all sample times are biased by halfw to leave room for BLEP/BLAMP to go back in time\n\n   if (num_samples <= 0)\n      return;\n\n   // convert parameters to times and slopes\n   hexwave_generate_linesegs(vert, hex, dt);\n\n   if (hex->prev_dt != dt) {\n      // if frequency changes, add a fixup at the derivative discontinuity starting at now\n      float slope;\n      for (j=1; j < 6; ++j)\n         if (t < vert[j].t)\n            break;\n      slope = vert[j].s;\n      if (slope != 0)\n         hex_blamp(output, 0, (dt - hex->prev_dt)*slope);\n      hex->prev_dt = dt;\n   }\n\n   // copy the buffered data from last call and clear the rest of the output array\n   memset(output, 0, sizeof(float)*num_samples);\n   memset(temp_output, 0, 2*hexblep.width*sizeof(float));\n\n   if (num_samples >= hexblep.width) {\n      memcpy(output, hex->buffer, buffered_length);\n   } else {\n      // if the output is shorter than hexblep.width, we do all synthesis to temp_output\n      memcpy(temp_output, hex->buffer, buffered_length);\n   }\n\n   for (pass=0; pass < 2; ++pass) {\n      int i0,i1;\n      float *out;\n\n      // we want to simulate having one buffer that is num_output + hexblep.width\n      // samples long, without putting that requirement on the user, and without\n      // allocating a temp buffer that's as long as the whole thing. so we use two\n      // overlapping buffers, one the user's buffer and one a fixed-length temp\n      // buffer.\n\n      if (pass == 0) {\n         if (num_samples < hexblep.width)\n            continue;\n         // run as far as we can without overwriting the end of the user's buffer \n         out = output;\n         i0 = 0;\n         i1 = num_samples - hexblep.width;\n      } else {\n         // generate the rest into a temp buffer\n         out = temp_output;\n         i0 = 0;\n         if (num_samples >= hexblep.width)\n            i1 = hexblep.width;\n         else\n            i1 = num_samples;\n      }\n\n      // determine current segment\n      for (j=0; j < 8; ++j)\n         if (t < vert[j+1].t)                                  \n            break;\n\n      i = i0;\n      for(;;) {\n         while (t < vert[j+1].t) {\n            if (i == i1)\n               goto done;\n            out[i+halfw] += vert[j].v + vert[j].s*(t - vert[j].t);\n            t += dt;\n            ++i;\n         }\n         // transition from lineseg starting at j to lineseg starting at j+1\n\n         if (vert[j].t == vert[j+1].t)\n            hex_blep(out+i, recip_dt*(t-vert[j+1].t), (vert[j+1].v - vert[j].v));\n         hex_blamp(out+i, recip_dt*(t-vert[j+1].t), dt*(vert[j+1].s - vert[j].s));\n         ++j;\n\n         if (j == 8) {\n            // change to different waveform if there's a change pending\n            j = 0;\n            t -= 1.0; // t was >= 1.f if j==8\n            if (hex->have_pending) {\n               float prev_s0 = vert[j].s;\n               float prev_v0 = vert[j].v;\n               hex->current = hex->pending;\n               hex->have_pending = 0;\n               hexwave_generate_linesegs(vert, hex, dt);\n               // the following never occurs with this oscillator, but it makes\n               // the code work in more general cases\n               if (vert[j].v != prev_v0)\n                  hex_blep (out+i, recip_dt*t,    (vert[j].v - prev_v0));\n               if (vert[j].s != prev_s0)\n                  hex_blamp(out+i, recip_dt*t, dt*(vert[j].s - prev_s0));\n            }\n         }\n      }\n     done:\n      ;\n   }\n\n   // at this point, we've written output[] and temp_output[]\n   if (num_samples >= hexblep.width) {\n      // the first half of temp[] overlaps the end of output, the second half will be the new start overlap\n      for (i=0; i < hexblep.width; ++i)\n         output[num_samples-hexblep.width + i] += temp_output[i];\n      memcpy(hex->buffer, temp_output+hexblep.width, buffered_length);\n   } else {\n      for (i=0; i < num_samples; ++i)\n         output[i] = temp_output[i];\n      memcpy(hex->buffer, temp_output+num_samples, buffered_length);\n   }\n\n   hex->t = t;\n}\n\nSTB_HEXWAVE_DEF void hexwave_shutdown(float *user_buffer)\n{\n   #ifndef STB_HEXWAVE_NO_ALLOCATION\n   if (user_buffer != 0) {\n      free(hexblep.blep);\n      free(hexblep.blamp);\n   }\n   #endif\n}\n\n// buffer should be NULL or must be 4*(width*(oversample+1)*2 + \nSTB_HEXWAVE_DEF void hexwave_init(int width, int oversample, float *user_buffer)\n{\n   int halfwidth = width/2;\n   int half = halfwidth*oversample;\n   int blep_buffer_count = width*(oversample+1);\n   int n = 2*half+1;\n#ifdef STB_HEXWAVE_NO_ALLOCATION\n   float *buffers = user_buffer;\n#else\n   float *buffers = user_buffer ? user_buffer : (float *) malloc(sizeof(float) * n * 2);\n#endif\n   float *step    = buffers+0*n;\n   float *ramp    = buffers+1*n;\n   float *blep_buffer, *blamp_buffer;\n   double integrate_impulse=0, integrate_step=0;\n   int i,j;\n\n   if (width > STB_HEXWAVE_MAX_BLEP_LENGTH)\n      width = STB_HEXWAVE_MAX_BLEP_LENGTH;\n\n   if (user_buffer == 0) {\n      #ifndef STB_HEXWAVE_NO_ALLOCATION\n      blep_buffer  = (float *) malloc(sizeof(float)*blep_buffer_count);\n      blamp_buffer = (float *) malloc(sizeof(float)*blep_buffer_count);\n      #endif\n   } else {\n      blep_buffer  = ramp+n;\n      blamp_buffer = blep_buffer + blep_buffer_count;\n   }\n\n   // compute BLEP and BLAMP by integerating windowed sinc\n   for (i=0; i < n; ++i) {\n      for (j=0; j < 16; ++j) {\n         float sinc_t = 3.141592f* (i-half) / oversample;\n         float sinc   = (i==half) ? 1.0f : (float) sin(sinc_t) / (sinc_t);\n         float wt     = 2.0f*3.1415926f * i / (n-1);\n         float window = (float) (0.355768 - 0.487396*cos(wt) + 0.144232*cos(2*wt) - 0.012604*cos(3*wt)); // Nuttall\n         double value       =         window * sinc;\n         integrate_impulse +=         value/16;\n         integrate_step    +=         integrate_impulse/16;\n      }\n      step[i]            = (float) integrate_impulse;\n      ramp[i]            = (float) integrate_step;\n   }\n\n   // renormalize\n   for (i=0; i < n; ++i) {\n      step[i] = step[i] * (float) (1.0       / step[n-1]); // step needs to reach to 1.0\n      ramp[i] = ramp[i] * (float) (halfwidth / ramp[n-1]); // ramp needs to become a slope of 1.0 after oversampling\n   }\n\n   // deinterleave to allow efficient interpolation e.g. w/SIMD\n   for (j=0; j <= oversample; ++j) {\n      for (i=0; i < width; ++i) {\n         blep_buffer [j*width+i] = step[j+i*oversample];\n         blamp_buffer[j*width+i] = ramp[j+i*oversample];\n      }\n   }\n\n   // subtract out the naive waveform; note we can't do this to the raw data\n   // above, because we want the discontinuity to be in a different locations\n   // for j=0 and j=oversample (which exists to provide something to interpolate against)\n   for (j=0; j <= oversample; ++j) {\n      // subtract step\n      for (i=halfwidth; i < width; ++i)\n         blep_buffer [j*width+i] -= 1.0f;\n      // subtract ramp\n      for (i=halfwidth; i < width; ++i)\n         blamp_buffer[j*width+i] -= (j+i*oversample-half)*(1.0f/oversample);\n   }\n\n   hexblep.blep  = blep_buffer;\n   hexblep.blamp = blamp_buffer;\n   hexblep.width = width;\n   hexblep.oversample = oversample;\n\n   #ifndef STB_HEXWAVE_NO_ALLOCATION\n   if (user_buffer == 0)\n      free(buffers);\n   #endif\n}\n#endif // STB_HEXWAVE_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_image.h",
    "content": "/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb\n                                  no warranty implied; use at your own risk\n\n   Do this:\n      #define STB_IMAGE_IMPLEMENTATION\n   before you include this file in *one* C or C++ file to create the implementation.\n\n   // i.e. it should look like this:\n   #include ...\n   #include ...\n   #include ...\n   #define STB_IMAGE_IMPLEMENTATION\n   #include \"stb_image.h\"\n\n   You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.\n   And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free\n\n\n   QUICK NOTES:\n      Primarily of interest to game developers and other people who can\n          avoid problematic images and only need the trivial interface\n\n      JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)\n      PNG 1/2/4/8/16-bit-per-channel\n\n      TGA (not sure what subset, if a subset)\n      BMP non-1bpp, non-RLE\n      PSD (composited view only, no extra channels, 8/16 bit-per-channel)\n\n      GIF (*comp always reports as 4-channel)\n      HDR (radiance rgbE format)\n      PIC (Softimage PIC)\n      PNM (PPM and PGM binary only)\n\n      Animated GIF still needs a proper API, but here's one way to do it:\n          http://gist.github.com/urraka/685d9a6340b26b830d49\n\n      - decode from memory or through FILE (define STBI_NO_STDIO to remove code)\n      - decode from arbitrary I/O callbacks\n      - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)\n\n   Full documentation under \"DOCUMENTATION\" below.\n\n\nLICENSE\n\n  See end of file for license information.\n\nRECENT REVISION HISTORY:\n\n      2.30  (2024-05-31) avoid erroneous gcc warning\n      2.29  (2023-05-xx) optimizations\n      2.28  (2023-01-29) many error fixes, security errors, just tons of stuff\n      2.27  (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes\n      2.26  (2020-07-13) many minor fixes\n      2.25  (2020-02-02) fix warnings\n      2.24  (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically\n      2.23  (2019-08-11) fix clang static analysis warning\n      2.22  (2019-03-04) gif fixes, fix warnings\n      2.21  (2019-02-25) fix typo in comment\n      2.20  (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs\n      2.19  (2018-02-11) fix warning\n      2.18  (2018-01-30) fix warnings\n      2.17  (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings\n      2.16  (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes\n      2.15  (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC\n      2.14  (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs\n      2.13  (2016-12-04) experimental 16-bit API, only for PNG so far; fixes\n      2.12  (2016-04-02) fix typo in 2.11 PSD fix that caused crashes\n      2.11  (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64\n                         RGB-format JPEG; remove white matting in PSD;\n                         allocate large structures on the stack;\n                         correct channel count for PNG & BMP\n      2.10  (2016-01-22) avoid warning introduced in 2.09\n      2.09  (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED\n\n   See end of file for full revision history.\n\n\n ============================    Contributors    =========================\n\n Image formats                          Extensions, features\n    Sean Barrett (jpeg, png, bmp)          Jetro Lauha (stbi_info)\n    Nicolas Schulz (hdr, psd)              Martin \"SpartanJ\" Golini (stbi_info)\n    Jonathan Dummer (tga)                  James \"moose2000\" Brown (iPhone PNG)\n    Jean-Marc Lienher (gif)                Ben \"Disch\" Wenger (io callbacks)\n    Tom Seddon (pic)                       Omar Cornut (1/2/4-bit PNG)\n    Thatcher Ulrich (psd)                  Nicolas Guillemot (vertical flip)\n    Ken Miller (pgm, ppm)                  Richard Mitton (16-bit PSD)\n    github:urraka (animated gif)           Junggon Kim (PNM comments)\n    Christopher Forseth (animated gif)     Daniel Gibson (16-bit TGA)\n                                           socks-the-fox (16-bit PNG)\n                                           Jeremy Sawicki (handle all ImageNet JPGs)\n Optimizations & bugfixes                  Mikhail Morozov (1-bit BMP)\n    Fabian \"ryg\" Giesen                    Anael Seghezzi (is-16-bit query)\n    Arseny Kapoulkine                      Simon Breuss (16-bit PNM)\n    John-Mark Allen\n    Carmelo J Fdez-Aguera\n\n Bug & warning fixes\n    Marc LeBlanc            David Woo          Guillaume George     Martins Mozeiko\n    Christpher Lloyd        Jerry Jansson      Joseph Thomson       Blazej Dariusz Roszkowski\n    Phil Jordan                                Dave Moore           Roy Eltham\n    Hayaki Saito            Nathan Reed        Won Chun\n    Luke Graham             Johan Duparc       Nick Verigakis       the Horde3D community\n    Thomas Ruf              Ronny Chevalier                         github:rlyeh\n    Janez Zemva             John Bartholomew   Michal Cichon        github:romigrou\n    Jonathan Blow           Ken Hamada         Tero Hanninen        github:svdijk\n    Eugene Golushkov        Laurent Gomila     Cort Stratton        github:snagar\n    Aruelien Pocheville     Sergio Gonzalez    Thibault Reuille     github:Zelex\n    Cass Everitt            Ryamond Barbiero                        github:grim210\n    Paul Du Bois            Engin Manap        Aldo Culquicondor    github:sammyhw\n    Philipp Wiesemann       Dale Weiler        Oriol Ferrer Mesia   github:phprus\n    Josh Tobin              Neil Bickford      Matthew Gregan       github:poppolopoppo\n    Julian Raschke          Gregory Mullen     Christian Floisand   github:darealshinji\n    Baldur Karlsson         Kevin Schmidt      JR Smith             github:Michaelangel007\n                            Brad Weinberger    Matvey Cherevko      github:mosra\n    Luca Sas                Alexander Veselov  Zack Middleton       [reserved]\n    Ryan C. Gordon          [reserved]                              [reserved]\n                     DO NOT ADD YOUR NAME HERE\n\n                     Jacko Dirks\n\n  To add your name to the credits, pick a random blank space in the middle and fill it.\n  80% of merge conflicts on stb PRs are due to people adding their name at the end\n  of the credits.\n*/\n\n#ifndef STBI_INCLUDE_STB_IMAGE_H\n#define STBI_INCLUDE_STB_IMAGE_H\n\n// DOCUMENTATION\n//\n// Limitations:\n//    - no 12-bit-per-channel JPEG\n//    - no JPEGs with arithmetic coding\n//    - GIF always returns *comp=4\n//\n// Basic usage (see HDR discussion below for HDR usage):\n//    int x,y,n;\n//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);\n//    // ... process data if not NULL ...\n//    // ... x = width, y = height, n = # 8-bit components per pixel ...\n//    // ... replace '0' with '1'..'4' to force that many components per pixel\n//    // ... but 'n' will always be the number that it would have been if you said 0\n//    stbi_image_free(data);\n//\n// Standard parameters:\n//    int *x                 -- outputs image width in pixels\n//    int *y                 -- outputs image height in pixels\n//    int *channels_in_file  -- outputs # of image components in image file\n//    int desired_channels   -- if non-zero, # of image components requested in result\n//\n// The return value from an image loader is an 'unsigned char *' which points\n// to the pixel data, or NULL on an allocation failure or if the image is\n// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,\n// with each pixel consisting of N interleaved 8-bit components; the first\n// pixel pointed to is top-left-most in the image. There is no padding between\n// image scanlines or between pixels, regardless of format. The number of\n// components N is 'desired_channels' if desired_channels is non-zero, or\n// *channels_in_file otherwise. If desired_channels is non-zero,\n// *channels_in_file has the number of components that _would_ have been\n// output otherwise. E.g. if you set desired_channels to 4, you will always\n// get RGBA output, but you can check *channels_in_file to see if it's trivially\n// opaque because e.g. there were only 3 channels in the source image.\n//\n// An output image with N components has the following components interleaved\n// in this order in each pixel:\n//\n//     N=#comp     components\n//       1           grey\n//       2           grey, alpha\n//       3           red, green, blue\n//       4           red, green, blue, alpha\n//\n// If image loading fails for any reason, the return value will be NULL,\n// and *x, *y, *channels_in_file will be unchanged. The function\n// stbi_failure_reason() can be queried for an extremely brief, end-user\n// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS\n// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly\n// more user-friendly ones.\n//\n// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.\n//\n// To query the width, height and component count of an image without having to\n// decode the full file, you can use the stbi_info family of functions:\n//\n//   int x,y,n,ok;\n//   ok = stbi_info(filename, &x, &y, &n);\n//   // returns ok=1 and sets x, y, n if image is a supported format,\n//   // 0 otherwise.\n//\n// Note that stb_image pervasively uses ints in its public API for sizes,\n// including sizes of memory buffers. This is now part of the API and thus\n// hard to change without causing breakage. As a result, the various image\n// loaders all have certain limits on image size; these differ somewhat\n// by format but generally boil down to either just under 2GB or just under\n// 1GB. When the decoded image would be larger than this, stb_image decoding\n// will fail.\n//\n// Additionally, stb_image will reject image files that have any of their\n// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,\n// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,\n// the only way to have an image with such dimensions load correctly\n// is for it to have a rather extreme aspect ratio. Either way, the\n// assumption here is that such larger images are likely to be malformed\n// or malicious. If you do need to load an image with individual dimensions\n// larger than that, and it still fits in the overall size limit, you can\n// #define STBI_MAX_DIMENSIONS on your own to be something larger.\n//\n// ===========================================================================\n//\n// UNICODE:\n//\n//   If compiling for Windows and you wish to use Unicode filenames, compile\n//   with\n//       #define STBI_WINDOWS_UTF8\n//   and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert\n//   Windows wchar_t filenames to utf8.\n//\n// ===========================================================================\n//\n// Philosophy\n//\n// stb libraries are designed with the following priorities:\n//\n//    1. easy to use\n//    2. easy to maintain\n//    3. good performance\n//\n// Sometimes I let \"good performance\" creep up in priority over \"easy to maintain\",\n// and for best performance I may provide less-easy-to-use APIs that give higher\n// performance, in addition to the easy-to-use ones. Nevertheless, it's important\n// to keep in mind that from the standpoint of you, a client of this library,\n// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all.\n//\n// Some secondary priorities arise directly from the first two, some of which\n// provide more explicit reasons why performance can't be emphasized.\n//\n//    - Portable (\"ease of use\")\n//    - Small source code footprint (\"easy to maintain\")\n//    - No dependencies (\"ease of use\")\n//\n// ===========================================================================\n//\n// I/O callbacks\n//\n// I/O callbacks allow you to read from arbitrary sources, like packaged\n// files or some other source. Data read from callbacks are processed\n// through a small internal buffer (currently 128 bytes) to try to reduce\n// overhead.\n//\n// The three functions you must define are \"read\" (reads some bytes of data),\n// \"skip\" (skips some bytes of data), \"eof\" (reports if the stream is at the end).\n//\n// ===========================================================================\n//\n// SIMD support\n//\n// The JPEG decoder will try to automatically use SIMD kernels on x86 when\n// supported by the compiler. For ARM Neon support, you must explicitly\n// request it.\n//\n// (The old do-it-yourself SIMD API is no longer supported in the current\n// code.)\n//\n// On x86, SSE2 will automatically be used when available based on a run-time\n// test; if not, the generic C versions are used as a fall-back. On ARM targets,\n// the typical path is to have separate builds for NEON and non-NEON devices\n// (at least this is true for iOS and Android). Therefore, the NEON support is\n// toggled by a build flag: define STBI_NEON to get NEON loops.\n//\n// If for some reason you do not want to use any of SIMD code, or if\n// you have issues compiling it, you can disable it entirely by\n// defining STBI_NO_SIMD.\n//\n// ===========================================================================\n//\n// HDR image support   (disable by defining STBI_NO_HDR)\n//\n// stb_image supports loading HDR images in general, and currently the Radiance\n// .HDR file format specifically. You can still load any file through the existing\n// interface; if you attempt to load an HDR file, it will be automatically remapped\n// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;\n// both of these constants can be reconfigured through this interface:\n//\n//     stbi_hdr_to_ldr_gamma(2.2f);\n//     stbi_hdr_to_ldr_scale(1.0f);\n//\n// (note, do not use _inverse_ constants; stbi_image will invert them\n// appropriately).\n//\n// Additionally, there is a new, parallel interface for loading files as\n// (linear) floats to preserve the full dynamic range:\n//\n//    float *data = stbi_loadf(filename, &x, &y, &n, 0);\n//\n// If you load LDR images through this interface, those images will\n// be promoted to floating point values, run through the inverse of\n// constants corresponding to the above:\n//\n//     stbi_ldr_to_hdr_scale(1.0f);\n//     stbi_ldr_to_hdr_gamma(2.2f);\n//\n// Finally, given a filename (or an open file or memory block--see header\n// file for details) containing image data, you can query for the \"most\n// appropriate\" interface to use (that is, whether the image is HDR or\n// not), using:\n//\n//     stbi_is_hdr(char *filename);\n//\n// ===========================================================================\n//\n// iPhone PNG support:\n//\n// We optionally support converting iPhone-formatted PNGs (which store\n// premultiplied BGRA) back to RGB, even though they're internally encoded\n// differently. To enable this conversion, call\n// stbi_convert_iphone_png_to_rgb(1).\n//\n// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per\n// pixel to remove any premultiplied alpha *only* if the image file explicitly\n// says there's premultiplied data (currently only happens in iPhone images,\n// and only if iPhone convert-to-rgb processing is on).\n//\n// ===========================================================================\n//\n// ADDITIONAL CONFIGURATION\n//\n//  - You can suppress implementation of any of the decoders to reduce\n//    your code footprint by #defining one or more of the following\n//    symbols before creating the implementation.\n//\n//        STBI_NO_JPEG\n//        STBI_NO_PNG\n//        STBI_NO_BMP\n//        STBI_NO_PSD\n//        STBI_NO_TGA\n//        STBI_NO_GIF\n//        STBI_NO_HDR\n//        STBI_NO_PIC\n//        STBI_NO_PNM   (.ppm and .pgm)\n//\n//  - You can request *only* certain decoders and suppress all other ones\n//    (this will be more forward-compatible, as addition of new decoders\n//    doesn't require you to disable them explicitly):\n//\n//        STBI_ONLY_JPEG\n//        STBI_ONLY_PNG\n//        STBI_ONLY_BMP\n//        STBI_ONLY_PSD\n//        STBI_ONLY_TGA\n//        STBI_ONLY_GIF\n//        STBI_ONLY_HDR\n//        STBI_ONLY_PIC\n//        STBI_ONLY_PNM   (.ppm and .pgm)\n//\n//   - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still\n//     want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB\n//\n//  - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater\n//    than that size (in either width or height) without further processing.\n//    This is to let programs in the wild set an upper bound to prevent\n//    denial-of-service attacks on untrusted data, as one could generate a\n//    valid image of gigantic dimensions and force stb_image to allocate a\n//    huge block of memory and spend disproportionate time decoding it. By\n//    default this is set to (1 << 24), which is 16777216, but that's still\n//    very big.\n\n#ifndef STBI_NO_STDIO\n#include <stdio.h>\n#endif // STBI_NO_STDIO\n\n#define STBI_VERSION 1\n\nenum\n{\n   STBI_default = 0, // only used for desired_channels\n\n   STBI_grey       = 1,\n   STBI_grey_alpha = 2,\n   STBI_rgb        = 3,\n   STBI_rgb_alpha  = 4\n};\n\n#include <stdlib.h>\ntypedef unsigned char stbi_uc;\ntypedef unsigned short stbi_us;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef STBIDEF\n#ifdef STB_IMAGE_STATIC\n#define STBIDEF static\n#else\n#define STBIDEF extern\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// PRIMARY API - works on images of any type\n//\n\n//\n// load image by filename, open file, or memory buffer\n//\n\ntypedef struct\n{\n   int      (*read)  (void *user,char *data,int size);   // fill 'data' with 'size' bytes.  return number of bytes actually read\n   void     (*skip)  (void *user,int n);                 // skip the next 'n' bytes, or 'unget' the last -n bytes if negative\n   int      (*eof)   (void *user);                       // returns nonzero if we are at end of file/data\n} stbi_io_callbacks;\n\n////////////////////////////////////\n//\n// 8-bits-per-channel interface\n//\n\nSTBIDEF stbi_uc *stbi_load_from_memory   (stbi_uc           const *buffer, int len   , int *x, int *y, int *channels_in_file, int desired_channels);\nSTBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk  , void *user, int *x, int *y, int *channels_in_file, int desired_channels);\n\n#ifndef STBI_NO_STDIO\nSTBIDEF stbi_uc *stbi_load            (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);\nSTBIDEF stbi_uc *stbi_load_from_file  (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);\n// for stbi_load_from_file, file pointer is left pointing immediately after image\n#endif\n\n#ifndef STBI_NO_GIF\nSTBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp);\n#endif\n\n#ifdef STBI_WINDOWS_UTF8\nSTBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);\n#endif\n\n////////////////////////////////////\n//\n// 16-bits-per-channel interface\n//\n\nSTBIDEF stbi_us *stbi_load_16_from_memory   (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);\nSTBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);\n\n#ifndef STBI_NO_STDIO\nSTBIDEF stbi_us *stbi_load_16          (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);\nSTBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);\n#endif\n\n////////////////////////////////////\n//\n// float-per-channel interface\n//\n#ifndef STBI_NO_LINEAR\n   STBIDEF float *stbi_loadf_from_memory     (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);\n   STBIDEF float *stbi_loadf_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y,  int *channels_in_file, int desired_channels);\n\n   #ifndef STBI_NO_STDIO\n   STBIDEF float *stbi_loadf            (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);\n   STBIDEF float *stbi_loadf_from_file  (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);\n   #endif\n#endif\n\n#ifndef STBI_NO_HDR\n   STBIDEF void   stbi_hdr_to_ldr_gamma(float gamma);\n   STBIDEF void   stbi_hdr_to_ldr_scale(float scale);\n#endif // STBI_NO_HDR\n\n#ifndef STBI_NO_LINEAR\n   STBIDEF void   stbi_ldr_to_hdr_gamma(float gamma);\n   STBIDEF void   stbi_ldr_to_hdr_scale(float scale);\n#endif // STBI_NO_LINEAR\n\n// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR\nSTBIDEF int    stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);\nSTBIDEF int    stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);\n#ifndef STBI_NO_STDIO\nSTBIDEF int      stbi_is_hdr          (char const *filename);\nSTBIDEF int      stbi_is_hdr_from_file(FILE *f);\n#endif // STBI_NO_STDIO\n\n\n// get a VERY brief reason for failure\n// on most compilers (and ALL modern mainstream compilers) this is threadsafe\nSTBIDEF const char *stbi_failure_reason  (void);\n\n// free the loaded image -- this is just free()\nSTBIDEF void     stbi_image_free      (void *retval_from_stbi_load);\n\n// get image dimensions & components without fully decoding\nSTBIDEF int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\nSTBIDEF int      stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);\nSTBIDEF int      stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len);\nSTBIDEF int      stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user);\n\n#ifndef STBI_NO_STDIO\nSTBIDEF int      stbi_info               (char const *filename,     int *x, int *y, int *comp);\nSTBIDEF int      stbi_info_from_file     (FILE *f,                  int *x, int *y, int *comp);\nSTBIDEF int      stbi_is_16_bit          (char const *filename);\nSTBIDEF int      stbi_is_16_bit_from_file(FILE *f);\n#endif\n\n\n\n// for image formats that explicitly notate that they have premultiplied alpha,\n// we just return the colors as stored in the file. set this flag to force\n// unpremultiplication. results are undefined if the unpremultiply overflow.\nSTBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);\n\n// indicate whether we should process iphone images back to canonical format,\n// or just pass them through \"as-is\"\nSTBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);\n\n// flip the image vertically, so the first pixel in the output array is the bottom left\nSTBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);\n\n// as above, but only applies to images loaded on the thread that calls the function\n// this function is only available if your compiler supports thread-local variables;\n// calling it will fail to link if your compiler doesn't\nSTBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);\nSTBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);\nSTBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);\n\n// ZLIB client - used by PNG, available for other purposes\n\nSTBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);\nSTBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);\nSTBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);\nSTBIDEF int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\n\nSTBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);\nSTBIDEF int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n//\n//\n////   end header file   /////////////////////////////////////////////////////\n#endif // STBI_INCLUDE_STB_IMAGE_H\n\n#ifdef STB_IMAGE_IMPLEMENTATION\n\n#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \\\n  || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \\\n  || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \\\n  || defined(STBI_ONLY_ZLIB)\n   #ifndef STBI_ONLY_JPEG\n   #define STBI_NO_JPEG\n   #endif\n   #ifndef STBI_ONLY_PNG\n   #define STBI_NO_PNG\n   #endif\n   #ifndef STBI_ONLY_BMP\n   #define STBI_NO_BMP\n   #endif\n   #ifndef STBI_ONLY_PSD\n   #define STBI_NO_PSD\n   #endif\n   #ifndef STBI_ONLY_TGA\n   #define STBI_NO_TGA\n   #endif\n   #ifndef STBI_ONLY_GIF\n   #define STBI_NO_GIF\n   #endif\n   #ifndef STBI_ONLY_HDR\n   #define STBI_NO_HDR\n   #endif\n   #ifndef STBI_ONLY_PIC\n   #define STBI_NO_PIC\n   #endif\n   #ifndef STBI_ONLY_PNM\n   #define STBI_NO_PNM\n   #endif\n#endif\n\n#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)\n#define STBI_NO_ZLIB\n#endif\n\n\n#include <stdarg.h>\n#include <stddef.h> // ptrdiff_t on osx\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n\n#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)\n#include <math.h>  // ldexp, pow\n#endif\n\n#ifndef STBI_NO_STDIO\n#include <stdio.h>\n#endif\n\n#ifndef STBI_ASSERT\n#include <assert.h>\n#define STBI_ASSERT(x) assert(x)\n#endif\n\n#ifdef __cplusplus\n#define STBI_EXTERN extern \"C\"\n#else\n#define STBI_EXTERN extern\n#endif\n\n\n#ifndef _MSC_VER\n   #ifdef __cplusplus\n   #define stbi_inline inline\n   #else\n   #define stbi_inline\n   #endif\n#else\n   #define stbi_inline __forceinline\n#endif\n\n#ifndef STBI_NO_THREAD_LOCALS\n   #if defined(__cplusplus) &&  __cplusplus >= 201103L\n      #define STBI_THREAD_LOCAL       thread_local\n   #elif defined(__GNUC__) && __GNUC__ < 5\n      #define STBI_THREAD_LOCAL       __thread\n   #elif defined(_MSC_VER)\n      #define STBI_THREAD_LOCAL       __declspec(thread)\n   #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)\n      #define STBI_THREAD_LOCAL       _Thread_local\n   #endif\n\n   #ifndef STBI_THREAD_LOCAL\n      #if defined(__GNUC__)\n        #define STBI_THREAD_LOCAL       __thread\n      #endif\n   #endif\n#endif\n\n#if defined(_MSC_VER) || defined(__SYMBIAN32__)\ntypedef unsigned short stbi__uint16;\ntypedef   signed short stbi__int16;\ntypedef unsigned int   stbi__uint32;\ntypedef   signed int   stbi__int32;\n#else\n#include <stdint.h>\ntypedef uint16_t stbi__uint16;\ntypedef int16_t  stbi__int16;\ntypedef uint32_t stbi__uint32;\ntypedef int32_t  stbi__int32;\n#endif\n\n// should produce compiler error if size is wrong\ntypedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];\n\n#ifdef _MSC_VER\n#define STBI_NOTUSED(v)  (void)(v)\n#else\n#define STBI_NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#ifdef _MSC_VER\n#define STBI_HAS_LROTL\n#endif\n\n#ifdef STBI_HAS_LROTL\n   #define stbi_lrot(x,y)  _lrotl(x,y)\n#else\n   #define stbi_lrot(x,y)  (((x) << (y)) | ((x) >> (-(y) & 31)))\n#endif\n\n#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))\n// ok\n#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)\n// ok\n#else\n#error \"Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED).\"\n#endif\n\n#ifndef STBI_MALLOC\n#define STBI_MALLOC(sz)           malloc(sz)\n#define STBI_REALLOC(p,newsz)     realloc(p,newsz)\n#define STBI_FREE(p)              free(p)\n#endif\n\n#ifndef STBI_REALLOC_SIZED\n#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz)\n#endif\n\n// x86/x64 detection\n#if defined(__x86_64__) || defined(_M_X64)\n#define STBI__X64_TARGET\n#elif defined(__i386) || defined(_M_IX86)\n#define STBI__X86_TARGET\n#endif\n\n#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)\n// gcc doesn't support sse2 intrinsics unless you compile with -msse2,\n// which in turn means it gets to use SSE2 everywhere. This is unfortunate,\n// but previous attempts to provide the SSE2 functions with runtime\n// detection caused numerous issues. The way architecture extensions are\n// exposed in GCC/Clang is, sadly, not really suited for one-file libs.\n// New behavior: if compiled with -msse2, we use SSE2 without any\n// detection; if not, we don't use it at all.\n#define STBI_NO_SIMD\n#endif\n\n#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)\n// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET\n//\n// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the\n// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.\n// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not\n// simultaneously enabling \"-mstackrealign\".\n//\n// See https://github.com/nothings/stb/issues/81 for more information.\n//\n// So default to no SSE2 on 32-bit MinGW. If you've read this far and added\n// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.\n#define STBI_NO_SIMD\n#endif\n\n#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))\n#define STBI_SSE2\n#include <emmintrin.h>\n\n#ifdef _MSC_VER\n\n#if _MSC_VER >= 1400  // not VC6\n#include <intrin.h> // __cpuid\nstatic int stbi__cpuid3(void)\n{\n   int info[4];\n   __cpuid(info,1);\n   return info[3];\n}\n#else\nstatic int stbi__cpuid3(void)\n{\n   int res;\n   __asm {\n      mov  eax,1\n      cpuid\n      mov  res,edx\n   }\n   return res;\n}\n#endif\n\n#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name\n\n#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)\nstatic int stbi__sse2_available(void)\n{\n   int info3 = stbi__cpuid3();\n   return ((info3 >> 26) & 1) != 0;\n}\n#endif\n\n#else // assume GCC-style if not VC++\n#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))\n\n#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)\nstatic int stbi__sse2_available(void)\n{\n   // If we're even attempting to compile this on GCC/Clang, that means\n   // -msse2 is on, which means the compiler is allowed to use SSE2\n   // instructions at will, and so are we.\n   return 1;\n}\n#endif\n\n#endif\n#endif\n\n// ARM NEON\n#if defined(STBI_NO_SIMD) && defined(STBI_NEON)\n#undef STBI_NEON\n#endif\n\n#ifdef STBI_NEON\n#include <arm_neon.h>\n#ifdef _MSC_VER\n#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name\n#else\n#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))\n#endif\n#endif\n\n#ifndef STBI_SIMD_ALIGN\n#define STBI_SIMD_ALIGN(type, name) type name\n#endif\n\n#ifndef STBI_MAX_DIMENSIONS\n#define STBI_MAX_DIMENSIONS (1 << 24)\n#endif\n\n///////////////////////////////////////////////\n//\n//  stbi__context struct and start_xxx functions\n\n// stbi__context structure is our basic context used by all images, so it\n// contains all the IO context, plus some basic image information\ntypedef struct\n{\n   stbi__uint32 img_x, img_y;\n   int img_n, img_out_n;\n\n   stbi_io_callbacks io;\n   void *io_user_data;\n\n   int read_from_callbacks;\n   int buflen;\n   stbi_uc buffer_start[128];\n   int callback_already_read;\n\n   stbi_uc *img_buffer, *img_buffer_end;\n   stbi_uc *img_buffer_original, *img_buffer_original_end;\n} stbi__context;\n\n\nstatic void stbi__refill_buffer(stbi__context *s);\n\n// initialize a memory-decode context\nstatic void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)\n{\n   s->io.read = NULL;\n   s->read_from_callbacks = 0;\n   s->callback_already_read = 0;\n   s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;\n   s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;\n}\n\n// initialize a callback-based context\nstatic void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)\n{\n   s->io = *c;\n   s->io_user_data = user;\n   s->buflen = sizeof(s->buffer_start);\n   s->read_from_callbacks = 1;\n   s->callback_already_read = 0;\n   s->img_buffer = s->img_buffer_original = s->buffer_start;\n   stbi__refill_buffer(s);\n   s->img_buffer_original_end = s->img_buffer_end;\n}\n\n#ifndef STBI_NO_STDIO\n\nstatic int stbi__stdio_read(void *user, char *data, int size)\n{\n   return (int) fread(data,1,size,(FILE*) user);\n}\n\nstatic void stbi__stdio_skip(void *user, int n)\n{\n   int ch;\n   fseek((FILE*) user, n, SEEK_CUR);\n   ch = fgetc((FILE*) user);  /* have to read a byte to reset feof()'s flag */\n   if (ch != EOF) {\n      ungetc(ch, (FILE *) user);  /* push byte back onto stream if valid. */\n   }\n}\n\nstatic int stbi__stdio_eof(void *user)\n{\n   return feof((FILE*) user) || ferror((FILE *) user);\n}\n\nstatic stbi_io_callbacks stbi__stdio_callbacks =\n{\n   stbi__stdio_read,\n   stbi__stdio_skip,\n   stbi__stdio_eof,\n};\n\nstatic void stbi__start_file(stbi__context *s, FILE *f)\n{\n   stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);\n}\n\n//static void stop_file(stbi__context *s) { }\n\n#endif // !STBI_NO_STDIO\n\nstatic void stbi__rewind(stbi__context *s)\n{\n   // conceptually rewind SHOULD rewind to the beginning of the stream,\n   // but we just rewind to the beginning of the initial buffer, because\n   // we only use it after doing 'test', which only ever looks at at most 92 bytes\n   s->img_buffer = s->img_buffer_original;\n   s->img_buffer_end = s->img_buffer_original_end;\n}\n\nenum\n{\n   STBI_ORDER_RGB,\n   STBI_ORDER_BGR\n};\n\ntypedef struct\n{\n   int bits_per_channel;\n   int num_channels;\n   int channel_order;\n} stbi__result_info;\n\n#ifndef STBI_NO_JPEG\nstatic int      stbi__jpeg_test(stbi__context *s);\nstatic void    *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);\n#endif\n\n#ifndef STBI_NO_PNG\nstatic int      stbi__png_test(stbi__context *s);\nstatic void    *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__png_info(stbi__context *s, int *x, int *y, int *comp);\nstatic int      stbi__png_is16(stbi__context *s);\n#endif\n\n#ifndef STBI_NO_BMP\nstatic int      stbi__bmp_test(stbi__context *s);\nstatic void    *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);\n#endif\n\n#ifndef STBI_NO_TGA\nstatic int      stbi__tga_test(stbi__context *s);\nstatic void    *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);\n#endif\n\n#ifndef STBI_NO_PSD\nstatic int      stbi__psd_test(stbi__context *s);\nstatic void    *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc);\nstatic int      stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);\nstatic int      stbi__psd_is16(stbi__context *s);\n#endif\n\n#ifndef STBI_NO_HDR\nstatic int      stbi__hdr_test(stbi__context *s);\nstatic float   *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);\n#endif\n\n#ifndef STBI_NO_PIC\nstatic int      stbi__pic_test(stbi__context *s);\nstatic void    *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);\n#endif\n\n#ifndef STBI_NO_GIF\nstatic int      stbi__gif_test(stbi__context *s);\nstatic void    *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic void    *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp);\nstatic int      stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);\n#endif\n\n#ifndef STBI_NO_PNM\nstatic int      stbi__pnm_test(stbi__context *s);\nstatic void    *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);\nstatic int      stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);\nstatic int      stbi__pnm_is16(stbi__context *s);\n#endif\n\nstatic\n#ifdef STBI_THREAD_LOCAL\nSTBI_THREAD_LOCAL\n#endif\nconst char *stbi__g_failure_reason;\n\nSTBIDEF const char *stbi_failure_reason(void)\n{\n   return stbi__g_failure_reason;\n}\n\n#ifndef STBI_NO_FAILURE_STRINGS\nstatic int stbi__err(const char *str)\n{\n   stbi__g_failure_reason = str;\n   return 0;\n}\n#endif\n\nstatic void *stbi__malloc(size_t size)\n{\n    return STBI_MALLOC(size);\n}\n\n// stb_image uses ints pervasively, including for offset calculations.\n// therefore the largest decoded image size we can support with the\n// current code, even on 64-bit targets, is INT_MAX. this is not a\n// significant limitation for the intended use case.\n//\n// we do, however, need to make sure our size calculations don't\n// overflow. hence a few helper functions for size calculations that\n// multiply integers together, making sure that they're non-negative\n// and no overflow occurs.\n\n// return 1 if the sum is valid, 0 on overflow.\n// negative terms are considered invalid.\nstatic int stbi__addsizes_valid(int a, int b)\n{\n   if (b < 0) return 0;\n   // now 0 <= b <= INT_MAX, hence also\n   // 0 <= INT_MAX - b <= INTMAX.\n   // And \"a + b <= INT_MAX\" (which might overflow) is the\n   // same as a <= INT_MAX - b (no overflow)\n   return a <= INT_MAX - b;\n}\n\n// returns 1 if the product is valid, 0 on overflow.\n// negative factors are considered invalid.\nstatic int stbi__mul2sizes_valid(int a, int b)\n{\n   if (a < 0 || b < 0) return 0;\n   if (b == 0) return 1; // mul-by-0 is always safe\n   // portable way to check for no overflows in a*b\n   return a <= INT_MAX/b;\n}\n\n#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)\n// returns 1 if \"a*b + add\" has no negative terms/factors and doesn't overflow\nstatic int stbi__mad2sizes_valid(int a, int b, int add)\n{\n   return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add);\n}\n#endif\n\n// returns 1 if \"a*b*c + add\" has no negative terms/factors and doesn't overflow\nstatic int stbi__mad3sizes_valid(int a, int b, int c, int add)\n{\n   return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&\n      stbi__addsizes_valid(a*b*c, add);\n}\n\n// returns 1 if \"a*b*c*d + add\" has no negative terms/factors and doesn't overflow\n#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)\nstatic int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)\n{\n   return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&\n      stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);\n}\n#endif\n\n#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)\n// mallocs with size overflow checking\nstatic void *stbi__malloc_mad2(int a, int b, int add)\n{\n   if (!stbi__mad2sizes_valid(a, b, add)) return NULL;\n   return stbi__malloc(a*b + add);\n}\n#endif\n\nstatic void *stbi__malloc_mad3(int a, int b, int c, int add)\n{\n   if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;\n   return stbi__malloc(a*b*c + add);\n}\n\n#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)\nstatic void *stbi__malloc_mad4(int a, int b, int c, int d, int add)\n{\n   if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;\n   return stbi__malloc(a*b*c*d + add);\n}\n#endif\n\n// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.\nstatic int stbi__addints_valid(int a, int b)\n{\n   if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow\n   if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0.\n   return a <= INT_MAX - b;\n}\n\n// returns 1 if the product of two ints fits in a signed short, 0 on overflow.\nstatic int stbi__mul2shorts_valid(int a, int b)\n{\n   if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow\n   if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid\n   if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN\n   return a >= SHRT_MIN / b;\n}\n\n// stbi__err - error\n// stbi__errpf - error returning pointer to float\n// stbi__errpuc - error returning pointer to unsigned char\n\n#ifdef STBI_NO_FAILURE_STRINGS\n   #define stbi__err(x,y)  0\n#elif defined(STBI_FAILURE_USERMSG)\n   #define stbi__err(x,y)  stbi__err(y)\n#else\n   #define stbi__err(x,y)  stbi__err(x)\n#endif\n\n#define stbi__errpf(x,y)   ((float *)(size_t) (stbi__err(x,y)?NULL:NULL))\n#define stbi__errpuc(x,y)  ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL))\n\nSTBIDEF void stbi_image_free(void *retval_from_stbi_load)\n{\n   STBI_FREE(retval_from_stbi_load);\n}\n\n#ifndef STBI_NO_LINEAR\nstatic float   *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);\n#endif\n\n#ifndef STBI_NO_HDR\nstatic stbi_uc *stbi__hdr_to_ldr(float   *data, int x, int y, int comp);\n#endif\n\nstatic int stbi__vertically_flip_on_load_global = 0;\n\nSTBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)\n{\n   stbi__vertically_flip_on_load_global = flag_true_if_should_flip;\n}\n\n#ifndef STBI_THREAD_LOCAL\n#define stbi__vertically_flip_on_load  stbi__vertically_flip_on_load_global\n#else\nstatic STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set;\n\nSTBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip)\n{\n   stbi__vertically_flip_on_load_local = flag_true_if_should_flip;\n   stbi__vertically_flip_on_load_set = 1;\n}\n\n#define stbi__vertically_flip_on_load  (stbi__vertically_flip_on_load_set       \\\n                                         ? stbi__vertically_flip_on_load_local  \\\n                                         : stbi__vertically_flip_on_load_global)\n#endif // STBI_THREAD_LOCAL\n\nstatic void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)\n{\n   memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields\n   ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed\n   ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order\n   ri->num_channels = 0;\n\n   // test the formats with a very explicit header first (at least a FOURCC\n   // or distinctive magic number first)\n   #ifndef STBI_NO_PNG\n   if (stbi__png_test(s))  return stbi__png_load(s,x,y,comp,req_comp, ri);\n   #endif\n   #ifndef STBI_NO_BMP\n   if (stbi__bmp_test(s))  return stbi__bmp_load(s,x,y,comp,req_comp, ri);\n   #endif\n   #ifndef STBI_NO_GIF\n   if (stbi__gif_test(s))  return stbi__gif_load(s,x,y,comp,req_comp, ri);\n   #endif\n   #ifndef STBI_NO_PSD\n   if (stbi__psd_test(s))  return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc);\n   #else\n   STBI_NOTUSED(bpc);\n   #endif\n   #ifndef STBI_NO_PIC\n   if (stbi__pic_test(s))  return stbi__pic_load(s,x,y,comp,req_comp, ri);\n   #endif\n\n   // then the formats that can end up attempting to load with just 1 or 2\n   // bytes matching expectations; these are prone to false positives, so\n   // try them later\n   #ifndef STBI_NO_JPEG\n   if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);\n   #endif\n   #ifndef STBI_NO_PNM\n   if (stbi__pnm_test(s))  return stbi__pnm_load(s,x,y,comp,req_comp, ri);\n   #endif\n\n   #ifndef STBI_NO_HDR\n   if (stbi__hdr_test(s)) {\n      float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri);\n      return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\n   }\n   #endif\n\n   #ifndef STBI_NO_TGA\n   // test tga last because it's a crappy test!\n   if (stbi__tga_test(s))\n      return stbi__tga_load(s,x,y,comp,req_comp, ri);\n   #endif\n\n   return stbi__errpuc(\"unknown image type\", \"Image not of any known type, or corrupt\");\n}\n\nstatic stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels)\n{\n   int i;\n   int img_len = w * h * channels;\n   stbi_uc *reduced;\n\n   reduced = (stbi_uc *) stbi__malloc(img_len);\n   if (reduced == NULL) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n\n   for (i = 0; i < img_len; ++i)\n      reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling\n\n   STBI_FREE(orig);\n   return reduced;\n}\n\nstatic stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels)\n{\n   int i;\n   int img_len = w * h * channels;\n   stbi__uint16 *enlarged;\n\n   enlarged = (stbi__uint16 *) stbi__malloc(img_len*2);\n   if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc(\"outofmem\", \"Out of memory\");\n\n   for (i = 0; i < img_len; ++i)\n      enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff\n\n   STBI_FREE(orig);\n   return enlarged;\n}\n\nstatic void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel)\n{\n   int row;\n   size_t bytes_per_row = (size_t)w * bytes_per_pixel;\n   stbi_uc temp[2048];\n   stbi_uc *bytes = (stbi_uc *)image;\n\n   for (row = 0; row < (h>>1); row++) {\n      stbi_uc *row0 = bytes + row*bytes_per_row;\n      stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row;\n      // swap row0 with row1\n      size_t bytes_left = bytes_per_row;\n      while (bytes_left) {\n         size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);\n         memcpy(temp, row0, bytes_copy);\n         memcpy(row0, row1, bytes_copy);\n         memcpy(row1, temp, bytes_copy);\n         row0 += bytes_copy;\n         row1 += bytes_copy;\n         bytes_left -= bytes_copy;\n      }\n   }\n}\n\n#ifndef STBI_NO_GIF\nstatic void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel)\n{\n   int slice;\n   int slice_size = w * h * bytes_per_pixel;\n\n   stbi_uc *bytes = (stbi_uc *)image;\n   for (slice = 0; slice < z; ++slice) {\n      stbi__vertical_flip(bytes, w, h, bytes_per_pixel);\n      bytes += slice_size;\n   }\n}\n#endif\n\nstatic unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__result_info ri;\n   void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);\n\n   if (result == NULL)\n      return NULL;\n\n   // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.\n   STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);\n\n   if (ri.bits_per_channel != 8) {\n      result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);\n      ri.bits_per_channel = 8;\n   }\n\n   // @TODO: move stbi__convert_format to here\n\n   if (stbi__vertically_flip_on_load) {\n      int channels = req_comp ? req_comp : *comp;\n      stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));\n   }\n\n   return (unsigned char *) result;\n}\n\nstatic stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__result_info ri;\n   void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);\n\n   if (result == NULL)\n      return NULL;\n\n   // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.\n   STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);\n\n   if (ri.bits_per_channel != 16) {\n      result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);\n      ri.bits_per_channel = 16;\n   }\n\n   // @TODO: move stbi__convert_format16 to here\n   // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision\n\n   if (stbi__vertically_flip_on_load) {\n      int channels = req_comp ? req_comp : *comp;\n      stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16));\n   }\n\n   return (stbi__uint16 *) result;\n}\n\n#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)\nstatic void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)\n{\n   if (stbi__vertically_flip_on_load && result != NULL) {\n      int channels = req_comp ? req_comp : *comp;\n      stbi__vertical_flip(result, *x, *y, channels * sizeof(float));\n   }\n}\n#endif\n\n#ifndef STBI_NO_STDIO\n\n#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)\nSTBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);\nSTBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);\n#endif\n\n#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)\nSTBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)\n{\n\treturn WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);\n}\n#endif\n\nstatic FILE *stbi__fopen(char const *filename, char const *mode)\n{\n   FILE *f;\n#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)\n   wchar_t wMode[64];\n   wchar_t wFilename[1024];\n\tif (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))\n      return 0;\n\n\tif (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))\n      return 0;\n\n#if defined(_MSC_VER) && _MSC_VER >= 1400\n\tif (0 != _wfopen_s(&f, wFilename, wMode))\n\t\tf = 0;\n#else\n   f = _wfopen(wFilename, wMode);\n#endif\n\n#elif defined(_MSC_VER) && _MSC_VER >= 1400\n   if (0 != fopen_s(&f, filename, mode))\n      f=0;\n#else\n   f = fopen(filename, mode);\n#endif\n   return f;\n}\n\n\nSTBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)\n{\n   FILE *f = stbi__fopen(filename, \"rb\");\n   unsigned char *result;\n   if (!f) return stbi__errpuc(\"can't fopen\", \"Unable to open file\");\n   result = stbi_load_from_file(f,x,y,comp,req_comp);\n   fclose(f);\n   return result;\n}\n\nSTBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\n{\n   unsigned char *result;\n   stbi__context s;\n   stbi__start_file(&s,f);\n   result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);\n   if (result) {\n      // need to 'unget' all the characters in the IO buffer\n      fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);\n   }\n   return result;\n}\n\nSTBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__uint16 *result;\n   stbi__context s;\n   stbi__start_file(&s,f);\n   result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp);\n   if (result) {\n      // need to 'unget' all the characters in the IO buffer\n      fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);\n   }\n   return result;\n}\n\nSTBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp)\n{\n   FILE *f = stbi__fopen(filename, \"rb\");\n   stbi__uint16 *result;\n   if (!f) return (stbi_us *) stbi__errpuc(\"can't fopen\", \"Unable to open file\");\n   result = stbi_load_from_file_16(f,x,y,comp,req_comp);\n   fclose(f);\n   return result;\n}\n\n\n#endif //!STBI_NO_STDIO\n\nSTBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels)\n{\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n   return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);\n}\n\nSTBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels)\n{\n   stbi__context s;\n   stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);\n   return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);\n}\n\nSTBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n   return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);\n}\n\nSTBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__context s;\n   stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);\n   return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);\n}\n\n#ifndef STBI_NO_GIF\nSTBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp)\n{\n   unsigned char *result;\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n\n   result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);\n   if (stbi__vertically_flip_on_load) {\n      stbi__vertical_flip_slices( result, *x, *y, *z, *comp );\n   }\n\n   return result;\n}\n#endif\n\n#ifndef STBI_NO_LINEAR\nstatic float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)\n{\n   unsigned char *data;\n   #ifndef STBI_NO_HDR\n   if (stbi__hdr_test(s)) {\n      stbi__result_info ri;\n      float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri);\n      if (hdr_data)\n         stbi__float_postprocess(hdr_data,x,y,comp,req_comp);\n      return hdr_data;\n   }\n   #endif\n   data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);\n   if (data)\n      return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\n   return stbi__errpf(\"unknown image type\", \"Image not of any known type, or corrupt\");\n}\n\nSTBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n   return stbi__loadf_main(&s,x,y,comp,req_comp);\n}\n\nSTBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__context s;\n   stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);\n   return stbi__loadf_main(&s,x,y,comp,req_comp);\n}\n\n#ifndef STBI_NO_STDIO\nSTBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)\n{\n   float *result;\n   FILE *f = stbi__fopen(filename, \"rb\");\n   if (!f) return stbi__errpf(\"can't fopen\", \"Unable to open file\");\n   result = stbi_loadf_from_file(f,x,y,comp,req_comp);\n   fclose(f);\n   return result;\n}\n\nSTBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\n{\n   stbi__context s;\n   stbi__start_file(&s,f);\n   return stbi__loadf_main(&s,x,y,comp,req_comp);\n}\n#endif // !STBI_NO_STDIO\n\n#endif // !STBI_NO_LINEAR\n\n// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is\n// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always\n// reports false!\n\nSTBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)\n{\n   #ifndef STBI_NO_HDR\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n   return stbi__hdr_test(&s);\n   #else\n   STBI_NOTUSED(buffer);\n   STBI_NOTUSED(len);\n   return 0;\n   #endif\n}\n\n#ifndef STBI_NO_STDIO\nSTBIDEF int      stbi_is_hdr          (char const *filename)\n{\n   FILE *f = stbi__fopen(filename, \"rb\");\n   int result=0;\n   if (f) {\n      result = stbi_is_hdr_from_file(f);\n      fclose(f);\n   }\n   return result;\n}\n\nSTBIDEF int stbi_is_hdr_from_file(FILE *f)\n{\n   #ifndef STBI_NO_HDR\n   long pos = ftell(f);\n   int res;\n   stbi__context s;\n   stbi__start_file(&s,f);\n   res = stbi__hdr_test(&s);\n   fseek(f, pos, SEEK_SET);\n   return res;\n   #else\n   STBI_NOTUSED(f);\n   return 0;\n   #endif\n}\n#endif // !STBI_NO_STDIO\n\nSTBIDEF int      stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)\n{\n   #ifndef STBI_NO_HDR\n   stbi__context s;\n   stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);\n   return stbi__hdr_test(&s);\n   #else\n   STBI_NOTUSED(clbk);\n   STBI_NOTUSED(user);\n   return 0;\n   #endif\n}\n\n#ifndef STBI_NO_LINEAR\nstatic float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;\n\nSTBIDEF void   stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }\nSTBIDEF void   stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }\n#endif\n\nstatic float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;\n\nSTBIDEF void   stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }\nSTBIDEF void   stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Common code used by all image loaders\n//\n\nenum\n{\n   STBI__SCAN_load=0,\n   STBI__SCAN_type,\n   STBI__SCAN_header\n};\n\nstatic void stbi__refill_buffer(stbi__context *s)\n{\n   int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);\n   s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original);\n   if (n == 0) {\n      // at end of file, treat same as if from memory, but need to handle case\n      // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file\n      s->read_from_callbacks = 0;\n      s->img_buffer = s->buffer_start;\n      s->img_buffer_end = s->buffer_start+1;\n      *s->img_buffer = 0;\n   } else {\n      s->img_buffer = s->buffer_start;\n      s->img_buffer_end = s->buffer_start + n;\n   }\n}\n\nstbi_inline static stbi_uc stbi__get8(stbi__context *s)\n{\n   if (s->img_buffer < s->img_buffer_end)\n      return *s->img_buffer++;\n   if (s->read_from_callbacks) {\n      stbi__refill_buffer(s);\n      return *s->img_buffer++;\n   }\n   return 0;\n}\n\n#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)\n// nothing\n#else\nstbi_inline static int stbi__at_eof(stbi__context *s)\n{\n   if (s->io.read) {\n      if (!(s->io.eof)(s->io_user_data)) return 0;\n      // if feof() is true, check if buffer = end\n      // special case: we've only got the special 0 character at the end\n      if (s->read_from_callbacks == 0) return 1;\n   }\n\n   return s->img_buffer >= s->img_buffer_end;\n}\n#endif\n\n#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC)\n// nothing\n#else\nstatic void stbi__skip(stbi__context *s, int n)\n{\n   if (n == 0) return;  // already there!\n   if (n < 0) {\n      s->img_buffer = s->img_buffer_end;\n      return;\n   }\n   if (s->io.read) {\n      int blen = (int) (s->img_buffer_end - s->img_buffer);\n      if (blen < n) {\n         s->img_buffer = s->img_buffer_end;\n         (s->io.skip)(s->io_user_data, n - blen);\n         return;\n      }\n   }\n   s->img_buffer += n;\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM)\n// nothing\n#else\nstatic int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)\n{\n   if (s->io.read) {\n      int blen = (int) (s->img_buffer_end - s->img_buffer);\n      if (blen < n) {\n         int res, count;\n\n         memcpy(buffer, s->img_buffer, blen);\n\n         count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);\n         res = (count == (n-blen));\n         s->img_buffer = s->img_buffer_end;\n         return res;\n      }\n   }\n\n   if (s->img_buffer+n <= s->img_buffer_end) {\n      memcpy(buffer, s->img_buffer, n);\n      s->img_buffer += n;\n      return 1;\n   } else\n      return 0;\n}\n#endif\n\n#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)\n// nothing\n#else\nstatic int stbi__get16be(stbi__context *s)\n{\n   int z = stbi__get8(s);\n   return (z << 8) + stbi__get8(s);\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)\n// nothing\n#else\nstatic stbi__uint32 stbi__get32be(stbi__context *s)\n{\n   stbi__uint32 z = stbi__get16be(s);\n   return (z << 16) + stbi__get16be(s);\n}\n#endif\n\n#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)\n// nothing\n#else\nstatic int stbi__get16le(stbi__context *s)\n{\n   int z = stbi__get8(s);\n   return z + (stbi__get8(s) << 8);\n}\n#endif\n\n#ifndef STBI_NO_BMP\nstatic stbi__uint32 stbi__get32le(stbi__context *s)\n{\n   stbi__uint32 z = stbi__get16le(s);\n   z += (stbi__uint32)stbi__get16le(s) << 16;\n   return z;\n}\n#endif\n\n#define STBI__BYTECAST(x)  ((stbi_uc) ((x) & 255))  // truncate int to byte without warnings\n\n#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)\n// nothing\n#else\n//////////////////////////////////////////////////////////////////////////////\n//\n//  generic converter from built-in img_n to req_comp\n//    individual types do this automatically as much as possible (e.g. jpeg\n//    does all cases internally since it needs to colorspace convert anyway,\n//    and it never has alpha, so very few cases ). png can automatically\n//    interleave an alpha=255 channel, but falls back to this for other cases\n//\n//  assume data buffer is malloced, so malloc a new one and free that one\n//  only failure mode is malloc failing\n\nstatic stbi_uc stbi__compute_y(int r, int g, int b)\n{\n   return (stbi_uc) (((r*77) + (g*150) +  (29*b)) >> 8);\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)\n// nothing\n#else\nstatic unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)\n{\n   int i,j;\n   unsigned char *good;\n\n   if (req_comp == img_n) return data;\n   STBI_ASSERT(req_comp >= 1 && req_comp <= 4);\n\n   good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);\n   if (good == NULL) {\n      STBI_FREE(data);\n      return stbi__errpuc(\"outofmem\", \"Out of memory\");\n   }\n\n   for (j=0; j < (int) y; ++j) {\n      unsigned char *src  = data + j * x * img_n   ;\n      unsigned char *dest = good + j * x * req_comp;\n\n      #define STBI__COMBO(a,b)  ((a)*8+(b))\n      #define STBI__CASE(a,b)   case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\n      // convert source image with img_n components to one with req_comp components;\n      // avoid switch per pixel, so use switch per scanline and massive macros\n      switch (STBI__COMBO(img_n, req_comp)) {\n         STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255;                                     } break;\n         STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0];                                  } break;\n         STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255;                     } break;\n         STBI__CASE(2,1) { dest[0]=src[0];                                                  } break;\n         STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0];                                  } break;\n         STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1];                  } break;\n         STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255;        } break;\n         STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]);                   } break;\n         STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255;    } break;\n         STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]);                   } break;\n         STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break;\n         STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];                    } break;\n         default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc(\"unsupported\", \"Unsupported format conversion\");\n      }\n      #undef STBI__CASE\n   }\n\n   STBI_FREE(data);\n   return good;\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)\n// nothing\n#else\nstatic stbi__uint16 stbi__compute_y_16(int r, int g, int b)\n{\n   return (stbi__uint16) (((r*77) + (g*150) +  (29*b)) >> 8);\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)\n// nothing\n#else\nstatic stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y)\n{\n   int i,j;\n   stbi__uint16 *good;\n\n   if (req_comp == img_n) return data;\n   STBI_ASSERT(req_comp >= 1 && req_comp <= 4);\n\n   good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2);\n   if (good == NULL) {\n      STBI_FREE(data);\n      return (stbi__uint16 *) stbi__errpuc(\"outofmem\", \"Out of memory\");\n   }\n\n   for (j=0; j < (int) y; ++j) {\n      stbi__uint16 *src  = data + j * x * img_n   ;\n      stbi__uint16 *dest = good + j * x * req_comp;\n\n      #define STBI__COMBO(a,b)  ((a)*8+(b))\n      #define STBI__CASE(a,b)   case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\n      // convert source image with img_n components to one with req_comp components;\n      // avoid switch per pixel, so use switch per scanline and massive macros\n      switch (STBI__COMBO(img_n, req_comp)) {\n         STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff;                                     } break;\n         STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0];                                     } break;\n         STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff;                     } break;\n         STBI__CASE(2,1) { dest[0]=src[0];                                                     } break;\n         STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0];                                     } break;\n         STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1];                     } break;\n         STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff;        } break;\n         STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]);                   } break;\n         STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break;\n         STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]);                   } break;\n         STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break;\n         STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];                       } break;\n         default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc(\"unsupported\", \"Unsupported format conversion\");\n      }\n      #undef STBI__CASE\n   }\n\n   STBI_FREE(data);\n   return good;\n}\n#endif\n\n#ifndef STBI_NO_LINEAR\nstatic float   *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)\n{\n   int i,k,n;\n   float *output;\n   if (!data) return NULL;\n   output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0);\n   if (output == NULL) { STBI_FREE(data); return stbi__errpf(\"outofmem\", \"Out of memory\"); }\n   // compute number of non-alpha components\n   if (comp & 1) n = comp; else n = comp-1;\n   for (i=0; i < x*y; ++i) {\n      for (k=0; k < n; ++k) {\n         output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);\n      }\n   }\n   if (n < comp) {\n      for (i=0; i < x*y; ++i) {\n         output[i*comp + n] = data[i*comp + n]/255.0f;\n      }\n   }\n   STBI_FREE(data);\n   return output;\n}\n#endif\n\n#ifndef STBI_NO_HDR\n#define stbi__float2int(x)   ((int) (x))\nstatic stbi_uc *stbi__hdr_to_ldr(float   *data, int x, int y, int comp)\n{\n   int i,k,n;\n   stbi_uc *output;\n   if (!data) return NULL;\n   output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0);\n   if (output == NULL) { STBI_FREE(data); return stbi__errpuc(\"outofmem\", \"Out of memory\"); }\n   // compute number of non-alpha components\n   if (comp & 1) n = comp; else n = comp-1;\n   for (i=0; i < x*y; ++i) {\n      for (k=0; k < n; ++k) {\n         float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;\n         if (z < 0) z = 0;\n         if (z > 255) z = 255;\n         output[i*comp + k] = (stbi_uc) stbi__float2int(z);\n      }\n      if (k < comp) {\n         float z = data[i*comp+k] * 255 + 0.5f;\n         if (z < 0) z = 0;\n         if (z > 255) z = 255;\n         output[i*comp + k] = (stbi_uc) stbi__float2int(z);\n      }\n   }\n   STBI_FREE(data);\n   return output;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  \"baseline\" JPEG/JFIF decoder\n//\n//    simple implementation\n//      - doesn't support delayed output of y-dimension\n//      - simple interface (only one output format: 8-bit interleaved RGB)\n//      - doesn't try to recover corrupt jpegs\n//      - doesn't allow partial loading, loading multiple at once\n//      - still fast on x86 (copying globals into locals doesn't help x86)\n//      - allocates lots of intermediate memory (full size of all components)\n//        - non-interleaved case requires this anyway\n//        - allows good upsampling (see next)\n//    high-quality\n//      - upsampled channels are bilinearly interpolated, even across blocks\n//      - quality integer IDCT derived from IJG's 'slow'\n//    performance\n//      - fast huffman; reasonable integer IDCT\n//      - some SIMD kernels for common paths on targets with SSE2/NEON\n//      - uses a lot of intermediate memory, could cache poorly\n\n#ifndef STBI_NO_JPEG\n\n// huffman decoding acceleration\n#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache\n\ntypedef struct\n{\n   stbi_uc  fast[1 << FAST_BITS];\n   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win\n   stbi__uint16 code[256];\n   stbi_uc  values[256];\n   stbi_uc  size[257];\n   unsigned int maxcode[18];\n   int    delta[17];   // old 'firstsymbol' - old 'firstcode'\n} stbi__huffman;\n\ntypedef struct\n{\n   stbi__context *s;\n   stbi__huffman huff_dc[4];\n   stbi__huffman huff_ac[4];\n   stbi__uint16 dequant[4][64];\n   stbi__int16 fast_ac[4][1 << FAST_BITS];\n\n// sizes for components, interleaved MCUs\n   int img_h_max, img_v_max;\n   int img_mcu_x, img_mcu_y;\n   int img_mcu_w, img_mcu_h;\n\n// definition of jpeg image component\n   struct\n   {\n      int id;\n      int h,v;\n      int tq;\n      int hd,ha;\n      int dc_pred;\n\n      int x,y,w2,h2;\n      stbi_uc *data;\n      void *raw_data, *raw_coeff;\n      stbi_uc *linebuf;\n      short   *coeff;   // progressive only\n      int      coeff_w, coeff_h; // number of 8x8 coefficient blocks\n   } img_comp[4];\n\n   stbi__uint32   code_buffer; // jpeg entropy-coded buffer\n   int            code_bits;   // number of valid bits\n   unsigned char  marker;      // marker seen while filling entropy buffer\n   int            nomore;      // flag if we saw a marker so must stop\n\n   int            progressive;\n   int            spec_start;\n   int            spec_end;\n   int            succ_high;\n   int            succ_low;\n   int            eob_run;\n   int            jfif;\n   int            app14_color_transform; // Adobe APP14 tag\n   int            rgb;\n\n   int scan_n, order[4];\n   int restart_interval, todo;\n\n// kernels\n   void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]);\n   void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step);\n   stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs);\n} stbi__jpeg;\n\nstatic int stbi__build_huffman(stbi__huffman *h, int *count)\n{\n   int i,j,k=0;\n   unsigned int code;\n   // build size list for each symbol (from JPEG spec)\n   for (i=0; i < 16; ++i) {\n      for (j=0; j < count[i]; ++j) {\n         h->size[k++] = (stbi_uc) (i+1);\n         if(k >= 257) return stbi__err(\"bad size list\",\"Corrupt JPEG\");\n      }\n   }\n   h->size[k] = 0;\n\n   // compute actual symbols (from jpeg spec)\n   code = 0;\n   k = 0;\n   for(j=1; j <= 16; ++j) {\n      // compute delta to add to code to compute symbol id\n      h->delta[j] = k - code;\n      if (h->size[k] == j) {\n         while (h->size[k] == j)\n            h->code[k++] = (stbi__uint16) (code++);\n         if (code-1 >= (1u << j)) return stbi__err(\"bad code lengths\",\"Corrupt JPEG\");\n      }\n      // compute largest code + 1 for this size, preshifted as needed later\n      h->maxcode[j] = code << (16-j);\n      code <<= 1;\n   }\n   h->maxcode[j] = 0xffffffff;\n\n   // build non-spec acceleration table; 255 is flag for not-accelerated\n   memset(h->fast, 255, 1 << FAST_BITS);\n   for (i=0; i < k; ++i) {\n      int s = h->size[i];\n      if (s <= FAST_BITS) {\n         int c = h->code[i] << (FAST_BITS-s);\n         int m = 1 << (FAST_BITS-s);\n         for (j=0; j < m; ++j) {\n            h->fast[c+j] = (stbi_uc) i;\n         }\n      }\n   }\n   return 1;\n}\n\n// build a table that decodes both magnitude and value of small ACs in\n// one go.\nstatic void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)\n{\n   int i;\n   for (i=0; i < (1 << FAST_BITS); ++i) {\n      stbi_uc fast = h->fast[i];\n      fast_ac[i] = 0;\n      if (fast < 255) {\n         int rs = h->values[fast];\n         int run = (rs >> 4) & 15;\n         int magbits = rs & 15;\n         int len = h->size[fast];\n\n         if (magbits && len + magbits <= FAST_BITS) {\n            // magnitude code followed by receive_extend code\n            int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);\n            int m = 1 << (magbits - 1);\n            if (k < m) k += (~0U << magbits) + 1;\n            // if the result is small enough, we can fit it in fast_ac table\n            if (k >= -128 && k <= 127)\n               fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits));\n         }\n      }\n   }\n}\n\nstatic void stbi__grow_buffer_unsafe(stbi__jpeg *j)\n{\n   do {\n      unsigned int b = j->nomore ? 0 : stbi__get8(j->s);\n      if (b == 0xff) {\n         int c = stbi__get8(j->s);\n         while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes\n         if (c != 0) {\n            j->marker = (unsigned char) c;\n            j->nomore = 1;\n            return;\n         }\n      }\n      j->code_buffer |= b << (24 - j->code_bits);\n      j->code_bits += 8;\n   } while (j->code_bits <= 24);\n}\n\n// (1 << n) - 1\nstatic const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};\n\n// decode a jpeg huffman value from the bitstream\nstbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)\n{\n   unsigned int temp;\n   int c,k;\n\n   if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);\n\n   // look at the top FAST_BITS and determine what symbol ID it is,\n   // if the code is <= FAST_BITS\n   c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);\n   k = h->fast[c];\n   if (k < 255) {\n      int s = h->size[k];\n      if (s > j->code_bits)\n         return -1;\n      j->code_buffer <<= s;\n      j->code_bits -= s;\n      return h->values[k];\n   }\n\n   // naive test is to shift the code_buffer down so k bits are\n   // valid, then test against maxcode. To speed this up, we've\n   // preshifted maxcode left so that it has (16-k) 0s at the\n   // end; in other words, regardless of the number of bits, it\n   // wants to be compared against something shifted to have 16;\n   // that way we don't need to shift inside the loop.\n   temp = j->code_buffer >> 16;\n   for (k=FAST_BITS+1 ; ; ++k)\n      if (temp < h->maxcode[k])\n         break;\n   if (k == 17) {\n      // error! code not found\n      j->code_bits -= 16;\n      return -1;\n   }\n\n   if (k > j->code_bits)\n      return -1;\n\n   // convert the huffman code to the symbol id\n   c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];\n   if(c < 0 || c >= 256) // symbol id out of bounds!\n       return -1;\n   STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);\n\n   // convert the id to a symbol\n   j->code_bits -= k;\n   j->code_buffer <<= k;\n   return h->values[c];\n}\n\n// bias[n] = (-1<<n) + 1\nstatic const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767};\n\n// combined JPEG 'receive' and JPEG 'extend', since baseline\n// always extends everything it receives.\nstbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)\n{\n   unsigned int k;\n   int sgn;\n   if (j->code_bits < n) stbi__grow_buffer_unsafe(j);\n   if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing\n\n   sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)\n   k = stbi_lrot(j->code_buffer, n);\n   j->code_buffer = k & ~stbi__bmask[n];\n   k &= stbi__bmask[n];\n   j->code_bits -= n;\n   return k + (stbi__jbias[n] & (sgn - 1));\n}\n\n// get some unsigned bits\nstbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)\n{\n   unsigned int k;\n   if (j->code_bits < n) stbi__grow_buffer_unsafe(j);\n   if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing\n   k = stbi_lrot(j->code_buffer, n);\n   j->code_buffer = k & ~stbi__bmask[n];\n   k &= stbi__bmask[n];\n   j->code_bits -= n;\n   return k;\n}\n\nstbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)\n{\n   unsigned int k;\n   if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);\n   if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing\n   k = j->code_buffer;\n   j->code_buffer <<= 1;\n   --j->code_bits;\n   return k & 0x80000000;\n}\n\n// given a value that's at position X in the zigzag stream,\n// where does it appear in the 8x8 matrix coded as row-major?\nstatic const stbi_uc stbi__jpeg_dezigzag[64+15] =\n{\n    0,  1,  8, 16,  9,  2,  3, 10,\n   17, 24, 32, 25, 18, 11,  4,  5,\n   12, 19, 26, 33, 40, 48, 41, 34,\n   27, 20, 13,  6,  7, 14, 21, 28,\n   35, 42, 49, 56, 57, 50, 43, 36,\n   29, 22, 15, 23, 30, 37, 44, 51,\n   58, 59, 52, 45, 38, 31, 39, 46,\n   53, 60, 61, 54, 47, 55, 62, 63,\n   // let corrupt input sample past end\n   63, 63, 63, 63, 63, 63, 63, 63,\n   63, 63, 63, 63, 63, 63, 63\n};\n\n// decode one 64-entry block--\nstatic int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant)\n{\n   int diff,dc,k;\n   int t;\n\n   if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);\n   t = stbi__jpeg_huff_decode(j, hdc);\n   if (t < 0 || t > 15) return stbi__err(\"bad huffman code\",\"Corrupt JPEG\");\n\n   // 0 all the ac values now so we can do it 32-bits at a time\n   memset(data,0,64*sizeof(data[0]));\n\n   diff = t ? stbi__extend_receive(j, t) : 0;\n   if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err(\"bad delta\",\"Corrupt JPEG\");\n   dc = j->img_comp[b].dc_pred + diff;\n   j->img_comp[b].dc_pred = dc;\n   if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err(\"can't merge dc and ac\", \"Corrupt JPEG\");\n   data[0] = (short) (dc * dequant[0]);\n\n   // decode AC components, see JPEG spec\n   k = 1;\n   do {\n      unsigned int zig;\n      int c,r,s;\n      if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);\n      c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);\n      r = fac[c];\n      if (r) { // fast-AC path\n         k += (r >> 4) & 15; // run\n         s = r & 15; // combined length\n         if (s > j->code_bits) return stbi__err(\"bad huffman code\", \"Combined length longer than code bits available\");\n         j->code_buffer <<= s;\n         j->code_bits -= s;\n         // decode into unzigzag'd location\n         zig = stbi__jpeg_dezigzag[k++];\n         data[zig] = (short) ((r >> 8) * dequant[zig]);\n      } else {\n         int rs = stbi__jpeg_huff_decode(j, hac);\n         if (rs < 0) return stbi__err(\"bad huffman code\",\"Corrupt JPEG\");\n         s = rs & 15;\n         r = rs >> 4;\n         if (s == 0) {\n            if (rs != 0xf0) break; // end block\n            k += 16;\n         } else {\n            k += r;\n            // decode into unzigzag'd location\n            zig = stbi__jpeg_dezigzag[k++];\n            data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]);\n         }\n      }\n   } while (k < 64);\n   return 1;\n}\n\nstatic int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b)\n{\n   int diff,dc;\n   int t;\n   if (j->spec_end != 0) return stbi__err(\"can't merge dc and ac\", \"Corrupt JPEG\");\n\n   if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);\n\n   if (j->succ_high == 0) {\n      // first scan for DC coefficient, must be first\n      memset(data,0,64*sizeof(data[0])); // 0 all the ac values now\n      t = stbi__jpeg_huff_decode(j, hdc);\n      if (t < 0 || t > 15) return stbi__err(\"can't merge dc and ac\", \"Corrupt JPEG\");\n      diff = t ? stbi__extend_receive(j, t) : 0;\n\n      if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err(\"bad delta\", \"Corrupt JPEG\");\n      dc = j->img_comp[b].dc_pred + diff;\n      j->img_comp[b].dc_pred = dc;\n      if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err(\"can't merge dc and ac\", \"Corrupt JPEG\");\n      data[0] = (short) (dc * (1 << j->succ_low));\n   } else {\n      // refinement scan for DC coefficient\n      if (stbi__jpeg_get_bit(j))\n         data[0] += (short) (1 << j->succ_low);\n   }\n   return 1;\n}\n\n// @OPTIMIZE: store non-zigzagged during the decode passes,\n// and only de-zigzag when dequantizing\nstatic int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac)\n{\n   int k;\n   if (j->spec_start == 0) return stbi__err(\"can't merge dc and ac\", \"Corrupt JPEG\");\n\n   if (j->succ_high == 0) {\n      int shift = j->succ_low;\n\n      if (j->eob_run) {\n         --j->eob_run;\n         return 1;\n      }\n\n      k = j->spec_start;\n      do {\n         unsigned int zig;\n         int c,r,s;\n         if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);\n         c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);\n         r = fac[c];\n         if (r) { // fast-AC path\n            k += (r >> 4) & 15; // run\n            s = r & 15; // combined length\n            if (s > j->code_bits) return stbi__err(\"bad huffman code\", \"Combined length longer than code bits available\");\n            j->code_buffer <<= s;\n            j->code_bits -= s;\n            zig = stbi__jpeg_dezigzag[k++];\n            data[zig] = (short) ((r >> 8) * (1 << shift));\n         } else {\n            int rs = stbi__jpeg_huff_decode(j, hac);\n            if (rs < 0) return stbi__err(\"bad huffman code\",\"Corrupt JPEG\");\n            s = rs & 15;\n            r = rs >> 4;\n            if (s == 0) {\n               if (r < 15) {\n                  j->eob_run = (1 << r);\n                  if (r)\n                     j->eob_run += stbi__jpeg_get_bits(j, r);\n                  --j->eob_run;\n                  break;\n               }\n               k += 16;\n            } else {\n               k += r;\n               zig = stbi__jpeg_dezigzag[k++];\n               data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift));\n            }\n         }\n      } while (k <= j->spec_end);\n   } else {\n      // refinement scan for these AC coefficients\n\n      short bit = (short) (1 << j->succ_low);\n\n      if (j->eob_run) {\n         --j->eob_run;\n         for (k = j->spec_start; k <= j->spec_end; ++k) {\n            short *p = &data[stbi__jpeg_dezigzag[k]];\n            if (*p != 0)\n               if (stbi__jpeg_get_bit(j))\n                  if ((*p & bit)==0) {\n                     if (*p > 0)\n                        *p += bit;\n                     else\n                        *p -= bit;\n                  }\n         }\n      } else {\n         k = j->spec_start;\n         do {\n            int r,s;\n            int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh\n            if (rs < 0) return stbi__err(\"bad huffman code\",\"Corrupt JPEG\");\n            s = rs & 15;\n            r = rs >> 4;\n            if (s == 0) {\n               if (r < 15) {\n                  j->eob_run = (1 << r) - 1;\n                  if (r)\n                     j->eob_run += stbi__jpeg_get_bits(j, r);\n                  r = 64; // force end of block\n               } else {\n                  // r=15 s=0 should write 16 0s, so we just do\n                  // a run of 15 0s and then write s (which is 0),\n                  // so we don't have to do anything special here\n               }\n            } else {\n               if (s != 1) return stbi__err(\"bad huffman code\", \"Corrupt JPEG\");\n               // sign bit\n               if (stbi__jpeg_get_bit(j))\n                  s = bit;\n               else\n                  s = -bit;\n            }\n\n            // advance by r\n            while (k <= j->spec_end) {\n               short *p = &data[stbi__jpeg_dezigzag[k++]];\n               if (*p != 0) {\n                  if (stbi__jpeg_get_bit(j))\n                     if ((*p & bit)==0) {\n                        if (*p > 0)\n                           *p += bit;\n                        else\n                           *p -= bit;\n                     }\n               } else {\n                  if (r == 0) {\n                     *p = (short) s;\n                     break;\n                  }\n                  --r;\n               }\n            }\n         } while (k <= j->spec_end);\n      }\n   }\n   return 1;\n}\n\n// take a -128..127 value and stbi__clamp it and convert to 0..255\nstbi_inline static stbi_uc stbi__clamp(int x)\n{\n   // trick to use a single test to catch both cases\n   if ((unsigned int) x > 255) {\n      if (x < 0) return 0;\n      if (x > 255) return 255;\n   }\n   return (stbi_uc) x;\n}\n\n#define stbi__f2f(x)  ((int) (((x) * 4096 + 0.5)))\n#define stbi__fsh(x)  ((x) * 4096)\n\n// derived from jidctint -- DCT_ISLOW\n#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \\\n   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \\\n   p2 = s2;                                    \\\n   p3 = s6;                                    \\\n   p1 = (p2+p3) * stbi__f2f(0.5411961f);       \\\n   t2 = p1 + p3*stbi__f2f(-1.847759065f);      \\\n   t3 = p1 + p2*stbi__f2f( 0.765366865f);      \\\n   p2 = s0;                                    \\\n   p3 = s4;                                    \\\n   t0 = stbi__fsh(p2+p3);                      \\\n   t1 = stbi__fsh(p2-p3);                      \\\n   x0 = t0+t3;                                 \\\n   x3 = t0-t3;                                 \\\n   x1 = t1+t2;                                 \\\n   x2 = t1-t2;                                 \\\n   t0 = s7;                                    \\\n   t1 = s5;                                    \\\n   t2 = s3;                                    \\\n   t3 = s1;                                    \\\n   p3 = t0+t2;                                 \\\n   p4 = t1+t3;                                 \\\n   p1 = t0+t3;                                 \\\n   p2 = t1+t2;                                 \\\n   p5 = (p3+p4)*stbi__f2f( 1.175875602f);      \\\n   t0 = t0*stbi__f2f( 0.298631336f);           \\\n   t1 = t1*stbi__f2f( 2.053119869f);           \\\n   t2 = t2*stbi__f2f( 3.072711026f);           \\\n   t3 = t3*stbi__f2f( 1.501321110f);           \\\n   p1 = p5 + p1*stbi__f2f(-0.899976223f);      \\\n   p2 = p5 + p2*stbi__f2f(-2.562915447f);      \\\n   p3 = p3*stbi__f2f(-1.961570560f);           \\\n   p4 = p4*stbi__f2f(-0.390180644f);           \\\n   t3 += p1+p4;                                \\\n   t2 += p2+p3;                                \\\n   t1 += p2+p4;                                \\\n   t0 += p1+p3;\n\nstatic void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])\n{\n   int i,val[64],*v=val;\n   stbi_uc *o;\n   short *d = data;\n\n   // columns\n   for (i=0; i < 8; ++i,++d, ++v) {\n      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\n      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\n           && d[40]==0 && d[48]==0 && d[56]==0) {\n         //    no shortcut                 0     seconds\n         //    (1|2|3|4|5|6|7)==0          0     seconds\n         //    all separate               -0.047 seconds\n         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\n         int dcterm = d[0]*4;\n         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\n      } else {\n         STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56])\n         // constants scaled things up by 1<<12; let's bring them back\n         // down, but keep 2 extra bits of precision\n         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\n         v[ 0] = (x0+t3) >> 10;\n         v[56] = (x0-t3) >> 10;\n         v[ 8] = (x1+t2) >> 10;\n         v[48] = (x1-t2) >> 10;\n         v[16] = (x2+t1) >> 10;\n         v[40] = (x2-t1) >> 10;\n         v[24] = (x3+t0) >> 10;\n         v[32] = (x3-t0) >> 10;\n      }\n   }\n\n   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\n      // no fast case since the first 1D IDCT spread components out\n      STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\n      // constants scaled things up by 1<<12, plus we had 1<<2 from first\n      // loop, plus horizontal and vertical each scale by sqrt(8) so together\n      // we've got an extra 1<<3, so 1<<17 total we need to remove.\n      // so we want to round that, which means adding 0.5 * 1<<17,\n      // aka 65536. Also, we'll end up with -128 to 127 that we want\n      // to encode as 0..255 by adding 128, so we'll add that before the shift\n      x0 += 65536 + (128<<17);\n      x1 += 65536 + (128<<17);\n      x2 += 65536 + (128<<17);\n      x3 += 65536 + (128<<17);\n      // tried computing the shifts into temps, or'ing the temps to see\n      // if any were out of range, but that was slower\n      o[0] = stbi__clamp((x0+t3) >> 17);\n      o[7] = stbi__clamp((x0-t3) >> 17);\n      o[1] = stbi__clamp((x1+t2) >> 17);\n      o[6] = stbi__clamp((x1-t2) >> 17);\n      o[2] = stbi__clamp((x2+t1) >> 17);\n      o[5] = stbi__clamp((x2-t1) >> 17);\n      o[3] = stbi__clamp((x3+t0) >> 17);\n      o[4] = stbi__clamp((x3-t0) >> 17);\n   }\n}\n\n#ifdef STBI_SSE2\n// sse2 integer IDCT. not the fastest possible implementation but it\n// produces bit-identical results to the generic C version so it's\n// fully \"transparent\".\nstatic void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])\n{\n   // This is constructed to match our regular (generic) integer IDCT exactly.\n   __m128i row0, row1, row2, row3, row4, row5, row6, row7;\n   __m128i tmp;\n\n   // dot product constant: even elems=x, odd elems=y\n   #define dct_const(x,y)  _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y))\n\n   // out(0) = c0[even]*x + c0[odd]*y   (c0, x, y 16-bit, out 32-bit)\n   // out(1) = c1[even]*x + c1[odd]*y\n   #define dct_rot(out0,out1, x,y,c0,c1) \\\n      __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \\\n      __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \\\n      __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \\\n      __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \\\n      __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \\\n      __m128i out1##_h = _mm_madd_epi16(c0##hi, c1)\n\n   // out = in << 12  (in 16-bit, out 32-bit)\n   #define dct_widen(out, in) \\\n      __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \\\n      __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)\n\n   // wide add\n   #define dct_wadd(out, a, b) \\\n      __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \\\n      __m128i out##_h = _mm_add_epi32(a##_h, b##_h)\n\n   // wide sub\n   #define dct_wsub(out, a, b) \\\n      __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \\\n      __m128i out##_h = _mm_sub_epi32(a##_h, b##_h)\n\n   // butterfly a/b, add bias, then shift by \"s\" and pack\n   #define dct_bfly32o(out0, out1, a,b,bias,s) \\\n      { \\\n         __m128i abiased_l = _mm_add_epi32(a##_l, bias); \\\n         __m128i abiased_h = _mm_add_epi32(a##_h, bias); \\\n         dct_wadd(sum, abiased, b); \\\n         dct_wsub(dif, abiased, b); \\\n         out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \\\n         out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \\\n      }\n\n   // 8-bit interleave step (for transposes)\n   #define dct_interleave8(a, b) \\\n      tmp = a; \\\n      a = _mm_unpacklo_epi8(a, b); \\\n      b = _mm_unpackhi_epi8(tmp, b)\n\n   // 16-bit interleave step (for transposes)\n   #define dct_interleave16(a, b) \\\n      tmp = a; \\\n      a = _mm_unpacklo_epi16(a, b); \\\n      b = _mm_unpackhi_epi16(tmp, b)\n\n   #define dct_pass(bias,shift) \\\n      { \\\n         /* even part */ \\\n         dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \\\n         __m128i sum04 = _mm_add_epi16(row0, row4); \\\n         __m128i dif04 = _mm_sub_epi16(row0, row4); \\\n         dct_widen(t0e, sum04); \\\n         dct_widen(t1e, dif04); \\\n         dct_wadd(x0, t0e, t3e); \\\n         dct_wsub(x3, t0e, t3e); \\\n         dct_wadd(x1, t1e, t2e); \\\n         dct_wsub(x2, t1e, t2e); \\\n         /* odd part */ \\\n         dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \\\n         dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \\\n         __m128i sum17 = _mm_add_epi16(row1, row7); \\\n         __m128i sum35 = _mm_add_epi16(row3, row5); \\\n         dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \\\n         dct_wadd(x4, y0o, y4o); \\\n         dct_wadd(x5, y1o, y5o); \\\n         dct_wadd(x6, y2o, y5o); \\\n         dct_wadd(x7, y3o, y4o); \\\n         dct_bfly32o(row0,row7, x0,x7,bias,shift); \\\n         dct_bfly32o(row1,row6, x1,x6,bias,shift); \\\n         dct_bfly32o(row2,row5, x2,x5,bias,shift); \\\n         dct_bfly32o(row3,row4, x3,x4,bias,shift); \\\n      }\n\n   __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));\n   __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f));\n   __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));\n   __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));\n   __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f));\n   __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f));\n   __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f));\n   __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f));\n\n   // rounding biases in column/row passes, see stbi__idct_block for explanation.\n   __m128i bias_0 = _mm_set1_epi32(512);\n   __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17));\n\n   // load\n   row0 = _mm_load_si128((const __m128i *) (data + 0*8));\n   row1 = _mm_load_si128((const __m128i *) (data + 1*8));\n   row2 = _mm_load_si128((const __m128i *) (data + 2*8));\n   row3 = _mm_load_si128((const __m128i *) (data + 3*8));\n   row4 = _mm_load_si128((const __m128i *) (data + 4*8));\n   row5 = _mm_load_si128((const __m128i *) (data + 5*8));\n   row6 = _mm_load_si128((const __m128i *) (data + 6*8));\n   row7 = _mm_load_si128((const __m128i *) (data + 7*8));\n\n   // column pass\n   dct_pass(bias_0, 10);\n\n   {\n      // 16bit 8x8 transpose pass 1\n      dct_interleave16(row0, row4);\n      dct_interleave16(row1, row5);\n      dct_interleave16(row2, row6);\n      dct_interleave16(row3, row7);\n\n      // transpose pass 2\n      dct_interleave16(row0, row2);\n      dct_interleave16(row1, row3);\n      dct_interleave16(row4, row6);\n      dct_interleave16(row5, row7);\n\n      // transpose pass 3\n      dct_interleave16(row0, row1);\n      dct_interleave16(row2, row3);\n      dct_interleave16(row4, row5);\n      dct_interleave16(row6, row7);\n   }\n\n   // row pass\n   dct_pass(bias_1, 17);\n\n   {\n      // pack\n      __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7\n      __m128i p1 = _mm_packus_epi16(row2, row3);\n      __m128i p2 = _mm_packus_epi16(row4, row5);\n      __m128i p3 = _mm_packus_epi16(row6, row7);\n\n      // 8bit 8x8 transpose pass 1\n      dct_interleave8(p0, p2); // a0e0a1e1...\n      dct_interleave8(p1, p3); // c0g0c1g1...\n\n      // transpose pass 2\n      dct_interleave8(p0, p1); // a0c0e0g0...\n      dct_interleave8(p2, p3); // b0d0f0h0...\n\n      // transpose pass 3\n      dct_interleave8(p0, p2); // a0b0c0d0...\n      dct_interleave8(p1, p3); // a4b4c4d4...\n\n      // store\n      _mm_storel_epi64((__m128i *) out, p0); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, p2); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, p1); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, p3); out += out_stride;\n      _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e));\n   }\n\n#undef dct_const\n#undef dct_rot\n#undef dct_widen\n#undef dct_wadd\n#undef dct_wsub\n#undef dct_bfly32o\n#undef dct_interleave8\n#undef dct_interleave16\n#undef dct_pass\n}\n\n#endif // STBI_SSE2\n\n#ifdef STBI_NEON\n\n// NEON integer IDCT. should produce bit-identical\n// results to the generic C version.\nstatic void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])\n{\n   int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;\n\n   int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));\n   int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));\n   int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f));\n   int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f));\n   int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));\n   int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));\n   int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));\n   int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));\n   int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f));\n   int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f));\n   int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f));\n   int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f));\n\n#define dct_long_mul(out, inq, coeff) \\\n   int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \\\n   int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)\n\n#define dct_long_mac(out, acc, inq, coeff) \\\n   int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \\\n   int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)\n\n#define dct_widen(out, inq) \\\n   int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \\\n   int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)\n\n// wide add\n#define dct_wadd(out, a, b) \\\n   int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \\\n   int32x4_t out##_h = vaddq_s32(a##_h, b##_h)\n\n// wide sub\n#define dct_wsub(out, a, b) \\\n   int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \\\n   int32x4_t out##_h = vsubq_s32(a##_h, b##_h)\n\n// butterfly a/b, then shift using \"shiftop\" by \"s\" and pack\n#define dct_bfly32o(out0,out1, a,b,shiftop,s) \\\n   { \\\n      dct_wadd(sum, a, b); \\\n      dct_wsub(dif, a, b); \\\n      out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \\\n      out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \\\n   }\n\n#define dct_pass(shiftop, shift) \\\n   { \\\n      /* even part */ \\\n      int16x8_t sum26 = vaddq_s16(row2, row6); \\\n      dct_long_mul(p1e, sum26, rot0_0); \\\n      dct_long_mac(t2e, p1e, row6, rot0_1); \\\n      dct_long_mac(t3e, p1e, row2, rot0_2); \\\n      int16x8_t sum04 = vaddq_s16(row0, row4); \\\n      int16x8_t dif04 = vsubq_s16(row0, row4); \\\n      dct_widen(t0e, sum04); \\\n      dct_widen(t1e, dif04); \\\n      dct_wadd(x0, t0e, t3e); \\\n      dct_wsub(x3, t0e, t3e); \\\n      dct_wadd(x1, t1e, t2e); \\\n      dct_wsub(x2, t1e, t2e); \\\n      /* odd part */ \\\n      int16x8_t sum15 = vaddq_s16(row1, row5); \\\n      int16x8_t sum17 = vaddq_s16(row1, row7); \\\n      int16x8_t sum35 = vaddq_s16(row3, row5); \\\n      int16x8_t sum37 = vaddq_s16(row3, row7); \\\n      int16x8_t sumodd = vaddq_s16(sum17, sum35); \\\n      dct_long_mul(p5o, sumodd, rot1_0); \\\n      dct_long_mac(p1o, p5o, sum17, rot1_1); \\\n      dct_long_mac(p2o, p5o, sum35, rot1_2); \\\n      dct_long_mul(p3o, sum37, rot2_0); \\\n      dct_long_mul(p4o, sum15, rot2_1); \\\n      dct_wadd(sump13o, p1o, p3o); \\\n      dct_wadd(sump24o, p2o, p4o); \\\n      dct_wadd(sump23o, p2o, p3o); \\\n      dct_wadd(sump14o, p1o, p4o); \\\n      dct_long_mac(x4, sump13o, row7, rot3_0); \\\n      dct_long_mac(x5, sump24o, row5, rot3_1); \\\n      dct_long_mac(x6, sump23o, row3, rot3_2); \\\n      dct_long_mac(x7, sump14o, row1, rot3_3); \\\n      dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \\\n      dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \\\n      dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \\\n      dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \\\n   }\n\n   // load\n   row0 = vld1q_s16(data + 0*8);\n   row1 = vld1q_s16(data + 1*8);\n   row2 = vld1q_s16(data + 2*8);\n   row3 = vld1q_s16(data + 3*8);\n   row4 = vld1q_s16(data + 4*8);\n   row5 = vld1q_s16(data + 5*8);\n   row6 = vld1q_s16(data + 6*8);\n   row7 = vld1q_s16(data + 7*8);\n\n   // add DC bias\n   row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));\n\n   // column pass\n   dct_pass(vrshrn_n_s32, 10);\n\n   // 16bit 8x8 transpose\n   {\n// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.\n// whether compilers actually get this is another story, sadly.\n#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; }\n#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); }\n#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); }\n\n      // pass 1\n      dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6\n      dct_trn16(row2, row3);\n      dct_trn16(row4, row5);\n      dct_trn16(row6, row7);\n\n      // pass 2\n      dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4\n      dct_trn32(row1, row3);\n      dct_trn32(row4, row6);\n      dct_trn32(row5, row7);\n\n      // pass 3\n      dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0\n      dct_trn64(row1, row5);\n      dct_trn64(row2, row6);\n      dct_trn64(row3, row7);\n\n#undef dct_trn16\n#undef dct_trn32\n#undef dct_trn64\n   }\n\n   // row pass\n   // vrshrn_n_s32 only supports shifts up to 16, we need\n   // 17. so do a non-rounding shift of 16 first then follow\n   // up with a rounding shift by 1.\n   dct_pass(vshrn_n_s32, 16);\n\n   {\n      // pack and round\n      uint8x8_t p0 = vqrshrun_n_s16(row0, 1);\n      uint8x8_t p1 = vqrshrun_n_s16(row1, 1);\n      uint8x8_t p2 = vqrshrun_n_s16(row2, 1);\n      uint8x8_t p3 = vqrshrun_n_s16(row3, 1);\n      uint8x8_t p4 = vqrshrun_n_s16(row4, 1);\n      uint8x8_t p5 = vqrshrun_n_s16(row5, 1);\n      uint8x8_t p6 = vqrshrun_n_s16(row6, 1);\n      uint8x8_t p7 = vqrshrun_n_s16(row7, 1);\n\n      // again, these can translate into one instruction, but often don't.\n#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; }\n#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); }\n#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); }\n\n      // sadly can't use interleaved stores here since we only write\n      // 8 bytes to each scan line!\n\n      // 8x8 8-bit transpose pass 1\n      dct_trn8_8(p0, p1);\n      dct_trn8_8(p2, p3);\n      dct_trn8_8(p4, p5);\n      dct_trn8_8(p6, p7);\n\n      // pass 2\n      dct_trn8_16(p0, p2);\n      dct_trn8_16(p1, p3);\n      dct_trn8_16(p4, p6);\n      dct_trn8_16(p5, p7);\n\n      // pass 3\n      dct_trn8_32(p0, p4);\n      dct_trn8_32(p1, p5);\n      dct_trn8_32(p2, p6);\n      dct_trn8_32(p3, p7);\n\n      // store\n      vst1_u8(out, p0); out += out_stride;\n      vst1_u8(out, p1); out += out_stride;\n      vst1_u8(out, p2); out += out_stride;\n      vst1_u8(out, p3); out += out_stride;\n      vst1_u8(out, p4); out += out_stride;\n      vst1_u8(out, p5); out += out_stride;\n      vst1_u8(out, p6); out += out_stride;\n      vst1_u8(out, p7);\n\n#undef dct_trn8_8\n#undef dct_trn8_16\n#undef dct_trn8_32\n   }\n\n#undef dct_long_mul\n#undef dct_long_mac\n#undef dct_widen\n#undef dct_wadd\n#undef dct_wsub\n#undef dct_bfly32o\n#undef dct_pass\n}\n\n#endif // STBI_NEON\n\n#define STBI__MARKER_none  0xff\n// if there's a pending marker from the entropy stream, return that\n// otherwise, fetch from the stream and get a marker. if there's no\n// marker, return 0xff, which is never a valid marker value\nstatic stbi_uc stbi__get_marker(stbi__jpeg *j)\n{\n   stbi_uc x;\n   if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }\n   x = stbi__get8(j->s);\n   if (x != 0xff) return STBI__MARKER_none;\n   while (x == 0xff)\n      x = stbi__get8(j->s); // consume repeated 0xff fill bytes\n   return x;\n}\n\n// in each scan, we'll have scan_n components, and the order\n// of the components is specified by order[]\n#define STBI__RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)\n\n// after a restart interval, stbi__jpeg_reset the entropy decoder and\n// the dc prediction\nstatic void stbi__jpeg_reset(stbi__jpeg *j)\n{\n   j->code_bits = 0;\n   j->code_buffer = 0;\n   j->nomore = 0;\n   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0;\n   j->marker = STBI__MARKER_none;\n   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;\n   j->eob_run = 0;\n   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,\n   // since we don't even allow 1<<30 pixels\n}\n\nstatic int stbi__parse_entropy_coded_data(stbi__jpeg *z)\n{\n   stbi__jpeg_reset(z);\n   if (!z->progressive) {\n      if (z->scan_n == 1) {\n         int i,j;\n         STBI_SIMD_ALIGN(short, data[64]);\n         int n = z->order[0];\n         // non-interleaved data, we just need to process one block at a time,\n         // in trivial scanline order\n         // number of blocks to do just depends on how many actual \"pixels\" this\n         // component has, independent of interleaved MCU blocking and such\n         int w = (z->img_comp[n].x+7) >> 3;\n         int h = (z->img_comp[n].y+7) >> 3;\n         for (j=0; j < h; ++j) {\n            for (i=0; i < w; ++i) {\n               int ha = z->img_comp[n].ha;\n               if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;\n               z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);\n               // every data block is an MCU, so countdown the restart interval\n               if (--z->todo <= 0) {\n                  if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);\n                  // if it's NOT a restart, then just bail, so we get corrupt data\n                  // rather than no data\n                  if (!STBI__RESTART(z->marker)) return 1;\n                  stbi__jpeg_reset(z);\n               }\n            }\n         }\n         return 1;\n      } else { // interleaved\n         int i,j,k,x,y;\n         STBI_SIMD_ALIGN(short, data[64]);\n         for (j=0; j < z->img_mcu_y; ++j) {\n            for (i=0; i < z->img_mcu_x; ++i) {\n               // scan an interleaved mcu... process scan_n components in order\n               for (k=0; k < z->scan_n; ++k) {\n                  int n = z->order[k];\n                  // scan out an mcu's worth of this component; that's just determined\n                  // by the basic H and V specified for the component\n                  for (y=0; y < z->img_comp[n].v; ++y) {\n                     for (x=0; x < z->img_comp[n].h; ++x) {\n                        int x2 = (i*z->img_comp[n].h + x)*8;\n                        int y2 = (j*z->img_comp[n].v + y)*8;\n                        int ha = z->img_comp[n].ha;\n                        if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;\n                        z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data);\n                     }\n                  }\n               }\n               // after all interleaved components, that's an interleaved MCU,\n               // so now count down the restart interval\n               if (--z->todo <= 0) {\n                  if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);\n                  if (!STBI__RESTART(z->marker)) return 1;\n                  stbi__jpeg_reset(z);\n               }\n            }\n         }\n         return 1;\n      }\n   } else {\n      if (z->scan_n == 1) {\n         int i,j;\n         int n = z->order[0];\n         // non-interleaved data, we just need to process one block at a time,\n         // in trivial scanline order\n         // number of blocks to do just depends on how many actual \"pixels\" this\n         // component has, independent of interleaved MCU blocking and such\n         int w = (z->img_comp[n].x+7) >> 3;\n         int h = (z->img_comp[n].y+7) >> 3;\n         for (j=0; j < h; ++j) {\n            for (i=0; i < w; ++i) {\n               short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);\n               if (z->spec_start == 0) {\n                  if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))\n                     return 0;\n               } else {\n                  int ha = z->img_comp[n].ha;\n                  if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))\n                     return 0;\n               }\n               // every data block is an MCU, so countdown the restart interval\n               if (--z->todo <= 0) {\n                  if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);\n                  if (!STBI__RESTART(z->marker)) return 1;\n                  stbi__jpeg_reset(z);\n               }\n            }\n         }\n         return 1;\n      } else { // interleaved\n         int i,j,k,x,y;\n         for (j=0; j < z->img_mcu_y; ++j) {\n            for (i=0; i < z->img_mcu_x; ++i) {\n               // scan an interleaved mcu... process scan_n components in order\n               for (k=0; k < z->scan_n; ++k) {\n                  int n = z->order[k];\n                  // scan out an mcu's worth of this component; that's just determined\n                  // by the basic H and V specified for the component\n                  for (y=0; y < z->img_comp[n].v; ++y) {\n                     for (x=0; x < z->img_comp[n].h; ++x) {\n                        int x2 = (i*z->img_comp[n].h + x);\n                        int y2 = (j*z->img_comp[n].v + y);\n                        short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);\n                        if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))\n                           return 0;\n                     }\n                  }\n               }\n               // after all interleaved components, that's an interleaved MCU,\n               // so now count down the restart interval\n               if (--z->todo <= 0) {\n                  if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);\n                  if (!STBI__RESTART(z->marker)) return 1;\n                  stbi__jpeg_reset(z);\n               }\n            }\n         }\n         return 1;\n      }\n   }\n}\n\nstatic void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant)\n{\n   int i;\n   for (i=0; i < 64; ++i)\n      data[i] *= dequant[i];\n}\n\nstatic void stbi__jpeg_finish(stbi__jpeg *z)\n{\n   if (z->progressive) {\n      // dequantize and idct the data\n      int i,j,n;\n      for (n=0; n < z->s->img_n; ++n) {\n         int w = (z->img_comp[n].x+7) >> 3;\n         int h = (z->img_comp[n].y+7) >> 3;\n         for (j=0; j < h; ++j) {\n            for (i=0; i < w; ++i) {\n               short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);\n               stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);\n               z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);\n            }\n         }\n      }\n   }\n}\n\nstatic int stbi__process_marker(stbi__jpeg *z, int m)\n{\n   int L;\n   switch (m) {\n      case STBI__MARKER_none: // no marker found\n         return stbi__err(\"expected marker\",\"Corrupt JPEG\");\n\n      case 0xDD: // DRI - specify restart interval\n         if (stbi__get16be(z->s) != 4) return stbi__err(\"bad DRI len\",\"Corrupt JPEG\");\n         z->restart_interval = stbi__get16be(z->s);\n         return 1;\n\n      case 0xDB: // DQT - define quantization table\n         L = stbi__get16be(z->s)-2;\n         while (L > 0) {\n            int q = stbi__get8(z->s);\n            int p = q >> 4, sixteen = (p != 0);\n            int t = q & 15,i;\n            if (p != 0 && p != 1) return stbi__err(\"bad DQT type\",\"Corrupt JPEG\");\n            if (t > 3) return stbi__err(\"bad DQT table\",\"Corrupt JPEG\");\n\n            for (i=0; i < 64; ++i)\n               z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));\n            L -= (sixteen ? 129 : 65);\n         }\n         return L==0;\n\n      case 0xC4: // DHT - define huffman table\n         L = stbi__get16be(z->s)-2;\n         while (L > 0) {\n            stbi_uc *v;\n            int sizes[16],i,n=0;\n            int q = stbi__get8(z->s);\n            int tc = q >> 4;\n            int th = q & 15;\n            if (tc > 1 || th > 3) return stbi__err(\"bad DHT header\",\"Corrupt JPEG\");\n            for (i=0; i < 16; ++i) {\n               sizes[i] = stbi__get8(z->s);\n               n += sizes[i];\n            }\n            if(n > 256) return stbi__err(\"bad DHT header\",\"Corrupt JPEG\"); // Loop over i < n would write past end of values!\n            L -= 17;\n            if (tc == 0) {\n               if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;\n               v = z->huff_dc[th].values;\n            } else {\n               if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;\n               v = z->huff_ac[th].values;\n            }\n            for (i=0; i < n; ++i)\n               v[i] = stbi__get8(z->s);\n            if (tc != 0)\n               stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);\n            L -= n;\n         }\n         return L==0;\n   }\n\n   // check for comment block or APP blocks\n   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {\n      L = stbi__get16be(z->s);\n      if (L < 2) {\n         if (m == 0xFE)\n            return stbi__err(\"bad COM len\",\"Corrupt JPEG\");\n         else\n            return stbi__err(\"bad APP len\",\"Corrupt JPEG\");\n      }\n      L -= 2;\n\n      if (m == 0xE0 && L >= 5) { // JFIF APP0 segment\n         static const unsigned char tag[5] = {'J','F','I','F','\\0'};\n         int ok = 1;\n         int i;\n         for (i=0; i < 5; ++i)\n            if (stbi__get8(z->s) != tag[i])\n               ok = 0;\n         L -= 5;\n         if (ok)\n            z->jfif = 1;\n      } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment\n         static const unsigned char tag[6] = {'A','d','o','b','e','\\0'};\n         int ok = 1;\n         int i;\n         for (i=0; i < 6; ++i)\n            if (stbi__get8(z->s) != tag[i])\n               ok = 0;\n         L -= 6;\n         if (ok) {\n            stbi__get8(z->s); // version\n            stbi__get16be(z->s); // flags0\n            stbi__get16be(z->s); // flags1\n            z->app14_color_transform = stbi__get8(z->s); // color transform\n            L -= 6;\n         }\n      }\n\n      stbi__skip(z->s, L);\n      return 1;\n   }\n\n   return stbi__err(\"unknown marker\",\"Corrupt JPEG\");\n}\n\n// after we see SOS\nstatic int stbi__process_scan_header(stbi__jpeg *z)\n{\n   int i;\n   int Ls = stbi__get16be(z->s);\n   z->scan_n = stbi__get8(z->s);\n   if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err(\"bad SOS component count\",\"Corrupt JPEG\");\n   if (Ls != 6+2*z->scan_n) return stbi__err(\"bad SOS len\",\"Corrupt JPEG\");\n   for (i=0; i < z->scan_n; ++i) {\n      int id = stbi__get8(z->s), which;\n      int q = stbi__get8(z->s);\n      for (which = 0; which < z->s->img_n; ++which)\n         if (z->img_comp[which].id == id)\n            break;\n      if (which == z->s->img_n) return 0; // no match\n      z->img_comp[which].hd = q >> 4;   if (z->img_comp[which].hd > 3) return stbi__err(\"bad DC huff\",\"Corrupt JPEG\");\n      z->img_comp[which].ha = q & 15;   if (z->img_comp[which].ha > 3) return stbi__err(\"bad AC huff\",\"Corrupt JPEG\");\n      z->order[i] = which;\n   }\n\n   {\n      int aa;\n      z->spec_start = stbi__get8(z->s);\n      z->spec_end   = stbi__get8(z->s); // should be 63, but might be 0\n      aa = stbi__get8(z->s);\n      z->succ_high = (aa >> 4);\n      z->succ_low  = (aa & 15);\n      if (z->progressive) {\n         if (z->spec_start > 63 || z->spec_end > 63  || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)\n            return stbi__err(\"bad SOS\", \"Corrupt JPEG\");\n      } else {\n         if (z->spec_start != 0) return stbi__err(\"bad SOS\",\"Corrupt JPEG\");\n         if (z->succ_high != 0 || z->succ_low != 0) return stbi__err(\"bad SOS\",\"Corrupt JPEG\");\n         z->spec_end = 63;\n      }\n   }\n\n   return 1;\n}\n\nstatic int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why)\n{\n   int i;\n   for (i=0; i < ncomp; ++i) {\n      if (z->img_comp[i].raw_data) {\n         STBI_FREE(z->img_comp[i].raw_data);\n         z->img_comp[i].raw_data = NULL;\n         z->img_comp[i].data = NULL;\n      }\n      if (z->img_comp[i].raw_coeff) {\n         STBI_FREE(z->img_comp[i].raw_coeff);\n         z->img_comp[i].raw_coeff = 0;\n         z->img_comp[i].coeff = 0;\n      }\n      if (z->img_comp[i].linebuf) {\n         STBI_FREE(z->img_comp[i].linebuf);\n         z->img_comp[i].linebuf = NULL;\n      }\n   }\n   return why;\n}\n\nstatic int stbi__process_frame_header(stbi__jpeg *z, int scan)\n{\n   stbi__context *s = z->s;\n   int Lf,p,i,q, h_max=1,v_max=1,c;\n   Lf = stbi__get16be(s);         if (Lf < 11) return stbi__err(\"bad SOF len\",\"Corrupt JPEG\"); // JPEG\n   p  = stbi__get8(s);            if (p != 8) return stbi__err(\"only 8-bit\",\"JPEG format not supported: 8-bit only\"); // JPEG baseline\n   s->img_y = stbi__get16be(s);   if (s->img_y == 0) return stbi__err(\"no header height\", \"JPEG format not supported: delayed height\"); // Legal, but we don't handle it--but neither does IJG\n   s->img_x = stbi__get16be(s);   if (s->img_x == 0) return stbi__err(\"0 width\",\"Corrupt JPEG\"); // JPEG requires\n   if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err(\"too large\",\"Very large image (corrupt?)\");\n   if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err(\"too large\",\"Very large image (corrupt?)\");\n   c = stbi__get8(s);\n   if (c != 3 && c != 1 && c != 4) return stbi__err(\"bad component count\",\"Corrupt JPEG\");\n   s->img_n = c;\n   for (i=0; i < c; ++i) {\n      z->img_comp[i].data = NULL;\n      z->img_comp[i].linebuf = NULL;\n   }\n\n   if (Lf != 8+3*s->img_n) return stbi__err(\"bad SOF len\",\"Corrupt JPEG\");\n\n   z->rgb = 0;\n   for (i=0; i < s->img_n; ++i) {\n      static const unsigned char rgb[3] = { 'R', 'G', 'B' };\n      z->img_comp[i].id = stbi__get8(s);\n      if (s->img_n == 3 && z->img_comp[i].id == rgb[i])\n         ++z->rgb;\n      q = stbi__get8(s);\n      z->img_comp[i].h = (q >> 4);  if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err(\"bad H\",\"Corrupt JPEG\");\n      z->img_comp[i].v = q & 15;    if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err(\"bad V\",\"Corrupt JPEG\");\n      z->img_comp[i].tq = stbi__get8(s);  if (z->img_comp[i].tq > 3) return stbi__err(\"bad TQ\",\"Corrupt JPEG\");\n   }\n\n   if (scan != STBI__SCAN_load) return 1;\n\n   if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err(\"too large\", \"Image too large to decode\");\n\n   for (i=0; i < s->img_n; ++i) {\n      if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;\n      if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;\n   }\n\n   // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios\n   // and I've never seen a non-corrupted JPEG file actually use them\n   for (i=0; i < s->img_n; ++i) {\n      if (h_max % z->img_comp[i].h != 0) return stbi__err(\"bad H\",\"Corrupt JPEG\");\n      if (v_max % z->img_comp[i].v != 0) return stbi__err(\"bad V\",\"Corrupt JPEG\");\n   }\n\n   // compute interleaved mcu info\n   z->img_h_max = h_max;\n   z->img_v_max = v_max;\n   z->img_mcu_w = h_max * 8;\n   z->img_mcu_h = v_max * 8;\n   // these sizes can't be more than 17 bits\n   z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;\n   z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;\n\n   for (i=0; i < s->img_n; ++i) {\n      // number of effective pixels (e.g. for non-interleaved MCU)\n      z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;\n      z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;\n      // to simplify generation, we'll allocate enough memory to decode\n      // the bogus oversized data from using interleaved MCUs and their\n      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't\n      // discard the extra data until colorspace conversion\n      //\n      // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)\n      // so these muls can't overflow with 32-bit ints (which we require)\n      z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;\n      z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;\n      z->img_comp[i].coeff = 0;\n      z->img_comp[i].raw_coeff = 0;\n      z->img_comp[i].linebuf = NULL;\n      z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);\n      if (z->img_comp[i].raw_data == NULL)\n         return stbi__free_jpeg_components(z, i+1, stbi__err(\"outofmem\", \"Out of memory\"));\n      // align blocks for idct using mmx/sse\n      z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);\n      if (z->progressive) {\n         // w2, h2 are multiples of 8 (see above)\n         z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;\n         z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;\n         z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);\n         if (z->img_comp[i].raw_coeff == NULL)\n            return stbi__free_jpeg_components(z, i+1, stbi__err(\"outofmem\", \"Out of memory\"));\n         z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);\n      }\n   }\n\n   return 1;\n}\n\n// use comparisons since in some cases we handle more than one case (e.g. SOF)\n#define stbi__DNL(x)         ((x) == 0xdc)\n#define stbi__SOI(x)         ((x) == 0xd8)\n#define stbi__EOI(x)         ((x) == 0xd9)\n#define stbi__SOF(x)         ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)\n#define stbi__SOS(x)         ((x) == 0xda)\n\n#define stbi__SOF_progressive(x)   ((x) == 0xc2)\n\nstatic int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)\n{\n   int m;\n   z->jfif = 0;\n   z->app14_color_transform = -1; // valid values are 0,1,2\n   z->marker = STBI__MARKER_none; // initialize cached marker to empty\n   m = stbi__get_marker(z);\n   if (!stbi__SOI(m)) return stbi__err(\"no SOI\",\"Corrupt JPEG\");\n   if (scan == STBI__SCAN_type) return 1;\n   m = stbi__get_marker(z);\n   while (!stbi__SOF(m)) {\n      if (!stbi__process_marker(z,m)) return 0;\n      m = stbi__get_marker(z);\n      while (m == STBI__MARKER_none) {\n         // some files have extra padding after their blocks, so ok, we'll scan\n         if (stbi__at_eof(z->s)) return stbi__err(\"no SOF\", \"Corrupt JPEG\");\n         m = stbi__get_marker(z);\n      }\n   }\n   z->progressive = stbi__SOF_progressive(m);\n   if (!stbi__process_frame_header(z, scan)) return 0;\n   return 1;\n}\n\nstatic stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j)\n{\n   // some JPEGs have junk at end, skip over it but if we find what looks\n   // like a valid marker, resume there\n   while (!stbi__at_eof(j->s)) {\n      stbi_uc x = stbi__get8(j->s);\n      while (x == 0xff) { // might be a marker\n         if (stbi__at_eof(j->s)) return STBI__MARKER_none;\n         x = stbi__get8(j->s);\n         if (x != 0x00 && x != 0xff) {\n            // not a stuffed zero or lead-in to another marker, looks\n            // like an actual marker, return it\n            return x;\n         }\n         // stuffed zero has x=0 now which ends the loop, meaning we go\n         // back to regular scan loop.\n         // repeated 0xff keeps trying to read the next byte of the marker.\n      }\n   }\n   return STBI__MARKER_none;\n}\n\n// decode image to YCbCr format\nstatic int stbi__decode_jpeg_image(stbi__jpeg *j)\n{\n   int m;\n   for (m = 0; m < 4; m++) {\n      j->img_comp[m].raw_data = NULL;\n      j->img_comp[m].raw_coeff = NULL;\n   }\n   j->restart_interval = 0;\n   if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;\n   m = stbi__get_marker(j);\n   while (!stbi__EOI(m)) {\n      if (stbi__SOS(m)) {\n         if (!stbi__process_scan_header(j)) return 0;\n         if (!stbi__parse_entropy_coded_data(j)) return 0;\n         if (j->marker == STBI__MARKER_none ) {\n         j->marker = stbi__skip_jpeg_junk_at_end(j);\n            // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0\n         }\n         m = stbi__get_marker(j);\n         if (STBI__RESTART(m))\n            m = stbi__get_marker(j);\n      } else if (stbi__DNL(m)) {\n         int Ld = stbi__get16be(j->s);\n         stbi__uint32 NL = stbi__get16be(j->s);\n         if (Ld != 4) return stbi__err(\"bad DNL len\", \"Corrupt JPEG\");\n         if (NL != j->s->img_y) return stbi__err(\"bad DNL height\", \"Corrupt JPEG\");\n         m = stbi__get_marker(j);\n      } else {\n         if (!stbi__process_marker(j, m)) return 1;\n         m = stbi__get_marker(j);\n      }\n   }\n   if (j->progressive)\n      stbi__jpeg_finish(j);\n   return 1;\n}\n\n// static jfif-centered resampling (across block boundaries)\n\ntypedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,\n                                    int w, int hs);\n\n#define stbi__div4(x) ((stbi_uc) ((x) >> 2))\n\nstatic stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)\n{\n   STBI_NOTUSED(out);\n   STBI_NOTUSED(in_far);\n   STBI_NOTUSED(w);\n   STBI_NOTUSED(hs);\n   return in_near;\n}\n\nstatic stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)\n{\n   // need to generate two samples vertically for every one in input\n   int i;\n   STBI_NOTUSED(hs);\n   for (i=0; i < w; ++i)\n      out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);\n   return out;\n}\n\nstatic stbi_uc*  stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)\n{\n   // need to generate two samples horizontally for every one in input\n   int i;\n   stbi_uc *input = in_near;\n\n   if (w == 1) {\n      // if only one sample, can't do any interpolation\n      out[0] = out[1] = input[0];\n      return out;\n   }\n\n   out[0] = input[0];\n   out[1] = stbi__div4(input[0]*3 + input[1] + 2);\n   for (i=1; i < w-1; ++i) {\n      int n = 3*input[i]+2;\n      out[i*2+0] = stbi__div4(n+input[i-1]);\n      out[i*2+1] = stbi__div4(n+input[i+1]);\n   }\n   out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);\n   out[i*2+1] = input[w-1];\n\n   STBI_NOTUSED(in_far);\n   STBI_NOTUSED(hs);\n\n   return out;\n}\n\n#define stbi__div16(x) ((stbi_uc) ((x) >> 4))\n\nstatic stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)\n{\n   // need to generate 2x2 samples for every one in input\n   int i,t0,t1;\n   if (w == 1) {\n      out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);\n      return out;\n   }\n\n   t1 = 3*in_near[0] + in_far[0];\n   out[0] = stbi__div4(t1+2);\n   for (i=1; i < w; ++i) {\n      t0 = t1;\n      t1 = 3*in_near[i]+in_far[i];\n      out[i*2-1] = stbi__div16(3*t0 + t1 + 8);\n      out[i*2  ] = stbi__div16(3*t1 + t0 + 8);\n   }\n   out[w*2-1] = stbi__div4(t1+2);\n\n   STBI_NOTUSED(hs);\n\n   return out;\n}\n\n#if defined(STBI_SSE2) || defined(STBI_NEON)\nstatic stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)\n{\n   // need to generate 2x2 samples for every one in input\n   int i=0,t0,t1;\n\n   if (w == 1) {\n      out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);\n      return out;\n   }\n\n   t1 = 3*in_near[0] + in_far[0];\n   // process groups of 8 pixels for as long as we can.\n   // note we can't handle the last pixel in a row in this loop\n   // because we need to handle the filter boundary conditions.\n   for (; i < ((w-1) & ~7); i += 8) {\n#if defined(STBI_SSE2)\n      // load and perform the vertical filtering pass\n      // this uses 3*x + y = 4*x + (y - x)\n      __m128i zero  = _mm_setzero_si128();\n      __m128i farb  = _mm_loadl_epi64((__m128i *) (in_far + i));\n      __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i));\n      __m128i farw  = _mm_unpacklo_epi8(farb, zero);\n      __m128i nearw = _mm_unpacklo_epi8(nearb, zero);\n      __m128i diff  = _mm_sub_epi16(farw, nearw);\n      __m128i nears = _mm_slli_epi16(nearw, 2);\n      __m128i curr  = _mm_add_epi16(nears, diff); // current row\n\n      // horizontal filter works the same based on shifted vers of current\n      // row. \"prev\" is current row shifted right by 1 pixel; we need to\n      // insert the previous pixel value (from t1).\n      // \"next\" is current row shifted left by 1 pixel, with first pixel\n      // of next block of 8 pixels added in.\n      __m128i prv0 = _mm_slli_si128(curr, 2);\n      __m128i nxt0 = _mm_srli_si128(curr, 2);\n      __m128i prev = _mm_insert_epi16(prv0, t1, 0);\n      __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7);\n\n      // horizontal filter, polyphase implementation since it's convenient:\n      // even pixels = 3*cur + prev = cur*4 + (prev - cur)\n      // odd  pixels = 3*cur + next = cur*4 + (next - cur)\n      // note the shared term.\n      __m128i bias  = _mm_set1_epi16(8);\n      __m128i curs = _mm_slli_epi16(curr, 2);\n      __m128i prvd = _mm_sub_epi16(prev, curr);\n      __m128i nxtd = _mm_sub_epi16(next, curr);\n      __m128i curb = _mm_add_epi16(curs, bias);\n      __m128i even = _mm_add_epi16(prvd, curb);\n      __m128i odd  = _mm_add_epi16(nxtd, curb);\n\n      // interleave even and odd pixels, then undo scaling.\n      __m128i int0 = _mm_unpacklo_epi16(even, odd);\n      __m128i int1 = _mm_unpackhi_epi16(even, odd);\n      __m128i de0  = _mm_srli_epi16(int0, 4);\n      __m128i de1  = _mm_srli_epi16(int1, 4);\n\n      // pack and write output\n      __m128i outv = _mm_packus_epi16(de0, de1);\n      _mm_storeu_si128((__m128i *) (out + i*2), outv);\n#elif defined(STBI_NEON)\n      // load and perform the vertical filtering pass\n      // this uses 3*x + y = 4*x + (y - x)\n      uint8x8_t farb  = vld1_u8(in_far + i);\n      uint8x8_t nearb = vld1_u8(in_near + i);\n      int16x8_t diff  = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));\n      int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));\n      int16x8_t curr  = vaddq_s16(nears, diff); // current row\n\n      // horizontal filter works the same based on shifted vers of current\n      // row. \"prev\" is current row shifted right by 1 pixel; we need to\n      // insert the previous pixel value (from t1).\n      // \"next\" is current row shifted left by 1 pixel, with first pixel\n      // of next block of 8 pixels added in.\n      int16x8_t prv0 = vextq_s16(curr, curr, 7);\n      int16x8_t nxt0 = vextq_s16(curr, curr, 1);\n      int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);\n      int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7);\n\n      // horizontal filter, polyphase implementation since it's convenient:\n      // even pixels = 3*cur + prev = cur*4 + (prev - cur)\n      // odd  pixels = 3*cur + next = cur*4 + (next - cur)\n      // note the shared term.\n      int16x8_t curs = vshlq_n_s16(curr, 2);\n      int16x8_t prvd = vsubq_s16(prev, curr);\n      int16x8_t nxtd = vsubq_s16(next, curr);\n      int16x8_t even = vaddq_s16(curs, prvd);\n      int16x8_t odd  = vaddq_s16(curs, nxtd);\n\n      // undo scaling and round, then store with even/odd phases interleaved\n      uint8x8x2_t o;\n      o.val[0] = vqrshrun_n_s16(even, 4);\n      o.val[1] = vqrshrun_n_s16(odd,  4);\n      vst2_u8(out + i*2, o);\n#endif\n\n      // \"previous\" value for next iter\n      t1 = 3*in_near[i+7] + in_far[i+7];\n   }\n\n   t0 = t1;\n   t1 = 3*in_near[i] + in_far[i];\n   out[i*2] = stbi__div16(3*t1 + t0 + 8);\n\n   for (++i; i < w; ++i) {\n      t0 = t1;\n      t1 = 3*in_near[i]+in_far[i];\n      out[i*2-1] = stbi__div16(3*t0 + t1 + 8);\n      out[i*2  ] = stbi__div16(3*t1 + t0 + 8);\n   }\n   out[w*2-1] = stbi__div4(t1+2);\n\n   STBI_NOTUSED(hs);\n\n   return out;\n}\n#endif\n\nstatic stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)\n{\n   // resample with nearest-neighbor\n   int i,j;\n   STBI_NOTUSED(in_far);\n   for (i=0; i < w; ++i)\n      for (j=0; j < hs; ++j)\n         out[i*hs+j] = in_near[i];\n   return out;\n}\n\n// this is a reduced-precision calculation of YCbCr-to-RGB introduced\n// to make sure the code produces the same results in both SIMD and scalar\n#define stbi__float2fixed(x)  (((int) ((x) * 4096.0f + 0.5f)) << 8)\nstatic void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)\n{\n   int i;\n   for (i=0; i < count; ++i) {\n      int y_fixed = (y[i] << 20) + (1<<19); // rounding\n      int r,g,b;\n      int cr = pcr[i] - 128;\n      int cb = pcb[i] - 128;\n      r = y_fixed +  cr* stbi__float2fixed(1.40200f);\n      g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);\n      b = y_fixed                                     +   cb* stbi__float2fixed(1.77200f);\n      r >>= 20;\n      g >>= 20;\n      b >>= 20;\n      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }\n      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }\n      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }\n      out[0] = (stbi_uc)r;\n      out[1] = (stbi_uc)g;\n      out[2] = (stbi_uc)b;\n      out[3] = 255;\n      out += step;\n   }\n}\n\n#if defined(STBI_SSE2) || defined(STBI_NEON)\nstatic void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step)\n{\n   int i = 0;\n\n#ifdef STBI_SSE2\n   // step == 3 is pretty ugly on the final interleave, and i'm not convinced\n   // it's useful in practice (you wouldn't use it for textures, for example).\n   // so just accelerate step == 4 case.\n   if (step == 4) {\n      // this is a fairly straightforward implementation and not super-optimized.\n      __m128i signflip  = _mm_set1_epi8(-0x80);\n      __m128i cr_const0 = _mm_set1_epi16(   (short) ( 1.40200f*4096.0f+0.5f));\n      __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f));\n      __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f));\n      __m128i cb_const1 = _mm_set1_epi16(   (short) ( 1.77200f*4096.0f+0.5f));\n      __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);\n      __m128i xw = _mm_set1_epi16(255); // alpha channel\n\n      for (; i+7 < count; i += 8) {\n         // load\n         __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i));\n         __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i));\n         __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i));\n         __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128\n         __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128\n\n         // unpack to short (and left-shift cr, cb by 8)\n         __m128i yw  = _mm_unpacklo_epi8(y_bias, y_bytes);\n         __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);\n         __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);\n\n         // color transform\n         __m128i yws = _mm_srli_epi16(yw, 4);\n         __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);\n         __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);\n         __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);\n         __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);\n         __m128i rws = _mm_add_epi16(cr0, yws);\n         __m128i gwt = _mm_add_epi16(cb0, yws);\n         __m128i bws = _mm_add_epi16(yws, cb1);\n         __m128i gws = _mm_add_epi16(gwt, cr1);\n\n         // descale\n         __m128i rw = _mm_srai_epi16(rws, 4);\n         __m128i bw = _mm_srai_epi16(bws, 4);\n         __m128i gw = _mm_srai_epi16(gws, 4);\n\n         // back to byte, set up for transpose\n         __m128i brb = _mm_packus_epi16(rw, bw);\n         __m128i gxb = _mm_packus_epi16(gw, xw);\n\n         // transpose to interleave channels\n         __m128i t0 = _mm_unpacklo_epi8(brb, gxb);\n         __m128i t1 = _mm_unpackhi_epi8(brb, gxb);\n         __m128i o0 = _mm_unpacklo_epi16(t0, t1);\n         __m128i o1 = _mm_unpackhi_epi16(t0, t1);\n\n         // store\n         _mm_storeu_si128((__m128i *) (out + 0), o0);\n         _mm_storeu_si128((__m128i *) (out + 16), o1);\n         out += 32;\n      }\n   }\n#endif\n\n#ifdef STBI_NEON\n   // in this version, step=3 support would be easy to add. but is there demand?\n   if (step == 4) {\n      // this is a fairly straightforward implementation and not super-optimized.\n      uint8x8_t signflip = vdup_n_u8(0x80);\n      int16x8_t cr_const0 = vdupq_n_s16(   (short) ( 1.40200f*4096.0f+0.5f));\n      int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f));\n      int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f));\n      int16x8_t cb_const1 = vdupq_n_s16(   (short) ( 1.77200f*4096.0f+0.5f));\n\n      for (; i+7 < count; i += 8) {\n         // load\n         uint8x8_t y_bytes  = vld1_u8(y + i);\n         uint8x8_t cr_bytes = vld1_u8(pcr + i);\n         uint8x8_t cb_bytes = vld1_u8(pcb + i);\n         int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));\n         int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));\n\n         // expand to s16\n         int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));\n         int16x8_t crw = vshll_n_s8(cr_biased, 7);\n         int16x8_t cbw = vshll_n_s8(cb_biased, 7);\n\n         // color transform\n         int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);\n         int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);\n         int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);\n         int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);\n         int16x8_t rws = vaddq_s16(yws, cr0);\n         int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);\n         int16x8_t bws = vaddq_s16(yws, cb1);\n\n         // undo scaling, round, convert to byte\n         uint8x8x4_t o;\n         o.val[0] = vqrshrun_n_s16(rws, 4);\n         o.val[1] = vqrshrun_n_s16(gws, 4);\n         o.val[2] = vqrshrun_n_s16(bws, 4);\n         o.val[3] = vdup_n_u8(255);\n\n         // store, interleaving r/g/b/a\n         vst4_u8(out, o);\n         out += 8*4;\n      }\n   }\n#endif\n\n   for (; i < count; ++i) {\n      int y_fixed = (y[i] << 20) + (1<<19); // rounding\n      int r,g,b;\n      int cr = pcr[i] - 128;\n      int cb = pcb[i] - 128;\n      r = y_fixed + cr* stbi__float2fixed(1.40200f);\n      g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);\n      b = y_fixed                                   +   cb* stbi__float2fixed(1.77200f);\n      r >>= 20;\n      g >>= 20;\n      b >>= 20;\n      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }\n      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }\n      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }\n      out[0] = (stbi_uc)r;\n      out[1] = (stbi_uc)g;\n      out[2] = (stbi_uc)b;\n      out[3] = 255;\n      out += step;\n   }\n}\n#endif\n\n// set up the kernels\nstatic void stbi__setup_jpeg(stbi__jpeg *j)\n{\n   j->idct_block_kernel = stbi__idct_block;\n   j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;\n   j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;\n\n#ifdef STBI_SSE2\n   if (stbi__sse2_available()) {\n      j->idct_block_kernel = stbi__idct_simd;\n      j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;\n      j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;\n   }\n#endif\n\n#ifdef STBI_NEON\n   j->idct_block_kernel = stbi__idct_simd;\n   j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;\n   j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;\n#endif\n}\n\n// clean up the temporary component buffers\nstatic void stbi__cleanup_jpeg(stbi__jpeg *j)\n{\n   stbi__free_jpeg_components(j, j->s->img_n, 0);\n}\n\ntypedef struct\n{\n   resample_row_func resample;\n   stbi_uc *line0,*line1;\n   int hs,vs;   // expansion factor in each axis\n   int w_lores; // horizontal pixels pre-expansion\n   int ystep;   // how far through vertical expansion we are\n   int ypos;    // which pre-expansion row we're on\n} stbi__resample;\n\n// fast 0..255 * 0..255 => 0..255 rounded multiplication\nstatic stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y)\n{\n   unsigned int t = x*y + 128;\n   return (stbi_uc) ((t + (t >>8)) >> 8);\n}\n\nstatic stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)\n{\n   int n, decode_n, is_rgb;\n   z->s->img_n = 0; // make stbi__cleanup_jpeg safe\n\n   // validate req_comp\n   if (req_comp < 0 || req_comp > 4) return stbi__errpuc(\"bad req_comp\", \"Internal error\");\n\n   // load a jpeg image from whichever source, but leave in YCbCr format\n   if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }\n\n   // determine actual number of components to generate\n   n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1;\n\n   is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));\n\n   if (z->s->img_n == 3 && n < 3 && !is_rgb)\n      decode_n = 1;\n   else\n      decode_n = z->s->img_n;\n\n   // nothing to do if no components requested; check this now to avoid\n   // accessing uninitialized coutput[0] later\n   if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; }\n\n   // resample and color-convert\n   {\n      int k;\n      unsigned int i,j;\n      stbi_uc *output;\n      stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL };\n\n      stbi__resample res_comp[4];\n\n      for (k=0; k < decode_n; ++k) {\n         stbi__resample *r = &res_comp[k];\n\n         // allocate line buffer big enough for upsampling off the edges\n         // with upsample factor of 4\n         z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);\n         if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc(\"outofmem\", \"Out of memory\"); }\n\n         r->hs      = z->img_h_max / z->img_comp[k].h;\n         r->vs      = z->img_v_max / z->img_comp[k].v;\n         r->ystep   = r->vs >> 1;\n         r->w_lores = (z->s->img_x + r->hs-1) / r->hs;\n         r->ypos    = 0;\n         r->line0   = r->line1 = z->img_comp[k].data;\n\n         if      (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;\n         else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;\n         else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;\n         else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;\n         else                               r->resample = stbi__resample_row_generic;\n      }\n\n      // can't error after this so, this is safe\n      output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);\n      if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc(\"outofmem\", \"Out of memory\"); }\n\n      // now go ahead and resample\n      for (j=0; j < z->s->img_y; ++j) {\n         stbi_uc *out = output + n * z->s->img_x * j;\n         for (k=0; k < decode_n; ++k) {\n            stbi__resample *r = &res_comp[k];\n            int y_bot = r->ystep >= (r->vs >> 1);\n            coutput[k] = r->resample(z->img_comp[k].linebuf,\n                                     y_bot ? r->line1 : r->line0,\n                                     y_bot ? r->line0 : r->line1,\n                                     r->w_lores, r->hs);\n            if (++r->ystep >= r->vs) {\n               r->ystep = 0;\n               r->line0 = r->line1;\n               if (++r->ypos < z->img_comp[k].y)\n                  r->line1 += z->img_comp[k].w2;\n            }\n         }\n         if (n >= 3) {\n            stbi_uc *y = coutput[0];\n            if (z->s->img_n == 3) {\n               if (is_rgb) {\n                  for (i=0; i < z->s->img_x; ++i) {\n                     out[0] = y[i];\n                     out[1] = coutput[1][i];\n                     out[2] = coutput[2][i];\n                     out[3] = 255;\n                     out += n;\n                  }\n               } else {\n                  z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);\n               }\n            } else if (z->s->img_n == 4) {\n               if (z->app14_color_transform == 0) { // CMYK\n                  for (i=0; i < z->s->img_x; ++i) {\n                     stbi_uc m = coutput[3][i];\n                     out[0] = stbi__blinn_8x8(coutput[0][i], m);\n                     out[1] = stbi__blinn_8x8(coutput[1][i], m);\n                     out[2] = stbi__blinn_8x8(coutput[2][i], m);\n                     out[3] = 255;\n                     out += n;\n                  }\n               } else if (z->app14_color_transform == 2) { // YCCK\n                  z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);\n                  for (i=0; i < z->s->img_x; ++i) {\n                     stbi_uc m = coutput[3][i];\n                     out[0] = stbi__blinn_8x8(255 - out[0], m);\n                     out[1] = stbi__blinn_8x8(255 - out[1], m);\n                     out[2] = stbi__blinn_8x8(255 - out[2], m);\n                     out += n;\n                  }\n               } else { // YCbCr + alpha?  Ignore the fourth channel for now\n                  z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);\n               }\n            } else\n               for (i=0; i < z->s->img_x; ++i) {\n                  out[0] = out[1] = out[2] = y[i];\n                  out[3] = 255; // not used if n==3\n                  out += n;\n               }\n         } else {\n            if (is_rgb) {\n               if (n == 1)\n                  for (i=0; i < z->s->img_x; ++i)\n                     *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);\n               else {\n                  for (i=0; i < z->s->img_x; ++i, out += 2) {\n                     out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);\n                     out[1] = 255;\n                  }\n               }\n            } else if (z->s->img_n == 4 && z->app14_color_transform == 0) {\n               for (i=0; i < z->s->img_x; ++i) {\n                  stbi_uc m = coutput[3][i];\n                  stbi_uc r = stbi__blinn_8x8(coutput[0][i], m);\n                  stbi_uc g = stbi__blinn_8x8(coutput[1][i], m);\n                  stbi_uc b = stbi__blinn_8x8(coutput[2][i], m);\n                  out[0] = stbi__compute_y(r, g, b);\n                  out[1] = 255;\n                  out += n;\n               }\n            } else if (z->s->img_n == 4 && z->app14_color_transform == 2) {\n               for (i=0; i < z->s->img_x; ++i) {\n                  out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);\n                  out[1] = 255;\n                  out += n;\n               }\n            } else {\n               stbi_uc *y = coutput[0];\n               if (n == 1)\n                  for (i=0; i < z->s->img_x; ++i) out[i] = y[i];\n               else\n                  for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; }\n            }\n         }\n      }\n      stbi__cleanup_jpeg(z);\n      *out_x = z->s->img_x;\n      *out_y = z->s->img_y;\n      if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output\n      return output;\n   }\n}\n\nstatic void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   unsigned char* result;\n   stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));\n   if (!j) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n   memset(j, 0, sizeof(stbi__jpeg));\n   STBI_NOTUSED(ri);\n   j->s = s;\n   stbi__setup_jpeg(j);\n   result = load_jpeg_image(j, x,y,comp,req_comp);\n   STBI_FREE(j);\n   return result;\n}\n\nstatic int stbi__jpeg_test(stbi__context *s)\n{\n   int r;\n   stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));\n   if (!j) return stbi__err(\"outofmem\", \"Out of memory\");\n   memset(j, 0, sizeof(stbi__jpeg));\n   j->s = s;\n   stbi__setup_jpeg(j);\n   r = stbi__decode_jpeg_header(j, STBI__SCAN_type);\n   stbi__rewind(s);\n   STBI_FREE(j);\n   return r;\n}\n\nstatic int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)\n{\n   if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {\n      stbi__rewind( j->s );\n      return 0;\n   }\n   if (x) *x = j->s->img_x;\n   if (y) *y = j->s->img_y;\n   if (comp) *comp = j->s->img_n >= 3 ? 3 : 1;\n   return 1;\n}\n\nstatic int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   int result;\n   stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));\n   if (!j) return stbi__err(\"outofmem\", \"Out of memory\");\n   memset(j, 0, sizeof(stbi__jpeg));\n   j->s = s;\n   result = stbi__jpeg_info_raw(j, x, y, comp);\n   STBI_FREE(j);\n   return result;\n}\n#endif\n\n// public domain zlib decode    v0.2  Sean Barrett 2006-11-18\n//    simple implementation\n//      - all input must be provided in an upfront buffer\n//      - all output is written to a single output buffer (can malloc/realloc)\n//    performance\n//      - fast huffman\n\n#ifndef STBI_NO_ZLIB\n\n// fast-way is faster to check than jpeg huffman, but slow way is slower\n#define STBI__ZFAST_BITS  9 // accelerate all cases in default tables\n#define STBI__ZFAST_MASK  ((1 << STBI__ZFAST_BITS) - 1)\n#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet\n\n// zlib-style huffman encoding\n// (jpegs packs from left, zlib from right, so can't share code)\ntypedef struct\n{\n   stbi__uint16 fast[1 << STBI__ZFAST_BITS];\n   stbi__uint16 firstcode[16];\n   int maxcode[17];\n   stbi__uint16 firstsymbol[16];\n   stbi_uc  size[STBI__ZNSYMS];\n   stbi__uint16 value[STBI__ZNSYMS];\n} stbi__zhuffman;\n\nstbi_inline static int stbi__bitreverse16(int n)\n{\n  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);\n  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);\n  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);\n  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);\n  return n;\n}\n\nstbi_inline static int stbi__bit_reverse(int v, int bits)\n{\n   STBI_ASSERT(bits <= 16);\n   // to bit reverse n bits, reverse 16 and shift\n   // e.g. 11 bits, bit reverse and shift away 5\n   return stbi__bitreverse16(v) >> (16-bits);\n}\n\nstatic int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num)\n{\n   int i,k=0;\n   int code, next_code[16], sizes[17];\n\n   // DEFLATE spec for generating codes\n   memset(sizes, 0, sizeof(sizes));\n   memset(z->fast, 0, sizeof(z->fast));\n   for (i=0; i < num; ++i)\n      ++sizes[sizelist[i]];\n   sizes[0] = 0;\n   for (i=1; i < 16; ++i)\n      if (sizes[i] > (1 << i))\n         return stbi__err(\"bad sizes\", \"Corrupt PNG\");\n   code = 0;\n   for (i=1; i < 16; ++i) {\n      next_code[i] = code;\n      z->firstcode[i] = (stbi__uint16) code;\n      z->firstsymbol[i] = (stbi__uint16) k;\n      code = (code + sizes[i]);\n      if (sizes[i])\n         if (code-1 >= (1 << i)) return stbi__err(\"bad codelengths\",\"Corrupt PNG\");\n      z->maxcode[i] = code << (16-i); // preshift for inner loop\n      code <<= 1;\n      k += sizes[i];\n   }\n   z->maxcode[16] = 0x10000; // sentinel\n   for (i=0; i < num; ++i) {\n      int s = sizelist[i];\n      if (s) {\n         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];\n         stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);\n         z->size [c] = (stbi_uc     ) s;\n         z->value[c] = (stbi__uint16) i;\n         if (s <= STBI__ZFAST_BITS) {\n            int j = stbi__bit_reverse(next_code[s],s);\n            while (j < (1 << STBI__ZFAST_BITS)) {\n               z->fast[j] = fastv;\n               j += (1 << s);\n            }\n         }\n         ++next_code[s];\n      }\n   }\n   return 1;\n}\n\n// zlib-from-memory implementation for PNG reading\n//    because PNG allows splitting the zlib stream arbitrarily,\n//    and it's annoying structurally to have PNG call ZLIB call PNG,\n//    we require PNG read all the IDATs and combine them into a single\n//    memory buffer\n\ntypedef struct\n{\n   stbi_uc *zbuffer, *zbuffer_end;\n   int num_bits;\n   int hit_zeof_once;\n   stbi__uint32 code_buffer;\n\n   char *zout;\n   char *zout_start;\n   char *zout_end;\n   int   z_expandable;\n\n   stbi__zhuffman z_length, z_distance;\n} stbi__zbuf;\n\nstbi_inline static int stbi__zeof(stbi__zbuf *z)\n{\n   return (z->zbuffer >= z->zbuffer_end);\n}\n\nstbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)\n{\n   return stbi__zeof(z) ? 0 : *z->zbuffer++;\n}\n\nstatic void stbi__fill_bits(stbi__zbuf *z)\n{\n   do {\n      if (z->code_buffer >= (1U << z->num_bits)) {\n        z->zbuffer = z->zbuffer_end;  /* treat this as EOF so we fail. */\n        return;\n      }\n      z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;\n      z->num_bits += 8;\n   } while (z->num_bits <= 24);\n}\n\nstbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)\n{\n   unsigned int k;\n   if (z->num_bits < n) stbi__fill_bits(z);\n   k = z->code_buffer & ((1 << n) - 1);\n   z->code_buffer >>= n;\n   z->num_bits -= n;\n   return k;\n}\n\nstatic int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)\n{\n   int b,s,k;\n   // not resolved by fast table, so compute it the slow way\n   // use jpeg approach, which requires MSbits at top\n   k = stbi__bit_reverse(a->code_buffer, 16);\n   for (s=STBI__ZFAST_BITS+1; ; ++s)\n      if (k < z->maxcode[s])\n         break;\n   if (s >= 16) return -1; // invalid code!\n   // code size is s, so:\n   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];\n   if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!\n   if (z->size[b] != s) return -1;  // was originally an assert, but report failure instead.\n   a->code_buffer >>= s;\n   a->num_bits -= s;\n   return z->value[b];\n}\n\nstbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)\n{\n   int b,s;\n   if (a->num_bits < 16) {\n      if (stbi__zeof(a)) {\n         if (!a->hit_zeof_once) {\n            // This is the first time we hit eof, insert 16 extra padding btis\n            // to allow us to keep going; if we actually consume any of them\n            // though, that is invalid data. This is caught later.\n            a->hit_zeof_once = 1;\n            a->num_bits += 16; // add 16 implicit zero bits\n         } else {\n            // We already inserted our extra 16 padding bits and are again\n            // out, this stream is actually prematurely terminated.\n            return -1;\n         }\n      } else {\n         stbi__fill_bits(a);\n      }\n   }\n   b = z->fast[a->code_buffer & STBI__ZFAST_MASK];\n   if (b) {\n      s = b >> 9;\n      a->code_buffer >>= s;\n      a->num_bits -= s;\n      return b & 511;\n   }\n   return stbi__zhuffman_decode_slowpath(a, z);\n}\n\nstatic int stbi__zexpand(stbi__zbuf *z, char *zout, int n)  // need to make room for n bytes\n{\n   char *q;\n   unsigned int cur, limit, old_limit;\n   z->zout = zout;\n   if (!z->z_expandable) return stbi__err(\"output buffer limit\",\"Corrupt PNG\");\n   cur   = (unsigned int) (z->zout - z->zout_start);\n   limit = old_limit = (unsigned) (z->zout_end - z->zout_start);\n   if (UINT_MAX - cur < (unsigned) n) return stbi__err(\"outofmem\", \"Out of memory\");\n   while (cur + n > limit) {\n      if(limit > UINT_MAX / 2) return stbi__err(\"outofmem\", \"Out of memory\");\n      limit *= 2;\n   }\n   q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);\n   STBI_NOTUSED(old_limit);\n   if (q == NULL) return stbi__err(\"outofmem\", \"Out of memory\");\n   z->zout_start = q;\n   z->zout       = q + cur;\n   z->zout_end   = q + limit;\n   return 1;\n}\n\nstatic const int stbi__zlength_base[31] = {\n   3,4,5,6,7,8,9,10,11,13,\n   15,17,19,23,27,31,35,43,51,59,\n   67,83,99,115,131,163,195,227,258,0,0 };\n\nstatic const int stbi__zlength_extra[31]=\n{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };\n\nstatic const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,\n257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};\n\nstatic const int stbi__zdist_extra[32] =\n{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\n\nstatic int stbi__parse_huffman_block(stbi__zbuf *a)\n{\n   char *zout = a->zout;\n   for(;;) {\n      int z = stbi__zhuffman_decode(a, &a->z_length);\n      if (z < 256) {\n         if (z < 0) return stbi__err(\"bad huffman code\",\"Corrupt PNG\"); // error in huffman codes\n         if (zout >= a->zout_end) {\n            if (!stbi__zexpand(a, zout, 1)) return 0;\n            zout = a->zout;\n         }\n         *zout++ = (char) z;\n      } else {\n         stbi_uc *p;\n         int len,dist;\n         if (z == 256) {\n            a->zout = zout;\n            if (a->hit_zeof_once && a->num_bits < 16) {\n               // The first time we hit zeof, we inserted 16 extra zero bits into our bit\n               // buffer so the decoder can just do its speculative decoding. But if we\n               // actually consumed any of those bits (which is the case when num_bits < 16),\n               // the stream actually read past the end so it is malformed.\n               return stbi__err(\"unexpected end\",\"Corrupt PNG\");\n            }\n            return 1;\n         }\n         if (z >= 286) return stbi__err(\"bad huffman code\",\"Corrupt PNG\"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data\n         z -= 257;\n         len = stbi__zlength_base[z];\n         if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);\n         z = stbi__zhuffman_decode(a, &a->z_distance);\n         if (z < 0 || z >= 30) return stbi__err(\"bad huffman code\",\"Corrupt PNG\"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data\n         dist = stbi__zdist_base[z];\n         if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);\n         if (zout - a->zout_start < dist) return stbi__err(\"bad dist\",\"Corrupt PNG\");\n         if (len > a->zout_end - zout) {\n            if (!stbi__zexpand(a, zout, len)) return 0;\n            zout = a->zout;\n         }\n         p = (stbi_uc *) (zout - dist);\n         if (dist == 1) { // run of one byte; common in images.\n            stbi_uc v = *p;\n            if (len) { do *zout++ = v; while (--len); }\n         } else {\n            if (len) { do *zout++ = *p++; while (--len); }\n         }\n      }\n   }\n}\n\nstatic int stbi__compute_huffman_codes(stbi__zbuf *a)\n{\n   static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };\n   stbi__zhuffman z_codelength;\n   stbi_uc lencodes[286+32+137];//padding for maximum single op\n   stbi_uc codelength_sizes[19];\n   int i,n;\n\n   int hlit  = stbi__zreceive(a,5) + 257;\n   int hdist = stbi__zreceive(a,5) + 1;\n   int hclen = stbi__zreceive(a,4) + 4;\n   int ntot  = hlit + hdist;\n\n   memset(codelength_sizes, 0, sizeof(codelength_sizes));\n   for (i=0; i < hclen; ++i) {\n      int s = stbi__zreceive(a,3);\n      codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;\n   }\n   if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;\n\n   n = 0;\n   while (n < ntot) {\n      int c = stbi__zhuffman_decode(a, &z_codelength);\n      if (c < 0 || c >= 19) return stbi__err(\"bad codelengths\", \"Corrupt PNG\");\n      if (c < 16)\n         lencodes[n++] = (stbi_uc) c;\n      else {\n         stbi_uc fill = 0;\n         if (c == 16) {\n            c = stbi__zreceive(a,2)+3;\n            if (n == 0) return stbi__err(\"bad codelengths\", \"Corrupt PNG\");\n            fill = lencodes[n-1];\n         } else if (c == 17) {\n            c = stbi__zreceive(a,3)+3;\n         } else if (c == 18) {\n            c = stbi__zreceive(a,7)+11;\n         } else {\n            return stbi__err(\"bad codelengths\", \"Corrupt PNG\");\n         }\n         if (ntot - n < c) return stbi__err(\"bad codelengths\", \"Corrupt PNG\");\n         memset(lencodes+n, fill, c);\n         n += c;\n      }\n   }\n   if (n != ntot) return stbi__err(\"bad codelengths\",\"Corrupt PNG\");\n   if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;\n   if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;\n   return 1;\n}\n\nstatic int stbi__parse_uncompressed_block(stbi__zbuf *a)\n{\n   stbi_uc header[4];\n   int len,nlen,k;\n   if (a->num_bits & 7)\n      stbi__zreceive(a, a->num_bits & 7); // discard\n   // drain the bit-packed data into header\n   k = 0;\n   while (a->num_bits > 0) {\n      header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check\n      a->code_buffer >>= 8;\n      a->num_bits -= 8;\n   }\n   if (a->num_bits < 0) return stbi__err(\"zlib corrupt\",\"Corrupt PNG\");\n   // now fill header the normal way\n   while (k < 4)\n      header[k++] = stbi__zget8(a);\n   len  = header[1] * 256 + header[0];\n   nlen = header[3] * 256 + header[2];\n   if (nlen != (len ^ 0xffff)) return stbi__err(\"zlib corrupt\",\"Corrupt PNG\");\n   if (a->zbuffer + len > a->zbuffer_end) return stbi__err(\"read past buffer\",\"Corrupt PNG\");\n   if (a->zout + len > a->zout_end)\n      if (!stbi__zexpand(a, a->zout, len)) return 0;\n   memcpy(a->zout, a->zbuffer, len);\n   a->zbuffer += len;\n   a->zout += len;\n   return 1;\n}\n\nstatic int stbi__parse_zlib_header(stbi__zbuf *a)\n{\n   int cmf   = stbi__zget8(a);\n   int cm    = cmf & 15;\n   /* int cinfo = cmf >> 4; */\n   int flg   = stbi__zget8(a);\n   if (stbi__zeof(a)) return stbi__err(\"bad zlib header\",\"Corrupt PNG\"); // zlib spec\n   if ((cmf*256+flg) % 31 != 0) return stbi__err(\"bad zlib header\",\"Corrupt PNG\"); // zlib spec\n   if (flg & 32) return stbi__err(\"no preset dict\",\"Corrupt PNG\"); // preset dictionary not allowed in png\n   if (cm != 8) return stbi__err(\"bad compression\",\"Corrupt PNG\"); // DEFLATE required for png\n   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output\n   return 1;\n}\n\nstatic const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =\n{\n   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,\n   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,\n   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,\n   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,\n   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,\n   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,\n   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,\n   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,\n   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8\n};\nstatic const stbi_uc stbi__zdefault_distance[32] =\n{\n   5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5\n};\n/*\nInit algorithm:\n{\n   int i;   // use <= to match clearly with spec\n   for (i=0; i <= 143; ++i)     stbi__zdefault_length[i]   = 8;\n   for (   ; i <= 255; ++i)     stbi__zdefault_length[i]   = 9;\n   for (   ; i <= 279; ++i)     stbi__zdefault_length[i]   = 7;\n   for (   ; i <= 287; ++i)     stbi__zdefault_length[i]   = 8;\n\n   for (i=0; i <=  31; ++i)     stbi__zdefault_distance[i] = 5;\n}\n*/\n\nstatic int stbi__parse_zlib(stbi__zbuf *a, int parse_header)\n{\n   int final, type;\n   if (parse_header)\n      if (!stbi__parse_zlib_header(a)) return 0;\n   a->num_bits = 0;\n   a->code_buffer = 0;\n   a->hit_zeof_once = 0;\n   do {\n      final = stbi__zreceive(a,1);\n      type = stbi__zreceive(a,2);\n      if (type == 0) {\n         if (!stbi__parse_uncompressed_block(a)) return 0;\n      } else if (type == 3) {\n         return 0;\n      } else {\n         if (type == 1) {\n            // use fixed code lengths\n            if (!stbi__zbuild_huffman(&a->z_length  , stbi__zdefault_length  , STBI__ZNSYMS)) return 0;\n            if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance,  32)) return 0;\n         } else {\n            if (!stbi__compute_huffman_codes(a)) return 0;\n         }\n         if (!stbi__parse_huffman_block(a)) return 0;\n      }\n   } while (!final);\n   return 1;\n}\n\nstatic int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)\n{\n   a->zout_start = obuf;\n   a->zout       = obuf;\n   a->zout_end   = obuf + olen;\n   a->z_expandable = exp;\n\n   return stbi__parse_zlib(a, parse_header);\n}\n\nSTBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)\n{\n   stbi__zbuf a;\n   char *p = (char *) stbi__malloc(initial_size);\n   if (p == NULL) return NULL;\n   a.zbuffer = (stbi_uc *) buffer;\n   a.zbuffer_end = (stbi_uc *) buffer + len;\n   if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {\n      if (outlen) *outlen = (int) (a.zout - a.zout_start);\n      return a.zout_start;\n   } else {\n      STBI_FREE(a.zout_start);\n      return NULL;\n   }\n}\n\nSTBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)\n{\n   return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);\n}\n\nSTBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)\n{\n   stbi__zbuf a;\n   char *p = (char *) stbi__malloc(initial_size);\n   if (p == NULL) return NULL;\n   a.zbuffer = (stbi_uc *) buffer;\n   a.zbuffer_end = (stbi_uc *) buffer + len;\n   if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {\n      if (outlen) *outlen = (int) (a.zout - a.zout_start);\n      return a.zout_start;\n   } else {\n      STBI_FREE(a.zout_start);\n      return NULL;\n   }\n}\n\nSTBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)\n{\n   stbi__zbuf a;\n   a.zbuffer = (stbi_uc *) ibuffer;\n   a.zbuffer_end = (stbi_uc *) ibuffer + ilen;\n   if (stbi__do_zlib(&a, obuffer, olen, 0, 1))\n      return (int) (a.zout - a.zout_start);\n   else\n      return -1;\n}\n\nSTBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)\n{\n   stbi__zbuf a;\n   char *p = (char *) stbi__malloc(16384);\n   if (p == NULL) return NULL;\n   a.zbuffer = (stbi_uc *) buffer;\n   a.zbuffer_end = (stbi_uc *) buffer+len;\n   if (stbi__do_zlib(&a, p, 16384, 1, 0)) {\n      if (outlen) *outlen = (int) (a.zout - a.zout_start);\n      return a.zout_start;\n   } else {\n      STBI_FREE(a.zout_start);\n      return NULL;\n   }\n}\n\nSTBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)\n{\n   stbi__zbuf a;\n   a.zbuffer = (stbi_uc *) ibuffer;\n   a.zbuffer_end = (stbi_uc *) ibuffer + ilen;\n   if (stbi__do_zlib(&a, obuffer, olen, 0, 0))\n      return (int) (a.zout - a.zout_start);\n   else\n      return -1;\n}\n#endif\n\n// public domain \"baseline\" PNG decoder   v0.10  Sean Barrett 2006-11-18\n//    simple implementation\n//      - only 8-bit samples\n//      - no CRC checking\n//      - allocates lots of intermediate memory\n//        - avoids problem of streaming data between subsystems\n//        - avoids explicit window management\n//    performance\n//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding\n\n#ifndef STBI_NO_PNG\ntypedef struct\n{\n   stbi__uint32 length;\n   stbi__uint32 type;\n} stbi__pngchunk;\n\nstatic stbi__pngchunk stbi__get_chunk_header(stbi__context *s)\n{\n   stbi__pngchunk c;\n   c.length = stbi__get32be(s);\n   c.type   = stbi__get32be(s);\n   return c;\n}\n\nstatic int stbi__check_png_header(stbi__context *s)\n{\n   static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };\n   int i;\n   for (i=0; i < 8; ++i)\n      if (stbi__get8(s) != png_sig[i]) return stbi__err(\"bad png sig\",\"Not a PNG\");\n   return 1;\n}\n\ntypedef struct\n{\n   stbi__context *s;\n   stbi_uc *idata, *expanded, *out;\n   int depth;\n} stbi__png;\n\n\nenum {\n   STBI__F_none=0,\n   STBI__F_sub=1,\n   STBI__F_up=2,\n   STBI__F_avg=3,\n   STBI__F_paeth=4,\n   // synthetic filter used for first scanline to avoid needing a dummy row of 0s\n   STBI__F_avg_first\n};\n\nstatic stbi_uc first_row_filter[5] =\n{\n   STBI__F_none,\n   STBI__F_sub,\n   STBI__F_none,\n   STBI__F_avg_first,\n   STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub\n};\n\nstatic int stbi__paeth(int a, int b, int c)\n{\n   // This formulation looks very different from the reference in the PNG spec, but is\n   // actually equivalent and has favorable data dependencies and admits straightforward\n   // generation of branch-free code, which helps performance significantly.\n   int thresh = c*3 - (a + b);\n   int lo = a < b ? a : b;\n   int hi = a < b ? b : a;\n   int t0 = (hi <= thresh) ? lo : c;\n   int t1 = (thresh <= lo) ? hi : t0;\n   return t1;\n}\n\nstatic const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };\n\n// adds an extra all-255 alpha channel\n// dest == src is legal\n// img_n must be 1 or 3\nstatic void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n)\n{\n   int i;\n   // must process data backwards since we allow dest==src\n   if (img_n == 1) {\n      for (i=x-1; i >= 0; --i) {\n         dest[i*2+1] = 255;\n         dest[i*2+0] = src[i];\n      }\n   } else {\n      STBI_ASSERT(img_n == 3);\n      for (i=x-1; i >= 0; --i) {\n         dest[i*4+3] = 255;\n         dest[i*4+2] = src[i*3+2];\n         dest[i*4+1] = src[i*3+1];\n         dest[i*4+0] = src[i*3+0];\n      }\n   }\n}\n\n// create the png data from post-deflated data\nstatic int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)\n{\n   int bytes = (depth == 16 ? 2 : 1);\n   stbi__context *s = a->s;\n   stbi__uint32 i,j,stride = x*out_n*bytes;\n   stbi__uint32 img_len, img_width_bytes;\n   stbi_uc *filter_buf;\n   int all_ok = 1;\n   int k;\n   int img_n = s->img_n; // copy it into a local for later\n\n   int output_bytes = out_n*bytes;\n   int filter_bytes = img_n*bytes;\n   int width = x;\n\n   STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);\n   a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into\n   if (!a->out) return stbi__err(\"outofmem\", \"Out of memory\");\n\n   // note: error exits here don't need to clean up a->out individually,\n   // stbi__do_png always does on error.\n   if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err(\"too large\", \"Corrupt PNG\");\n   img_width_bytes = (((img_n * x * depth) + 7) >> 3);\n   if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err(\"too large\", \"Corrupt PNG\");\n   img_len = (img_width_bytes + 1) * y;\n\n   // we used to check for exact match between raw_len and img_len on non-interlaced PNGs,\n   // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros),\n   // so just check for raw_len < img_len always.\n   if (raw_len < img_len) return stbi__err(\"not enough pixels\",\"Corrupt PNG\");\n\n   // Allocate two scan lines worth of filter workspace buffer.\n   filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0);\n   if (!filter_buf) return stbi__err(\"outofmem\", \"Out of memory\");\n\n   // Filtering for low-bit-depth images\n   if (depth < 8) {\n      filter_bytes = 1;\n      width = img_width_bytes;\n   }\n\n   for (j=0; j < y; ++j) {\n      // cur/prior filter buffers alternate\n      stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes;\n      stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes;\n      stbi_uc *dest = a->out + stride*j;\n      int nk = width * filter_bytes;\n      int filter = *raw++;\n\n      // check filter type\n      if (filter > 4) {\n         all_ok = stbi__err(\"invalid filter\",\"Corrupt PNG\");\n         break;\n      }\n\n      // if first row, use special filter that doesn't sample previous row\n      if (j == 0) filter = first_row_filter[filter];\n\n      // perform actual filtering\n      switch (filter) {\n      case STBI__F_none:\n         memcpy(cur, raw, nk);\n         break;\n      case STBI__F_sub:\n         memcpy(cur, raw, filter_bytes);\n         for (k = filter_bytes; k < nk; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]);\n         break;\n      case STBI__F_up:\n         for (k = 0; k < nk; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + prior[k]);\n         break;\n      case STBI__F_avg:\n         for (k = 0; k < filter_bytes; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1));\n         for (k = filter_bytes; k < nk; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1));\n         break;\n      case STBI__F_paeth:\n         for (k = 0; k < filter_bytes; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)\n         for (k = filter_bytes; k < nk; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes]));\n         break;\n      case STBI__F_avg_first:\n         memcpy(cur, raw, filter_bytes);\n         for (k = filter_bytes; k < nk; ++k)\n            cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1));\n         break;\n      }\n\n      raw += nk;\n\n      // expand decoded bits in cur to dest, also adding an extra alpha channel if desired\n      if (depth < 8) {\n         stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range\n         stbi_uc *in = cur;\n         stbi_uc *out = dest;\n         stbi_uc inb = 0;\n         stbi__uint32 nsmp = x*img_n;\n\n         // expand bits to bytes first\n         if (depth == 4) {\n            for (i=0; i < nsmp; ++i) {\n               if ((i & 1) == 0) inb = *in++;\n               *out++ = scale * (inb >> 4);\n               inb <<= 4;\n            }\n         } else if (depth == 2) {\n            for (i=0; i < nsmp; ++i) {\n               if ((i & 3) == 0) inb = *in++;\n               *out++ = scale * (inb >> 6);\n               inb <<= 2;\n            }\n         } else {\n            STBI_ASSERT(depth == 1);\n            for (i=0; i < nsmp; ++i) {\n               if ((i & 7) == 0) inb = *in++;\n               *out++ = scale * (inb >> 7);\n               inb <<= 1;\n            }\n         }\n\n         // insert alpha=255 values if desired\n         if (img_n != out_n)\n            stbi__create_png_alpha_expand8(dest, dest, x, img_n);\n      } else if (depth == 8) {\n         if (img_n == out_n)\n            memcpy(dest, cur, x*img_n);\n         else\n            stbi__create_png_alpha_expand8(dest, cur, x, img_n);\n      } else if (depth == 16) {\n         // convert the image data from big-endian to platform-native\n         stbi__uint16 *dest16 = (stbi__uint16*)dest;\n         stbi__uint32 nsmp = x*img_n;\n\n         if (img_n == out_n) {\n            for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)\n               *dest16 = (cur[0] << 8) | cur[1];\n         } else {\n            STBI_ASSERT(img_n+1 == out_n);\n            if (img_n == 1) {\n               for (i = 0; i < x; ++i, dest16 += 2, cur += 2) {\n                  dest16[0] = (cur[0] << 8) | cur[1];\n                  dest16[1] = 0xffff;\n               }\n            } else {\n               STBI_ASSERT(img_n == 3);\n               for (i = 0; i < x; ++i, dest16 += 4, cur += 6) {\n                  dest16[0] = (cur[0] << 8) | cur[1];\n                  dest16[1] = (cur[2] << 8) | cur[3];\n                  dest16[2] = (cur[4] << 8) | cur[5];\n                  dest16[3] = 0xffff;\n               }\n            }\n         }\n      }\n   }\n\n   STBI_FREE(filter_buf);\n   if (!all_ok) return 0;\n\n   return 1;\n}\n\nstatic int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)\n{\n   int bytes = (depth == 16 ? 2 : 1);\n   int out_bytes = out_n * bytes;\n   stbi_uc *final;\n   int p;\n   if (!interlaced)\n      return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);\n\n   // de-interlacing\n   final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);\n   if (!final) return stbi__err(\"outofmem\", \"Out of memory\");\n   for (p=0; p < 7; ++p) {\n      int xorig[] = { 0,4,0,2,0,1,0 };\n      int yorig[] = { 0,0,4,0,2,0,1 };\n      int xspc[]  = { 8,8,4,4,2,2,1 };\n      int yspc[]  = { 8,8,8,4,4,2,2 };\n      int i,j,x,y;\n      // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1\n      x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];\n      y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];\n      if (x && y) {\n         stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;\n         if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {\n            STBI_FREE(final);\n            return 0;\n         }\n         for (j=0; j < y; ++j) {\n            for (i=0; i < x; ++i) {\n               int out_y = j*yspc[p]+yorig[p];\n               int out_x = i*xspc[p]+xorig[p];\n               memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes,\n                      a->out + (j*x+i)*out_bytes, out_bytes);\n            }\n         }\n         STBI_FREE(a->out);\n         image_data += img_len;\n         image_data_len -= img_len;\n      }\n   }\n   a->out = final;\n\n   return 1;\n}\n\nstatic int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)\n{\n   stbi__context *s = z->s;\n   stbi__uint32 i, pixel_count = s->img_x * s->img_y;\n   stbi_uc *p = z->out;\n\n   // compute color-based transparency, assuming we've\n   // already got 255 as the alpha value in the output\n   STBI_ASSERT(out_n == 2 || out_n == 4);\n\n   if (out_n == 2) {\n      for (i=0; i < pixel_count; ++i) {\n         p[1] = (p[0] == tc[0] ? 0 : 255);\n         p += 2;\n      }\n   } else {\n      for (i=0; i < pixel_count; ++i) {\n         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])\n            p[3] = 0;\n         p += 4;\n      }\n   }\n   return 1;\n}\n\nstatic int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n)\n{\n   stbi__context *s = z->s;\n   stbi__uint32 i, pixel_count = s->img_x * s->img_y;\n   stbi__uint16 *p = (stbi__uint16*) z->out;\n\n   // compute color-based transparency, assuming we've\n   // already got 65535 as the alpha value in the output\n   STBI_ASSERT(out_n == 2 || out_n == 4);\n\n   if (out_n == 2) {\n      for (i = 0; i < pixel_count; ++i) {\n         p[1] = (p[0] == tc[0] ? 0 : 65535);\n         p += 2;\n      }\n   } else {\n      for (i = 0; i < pixel_count; ++i) {\n         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])\n            p[3] = 0;\n         p += 4;\n      }\n   }\n   return 1;\n}\n\nstatic int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)\n{\n   stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;\n   stbi_uc *p, *temp_out, *orig = a->out;\n\n   p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0);\n   if (p == NULL) return stbi__err(\"outofmem\", \"Out of memory\");\n\n   // between here and free(out) below, exitting would leak\n   temp_out = p;\n\n   if (pal_img_n == 3) {\n      for (i=0; i < pixel_count; ++i) {\n         int n = orig[i]*4;\n         p[0] = palette[n  ];\n         p[1] = palette[n+1];\n         p[2] = palette[n+2];\n         p += 3;\n      }\n   } else {\n      for (i=0; i < pixel_count; ++i) {\n         int n = orig[i]*4;\n         p[0] = palette[n  ];\n         p[1] = palette[n+1];\n         p[2] = palette[n+2];\n         p[3] = palette[n+3];\n         p += 4;\n      }\n   }\n   STBI_FREE(a->out);\n   a->out = temp_out;\n\n   STBI_NOTUSED(len);\n\n   return 1;\n}\n\nstatic int stbi__unpremultiply_on_load_global = 0;\nstatic int stbi__de_iphone_flag_global = 0;\n\nSTBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)\n{\n   stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;\n}\n\nSTBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)\n{\n   stbi__de_iphone_flag_global = flag_true_if_should_convert;\n}\n\n#ifndef STBI_THREAD_LOCAL\n#define stbi__unpremultiply_on_load  stbi__unpremultiply_on_load_global\n#define stbi__de_iphone_flag  stbi__de_iphone_flag_global\n#else\nstatic STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;\nstatic STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;\n\nSTBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)\n{\n   stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;\n   stbi__unpremultiply_on_load_set = 1;\n}\n\nSTBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)\n{\n   stbi__de_iphone_flag_local = flag_true_if_should_convert;\n   stbi__de_iphone_flag_set = 1;\n}\n\n#define stbi__unpremultiply_on_load  (stbi__unpremultiply_on_load_set           \\\n                                       ? stbi__unpremultiply_on_load_local      \\\n                                       : stbi__unpremultiply_on_load_global)\n#define stbi__de_iphone_flag  (stbi__de_iphone_flag_set                         \\\n                                ? stbi__de_iphone_flag_local                    \\\n                                : stbi__de_iphone_flag_global)\n#endif // STBI_THREAD_LOCAL\n\nstatic void stbi__de_iphone(stbi__png *z)\n{\n   stbi__context *s = z->s;\n   stbi__uint32 i, pixel_count = s->img_x * s->img_y;\n   stbi_uc *p = z->out;\n\n   if (s->img_out_n == 3) {  // convert bgr to rgb\n      for (i=0; i < pixel_count; ++i) {\n         stbi_uc t = p[0];\n         p[0] = p[2];\n         p[2] = t;\n         p += 3;\n      }\n   } else {\n      STBI_ASSERT(s->img_out_n == 4);\n      if (stbi__unpremultiply_on_load) {\n         // convert bgr to rgb and unpremultiply\n         for (i=0; i < pixel_count; ++i) {\n            stbi_uc a = p[3];\n            stbi_uc t = p[0];\n            if (a) {\n               stbi_uc half = a / 2;\n               p[0] = (p[2] * 255 + half) / a;\n               p[1] = (p[1] * 255 + half) / a;\n               p[2] = ( t   * 255 + half) / a;\n            } else {\n               p[0] = p[2];\n               p[2] = t;\n            }\n            p += 4;\n         }\n      } else {\n         // convert bgr to rgb\n         for (i=0; i < pixel_count; ++i) {\n            stbi_uc t = p[0];\n            p[0] = p[2];\n            p[2] = t;\n            p += 4;\n         }\n      }\n   }\n}\n\n#define STBI__PNG_TYPE(a,b,c,d)  (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d))\n\nstatic int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)\n{\n   stbi_uc palette[1024], pal_img_n=0;\n   stbi_uc has_trans=0, tc[3]={0};\n   stbi__uint16 tc16[3];\n   stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;\n   int first=1,k,interlace=0, color=0, is_iphone=0;\n   stbi__context *s = z->s;\n\n   z->expanded = NULL;\n   z->idata = NULL;\n   z->out = NULL;\n\n   if (!stbi__check_png_header(s)) return 0;\n\n   if (scan == STBI__SCAN_type) return 1;\n\n   for (;;) {\n      stbi__pngchunk c = stbi__get_chunk_header(s);\n      switch (c.type) {\n         case STBI__PNG_TYPE('C','g','B','I'):\n            is_iphone = 1;\n            stbi__skip(s, c.length);\n            break;\n         case STBI__PNG_TYPE('I','H','D','R'): {\n            int comp,filter;\n            if (!first) return stbi__err(\"multiple IHDR\",\"Corrupt PNG\");\n            first = 0;\n            if (c.length != 13) return stbi__err(\"bad IHDR len\",\"Corrupt PNG\");\n            s->img_x = stbi__get32be(s);\n            s->img_y = stbi__get32be(s);\n            if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err(\"too large\",\"Very large image (corrupt?)\");\n            if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err(\"too large\",\"Very large image (corrupt?)\");\n            z->depth = stbi__get8(s);  if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16)  return stbi__err(\"1/2/4/8/16-bit only\",\"PNG not supported: 1/2/4/8/16-bit only\");\n            color = stbi__get8(s);  if (color > 6)         return stbi__err(\"bad ctype\",\"Corrupt PNG\");\n            if (color == 3 && z->depth == 16)                  return stbi__err(\"bad ctype\",\"Corrupt PNG\");\n            if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err(\"bad ctype\",\"Corrupt PNG\");\n            comp  = stbi__get8(s);  if (comp) return stbi__err(\"bad comp method\",\"Corrupt PNG\");\n            filter= stbi__get8(s);  if (filter) return stbi__err(\"bad filter method\",\"Corrupt PNG\");\n            interlace = stbi__get8(s); if (interlace>1) return stbi__err(\"bad interlace method\",\"Corrupt PNG\");\n            if (!s->img_x || !s->img_y) return stbi__err(\"0-pixel image\",\"Corrupt PNG\");\n            if (!pal_img_n) {\n               s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);\n               if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err(\"too large\", \"Image too large to decode\");\n            } else {\n               // if paletted, then pal_n is our final components, and\n               // img_n is # components to decompress/filter.\n               s->img_n = 1;\n               if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err(\"too large\",\"Corrupt PNG\");\n            }\n            // even with SCAN_header, have to scan to see if we have a tRNS\n            break;\n         }\n\n         case STBI__PNG_TYPE('P','L','T','E'):  {\n            if (first) return stbi__err(\"first not IHDR\", \"Corrupt PNG\");\n            if (c.length > 256*3) return stbi__err(\"invalid PLTE\",\"Corrupt PNG\");\n            pal_len = c.length / 3;\n            if (pal_len * 3 != c.length) return stbi__err(\"invalid PLTE\",\"Corrupt PNG\");\n            for (i=0; i < pal_len; ++i) {\n               palette[i*4+0] = stbi__get8(s);\n               palette[i*4+1] = stbi__get8(s);\n               palette[i*4+2] = stbi__get8(s);\n               palette[i*4+3] = 255;\n            }\n            break;\n         }\n\n         case STBI__PNG_TYPE('t','R','N','S'): {\n            if (first) return stbi__err(\"first not IHDR\", \"Corrupt PNG\");\n            if (z->idata) return stbi__err(\"tRNS after IDAT\",\"Corrupt PNG\");\n            if (pal_img_n) {\n               if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }\n               if (pal_len == 0) return stbi__err(\"tRNS before PLTE\",\"Corrupt PNG\");\n               if (c.length > pal_len) return stbi__err(\"bad tRNS len\",\"Corrupt PNG\");\n               pal_img_n = 4;\n               for (i=0; i < c.length; ++i)\n                  palette[i*4+3] = stbi__get8(s);\n            } else {\n               if (!(s->img_n & 1)) return stbi__err(\"tRNS with alpha\",\"Corrupt PNG\");\n               if (c.length != (stbi__uint32) s->img_n*2) return stbi__err(\"bad tRNS len\",\"Corrupt PNG\");\n               has_trans = 1;\n               // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now.\n               if (scan == STBI__SCAN_header) { ++s->img_n; return 1; }\n               if (z->depth == 16) {\n                  for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning\n                     tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is\n               } else {\n                  for (k = 0; k < s->img_n && k < 3; ++k)\n                     tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger\n               }\n            }\n            break;\n         }\n\n         case STBI__PNG_TYPE('I','D','A','T'): {\n            if (first) return stbi__err(\"first not IHDR\", \"Corrupt PNG\");\n            if (pal_img_n && !pal_len) return stbi__err(\"no PLTE\",\"Corrupt PNG\");\n            if (scan == STBI__SCAN_header) {\n               // header scan definitely stops at first IDAT\n               if (pal_img_n)\n                  s->img_n = pal_img_n;\n               return 1;\n            }\n            if (c.length > (1u << 30)) return stbi__err(\"IDAT size limit\", \"IDAT section larger than 2^30 bytes\");\n            if ((int)(ioff + c.length) < (int)ioff) return 0;\n            if (ioff + c.length > idata_limit) {\n               stbi__uint32 idata_limit_old = idata_limit;\n               stbi_uc *p;\n               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;\n               while (ioff + c.length > idata_limit)\n                  idata_limit *= 2;\n               STBI_NOTUSED(idata_limit_old);\n               p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err(\"outofmem\", \"Out of memory\");\n               z->idata = p;\n            }\n            if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err(\"outofdata\",\"Corrupt PNG\");\n            ioff += c.length;\n            break;\n         }\n\n         case STBI__PNG_TYPE('I','E','N','D'): {\n            stbi__uint32 raw_len, bpl;\n            if (first) return stbi__err(\"first not IHDR\", \"Corrupt PNG\");\n            if (scan != STBI__SCAN_load) return 1;\n            if (z->idata == NULL) return stbi__err(\"no IDAT\",\"Corrupt PNG\");\n            // initial guess for decoded data size to avoid unnecessary reallocs\n            bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component\n            raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;\n            z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);\n            if (z->expanded == NULL) return 0; // zlib should set error\n            STBI_FREE(z->idata); z->idata = NULL;\n            if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)\n               s->img_out_n = s->img_n+1;\n            else\n               s->img_out_n = s->img_n;\n            if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0;\n            if (has_trans) {\n               if (z->depth == 16) {\n                  if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;\n               } else {\n                  if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;\n               }\n            }\n            if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)\n               stbi__de_iphone(z);\n            if (pal_img_n) {\n               // pal_img_n == 3 or 4\n               s->img_n = pal_img_n; // record the actual colors we had\n               s->img_out_n = pal_img_n;\n               if (req_comp >= 3) s->img_out_n = req_comp;\n               if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))\n                  return 0;\n            } else if (has_trans) {\n               // non-paletted image with tRNS -> source image has (constant) alpha\n               ++s->img_n;\n            }\n            STBI_FREE(z->expanded); z->expanded = NULL;\n            // end of PNG chunk, read and skip CRC\n            stbi__get32be(s);\n            return 1;\n         }\n\n         default:\n            // if critical, fail\n            if (first) return stbi__err(\"first not IHDR\", \"Corrupt PNG\");\n            if ((c.type & (1 << 29)) == 0) {\n               #ifndef STBI_NO_FAILURE_STRINGS\n               // not threadsafe\n               static char invalid_chunk[] = \"XXXX PNG chunk not known\";\n               invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);\n               invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);\n               invalid_chunk[2] = STBI__BYTECAST(c.type >>  8);\n               invalid_chunk[3] = STBI__BYTECAST(c.type >>  0);\n               #endif\n               return stbi__err(invalid_chunk, \"PNG not supported: unknown PNG chunk type\");\n            }\n            stbi__skip(s, c.length);\n            break;\n      }\n      // end of PNG chunk, read and skip CRC\n      stbi__get32be(s);\n   }\n}\n\nstatic void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri)\n{\n   void *result=NULL;\n   if (req_comp < 0 || req_comp > 4) return stbi__errpuc(\"bad req_comp\", \"Internal error\");\n   if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {\n      if (p->depth <= 8)\n         ri->bits_per_channel = 8;\n      else if (p->depth == 16)\n         ri->bits_per_channel = 16;\n      else\n         return stbi__errpuc(\"bad bits_per_channel\", \"PNG not supported: unsupported color depth\");\n      result = p->out;\n      p->out = NULL;\n      if (req_comp && req_comp != p->s->img_out_n) {\n         if (ri->bits_per_channel == 8)\n            result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);\n         else\n            result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);\n         p->s->img_out_n = req_comp;\n         if (result == NULL) return result;\n      }\n      *x = p->s->img_x;\n      *y = p->s->img_y;\n      if (n) *n = p->s->img_n;\n   }\n   STBI_FREE(p->out);      p->out      = NULL;\n   STBI_FREE(p->expanded); p->expanded = NULL;\n   STBI_FREE(p->idata);    p->idata    = NULL;\n\n   return result;\n}\n\nstatic void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   stbi__png p;\n   p.s = s;\n   return stbi__do_png(&p, x,y,comp,req_comp, ri);\n}\n\nstatic int stbi__png_test(stbi__context *s)\n{\n   int r;\n   r = stbi__check_png_header(s);\n   stbi__rewind(s);\n   return r;\n}\n\nstatic int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)\n{\n   if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {\n      stbi__rewind( p->s );\n      return 0;\n   }\n   if (x) *x = p->s->img_x;\n   if (y) *y = p->s->img_y;\n   if (comp) *comp = p->s->img_n;\n   return 1;\n}\n\nstatic int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   stbi__png p;\n   p.s = s;\n   return stbi__png_info_raw(&p, x, y, comp);\n}\n\nstatic int stbi__png_is16(stbi__context *s)\n{\n   stbi__png p;\n   p.s = s;\n   if (!stbi__png_info_raw(&p, NULL, NULL, NULL))\n\t   return 0;\n   if (p.depth != 16) {\n      stbi__rewind(p.s);\n      return 0;\n   }\n   return 1;\n}\n#endif\n\n// Microsoft/Windows BMP image\n\n#ifndef STBI_NO_BMP\nstatic int stbi__bmp_test_raw(stbi__context *s)\n{\n   int r;\n   int sz;\n   if (stbi__get8(s) != 'B') return 0;\n   if (stbi__get8(s) != 'M') return 0;\n   stbi__get32le(s); // discard filesize\n   stbi__get16le(s); // discard reserved\n   stbi__get16le(s); // discard reserved\n   stbi__get32le(s); // discard data offset\n   sz = stbi__get32le(s);\n   r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);\n   return r;\n}\n\nstatic int stbi__bmp_test(stbi__context *s)\n{\n   int r = stbi__bmp_test_raw(s);\n   stbi__rewind(s);\n   return r;\n}\n\n\n// returns 0..31 for the highest set bit\nstatic int stbi__high_bit(unsigned int z)\n{\n   int n=0;\n   if (z == 0) return -1;\n   if (z >= 0x10000) { n += 16; z >>= 16; }\n   if (z >= 0x00100) { n +=  8; z >>=  8; }\n   if (z >= 0x00010) { n +=  4; z >>=  4; }\n   if (z >= 0x00004) { n +=  2; z >>=  2; }\n   if (z >= 0x00002) { n +=  1;/* >>=  1;*/ }\n   return n;\n}\n\nstatic int stbi__bitcount(unsigned int a)\n{\n   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2\n   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4\n   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits\n   a = (a + (a >> 8)); // max 16 per 8 bits\n   a = (a + (a >> 16)); // max 32 per 8 bits\n   return a & 0xff;\n}\n\n// extract an arbitrarily-aligned N-bit value (N=bits)\n// from v, and then make it 8-bits long and fractionally\n// extend it to full full range.\nstatic int stbi__shiftsigned(unsigned int v, int shift, int bits)\n{\n   static unsigned int mul_table[9] = {\n      0,\n      0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/,\n      0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/,\n   };\n   static unsigned int shift_table[9] = {\n      0, 0,0,1,0,2,4,6,0,\n   };\n   if (shift < 0)\n      v <<= -shift;\n   else\n      v >>= shift;\n   STBI_ASSERT(v < 256);\n   v >>= (8-bits);\n   STBI_ASSERT(bits >= 0 && bits <= 8);\n   return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits];\n}\n\ntypedef struct\n{\n   int bpp, offset, hsz;\n   unsigned int mr,mg,mb,ma, all_a;\n   int extra_read;\n} stbi__bmp_data;\n\nstatic int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress)\n{\n   // BI_BITFIELDS specifies masks explicitly, don't override\n   if (compress == 3)\n      return 1;\n\n   if (compress == 0) {\n      if (info->bpp == 16) {\n         info->mr = 31u << 10;\n         info->mg = 31u <<  5;\n         info->mb = 31u <<  0;\n      } else if (info->bpp == 32) {\n         info->mr = 0xffu << 16;\n         info->mg = 0xffu <<  8;\n         info->mb = 0xffu <<  0;\n         info->ma = 0xffu << 24;\n         info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0\n      } else {\n         // otherwise, use defaults, which is all-0\n         info->mr = info->mg = info->mb = info->ma = 0;\n      }\n      return 1;\n   }\n   return 0; // error\n}\n\nstatic void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)\n{\n   int hsz;\n   if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc(\"not BMP\", \"Corrupt BMP\");\n   stbi__get32le(s); // discard filesize\n   stbi__get16le(s); // discard reserved\n   stbi__get16le(s); // discard reserved\n   info->offset = stbi__get32le(s);\n   info->hsz = hsz = stbi__get32le(s);\n   info->mr = info->mg = info->mb = info->ma = 0;\n   info->extra_read = 14;\n\n   if (info->offset < 0) return stbi__errpuc(\"bad BMP\", \"bad BMP\");\n\n   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc(\"unknown BMP\", \"BMP type not supported: unknown\");\n   if (hsz == 12) {\n      s->img_x = stbi__get16le(s);\n      s->img_y = stbi__get16le(s);\n   } else {\n      s->img_x = stbi__get32le(s);\n      s->img_y = stbi__get32le(s);\n   }\n   if (stbi__get16le(s) != 1) return stbi__errpuc(\"bad BMP\", \"bad BMP\");\n   info->bpp = stbi__get16le(s);\n   if (hsz != 12) {\n      int compress = stbi__get32le(s);\n      if (compress == 1 || compress == 2) return stbi__errpuc(\"BMP RLE\", \"BMP type not supported: RLE\");\n      if (compress >= 4) return stbi__errpuc(\"BMP JPEG/PNG\", \"BMP type not supported: unsupported compression\"); // this includes PNG/JPEG modes\n      if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc(\"bad BMP\", \"bad BMP\"); // bitfields requires 16 or 32 bits/pixel\n      stbi__get32le(s); // discard sizeof\n      stbi__get32le(s); // discard hres\n      stbi__get32le(s); // discard vres\n      stbi__get32le(s); // discard colorsused\n      stbi__get32le(s); // discard max important\n      if (hsz == 40 || hsz == 56) {\n         if (hsz == 56) {\n            stbi__get32le(s);\n            stbi__get32le(s);\n            stbi__get32le(s);\n            stbi__get32le(s);\n         }\n         if (info->bpp == 16 || info->bpp == 32) {\n            if (compress == 0) {\n               stbi__bmp_set_mask_defaults(info, compress);\n            } else if (compress == 3) {\n               info->mr = stbi__get32le(s);\n               info->mg = stbi__get32le(s);\n               info->mb = stbi__get32le(s);\n               info->extra_read += 12;\n               // not documented, but generated by photoshop and handled by mspaint\n               if (info->mr == info->mg && info->mg == info->mb) {\n                  // ?!?!?\n                  return stbi__errpuc(\"bad BMP\", \"bad BMP\");\n               }\n            } else\n               return stbi__errpuc(\"bad BMP\", \"bad BMP\");\n         }\n      } else {\n         // V4/V5 header\n         int i;\n         if (hsz != 108 && hsz != 124)\n            return stbi__errpuc(\"bad BMP\", \"bad BMP\");\n         info->mr = stbi__get32le(s);\n         info->mg = stbi__get32le(s);\n         info->mb = stbi__get32le(s);\n         info->ma = stbi__get32le(s);\n         if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs\n            stbi__bmp_set_mask_defaults(info, compress);\n         stbi__get32le(s); // discard color space\n         for (i=0; i < 12; ++i)\n            stbi__get32le(s); // discard color space parameters\n         if (hsz == 124) {\n            stbi__get32le(s); // discard rendering intent\n            stbi__get32le(s); // discard offset of profile data\n            stbi__get32le(s); // discard size of profile data\n            stbi__get32le(s); // discard reserved\n         }\n      }\n   }\n   return (void *) 1;\n}\n\n\nstatic void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   stbi_uc *out;\n   unsigned int mr=0,mg=0,mb=0,ma=0, all_a;\n   stbi_uc pal[256][4];\n   int psize=0,i,j,width;\n   int flip_vertically, pad, target;\n   stbi__bmp_data info;\n   STBI_NOTUSED(ri);\n\n   info.all_a = 255;\n   if (stbi__bmp_parse_header(s, &info) == NULL)\n      return NULL; // error code already set\n\n   flip_vertically = ((int) s->img_y) > 0;\n   s->img_y = abs((int) s->img_y);\n\n   if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n   if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n\n   mr = info.mr;\n   mg = info.mg;\n   mb = info.mb;\n   ma = info.ma;\n   all_a = info.all_a;\n\n   if (info.hsz == 12) {\n      if (info.bpp < 24)\n         psize = (info.offset - info.extra_read - 24) / 3;\n   } else {\n      if (info.bpp < 16)\n         psize = (info.offset - info.extra_read - info.hsz) >> 2;\n   }\n   if (psize == 0) {\n      // accept some number of extra bytes after the header, but if the offset points either to before\n      // the header ends or implies a large amount of extra data, reject the file as malformed\n      int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original);\n      int header_limit = 1024; // max we actually read is below 256 bytes currently.\n      int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.\n      if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) {\n         return stbi__errpuc(\"bad header\", \"Corrupt BMP\");\n      }\n      // we established that bytes_read_so_far is positive and sensible.\n      // the first half of this test rejects offsets that are either too small positives, or\n      // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn\n      // ensures the number computed in the second half of the test can't overflow.\n      if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) {\n         return stbi__errpuc(\"bad offset\", \"Corrupt BMP\");\n      } else {\n         stbi__skip(s, info.offset - bytes_read_so_far);\n      }\n   }\n\n   if (info.bpp == 24 && ma == 0xff000000)\n      s->img_n = 3;\n   else\n      s->img_n = ma ? 4 : 3;\n   if (req_comp && req_comp >= 3) // we can directly decode 3 or 4\n      target = req_comp;\n   else\n      target = s->img_n; // if they want monochrome, we'll post-convert\n\n   // sanity-check size\n   if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0))\n      return stbi__errpuc(\"too large\", \"Corrupt BMP\");\n\n   out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0);\n   if (!out) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n   if (info.bpp < 16) {\n      int z=0;\n      if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc(\"invalid\", \"Corrupt BMP\"); }\n      for (i=0; i < psize; ++i) {\n         pal[i][2] = stbi__get8(s);\n         pal[i][1] = stbi__get8(s);\n         pal[i][0] = stbi__get8(s);\n         if (info.hsz != 12) stbi__get8(s);\n         pal[i][3] = 255;\n      }\n      stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4));\n      if (info.bpp == 1) width = (s->img_x + 7) >> 3;\n      else if (info.bpp == 4) width = (s->img_x + 1) >> 1;\n      else if (info.bpp == 8) width = s->img_x;\n      else { STBI_FREE(out); return stbi__errpuc(\"bad bpp\", \"Corrupt BMP\"); }\n      pad = (-width)&3;\n      if (info.bpp == 1) {\n         for (j=0; j < (int) s->img_y; ++j) {\n            int bit_offset = 7, v = stbi__get8(s);\n            for (i=0; i < (int) s->img_x; ++i) {\n               int color = (v>>bit_offset)&0x1;\n               out[z++] = pal[color][0];\n               out[z++] = pal[color][1];\n               out[z++] = pal[color][2];\n               if (target == 4) out[z++] = 255;\n               if (i+1 == (int) s->img_x) break;\n               if((--bit_offset) < 0) {\n                  bit_offset = 7;\n                  v = stbi__get8(s);\n               }\n            }\n            stbi__skip(s, pad);\n         }\n      } else {\n         for (j=0; j < (int) s->img_y; ++j) {\n            for (i=0; i < (int) s->img_x; i += 2) {\n               int v=stbi__get8(s),v2=0;\n               if (info.bpp == 4) {\n                  v2 = v & 15;\n                  v >>= 4;\n               }\n               out[z++] = pal[v][0];\n               out[z++] = pal[v][1];\n               out[z++] = pal[v][2];\n               if (target == 4) out[z++] = 255;\n               if (i+1 == (int) s->img_x) break;\n               v = (info.bpp == 8) ? stbi__get8(s) : v2;\n               out[z++] = pal[v][0];\n               out[z++] = pal[v][1];\n               out[z++] = pal[v][2];\n               if (target == 4) out[z++] = 255;\n            }\n            stbi__skip(s, pad);\n         }\n      }\n   } else {\n      int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;\n      int z = 0;\n      int easy=0;\n      stbi__skip(s, info.offset - info.extra_read - info.hsz);\n      if (info.bpp == 24) width = 3 * s->img_x;\n      else if (info.bpp == 16) width = 2*s->img_x;\n      else /* bpp = 32 and pad = 0 */ width=0;\n      pad = (-width) & 3;\n      if (info.bpp == 24) {\n         easy = 1;\n      } else if (info.bpp == 32) {\n         if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)\n            easy = 2;\n      }\n      if (!easy) {\n         if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc(\"bad masks\", \"Corrupt BMP\"); }\n         // right shift amt to put high bit in position #7\n         rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);\n         gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);\n         bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);\n         ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);\n         if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc(\"bad masks\", \"Corrupt BMP\"); }\n      }\n      for (j=0; j < (int) s->img_y; ++j) {\n         if (easy) {\n            for (i=0; i < (int) s->img_x; ++i) {\n               unsigned char a;\n               out[z+2] = stbi__get8(s);\n               out[z+1] = stbi__get8(s);\n               out[z+0] = stbi__get8(s);\n               z += 3;\n               a = (easy == 2 ? stbi__get8(s) : 255);\n               all_a |= a;\n               if (target == 4) out[z++] = a;\n            }\n         } else {\n            int bpp = info.bpp;\n            for (i=0; i < (int) s->img_x; ++i) {\n               stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));\n               unsigned int a;\n               out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));\n               out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));\n               out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));\n               a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);\n               all_a |= a;\n               if (target == 4) out[z++] = STBI__BYTECAST(a);\n            }\n         }\n         stbi__skip(s, pad);\n      }\n   }\n\n   // if alpha channel is all 0s, replace with all 255s\n   if (target == 4 && all_a == 0)\n      for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4)\n         out[i] = 255;\n\n   if (flip_vertically) {\n      stbi_uc t;\n      for (j=0; j < (int) s->img_y>>1; ++j) {\n         stbi_uc *p1 = out +      j     *s->img_x*target;\n         stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;\n         for (i=0; i < (int) s->img_x*target; ++i) {\n            t = p1[i]; p1[i] = p2[i]; p2[i] = t;\n         }\n      }\n   }\n\n   if (req_comp && req_comp != target) {\n      out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);\n      if (out == NULL) return out; // stbi__convert_format frees input on failure\n   }\n\n   *x = s->img_x;\n   *y = s->img_y;\n   if (comp) *comp = s->img_n;\n   return out;\n}\n#endif\n\n// Targa Truevision - TGA\n// by Jonathan Dummer\n#ifndef STBI_NO_TGA\n// returns STBI_rgb or whatever, 0 on error\nstatic int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16)\n{\n   // only RGB or RGBA (incl. 16bit) or grey allowed\n   if (is_rgb16) *is_rgb16 = 0;\n   switch(bits_per_pixel) {\n      case 8:  return STBI_grey;\n      case 16: if(is_grey) return STBI_grey_alpha;\n               // fallthrough\n      case 15: if(is_rgb16) *is_rgb16 = 1;\n               return STBI_rgb;\n      case 24: // fallthrough\n      case 32: return bits_per_pixel/8;\n      default: return 0;\n   }\n}\n\nstatic int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)\n{\n    int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;\n    int sz, tga_colormap_type;\n    stbi__get8(s);                   // discard Offset\n    tga_colormap_type = stbi__get8(s); // colormap type\n    if( tga_colormap_type > 1 ) {\n        stbi__rewind(s);\n        return 0;      // only RGB or indexed allowed\n    }\n    tga_image_type = stbi__get8(s); // image type\n    if ( tga_colormap_type == 1 ) { // colormapped (paletted) image\n        if (tga_image_type != 1 && tga_image_type != 9) {\n            stbi__rewind(s);\n            return 0;\n        }\n        stbi__skip(s,4);       // skip index of first colormap entry and number of entries\n        sz = stbi__get8(s);    //   check bits per palette color entry\n        if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) {\n            stbi__rewind(s);\n            return 0;\n        }\n        stbi__skip(s,4);       // skip image x and y origin\n        tga_colormap_bpp = sz;\n    } else { // \"normal\" image w/o colormap - only RGB or grey allowed, +/- RLE\n        if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) {\n            stbi__rewind(s);\n            return 0; // only RGB or grey allowed, +/- RLE\n        }\n        stbi__skip(s,9); // skip colormap specification and image x/y origin\n        tga_colormap_bpp = 0;\n    }\n    tga_w = stbi__get16le(s);\n    if( tga_w < 1 ) {\n        stbi__rewind(s);\n        return 0;   // test width\n    }\n    tga_h = stbi__get16le(s);\n    if( tga_h < 1 ) {\n        stbi__rewind(s);\n        return 0;   // test height\n    }\n    tga_bits_per_pixel = stbi__get8(s); // bits per pixel\n    stbi__get8(s); // ignore alpha bits\n    if (tga_colormap_bpp != 0) {\n        if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) {\n            // when using a colormap, tga_bits_per_pixel is the size of the indexes\n            // I don't think anything but 8 or 16bit indexes makes sense\n            stbi__rewind(s);\n            return 0;\n        }\n        tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);\n    } else {\n        tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL);\n    }\n    if(!tga_comp) {\n      stbi__rewind(s);\n      return 0;\n    }\n    if (x) *x = tga_w;\n    if (y) *y = tga_h;\n    if (comp) *comp = tga_comp;\n    return 1;                   // seems to have passed everything\n}\n\nstatic int stbi__tga_test(stbi__context *s)\n{\n   int res = 0;\n   int sz, tga_color_type;\n   stbi__get8(s);      //   discard Offset\n   tga_color_type = stbi__get8(s);   //   color type\n   if ( tga_color_type > 1 ) goto errorEnd;   //   only RGB or indexed allowed\n   sz = stbi__get8(s);   //   image type\n   if ( tga_color_type == 1 ) { // colormapped (paletted) image\n      if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9\n      stbi__skip(s,4);       // skip index of first colormap entry and number of entries\n      sz = stbi__get8(s);    //   check bits per palette color entry\n      if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;\n      stbi__skip(s,4);       // skip image x and y origin\n   } else { // \"normal\" image w/o colormap\n      if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE\n      stbi__skip(s,9); // skip colormap specification and image x/y origin\n   }\n   if ( stbi__get16le(s) < 1 ) goto errorEnd;      //   test width\n   if ( stbi__get16le(s) < 1 ) goto errorEnd;      //   test height\n   sz = stbi__get8(s);   //   bits per pixel\n   if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index\n   if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;\n\n   res = 1; // if we got this far, everything's good and we can return 1 instead of 0\n\nerrorEnd:\n   stbi__rewind(s);\n   return res;\n}\n\n// read 16bit value and convert to 24bit RGB\nstatic void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)\n{\n   stbi__uint16 px = (stbi__uint16)stbi__get16le(s);\n   stbi__uint16 fiveBitMask = 31;\n   // we have 3 channels with 5bits each\n   int r = (px >> 10) & fiveBitMask;\n   int g = (px >> 5) & fiveBitMask;\n   int b = px & fiveBitMask;\n   // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later\n   out[0] = (stbi_uc)((r * 255)/31);\n   out[1] = (stbi_uc)((g * 255)/31);\n   out[2] = (stbi_uc)((b * 255)/31);\n\n   // some people claim that the most significant bit might be used for alpha\n   // (possibly if an alpha-bit is set in the \"image descriptor byte\")\n   // but that only made 16bit test images completely translucent..\n   // so let's treat all 15 and 16bit TGAs as RGB with no alpha.\n}\n\nstatic void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   //   read in the TGA header stuff\n   int tga_offset = stbi__get8(s);\n   int tga_indexed = stbi__get8(s);\n   int tga_image_type = stbi__get8(s);\n   int tga_is_RLE = 0;\n   int tga_palette_start = stbi__get16le(s);\n   int tga_palette_len = stbi__get16le(s);\n   int tga_palette_bits = stbi__get8(s);\n   int tga_x_origin = stbi__get16le(s);\n   int tga_y_origin = stbi__get16le(s);\n   int tga_width = stbi__get16le(s);\n   int tga_height = stbi__get16le(s);\n   int tga_bits_per_pixel = stbi__get8(s);\n   int tga_comp, tga_rgb16=0;\n   int tga_inverted = stbi__get8(s);\n   // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?)\n   //   image data\n   unsigned char *tga_data;\n   unsigned char *tga_palette = NULL;\n   int i, j;\n   unsigned char raw_data[4] = {0};\n   int RLE_count = 0;\n   int RLE_repeating = 0;\n   int read_next_pixel = 1;\n   STBI_NOTUSED(ri);\n   STBI_NOTUSED(tga_x_origin); // @TODO\n   STBI_NOTUSED(tga_y_origin); // @TODO\n\n   if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n   if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n\n   //   do a tiny bit of precessing\n   if ( tga_image_type >= 8 )\n   {\n      tga_image_type -= 8;\n      tga_is_RLE = 1;\n   }\n   tga_inverted = 1 - ((tga_inverted >> 5) & 1);\n\n   //   If I'm paletted, then I'll use the number of bits from the palette\n   if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);\n   else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);\n\n   if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency\n      return stbi__errpuc(\"bad format\", \"Can't find out TGA pixelformat\");\n\n   //   tga info\n   *x = tga_width;\n   *y = tga_height;\n   if (comp) *comp = tga_comp;\n\n   if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))\n      return stbi__errpuc(\"too large\", \"Corrupt TGA\");\n\n   tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);\n   if (!tga_data) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n\n   // skip to the data's starting position (offset usually = 0)\n   stbi__skip(s, tga_offset );\n\n   if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) {\n      for (i=0; i < tga_height; ++i) {\n         int row = tga_inverted ? tga_height -i - 1 : i;\n         stbi_uc *tga_row = tga_data + row*tga_width*tga_comp;\n         stbi__getn(s, tga_row, tga_width * tga_comp);\n      }\n   } else  {\n      //   do I need to load a palette?\n      if ( tga_indexed)\n      {\n         if (tga_palette_len == 0) {  /* you have to have at least one entry! */\n            STBI_FREE(tga_data);\n            return stbi__errpuc(\"bad palette\", \"Corrupt TGA\");\n         }\n\n         //   any data to skip? (offset usually = 0)\n         stbi__skip(s, tga_palette_start );\n         //   load the palette\n         tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0);\n         if (!tga_palette) {\n            STBI_FREE(tga_data);\n            return stbi__errpuc(\"outofmem\", \"Out of memory\");\n         }\n         if (tga_rgb16) {\n            stbi_uc *pal_entry = tga_palette;\n            STBI_ASSERT(tga_comp == STBI_rgb);\n            for (i=0; i < tga_palette_len; ++i) {\n               stbi__tga_read_rgb16(s, pal_entry);\n               pal_entry += tga_comp;\n            }\n         } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) {\n               STBI_FREE(tga_data);\n               STBI_FREE(tga_palette);\n               return stbi__errpuc(\"bad palette\", \"Corrupt TGA\");\n         }\n      }\n      //   load the data\n      for (i=0; i < tga_width * tga_height; ++i)\n      {\n         //   if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?\n         if ( tga_is_RLE )\n         {\n            if ( RLE_count == 0 )\n            {\n               //   yep, get the next byte as a RLE command\n               int RLE_cmd = stbi__get8(s);\n               RLE_count = 1 + (RLE_cmd & 127);\n               RLE_repeating = RLE_cmd >> 7;\n               read_next_pixel = 1;\n            } else if ( !RLE_repeating )\n            {\n               read_next_pixel = 1;\n            }\n         } else\n         {\n            read_next_pixel = 1;\n         }\n         //   OK, if I need to read a pixel, do it now\n         if ( read_next_pixel )\n         {\n            //   load however much data we did have\n            if ( tga_indexed )\n            {\n               // read in index, then perform the lookup\n               int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);\n               if ( pal_idx >= tga_palette_len ) {\n                  // invalid index\n                  pal_idx = 0;\n               }\n               pal_idx *= tga_comp;\n               for (j = 0; j < tga_comp; ++j) {\n                  raw_data[j] = tga_palette[pal_idx+j];\n               }\n            } else if(tga_rgb16) {\n               STBI_ASSERT(tga_comp == STBI_rgb);\n               stbi__tga_read_rgb16(s, raw_data);\n            } else {\n               //   read in the data raw\n               for (j = 0; j < tga_comp; ++j) {\n                  raw_data[j] = stbi__get8(s);\n               }\n            }\n            //   clear the reading flag for the next pixel\n            read_next_pixel = 0;\n         } // end of reading a pixel\n\n         // copy data\n         for (j = 0; j < tga_comp; ++j)\n           tga_data[i*tga_comp+j] = raw_data[j];\n\n         //   in case we're in RLE mode, keep counting down\n         --RLE_count;\n      }\n      //   do I need to invert the image?\n      if ( tga_inverted )\n      {\n         for (j = 0; j*2 < tga_height; ++j)\n         {\n            int index1 = j * tga_width * tga_comp;\n            int index2 = (tga_height - 1 - j) * tga_width * tga_comp;\n            for (i = tga_width * tga_comp; i > 0; --i)\n            {\n               unsigned char temp = tga_data[index1];\n               tga_data[index1] = tga_data[index2];\n               tga_data[index2] = temp;\n               ++index1;\n               ++index2;\n            }\n         }\n      }\n      //   clear my palette, if I had one\n      if ( tga_palette != NULL )\n      {\n         STBI_FREE( tga_palette );\n      }\n   }\n\n   // swap RGB - if the source data was RGB16, it already is in the right order\n   if (tga_comp >= 3 && !tga_rgb16)\n   {\n      unsigned char* tga_pixel = tga_data;\n      for (i=0; i < tga_width * tga_height; ++i)\n      {\n         unsigned char temp = tga_pixel[0];\n         tga_pixel[0] = tga_pixel[2];\n         tga_pixel[2] = temp;\n         tga_pixel += tga_comp;\n      }\n   }\n\n   // convert to target component count\n   if (req_comp && req_comp != tga_comp)\n      tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);\n\n   //   the things I do to get rid of an error message, and yet keep\n   //   Microsoft's C compilers happy... [8^(\n   tga_palette_start = tga_palette_len = tga_palette_bits =\n         tga_x_origin = tga_y_origin = 0;\n   STBI_NOTUSED(tga_palette_start);\n   //   OK, done\n   return tga_data;\n}\n#endif\n\n// *************************************************************************************************\n// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB\n\n#ifndef STBI_NO_PSD\nstatic int stbi__psd_test(stbi__context *s)\n{\n   int r = (stbi__get32be(s) == 0x38425053);\n   stbi__rewind(s);\n   return r;\n}\n\nstatic int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount)\n{\n   int count, nleft, len;\n\n   count = 0;\n   while ((nleft = pixelCount - count) > 0) {\n      len = stbi__get8(s);\n      if (len == 128) {\n         // No-op.\n      } else if (len < 128) {\n         // Copy next len+1 bytes literally.\n         len++;\n         if (len > nleft) return 0; // corrupt data\n         count += len;\n         while (len) {\n            *p = stbi__get8(s);\n            p += 4;\n            len--;\n         }\n      } else if (len > 128) {\n         stbi_uc   val;\n         // Next -len+1 bytes in the dest are replicated from next source byte.\n         // (Interpret len as a negative 8-bit int.)\n         len = 257 - len;\n         if (len > nleft) return 0; // corrupt data\n         val = stbi__get8(s);\n         count += len;\n         while (len) {\n            *p = val;\n            p += 4;\n            len--;\n         }\n      }\n   }\n\n   return 1;\n}\n\nstatic void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)\n{\n   int pixelCount;\n   int channelCount, compression;\n   int channel, i;\n   int bitdepth;\n   int w,h;\n   stbi_uc *out;\n   STBI_NOTUSED(ri);\n\n   // Check identifier\n   if (stbi__get32be(s) != 0x38425053)   // \"8BPS\"\n      return stbi__errpuc(\"not PSD\", \"Corrupt PSD image\");\n\n   // Check file type version.\n   if (stbi__get16be(s) != 1)\n      return stbi__errpuc(\"wrong version\", \"Unsupported version of PSD image\");\n\n   // Skip 6 reserved bytes.\n   stbi__skip(s, 6 );\n\n   // Read the number of channels (R, G, B, A, etc).\n   channelCount = stbi__get16be(s);\n   if (channelCount < 0 || channelCount > 16)\n      return stbi__errpuc(\"wrong channel count\", \"Unsupported number of channels in PSD image\");\n\n   // Read the rows and columns of the image.\n   h = stbi__get32be(s);\n   w = stbi__get32be(s);\n\n   if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n   if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n\n   // Make sure the depth is 8 bits.\n   bitdepth = stbi__get16be(s);\n   if (bitdepth != 8 && bitdepth != 16)\n      return stbi__errpuc(\"unsupported bit depth\", \"PSD bit depth is not 8 or 16 bit\");\n\n   // Make sure the color mode is RGB.\n   // Valid options are:\n   //   0: Bitmap\n   //   1: Grayscale\n   //   2: Indexed color\n   //   3: RGB color\n   //   4: CMYK color\n   //   7: Multichannel\n   //   8: Duotone\n   //   9: Lab color\n   if (stbi__get16be(s) != 3)\n      return stbi__errpuc(\"wrong color format\", \"PSD is not in RGB color format\");\n\n   // Skip the Mode Data.  (It's the palette for indexed color; other info for other modes.)\n   stbi__skip(s,stbi__get32be(s) );\n\n   // Skip the image resources.  (resolution, pen tool paths, etc)\n   stbi__skip(s, stbi__get32be(s) );\n\n   // Skip the reserved data.\n   stbi__skip(s, stbi__get32be(s) );\n\n   // Find out if the data is compressed.\n   // Known values:\n   //   0: no compression\n   //   1: RLE compressed\n   compression = stbi__get16be(s);\n   if (compression > 1)\n      return stbi__errpuc(\"bad compression\", \"PSD has an unknown compression format\");\n\n   // Check size\n   if (!stbi__mad3sizes_valid(4, w, h, 0))\n      return stbi__errpuc(\"too large\", \"Corrupt PSD\");\n\n   // Create the destination image.\n\n   if (!compression && bitdepth == 16 && bpc == 16) {\n      out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0);\n      ri->bits_per_channel = 16;\n   } else\n      out = (stbi_uc *) stbi__malloc(4 * w*h);\n\n   if (!out) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n   pixelCount = w*h;\n\n   // Initialize the data to zero.\n   //memset( out, 0, pixelCount * 4 );\n\n   // Finally, the image data.\n   if (compression) {\n      // RLE as used by .PSD and .TIFF\n      // Loop until you get the number of unpacked bytes you are expecting:\n      //     Read the next source byte into n.\n      //     If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.\n      //     Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.\n      //     Else if n is 128, noop.\n      // Endloop\n\n      // The RLE-compressed data is preceded by a 2-byte data count for each row in the data,\n      // which we're going to just skip.\n      stbi__skip(s, h * channelCount * 2 );\n\n      // Read the RLE data by channel.\n      for (channel = 0; channel < 4; channel++) {\n         stbi_uc *p;\n\n         p = out+channel;\n         if (channel >= channelCount) {\n            // Fill this channel with default data.\n            for (i = 0; i < pixelCount; i++, p += 4)\n               *p = (channel == 3 ? 255 : 0);\n         } else {\n            // Read the RLE data.\n            if (!stbi__psd_decode_rle(s, p, pixelCount)) {\n               STBI_FREE(out);\n               return stbi__errpuc(\"corrupt\", \"bad RLE data\");\n            }\n         }\n      }\n\n   } else {\n      // We're at the raw image data.  It's each channel in order (Red, Green, Blue, Alpha, ...)\n      // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image.\n\n      // Read the data by channel.\n      for (channel = 0; channel < 4; channel++) {\n         if (channel >= channelCount) {\n            // Fill this channel with default data.\n            if (bitdepth == 16 && bpc == 16) {\n               stbi__uint16 *q = ((stbi__uint16 *) out) + channel;\n               stbi__uint16 val = channel == 3 ? 65535 : 0;\n               for (i = 0; i < pixelCount; i++, q += 4)\n                  *q = val;\n            } else {\n               stbi_uc *p = out+channel;\n               stbi_uc val = channel == 3 ? 255 : 0;\n               for (i = 0; i < pixelCount; i++, p += 4)\n                  *p = val;\n            }\n         } else {\n            if (ri->bits_per_channel == 16) {    // output bpc\n               stbi__uint16 *q = ((stbi__uint16 *) out) + channel;\n               for (i = 0; i < pixelCount; i++, q += 4)\n                  *q = (stbi__uint16) stbi__get16be(s);\n            } else {\n               stbi_uc *p = out+channel;\n               if (bitdepth == 16) {  // input bpc\n                  for (i = 0; i < pixelCount; i++, p += 4)\n                     *p = (stbi_uc) (stbi__get16be(s) >> 8);\n               } else {\n                  for (i = 0; i < pixelCount; i++, p += 4)\n                     *p = stbi__get8(s);\n               }\n            }\n         }\n      }\n   }\n\n   // remove weird white matte from PSD\n   if (channelCount >= 4) {\n      if (ri->bits_per_channel == 16) {\n         for (i=0; i < w*h; ++i) {\n            stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i;\n            if (pixel[3] != 0 && pixel[3] != 65535) {\n               float a = pixel[3] / 65535.0f;\n               float ra = 1.0f / a;\n               float inv_a = 65535.0f * (1 - ra);\n               pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a);\n               pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a);\n               pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a);\n            }\n         }\n      } else {\n         for (i=0; i < w*h; ++i) {\n            unsigned char *pixel = out + 4*i;\n            if (pixel[3] != 0 && pixel[3] != 255) {\n               float a = pixel[3] / 255.0f;\n               float ra = 1.0f / a;\n               float inv_a = 255.0f * (1 - ra);\n               pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);\n               pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);\n               pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);\n            }\n         }\n      }\n   }\n\n   // convert to desired output format\n   if (req_comp && req_comp != 4) {\n      if (ri->bits_per_channel == 16)\n         out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h);\n      else\n         out = stbi__convert_format(out, 4, req_comp, w, h);\n      if (out == NULL) return out; // stbi__convert_format frees input on failure\n   }\n\n   if (comp) *comp = 4;\n   *y = h;\n   *x = w;\n\n   return out;\n}\n#endif\n\n// *************************************************************************************************\n// Softimage PIC loader\n// by Tom Seddon\n//\n// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format\n// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/\n\n#ifndef STBI_NO_PIC\nstatic int stbi__pic_is4(stbi__context *s,const char *str)\n{\n   int i;\n   for (i=0; i<4; ++i)\n      if (stbi__get8(s) != (stbi_uc)str[i])\n         return 0;\n\n   return 1;\n}\n\nstatic int stbi__pic_test_core(stbi__context *s)\n{\n   int i;\n\n   if (!stbi__pic_is4(s,\"\\x53\\x80\\xF6\\x34\"))\n      return 0;\n\n   for(i=0;i<84;++i)\n      stbi__get8(s);\n\n   if (!stbi__pic_is4(s,\"PICT\"))\n      return 0;\n\n   return 1;\n}\n\ntypedef struct\n{\n   stbi_uc size,type,channel;\n} stbi__pic_packet;\n\nstatic stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)\n{\n   int mask=0x80, i;\n\n   for (i=0; i<4; ++i, mask>>=1) {\n      if (channel & mask) {\n         if (stbi__at_eof(s)) return stbi__errpuc(\"bad file\",\"PIC file too short\");\n         dest[i]=stbi__get8(s);\n      }\n   }\n\n   return dest;\n}\n\nstatic void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)\n{\n   int mask=0x80,i;\n\n   for (i=0;i<4; ++i, mask>>=1)\n      if (channel&mask)\n         dest[i]=src[i];\n}\n\nstatic stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)\n{\n   int act_comp=0,num_packets=0,y,chained;\n   stbi__pic_packet packets[10];\n\n   // this will (should...) cater for even some bizarre stuff like having data\n    // for the same channel in multiple packets.\n   do {\n      stbi__pic_packet *packet;\n\n      if (num_packets==sizeof(packets)/sizeof(packets[0]))\n         return stbi__errpuc(\"bad format\",\"too many packets\");\n\n      packet = &packets[num_packets++];\n\n      chained = stbi__get8(s);\n      packet->size    = stbi__get8(s);\n      packet->type    = stbi__get8(s);\n      packet->channel = stbi__get8(s);\n\n      act_comp |= packet->channel;\n\n      if (stbi__at_eof(s))          return stbi__errpuc(\"bad file\",\"file too short (reading packets)\");\n      if (packet->size != 8)  return stbi__errpuc(\"bad format\",\"packet isn't 8bpp\");\n   } while (chained);\n\n   *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?\n\n   for(y=0; y<height; ++y) {\n      int packet_idx;\n\n      for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {\n         stbi__pic_packet *packet = &packets[packet_idx];\n         stbi_uc *dest = result+y*width*4;\n\n         switch (packet->type) {\n            default:\n               return stbi__errpuc(\"bad format\",\"packet has bad compression type\");\n\n            case 0: {//uncompressed\n               int x;\n\n               for(x=0;x<width;++x, dest+=4)\n                  if (!stbi__readval(s,packet->channel,dest))\n                     return 0;\n               break;\n            }\n\n            case 1://Pure RLE\n               {\n                  int left=width, i;\n\n                  while (left>0) {\n                     stbi_uc count,value[4];\n\n                     count=stbi__get8(s);\n                     if (stbi__at_eof(s))   return stbi__errpuc(\"bad file\",\"file too short (pure read count)\");\n\n                     if (count > left)\n                        count = (stbi_uc) left;\n\n                     if (!stbi__readval(s,packet->channel,value))  return 0;\n\n                     for(i=0; i<count; ++i,dest+=4)\n                        stbi__copyval(packet->channel,dest,value);\n                     left -= count;\n                  }\n               }\n               break;\n\n            case 2: {//Mixed RLE\n               int left=width;\n               while (left>0) {\n                  int count = stbi__get8(s), i;\n                  if (stbi__at_eof(s))  return stbi__errpuc(\"bad file\",\"file too short (mixed read count)\");\n\n                  if (count >= 128) { // Repeated\n                     stbi_uc value[4];\n\n                     if (count==128)\n                        count = stbi__get16be(s);\n                     else\n                        count -= 127;\n                     if (count > left)\n                        return stbi__errpuc(\"bad file\",\"scanline overrun\");\n\n                     if (!stbi__readval(s,packet->channel,value))\n                        return 0;\n\n                     for(i=0;i<count;++i, dest += 4)\n                        stbi__copyval(packet->channel,dest,value);\n                  } else { // Raw\n                     ++count;\n                     if (count>left) return stbi__errpuc(\"bad file\",\"scanline overrun\");\n\n                     for(i=0;i<count;++i, dest+=4)\n                        if (!stbi__readval(s,packet->channel,dest))\n                           return 0;\n                  }\n                  left-=count;\n               }\n               break;\n            }\n         }\n      }\n   }\n\n   return result;\n}\n\nstatic void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri)\n{\n   stbi_uc *result;\n   int i, x,y, internal_comp;\n   STBI_NOTUSED(ri);\n\n   if (!comp) comp = &internal_comp;\n\n   for (i=0; i<92; ++i)\n      stbi__get8(s);\n\n   x = stbi__get16be(s);\n   y = stbi__get16be(s);\n\n   if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n   if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n\n   if (stbi__at_eof(s))  return stbi__errpuc(\"bad file\",\"file too short (pic header)\");\n   if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc(\"too large\", \"PIC image too large to decode\");\n\n   stbi__get32be(s); //skip `ratio'\n   stbi__get16be(s); //skip `fields'\n   stbi__get16be(s); //skip `pad'\n\n   // intermediate buffer is RGBA\n   result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);\n   if (!result) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n   memset(result, 0xff, x*y*4);\n\n   if (!stbi__pic_load_core(s,x,y,comp, result)) {\n      STBI_FREE(result);\n      result=0;\n   }\n   *px = x;\n   *py = y;\n   if (req_comp == 0) req_comp = *comp;\n   result=stbi__convert_format(result,4,req_comp,x,y);\n\n   return result;\n}\n\nstatic int stbi__pic_test(stbi__context *s)\n{\n   int r = stbi__pic_test_core(s);\n   stbi__rewind(s);\n   return r;\n}\n#endif\n\n// *************************************************************************************************\n// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb\n\n#ifndef STBI_NO_GIF\ntypedef struct\n{\n   stbi__int16 prefix;\n   stbi_uc first;\n   stbi_uc suffix;\n} stbi__gif_lzw;\n\ntypedef struct\n{\n   int w,h;\n   stbi_uc *out;                 // output buffer (always 4 components)\n   stbi_uc *background;          // The current \"background\" as far as a gif is concerned\n   stbi_uc *history;\n   int flags, bgindex, ratio, transparent, eflags;\n   stbi_uc  pal[256][4];\n   stbi_uc lpal[256][4];\n   stbi__gif_lzw codes[8192];\n   stbi_uc *color_table;\n   int parse, step;\n   int lflags;\n   int start_x, start_y;\n   int max_x, max_y;\n   int cur_x, cur_y;\n   int line_size;\n   int delay;\n} stbi__gif;\n\nstatic int stbi__gif_test_raw(stbi__context *s)\n{\n   int sz;\n   if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;\n   sz = stbi__get8(s);\n   if (sz != '9' && sz != '7') return 0;\n   if (stbi__get8(s) != 'a') return 0;\n   return 1;\n}\n\nstatic int stbi__gif_test(stbi__context *s)\n{\n   int r = stbi__gif_test_raw(s);\n   stbi__rewind(s);\n   return r;\n}\n\nstatic void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)\n{\n   int i;\n   for (i=0; i < num_entries; ++i) {\n      pal[i][2] = stbi__get8(s);\n      pal[i][1] = stbi__get8(s);\n      pal[i][0] = stbi__get8(s);\n      pal[i][3] = transp == i ? 0 : 255;\n   }\n}\n\nstatic int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)\n{\n   stbi_uc version;\n   if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')\n      return stbi__err(\"not GIF\", \"Corrupt GIF\");\n\n   version = stbi__get8(s);\n   if (version != '7' && version != '9')    return stbi__err(\"not GIF\", \"Corrupt GIF\");\n   if (stbi__get8(s) != 'a')                return stbi__err(\"not GIF\", \"Corrupt GIF\");\n\n   stbi__g_failure_reason = \"\";\n   g->w = stbi__get16le(s);\n   g->h = stbi__get16le(s);\n   g->flags = stbi__get8(s);\n   g->bgindex = stbi__get8(s);\n   g->ratio = stbi__get8(s);\n   g->transparent = -1;\n\n   if (g->w > STBI_MAX_DIMENSIONS) return stbi__err(\"too large\",\"Very large image (corrupt?)\");\n   if (g->h > STBI_MAX_DIMENSIONS) return stbi__err(\"too large\",\"Very large image (corrupt?)\");\n\n   if (comp != 0) *comp = 4;  // can't actually tell whether it's 3 or 4 until we parse the comments\n\n   if (is_info) return 1;\n\n   if (g->flags & 0x80)\n      stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);\n\n   return 1;\n}\n\nstatic int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)\n{\n   stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));\n   if (!g) return stbi__err(\"outofmem\", \"Out of memory\");\n   if (!stbi__gif_header(s, g, comp, 1)) {\n      STBI_FREE(g);\n      stbi__rewind( s );\n      return 0;\n   }\n   if (x) *x = g->w;\n   if (y) *y = g->h;\n   STBI_FREE(g);\n   return 1;\n}\n\nstatic void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)\n{\n   stbi_uc *p, *c;\n   int idx;\n\n   // recurse to decode the prefixes, since the linked-list is backwards,\n   // and working backwards through an interleaved image would be nasty\n   if (g->codes[code].prefix >= 0)\n      stbi__out_gif_code(g, g->codes[code].prefix);\n\n   if (g->cur_y >= g->max_y) return;\n\n   idx = g->cur_x + g->cur_y;\n   p = &g->out[idx];\n   g->history[idx / 4] = 1;\n\n   c = &g->color_table[g->codes[code].suffix * 4];\n   if (c[3] > 128) { // don't render transparent pixels;\n      p[0] = c[2];\n      p[1] = c[1];\n      p[2] = c[0];\n      p[3] = c[3];\n   }\n   g->cur_x += 4;\n\n   if (g->cur_x >= g->max_x) {\n      g->cur_x = g->start_x;\n      g->cur_y += g->step;\n\n      while (g->cur_y >= g->max_y && g->parse > 0) {\n         g->step = (1 << g->parse) * g->line_size;\n         g->cur_y = g->start_y + (g->step >> 1);\n         --g->parse;\n      }\n   }\n}\n\nstatic stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)\n{\n   stbi_uc lzw_cs;\n   stbi__int32 len, init_code;\n   stbi__uint32 first;\n   stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;\n   stbi__gif_lzw *p;\n\n   lzw_cs = stbi__get8(s);\n   if (lzw_cs > 12) return NULL;\n   clear = 1 << lzw_cs;\n   first = 1;\n   codesize = lzw_cs + 1;\n   codemask = (1 << codesize) - 1;\n   bits = 0;\n   valid_bits = 0;\n   for (init_code = 0; init_code < clear; init_code++) {\n      g->codes[init_code].prefix = -1;\n      g->codes[init_code].first = (stbi_uc) init_code;\n      g->codes[init_code].suffix = (stbi_uc) init_code;\n   }\n\n   // support no starting clear code\n   avail = clear+2;\n   oldcode = -1;\n\n   len = 0;\n   for(;;) {\n      if (valid_bits < codesize) {\n         if (len == 0) {\n            len = stbi__get8(s); // start new block\n            if (len == 0)\n               return g->out;\n         }\n         --len;\n         bits |= (stbi__int32) stbi__get8(s) << valid_bits;\n         valid_bits += 8;\n      } else {\n         stbi__int32 code = bits & codemask;\n         bits >>= codesize;\n         valid_bits -= codesize;\n         // @OPTIMIZE: is there some way we can accelerate the non-clear path?\n         if (code == clear) {  // clear code\n            codesize = lzw_cs + 1;\n            codemask = (1 << codesize) - 1;\n            avail = clear + 2;\n            oldcode = -1;\n            first = 0;\n         } else if (code == clear + 1) { // end of stream code\n            stbi__skip(s, len);\n            while ((len = stbi__get8(s)) > 0)\n               stbi__skip(s,len);\n            return g->out;\n         } else if (code <= avail) {\n            if (first) {\n               return stbi__errpuc(\"no clear code\", \"Corrupt GIF\");\n            }\n\n            if (oldcode >= 0) {\n               p = &g->codes[avail++];\n               if (avail > 8192) {\n                  return stbi__errpuc(\"too many codes\", \"Corrupt GIF\");\n               }\n\n               p->prefix = (stbi__int16) oldcode;\n               p->first = g->codes[oldcode].first;\n               p->suffix = (code == avail) ? p->first : g->codes[code].first;\n            } else if (code == avail)\n               return stbi__errpuc(\"illegal code in raster\", \"Corrupt GIF\");\n\n            stbi__out_gif_code(g, (stbi__uint16) code);\n\n            if ((avail & codemask) == 0 && avail <= 0x0FFF) {\n               codesize++;\n               codemask = (1 << codesize) - 1;\n            }\n\n            oldcode = code;\n         } else {\n            return stbi__errpuc(\"illegal code in raster\", \"Corrupt GIF\");\n         }\n      }\n   }\n}\n\n// this function is designed to support animated gifs, although stb_image doesn't support it\n// two back is the image from two frames ago, used for a very specific disposal format\nstatic stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back)\n{\n   int dispose;\n   int first_frame;\n   int pi;\n   int pcount;\n   STBI_NOTUSED(req_comp);\n\n   // on first frame, any non-written pixels get the background colour (non-transparent)\n   first_frame = 0;\n   if (g->out == 0) {\n      if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header\n      if (!stbi__mad3sizes_valid(4, g->w, g->h, 0))\n         return stbi__errpuc(\"too large\", \"GIF image is too large\");\n      pcount = g->w * g->h;\n      g->out = (stbi_uc *) stbi__malloc(4 * pcount);\n      g->background = (stbi_uc *) stbi__malloc(4 * pcount);\n      g->history = (stbi_uc *) stbi__malloc(pcount);\n      if (!g->out || !g->background || !g->history)\n         return stbi__errpuc(\"outofmem\", \"Out of memory\");\n\n      // image is treated as \"transparent\" at the start - ie, nothing overwrites the current background;\n      // background colour is only used for pixels that are not rendered first frame, after that \"background\"\n      // color refers to the color that was there the previous frame.\n      memset(g->out, 0x00, 4 * pcount);\n      memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent)\n      memset(g->history, 0x00, pcount);        // pixels that were affected previous frame\n      first_frame = 1;\n   } else {\n      // second frame - how do we dispose of the previous one?\n      dispose = (g->eflags & 0x1C) >> 2;\n      pcount = g->w * g->h;\n\n      if ((dispose == 3) && (two_back == 0)) {\n         dispose = 2; // if I don't have an image to revert back to, default to the old background\n      }\n\n      if (dispose == 3) { // use previous graphic\n         for (pi = 0; pi < pcount; ++pi) {\n            if (g->history[pi]) {\n               memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 );\n            }\n         }\n      } else if (dispose == 2) {\n         // restore what was changed last frame to background before that frame;\n         for (pi = 0; pi < pcount; ++pi) {\n            if (g->history[pi]) {\n               memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 );\n            }\n         }\n      } else {\n         // This is a non-disposal case eithe way, so just\n         // leave the pixels as is, and they will become the new background\n         // 1: do not dispose\n         // 0:  not specified.\n      }\n\n      // background is what out is after the undoing of the previou frame;\n      memcpy( g->background, g->out, 4 * g->w * g->h );\n   }\n\n   // clear my history;\n   memset( g->history, 0x00, g->w * g->h );        // pixels that were affected previous frame\n\n   for (;;) {\n      int tag = stbi__get8(s);\n      switch (tag) {\n         case 0x2C: /* Image Descriptor */\n         {\n            stbi__int32 x, y, w, h;\n            stbi_uc *o;\n\n            x = stbi__get16le(s);\n            y = stbi__get16le(s);\n            w = stbi__get16le(s);\n            h = stbi__get16le(s);\n            if (((x + w) > (g->w)) || ((y + h) > (g->h)))\n               return stbi__errpuc(\"bad Image Descriptor\", \"Corrupt GIF\");\n\n            g->line_size = g->w * 4;\n            g->start_x = x * 4;\n            g->start_y = y * g->line_size;\n            g->max_x   = g->start_x + w * 4;\n            g->max_y   = g->start_y + h * g->line_size;\n            g->cur_x   = g->start_x;\n            g->cur_y   = g->start_y;\n\n            // if the width of the specified rectangle is 0, that means\n            // we may not see *any* pixels or the image is malformed;\n            // to make sure this is caught, move the current y down to\n            // max_y (which is what out_gif_code checks).\n            if (w == 0)\n               g->cur_y = g->max_y;\n\n            g->lflags = stbi__get8(s);\n\n            if (g->lflags & 0x40) {\n               g->step = 8 * g->line_size; // first interlaced spacing\n               g->parse = 3;\n            } else {\n               g->step = g->line_size;\n               g->parse = 0;\n            }\n\n            if (g->lflags & 0x80) {\n               stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);\n               g->color_table = (stbi_uc *) g->lpal;\n            } else if (g->flags & 0x80) {\n               g->color_table = (stbi_uc *) g->pal;\n            } else\n               return stbi__errpuc(\"missing color table\", \"Corrupt GIF\");\n\n            o = stbi__process_gif_raster(s, g);\n            if (!o) return NULL;\n\n            // if this was the first frame,\n            pcount = g->w * g->h;\n            if (first_frame && (g->bgindex > 0)) {\n               // if first frame, any pixel not drawn to gets the background color\n               for (pi = 0; pi < pcount; ++pi) {\n                  if (g->history[pi] == 0) {\n                     g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be;\n                     memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 );\n                  }\n               }\n            }\n\n            return o;\n         }\n\n         case 0x21: // Comment Extension.\n         {\n            int len;\n            int ext = stbi__get8(s);\n            if (ext == 0xF9) { // Graphic Control Extension.\n               len = stbi__get8(s);\n               if (len == 4) {\n                  g->eflags = stbi__get8(s);\n                  g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths.\n\n                  // unset old transparent\n                  if (g->transparent >= 0) {\n                     g->pal[g->transparent][3] = 255;\n                  }\n                  if (g->eflags & 0x01) {\n                     g->transparent = stbi__get8(s);\n                     if (g->transparent >= 0) {\n                        g->pal[g->transparent][3] = 0;\n                     }\n                  } else {\n                     // don't need transparent\n                     stbi__skip(s, 1);\n                     g->transparent = -1;\n                  }\n               } else {\n                  stbi__skip(s, len);\n                  break;\n               }\n            }\n            while ((len = stbi__get8(s)) != 0) {\n               stbi__skip(s, len);\n            }\n            break;\n         }\n\n         case 0x3B: // gif stream termination code\n            return (stbi_uc *) s; // using '1' causes warning on some compilers\n\n         default:\n            return stbi__errpuc(\"unknown code\", \"Corrupt GIF\");\n      }\n   }\n}\n\nstatic void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays)\n{\n   STBI_FREE(g->out);\n   STBI_FREE(g->history);\n   STBI_FREE(g->background);\n\n   if (out) STBI_FREE(out);\n   if (delays && *delays) STBI_FREE(*delays);\n   return stbi__errpuc(\"outofmem\", \"Out of memory\");\n}\n\nstatic void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp)\n{\n   if (stbi__gif_test(s)) {\n      int layers = 0;\n      stbi_uc *u = 0;\n      stbi_uc *out = 0;\n      stbi_uc *two_back = 0;\n      stbi__gif g;\n      int stride;\n      int out_size = 0;\n      int delays_size = 0;\n\n      STBI_NOTUSED(out_size);\n      STBI_NOTUSED(delays_size);\n\n      memset(&g, 0, sizeof(g));\n      if (delays) {\n         *delays = 0;\n      }\n\n      do {\n         u = stbi__gif_load_next(s, &g, comp, req_comp, two_back);\n         if (u == (stbi_uc *) s) u = 0;  // end of animated gif marker\n\n         if (u) {\n            *x = g.w;\n            *y = g.h;\n            ++layers;\n            stride = g.w * g.h * 4;\n\n            if (out) {\n               void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride );\n               if (!tmp)\n                  return stbi__load_gif_main_outofmem(&g, out, delays);\n               else {\n                   out = (stbi_uc*) tmp;\n                   out_size = layers * stride;\n               }\n\n               if (delays) {\n                  int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );\n                  if (!new_delays)\n                     return stbi__load_gif_main_outofmem(&g, out, delays);\n                  *delays = new_delays;\n                  delays_size = layers * sizeof(int);\n               }\n            } else {\n               out = (stbi_uc*)stbi__malloc( layers * stride );\n               if (!out)\n                  return stbi__load_gif_main_outofmem(&g, out, delays);\n               out_size = layers * stride;\n               if (delays) {\n                  *delays = (int*) stbi__malloc( layers * sizeof(int) );\n                  if (!*delays)\n                     return stbi__load_gif_main_outofmem(&g, out, delays);\n                  delays_size = layers * sizeof(int);\n               }\n            }\n            memcpy( out + ((layers - 1) * stride), u, stride );\n            if (layers >= 2) {\n               two_back = out - 2 * stride;\n            }\n\n            if (delays) {\n               (*delays)[layers - 1U] = g.delay;\n            }\n         }\n      } while (u != 0);\n\n      // free temp buffer;\n      STBI_FREE(g.out);\n      STBI_FREE(g.history);\n      STBI_FREE(g.background);\n\n      // do the final conversion after loading everything;\n      if (req_comp && req_comp != 4)\n         out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h);\n\n      *z = layers;\n      return out;\n   } else {\n      return stbi__errpuc(\"not GIF\", \"Image was not as a gif type.\");\n   }\n}\n\nstatic void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   stbi_uc *u = 0;\n   stbi__gif g;\n   memset(&g, 0, sizeof(g));\n   STBI_NOTUSED(ri);\n\n   u = stbi__gif_load_next(s, &g, comp, req_comp, 0);\n   if (u == (stbi_uc *) s) u = 0;  // end of animated gif marker\n   if (u) {\n      *x = g.w;\n      *y = g.h;\n\n      // moved conversion to after successful load so that the same\n      // can be done for multiple frames.\n      if (req_comp && req_comp != 4)\n         u = stbi__convert_format(u, 4, req_comp, g.w, g.h);\n   } else if (g.out) {\n      // if there was an error and we allocated an image buffer, free it!\n      STBI_FREE(g.out);\n   }\n\n   // free buffers needed for multiple frame loading;\n   STBI_FREE(g.history);\n   STBI_FREE(g.background);\n\n   return u;\n}\n\nstatic int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   return stbi__gif_info_raw(s,x,y,comp);\n}\n#endif\n\n// *************************************************************************************************\n// Radiance RGBE HDR loader\n// originally by Nicolas Schulz\n#ifndef STBI_NO_HDR\nstatic int stbi__hdr_test_core(stbi__context *s, const char *signature)\n{\n   int i;\n   for (i=0; signature[i]; ++i)\n      if (stbi__get8(s) != signature[i])\n          return 0;\n   stbi__rewind(s);\n   return 1;\n}\n\nstatic int stbi__hdr_test(stbi__context* s)\n{\n   int r = stbi__hdr_test_core(s, \"#?RADIANCE\\n\");\n   stbi__rewind(s);\n   if(!r) {\n       r = stbi__hdr_test_core(s, \"#?RGBE\\n\");\n       stbi__rewind(s);\n   }\n   return r;\n}\n\n#define STBI__HDR_BUFLEN  1024\nstatic char *stbi__hdr_gettoken(stbi__context *z, char *buffer)\n{\n   int len=0;\n   char c = '\\0';\n\n   c = (char) stbi__get8(z);\n\n   while (!stbi__at_eof(z) && c != '\\n') {\n      buffer[len++] = c;\n      if (len == STBI__HDR_BUFLEN-1) {\n         // flush to end of line\n         while (!stbi__at_eof(z) && stbi__get8(z) != '\\n')\n            ;\n         break;\n      }\n      c = (char) stbi__get8(z);\n   }\n\n   buffer[len] = 0;\n   return buffer;\n}\n\nstatic void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)\n{\n   if ( input[3] != 0 ) {\n      float f1;\n      // Exponent\n      f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));\n      if (req_comp <= 2)\n         output[0] = (input[0] + input[1] + input[2]) * f1 / 3;\n      else {\n         output[0] = input[0] * f1;\n         output[1] = input[1] * f1;\n         output[2] = input[2] * f1;\n      }\n      if (req_comp == 2) output[1] = 1;\n      if (req_comp == 4) output[3] = 1;\n   } else {\n      switch (req_comp) {\n         case 4: output[3] = 1; /* fallthrough */\n         case 3: output[0] = output[1] = output[2] = 0;\n                 break;\n         case 2: output[1] = 1; /* fallthrough */\n         case 1: output[0] = 0;\n                 break;\n      }\n   }\n}\n\nstatic float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   char buffer[STBI__HDR_BUFLEN];\n   char *token;\n   int valid = 0;\n   int width, height;\n   stbi_uc *scanline;\n   float *hdr_data;\n   int len;\n   unsigned char count, value;\n   int i, j, k, c1,c2, z;\n   const char *headerToken;\n   STBI_NOTUSED(ri);\n\n   // Check identifier\n   headerToken = stbi__hdr_gettoken(s,buffer);\n   if (strcmp(headerToken, \"#?RADIANCE\") != 0 && strcmp(headerToken, \"#?RGBE\") != 0)\n      return stbi__errpf(\"not HDR\", \"Corrupt HDR image\");\n\n   // Parse header\n   for(;;) {\n      token = stbi__hdr_gettoken(s,buffer);\n      if (token[0] == 0) break;\n      if (strcmp(token, \"FORMAT=32-bit_rle_rgbe\") == 0) valid = 1;\n   }\n\n   if (!valid)    return stbi__errpf(\"unsupported format\", \"Unsupported HDR format\");\n\n   // Parse width and height\n   // can't use sscanf() if we're not using stdio!\n   token = stbi__hdr_gettoken(s,buffer);\n   if (strncmp(token, \"-Y \", 3))  return stbi__errpf(\"unsupported data layout\", \"Unsupported HDR format\");\n   token += 3;\n   height = (int) strtol(token, &token, 10);\n   while (*token == ' ') ++token;\n   if (strncmp(token, \"+X \", 3))  return stbi__errpf(\"unsupported data layout\", \"Unsupported HDR format\");\n   token += 3;\n   width = (int) strtol(token, NULL, 10);\n\n   if (height > STBI_MAX_DIMENSIONS) return stbi__errpf(\"too large\",\"Very large image (corrupt?)\");\n   if (width > STBI_MAX_DIMENSIONS) return stbi__errpf(\"too large\",\"Very large image (corrupt?)\");\n\n   *x = width;\n   *y = height;\n\n   if (comp) *comp = 3;\n   if (req_comp == 0) req_comp = 3;\n\n   if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0))\n      return stbi__errpf(\"too large\", \"HDR image is too large\");\n\n   // Read data\n   hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);\n   if (!hdr_data)\n      return stbi__errpf(\"outofmem\", \"Out of memory\");\n\n   // Load image data\n   // image data is stored as some number of sca\n   if ( width < 8 || width >= 32768) {\n      // Read flat data\n      for (j=0; j < height; ++j) {\n         for (i=0; i < width; ++i) {\n            stbi_uc rgbe[4];\n           main_decode_loop:\n            stbi__getn(s, rgbe, 4);\n            stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);\n         }\n      }\n   } else {\n      // Read RLE-encoded data\n      scanline = NULL;\n\n      for (j = 0; j < height; ++j) {\n         c1 = stbi__get8(s);\n         c2 = stbi__get8(s);\n         len = stbi__get8(s);\n         if (c1 != 2 || c2 != 2 || (len & 0x80)) {\n            // not run-length encoded, so we have to actually use THIS data as a decoded\n            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)\n            stbi_uc rgbe[4];\n            rgbe[0] = (stbi_uc) c1;\n            rgbe[1] = (stbi_uc) c2;\n            rgbe[2] = (stbi_uc) len;\n            rgbe[3] = (stbi_uc) stbi__get8(s);\n            stbi__hdr_convert(hdr_data, rgbe, req_comp);\n            i = 1;\n            j = 0;\n            STBI_FREE(scanline);\n            goto main_decode_loop; // yes, this makes no sense\n         }\n         len <<= 8;\n         len |= stbi__get8(s);\n         if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf(\"invalid decoded scanline length\", \"corrupt HDR\"); }\n         if (scanline == NULL) {\n            scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0);\n            if (!scanline) {\n               STBI_FREE(hdr_data);\n               return stbi__errpf(\"outofmem\", \"Out of memory\");\n            }\n         }\n\n         for (k = 0; k < 4; ++k) {\n            int nleft;\n            i = 0;\n            while ((nleft = width - i) > 0) {\n               count = stbi__get8(s);\n               if (count > 128) {\n                  // Run\n                  value = stbi__get8(s);\n                  count -= 128;\n                  if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf(\"corrupt\", \"bad RLE data in HDR\"); }\n                  for (z = 0; z < count; ++z)\n                     scanline[i++ * 4 + k] = value;\n               } else {\n                  // Dump\n                  if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf(\"corrupt\", \"bad RLE data in HDR\"); }\n                  for (z = 0; z < count; ++z)\n                     scanline[i++ * 4 + k] = stbi__get8(s);\n               }\n            }\n         }\n         for (i=0; i < width; ++i)\n            stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);\n      }\n      if (scanline)\n         STBI_FREE(scanline);\n   }\n\n   return hdr_data;\n}\n\nstatic int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   char buffer[STBI__HDR_BUFLEN];\n   char *token;\n   int valid = 0;\n   int dummy;\n\n   if (!x) x = &dummy;\n   if (!y) y = &dummy;\n   if (!comp) comp = &dummy;\n\n   if (stbi__hdr_test(s) == 0) {\n       stbi__rewind( s );\n       return 0;\n   }\n\n   for(;;) {\n      token = stbi__hdr_gettoken(s,buffer);\n      if (token[0] == 0) break;\n      if (strcmp(token, \"FORMAT=32-bit_rle_rgbe\") == 0) valid = 1;\n   }\n\n   if (!valid) {\n       stbi__rewind( s );\n       return 0;\n   }\n   token = stbi__hdr_gettoken(s,buffer);\n   if (strncmp(token, \"-Y \", 3)) {\n       stbi__rewind( s );\n       return 0;\n   }\n   token += 3;\n   *y = (int) strtol(token, &token, 10);\n   while (*token == ' ') ++token;\n   if (strncmp(token, \"+X \", 3)) {\n       stbi__rewind( s );\n       return 0;\n   }\n   token += 3;\n   *x = (int) strtol(token, NULL, 10);\n   *comp = 3;\n   return 1;\n}\n#endif // STBI_NO_HDR\n\n#ifndef STBI_NO_BMP\nstatic int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   void *p;\n   stbi__bmp_data info;\n\n   info.all_a = 255;\n   p = stbi__bmp_parse_header(s, &info);\n   if (p == NULL) {\n      stbi__rewind( s );\n      return 0;\n   }\n   if (x) *x = s->img_x;\n   if (y) *y = s->img_y;\n   if (comp) {\n      if (info.bpp == 24 && info.ma == 0xff000000)\n         *comp = 3;\n      else\n         *comp = info.ma ? 4 : 3;\n   }\n   return 1;\n}\n#endif\n\n#ifndef STBI_NO_PSD\nstatic int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   int channelCount, dummy, depth;\n   if (!x) x = &dummy;\n   if (!y) y = &dummy;\n   if (!comp) comp = &dummy;\n   if (stbi__get32be(s) != 0x38425053) {\n       stbi__rewind( s );\n       return 0;\n   }\n   if (stbi__get16be(s) != 1) {\n       stbi__rewind( s );\n       return 0;\n   }\n   stbi__skip(s, 6);\n   channelCount = stbi__get16be(s);\n   if (channelCount < 0 || channelCount > 16) {\n       stbi__rewind( s );\n       return 0;\n   }\n   *y = stbi__get32be(s);\n   *x = stbi__get32be(s);\n   depth = stbi__get16be(s);\n   if (depth != 8 && depth != 16) {\n       stbi__rewind( s );\n       return 0;\n   }\n   if (stbi__get16be(s) != 3) {\n       stbi__rewind( s );\n       return 0;\n   }\n   *comp = 4;\n   return 1;\n}\n\nstatic int stbi__psd_is16(stbi__context *s)\n{\n   int channelCount, depth;\n   if (stbi__get32be(s) != 0x38425053) {\n       stbi__rewind( s );\n       return 0;\n   }\n   if (stbi__get16be(s) != 1) {\n       stbi__rewind( s );\n       return 0;\n   }\n   stbi__skip(s, 6);\n   channelCount = stbi__get16be(s);\n   if (channelCount < 0 || channelCount > 16) {\n       stbi__rewind( s );\n       return 0;\n   }\n   STBI_NOTUSED(stbi__get32be(s));\n   STBI_NOTUSED(stbi__get32be(s));\n   depth = stbi__get16be(s);\n   if (depth != 16) {\n       stbi__rewind( s );\n       return 0;\n   }\n   return 1;\n}\n#endif\n\n#ifndef STBI_NO_PIC\nstatic int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   int act_comp=0,num_packets=0,chained,dummy;\n   stbi__pic_packet packets[10];\n\n   if (!x) x = &dummy;\n   if (!y) y = &dummy;\n   if (!comp) comp = &dummy;\n\n   if (!stbi__pic_is4(s,\"\\x53\\x80\\xF6\\x34\")) {\n      stbi__rewind(s);\n      return 0;\n   }\n\n   stbi__skip(s, 88);\n\n   *x = stbi__get16be(s);\n   *y = stbi__get16be(s);\n   if (stbi__at_eof(s)) {\n      stbi__rewind( s);\n      return 0;\n   }\n   if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {\n      stbi__rewind( s );\n      return 0;\n   }\n\n   stbi__skip(s, 8);\n\n   do {\n      stbi__pic_packet *packet;\n\n      if (num_packets==sizeof(packets)/sizeof(packets[0]))\n         return 0;\n\n      packet = &packets[num_packets++];\n      chained = stbi__get8(s);\n      packet->size    = stbi__get8(s);\n      packet->type    = stbi__get8(s);\n      packet->channel = stbi__get8(s);\n      act_comp |= packet->channel;\n\n      if (stbi__at_eof(s)) {\n          stbi__rewind( s );\n          return 0;\n      }\n      if (packet->size != 8) {\n          stbi__rewind( s );\n          return 0;\n      }\n   } while (chained);\n\n   *comp = (act_comp & 0x10 ? 4 : 3);\n\n   return 1;\n}\n#endif\n\n// *************************************************************************************************\n// Portable Gray Map and Portable Pixel Map loader\n// by Ken Miller\n//\n// PGM: http://netpbm.sourceforge.net/doc/pgm.html\n// PPM: http://netpbm.sourceforge.net/doc/ppm.html\n//\n// Known limitations:\n//    Does not support comments in the header section\n//    Does not support ASCII image data (formats P2 and P3)\n\n#ifndef STBI_NO_PNM\n\nstatic int      stbi__pnm_test(stbi__context *s)\n{\n   char p, t;\n   p = (char) stbi__get8(s);\n   t = (char) stbi__get8(s);\n   if (p != 'P' || (t != '5' && t != '6')) {\n       stbi__rewind( s );\n       return 0;\n   }\n   return 1;\n}\n\nstatic void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)\n{\n   stbi_uc *out;\n   STBI_NOTUSED(ri);\n\n   ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n);\n   if (ri->bits_per_channel == 0)\n      return 0;\n\n   if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n   if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc(\"too large\",\"Very large image (corrupt?)\");\n\n   *x = s->img_x;\n   *y = s->img_y;\n   if (comp) *comp = s->img_n;\n\n   if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))\n      return stbi__errpuc(\"too large\", \"PNM too large\");\n\n   out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);\n   if (!out) return stbi__errpuc(\"outofmem\", \"Out of memory\");\n   if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) {\n      STBI_FREE(out);\n      return stbi__errpuc(\"bad PNM\", \"PNM file truncated\");\n   }\n\n   if (req_comp && req_comp != s->img_n) {\n      if (ri->bits_per_channel == 16) {\n         out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y);\n      } else {\n         out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);\n      }\n      if (out == NULL) return out; // stbi__convert_format frees input on failure\n   }\n   return out;\n}\n\nstatic int      stbi__pnm_isspace(char c)\n{\n   return c == ' ' || c == '\\t' || c == '\\n' || c == '\\v' || c == '\\f' || c == '\\r';\n}\n\nstatic void     stbi__pnm_skip_whitespace(stbi__context *s, char *c)\n{\n   for (;;) {\n      while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))\n         *c = (char) stbi__get8(s);\n\n      if (stbi__at_eof(s) || *c != '#')\n         break;\n\n      while (!stbi__at_eof(s) && *c != '\\n' && *c != '\\r' )\n         *c = (char) stbi__get8(s);\n   }\n}\n\nstatic int      stbi__pnm_isdigit(char c)\n{\n   return c >= '0' && c <= '9';\n}\n\nstatic int      stbi__pnm_getinteger(stbi__context *s, char *c)\n{\n   int value = 0;\n\n   while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {\n      value = value*10 + (*c - '0');\n      *c = (char) stbi__get8(s);\n      if((value > 214748364) || (value == 214748364 && *c > '7'))\n          return stbi__err(\"integer parse overflow\", \"Parsing an integer in the PPM header overflowed a 32-bit int\");\n   }\n\n   return value;\n}\n\nstatic int      stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)\n{\n   int maxv, dummy;\n   char c, p, t;\n\n   if (!x) x = &dummy;\n   if (!y) y = &dummy;\n   if (!comp) comp = &dummy;\n\n   stbi__rewind(s);\n\n   // Get identifier\n   p = (char) stbi__get8(s);\n   t = (char) stbi__get8(s);\n   if (p != 'P' || (t != '5' && t != '6')) {\n       stbi__rewind(s);\n       return 0;\n   }\n\n   *comp = (t == '6') ? 3 : 1;  // '5' is 1-component .pgm; '6' is 3-component .ppm\n\n   c = (char) stbi__get8(s);\n   stbi__pnm_skip_whitespace(s, &c);\n\n   *x = stbi__pnm_getinteger(s, &c); // read width\n   if(*x == 0)\n       return stbi__err(\"invalid width\", \"PPM image header had zero or overflowing width\");\n   stbi__pnm_skip_whitespace(s, &c);\n\n   *y = stbi__pnm_getinteger(s, &c); // read height\n   if (*y == 0)\n       return stbi__err(\"invalid width\", \"PPM image header had zero or overflowing width\");\n   stbi__pnm_skip_whitespace(s, &c);\n\n   maxv = stbi__pnm_getinteger(s, &c);  // read max value\n   if (maxv > 65535)\n      return stbi__err(\"max value > 65535\", \"PPM image supports only 8-bit and 16-bit images\");\n   else if (maxv > 255)\n      return 16;\n   else\n      return 8;\n}\n\nstatic int stbi__pnm_is16(stbi__context *s)\n{\n   if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)\n\t   return 1;\n   return 0;\n}\n#endif\n\nstatic int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)\n{\n   #ifndef STBI_NO_JPEG\n   if (stbi__jpeg_info(s, x, y, comp)) return 1;\n   #endif\n\n   #ifndef STBI_NO_PNG\n   if (stbi__png_info(s, x, y, comp))  return 1;\n   #endif\n\n   #ifndef STBI_NO_GIF\n   if (stbi__gif_info(s, x, y, comp))  return 1;\n   #endif\n\n   #ifndef STBI_NO_BMP\n   if (stbi__bmp_info(s, x, y, comp))  return 1;\n   #endif\n\n   #ifndef STBI_NO_PSD\n   if (stbi__psd_info(s, x, y, comp))  return 1;\n   #endif\n\n   #ifndef STBI_NO_PIC\n   if (stbi__pic_info(s, x, y, comp))  return 1;\n   #endif\n\n   #ifndef STBI_NO_PNM\n   if (stbi__pnm_info(s, x, y, comp))  return 1;\n   #endif\n\n   #ifndef STBI_NO_HDR\n   if (stbi__hdr_info(s, x, y, comp))  return 1;\n   #endif\n\n   // test tga last because it's a crappy test!\n   #ifndef STBI_NO_TGA\n   if (stbi__tga_info(s, x, y, comp))\n       return 1;\n   #endif\n   return stbi__err(\"unknown image type\", \"Image not of any known type, or corrupt\");\n}\n\nstatic int stbi__is_16_main(stbi__context *s)\n{\n   #ifndef STBI_NO_PNG\n   if (stbi__png_is16(s))  return 1;\n   #endif\n\n   #ifndef STBI_NO_PSD\n   if (stbi__psd_is16(s))  return 1;\n   #endif\n\n   #ifndef STBI_NO_PNM\n   if (stbi__pnm_is16(s))  return 1;\n   #endif\n   return 0;\n}\n\n#ifndef STBI_NO_STDIO\nSTBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)\n{\n    FILE *f = stbi__fopen(filename, \"rb\");\n    int result;\n    if (!f) return stbi__err(\"can't fopen\", \"Unable to open file\");\n    result = stbi_info_from_file(f, x, y, comp);\n    fclose(f);\n    return result;\n}\n\nSTBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)\n{\n   int r;\n   stbi__context s;\n   long pos = ftell(f);\n   stbi__start_file(&s, f);\n   r = stbi__info_main(&s,x,y,comp);\n   fseek(f,pos,SEEK_SET);\n   return r;\n}\n\nSTBIDEF int stbi_is_16_bit(char const *filename)\n{\n    FILE *f = stbi__fopen(filename, \"rb\");\n    int result;\n    if (!f) return stbi__err(\"can't fopen\", \"Unable to open file\");\n    result = stbi_is_16_bit_from_file(f);\n    fclose(f);\n    return result;\n}\n\nSTBIDEF int stbi_is_16_bit_from_file(FILE *f)\n{\n   int r;\n   stbi__context s;\n   long pos = ftell(f);\n   stbi__start_file(&s, f);\n   r = stbi__is_16_main(&s);\n   fseek(f,pos,SEEK_SET);\n   return r;\n}\n#endif // !STBI_NO_STDIO\n\nSTBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\n{\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n   return stbi__info_main(&s,x,y,comp);\n}\n\nSTBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)\n{\n   stbi__context s;\n   stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);\n   return stbi__info_main(&s,x,y,comp);\n}\n\nSTBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len)\n{\n   stbi__context s;\n   stbi__start_mem(&s,buffer,len);\n   return stbi__is_16_main(&s);\n}\n\nSTBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user)\n{\n   stbi__context s;\n   stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);\n   return stbi__is_16_main(&s);\n}\n\n#endif // STB_IMAGE_IMPLEMENTATION\n\n/*\n   revision history:\n      2.20  (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs\n      2.19  (2018-02-11) fix warning\n      2.18  (2018-01-30) fix warnings\n      2.17  (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug\n                         1-bit BMP\n                         *_is_16_bit api\n                         avoid warnings\n      2.16  (2017-07-23) all functions have 16-bit variants;\n                         STBI_NO_STDIO works again;\n                         compilation fixes;\n                         fix rounding in unpremultiply;\n                         optimize vertical flip;\n                         disable raw_len validation;\n                         documentation fixes\n      2.15  (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode;\n                         warning fixes; disable run-time SSE detection on gcc;\n                         uniform handling of optional \"return\" values;\n                         thread-safe initialization of zlib tables\n      2.14  (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs\n      2.13  (2016-11-29) add 16-bit API, only supported for PNG right now\n      2.12  (2016-04-02) fix typo in 2.11 PSD fix that caused crashes\n      2.11  (2016-04-02) allocate large structures on the stack\n                         remove white matting for transparent PSD\n                         fix reported channel count for PNG & BMP\n                         re-enable SSE2 in non-gcc 64-bit\n                         support RGB-formatted JPEG\n                         read 16-bit PNGs (only as 8-bit)\n      2.10  (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED\n      2.09  (2016-01-16) allow comments in PNM files\n                         16-bit-per-pixel TGA (not bit-per-component)\n                         info() for TGA could break due to .hdr handling\n                         info() for BMP to shares code instead of sloppy parse\n                         can use STBI_REALLOC_SIZED if allocator doesn't support realloc\n                         code cleanup\n      2.08  (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA\n      2.07  (2015-09-13) fix compiler warnings\n                         partial animated GIF support\n                         limited 16-bpc PSD support\n                         #ifdef unused functions\n                         bug with < 92 byte PIC,PNM,HDR,TGA\n      2.06  (2015-04-19) fix bug where PSD returns wrong '*comp' value\n      2.05  (2015-04-19) fix bug in progressive JPEG handling, fix warning\n      2.04  (2015-04-15) try to re-enable SIMD on MinGW 64-bit\n      2.03  (2015-04-12) extra corruption checking (mmozeiko)\n                         stbi_set_flip_vertically_on_load (nguillemot)\n                         fix NEON support; fix mingw support\n      2.02  (2015-01-19) fix incorrect assert, fix warning\n      2.01  (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2\n      2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG\n      2.00  (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)\n                         progressive JPEG (stb)\n                         PGM/PPM support (Ken Miller)\n                         STBI_MALLOC,STBI_REALLOC,STBI_FREE\n                         GIF bugfix -- seemingly never worked\n                         STBI_NO_*, STBI_ONLY_*\n      1.48  (2014-12-14) fix incorrectly-named assert()\n      1.47  (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)\n                         optimize PNG (ryg)\n                         fix bug in interlaced PNG with user-specified channel count (stb)\n      1.46  (2014-08-26)\n              fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG\n      1.45  (2014-08-16)\n              fix MSVC-ARM internal compiler error by wrapping malloc\n      1.44  (2014-08-07)\n              various warning fixes from Ronny Chevalier\n      1.43  (2014-07-15)\n              fix MSVC-only compiler problem in code changed in 1.42\n      1.42  (2014-07-09)\n              don't define _CRT_SECURE_NO_WARNINGS (affects user code)\n              fixes to stbi__cleanup_jpeg path\n              added STBI_ASSERT to avoid requiring assert.h\n      1.41  (2014-06-25)\n              fix search&replace from 1.36 that messed up comments/error messages\n      1.40  (2014-06-22)\n              fix gcc struct-initialization warning\n      1.39  (2014-06-15)\n              fix to TGA optimization when req_comp != number of components in TGA;\n              fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)\n              add support for BMP version 5 (more ignored fields)\n      1.38  (2014-06-06)\n              suppress MSVC warnings on integer casts truncating values\n              fix accidental rename of 'skip' field of I/O\n      1.37  (2014-06-04)\n              remove duplicate typedef\n      1.36  (2014-06-03)\n              convert to header file single-file library\n              if de-iphone isn't set, load iphone images color-swapped instead of returning NULL\n      1.35  (2014-05-27)\n              various warnings\n              fix broken STBI_SIMD path\n              fix bug where stbi_load_from_file no longer left file pointer in correct place\n              fix broken non-easy path for 32-bit BMP (possibly never used)\n              TGA optimization by Arseny Kapoulkine\n      1.34  (unknown)\n              use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case\n      1.33  (2011-07-14)\n              make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements\n      1.32  (2011-07-13)\n              support for \"info\" function for all supported filetypes (SpartanJ)\n      1.31  (2011-06-20)\n              a few more leak fixes, bug in PNG handling (SpartanJ)\n      1.30  (2011-06-11)\n              added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)\n              removed deprecated format-specific test/load functions\n              removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway\n              error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)\n              fix inefficiency in decoding 32-bit BMP (David Woo)\n      1.29  (2010-08-16)\n              various warning fixes from Aurelien Pocheville\n      1.28  (2010-08-01)\n              fix bug in GIF palette transparency (SpartanJ)\n      1.27  (2010-08-01)\n              cast-to-stbi_uc to fix warnings\n      1.26  (2010-07-24)\n              fix bug in file buffering for PNG reported by SpartanJ\n      1.25  (2010-07-17)\n              refix trans_data warning (Won Chun)\n      1.24  (2010-07-12)\n              perf improvements reading from files on platforms with lock-heavy fgetc()\n              minor perf improvements for jpeg\n              deprecated type-specific functions so we'll get feedback if they're needed\n              attempt to fix trans_data warning (Won Chun)\n      1.23    fixed bug in iPhone support\n      1.22  (2010-07-10)\n              removed image *writing* support\n              stbi_info support from Jetro Lauha\n              GIF support from Jean-Marc Lienher\n              iPhone PNG-extensions from James Brown\n              warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)\n      1.21    fix use of 'stbi_uc' in header (reported by jon blow)\n      1.20    added support for Softimage PIC, by Tom Seddon\n      1.19    bug in interlaced PNG corruption check (found by ryg)\n      1.18  (2008-08-02)\n              fix a threading bug (local mutable static)\n      1.17    support interlaced PNG\n      1.16    major bugfix - stbi__convert_format converted one too many pixels\n      1.15    initialize some fields for thread safety\n      1.14    fix threadsafe conversion bug\n              header-file-only version (#define STBI_HEADER_FILE_ONLY before including)\n      1.13    threadsafe\n      1.12    const qualifiers in the API\n      1.11    Support installable IDCT, colorspace conversion routines\n      1.10    Fixes for 64-bit (don't use \"unsigned long\")\n              optimized upsampling by Fabian \"ryg\" Giesen\n      1.09    Fix format-conversion for PSD code (bad global variables!)\n      1.08    Thatcher Ulrich's PSD code integrated by Nicolas Schulz\n      1.07    attempt to fix C++ warning/errors again\n      1.06    attempt to fix C++ warning/errors again\n      1.05    fix TGA loading to return correct *comp and use good luminance calc\n      1.04    default float alpha is 1, not 255; use 'void *' for stbi_image_free\n      1.03    bugfixes to STBI_NO_STDIO, STBI_NO_HDR\n      1.02    support for (subset of) HDR files, float interface for preferred access to them\n      1.01    fix bug: possible bug in handling right-side up bmps... not sure\n              fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all\n      1.00    interface to zlib that skips zlib header\n      0.99    correct handling of alpha in palette\n      0.98    TGA loader by lonesock; dynamically add loaders (untested)\n      0.97    jpeg errors on too large a file; also catch another malloc failure\n      0.96    fix detection of invalid v value - particleman@mollyrocket forum\n      0.95    during header scan, seek to markers in case of padding\n      0.94    STBI_NO_STDIO to disable stdio usage; rename all #defines the same\n      0.93    handle jpegtran output; verbose errors\n      0.92    read 4,8,16,24,32-bit BMP files of several formats\n      0.91    output 24-bit Windows 3.0 BMP files\n      0.90    fix a few more warnings; bump version number to approach 1.0\n      0.61    bugfixes due to Marc LeBlanc, Christopher Lloyd\n      0.60    fix compiling as c++\n      0.59    fix warnings: merge Dave Moore's -Wall fixes\n      0.58    fix bug: zlib uncompressed mode len/nlen was wrong endian\n      0.57    fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available\n      0.56    fix bug: zlib uncompressed mode len vs. nlen\n      0.55    fix bug: restart_interval not initialized to 0\n      0.54    allow NULL for 'int *comp'\n      0.53    fix bug in png 3->4; speedup png decoding\n      0.52    png handles req_comp=3,4 directly; minor cleanup; jpeg comments\n      0.51    obey req_comp requests, 1-component jpegs return as 1-component,\n              on 'test' only check type, not whether we support this variant\n      0.50  (2006-11-19)\n              first released version\n*/\n\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_image_resize2.h",
    "content": "/* stb_image_resize2 - v2.18 - public domain image resizing\n\n   by Jeff Roberts (v2) and Jorge L Rodriguez\n   http://github.com/nothings/stb\n\n   Can be threaded with the extended API. SSE2, AVX, Neon and WASM SIMD support. Only\n   scaling and translation is supported, no rotations or shears.\n\n   COMPILING & LINKING\n      In one C/C++ file that #includes this file, do this:\n         #define STB_IMAGE_RESIZE_IMPLEMENTATION\n      before the #include. That will create the implementation in that file.\n\n   EASY API CALLS:\n     Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation, clamps to edge.\n\n     stbir_resize_uint8_srgb( input_pixels,  input_w,  input_h,  input_stride_in_bytes,\n                              output_pixels, output_w, output_h, output_stride_in_bytes,\n                              pixel_layout_enum )\n\n     stbir_resize_uint8_linear( input_pixels,  input_w,  input_h,  input_stride_in_bytes,\n                                output_pixels, output_w, output_h, output_stride_in_bytes,\n                                pixel_layout_enum )\n\n     stbir_resize_float_linear( input_pixels,  input_w,  input_h,  input_stride_in_bytes,\n                                output_pixels, output_w, output_h, output_stride_in_bytes,\n                                pixel_layout_enum )\n\n     If you pass NULL or zero for the output_pixels, we will allocate the output buffer\n     for you and return it from the function (free with free() or STBIR_FREE).\n     As a special case, XX_stride_in_bytes of 0 means packed continuously in memory.\n\n   API LEVELS\n      There are three levels of API - easy-to-use, medium-complexity and extended-complexity.\n\n      See the \"header file\" section of the source for API documentation.\n\n   ADDITIONAL DOCUMENTATION\n\n      MEMORY ALLOCATION\n         By default, we use malloc and free for memory allocation.  To override the\n         memory allocation, before the implementation #include, add a:\n\n            #define STBIR_MALLOC(size,user_data) ...\n            #define STBIR_FREE(ptr,user_data)   ...\n\n         Each resize makes exactly one call to malloc/free (unless you use the\n         extended API where you can do one allocation for many resizes). Under\n         address sanitizer, we do separate allocations to find overread/writes.\n\n      PERFORMANCE\n         This library was written with an emphasis on performance. When testing\n         stb_image_resize with RGBA, the fastest mode is STBIR_4CHANNEL with\n         STBIR_TYPE_UINT8 pixels and CLAMPed edges (which is what many other resize\n         libs do by default). Also, make sure SIMD is turned on of course (default\n         for 64-bit targets). Avoid WRAP edge mode if you want the fastest speed.\n\n         This library also comes with profiling built-in. If you define STBIR_PROFILE,\n         you can use the advanced API and get low-level profiling information by\n         calling stbir_resize_extended_profile_info() or stbir_resize_split_profile_info()\n         after a resize.\n\n      SIMD\n         Most of the routines have optimized SSE2, AVX, NEON and WASM versions.\n\n         On Microsoft compilers, we automatically turn on SIMD for 64-bit x64 and\n         ARM; for 32-bit x86 and ARM, you select SIMD mode by defining STBIR_SSE2 or\n         STBIR_NEON. For AVX and AVX2, we auto-select it by detecting the /arch:AVX\n         or /arch:AVX2 switches. You can also always manually turn SSE2, AVX or AVX2\n         support on by defining STBIR_SSE2, STBIR_AVX or STBIR_AVX2.\n\n         On Linux, SSE2 and Neon is on by default for 64-bit x64 or ARM64. For 32-bit,\n         we select x86 SIMD mode by whether you have -msse2, -mavx or -mavx2 enabled\n         on the command line. For 32-bit ARM, you must pass -mfpu=neon-vfpv4 for both\n         clang and GCC, but GCC also requires an additional -mfp16-format=ieee to\n         automatically enable NEON.\n\n         On x86 platforms, you can also define STBIR_FP16C to turn on FP16C instructions\n         for converting back and forth to half-floats. This is autoselected when we\n         are using AVX2. Clang and GCC also require the -mf16c switch. ARM always uses\n         the built-in half float hardware NEON instructions.\n\n         You can also tell us to use multiply-add instructions with STBIR_USE_FMA.\n         Because x86 doesn't always have fma, we turn it off by default to maintain\n         determinism across all platforms. If you don't care about non-FMA determinism\n         and are willing to restrict yourself to more recent x86 CPUs (around the AVX\n         timeframe), then fma will give you around a 15% speedup.\n\n         You can force off SIMD in all cases by defining STBIR_NO_SIMD. You can turn\n         off AVX or AVX2 specifically with STBIR_NO_AVX or STBIR_NO_AVX2. AVX is 10%\n         to 40% faster, and AVX2 is generally another 12%.\n\n      ALPHA CHANNEL\n         Most of the resizing functions provide the ability to control how the alpha\n         channel of an image is processed.\n\n         When alpha represents transparency, it is important that when combining\n         colors with filtering, the pixels should not be treated equally; they\n         should use a weighted average based on their alpha values. For example,\n         if a pixel is 1% opaque bright green and another pixel is 99% opaque\n         black and you average them, the average will be 50% opaque, but the\n         unweighted average and will be a middling green color, while the weighted\n         average will be nearly black. This means the unweighted version introduced\n         green energy that didn't exist in the source image.\n\n         (If you want to know why this makes sense, you can work out the math for\n         the following: consider what happens if you alpha composite a source image\n         over a fixed color and then average the output, vs. if you average the\n         source image pixels and then composite that over the same fixed color.\n         Only the weighted average produces the same result as the ground truth\n         composite-then-average result.)\n\n         Therefore, it is in general best to \"alpha weight\" the pixels when applying\n         filters to them. This essentially means multiplying the colors by the alpha\n         values before combining them, and then dividing by the alpha value at the\n         end.\n\n         The computer graphics industry introduced a technique called \"premultiplied\n         alpha\" or \"associated alpha\" in which image colors are stored in image files\n         already multiplied by their alpha. This saves some math when compositing,\n         and also avoids the need to divide by the alpha at the end (which is quite\n         inefficient). However, while premultiplied alpha is common in the movie CGI\n         industry, it is not commonplace in other industries like videogames, and most\n         consumer file formats are generally expected to contain not-premultiplied\n         colors. For example, Photoshop saves PNG files \"unpremultiplied\", and web\n         browsers like Chrome and Firefox expect PNG images to be unpremultiplied.\n\n         Note that there are three possibilities that might describe your image\n         and resize expectation:\n\n             1. images are not premultiplied, alpha weighting is desired\n             2. images are not premultiplied, alpha weighting is not desired\n             3. images are premultiplied\n\n         Both case #2 and case #3 require the exact same math: no alpha weighting\n         should be applied or removed. Only case 1 requires extra math operations;\n         the other two cases can be handled identically.\n\n         stb_image_resize expects case #1 by default, applying alpha weighting to\n         images, expecting the input images to be unpremultiplied. This is what the\n         COLOR+ALPHA buffer types tell the resizer to do.\n\n         When you use the pixel layouts STBIR_RGBA, STBIR_BGRA, STBIR_ARGB,\n         STBIR_ABGR, STBIR_RA, or STBIR_AR you are telling us that the pixels are\n         non-premultiplied. In these cases, the resizer will alpha weight the colors\n         (effectively creating the premultiplied image), do the filtering, and then\n         convert back to non-premult on exit.\n\n         When you use the pixel layouts STBIR_RGBA_PM, STBIR_BGRA_PM, STBIR_ARGB_PM,\n         STBIR_ABGR_PM, STBIR_RA_PM or STBIR_AR_PM, you are telling that the pixels\n         ARE premultiplied. In this case, the resizer doesn't have to do the\n         premultipling - it can filter directly on the input. This about twice as\n         fast as the non-premultiplied case, so it's the right option if your data is\n         already setup correctly.\n\n         When you use the pixel layout STBIR_4CHANNEL or STBIR_2CHANNEL, you are\n         telling us that there is no channel that represents transparency; it may be\n         RGB and some unrelated fourth channel that has been stored in the alpha\n         channel, but it is actually not alpha. No special processing will be\n         performed.\n\n         The difference between the generic 4 or 2 channel layouts, and the\n         specialized _PM versions is with the _PM versions you are telling us that\n         the data *is* alpha, just don't premultiply it. That's important when\n         using SRGB pixel formats, we need to know where the alpha is, because\n         it is converted linearly (rather than with the SRGB converters).\n\n         Because alpha weighting produces the same effect as premultiplying, you\n         even have the option with non-premultiplied inputs to let the resizer\n         produce a premultiplied output. Because the intially computed alpha-weighted\n         output image is effectively premultiplied, this is actually more performant\n         than the normal path which un-premultiplies the output image as a final step.\n\n         Finally, when converting both in and out of non-premulitplied space (for\n         example, when using STBIR_RGBA), we go to somewhat heroic measures to\n         ensure that areas with zero alpha value pixels get something reasonable\n         in the RGB values. If you don't care about the RGB values of zero alpha\n         pixels, you can call the stbir_set_non_pm_alpha_speed_over_quality()\n         function - this runs a premultiplied resize about 25% faster. That said,\n         when you really care about speed, using premultiplied pixels for both in\n         and out (STBIR_RGBA_PM, etc) much faster than both of these premultiplied\n         options.\n\n      PIXEL LAYOUT CONVERSION\n         The resizer can convert from some pixel layouts to others. When using the\n         stbir_set_pixel_layouts(), you can, for example, specify STBIR_RGBA\n         on input, and STBIR_ARGB on output, and it will re-organize the channels\n         during the resize. Currently, you can only convert between two pixel\n         layouts with the same number of channels.\n\n      DETERMINISM\n         We commit to being deterministic (from x64 to ARM to scalar to SIMD, etc).\n         This requires compiling with fast-math off (using at least /fp:precise).\n         Also, you must turn off fp-contracting (which turns mult+adds into fmas)!\n         We attempt to do this with pragmas, but with Clang, you usually want to add\n         -ffp-contract=off to the command line as well.\n\n         For 32-bit x86, you must use SSE and SSE2 codegen for determinism. That is,\n         if the scalar x87 unit gets used at all, we immediately lose determinism.\n         On Microsoft Visual Studio 2008 and earlier, from what we can tell there is\n         no way to be deterministic in 32-bit x86 (some x87 always leaks in, even\n         with fp:strict). On 32-bit x86 GCC, determinism requires both -msse2 and\n         -fpmath=sse.\n\n         Note that we will not be deterministic with float data containing NaNs -\n         the NaNs will propagate differently on different SIMD and platforms.\n\n         If you turn on STBIR_USE_FMA, then we will be deterministic with other\n         fma targets, but we will differ from non-fma targets (this is unavoidable,\n         because a fma isn't simply an add with a mult - it also introduces a\n         rounding difference compared to non-fma instruction sequences.\n\n      FLOAT PIXEL FORMAT RANGE\n         Any range of values can be used for the non-alpha float data that you pass\n         in (0 to 1, -1 to 1, whatever). However, if you are inputting float values\n         but *outputting* bytes or shorts, you must use a range of 0 to 1 so that we\n         scale back properly. The alpha channel must also be 0 to 1 for any format\n         that does premultiplication prior to resizing.\n\n         Note also that with float output, using filters with negative lobes, the\n         output filtered values might go slightly out of range. You can define\n         STBIR_FLOAT_LOW_CLAMP and/or STBIR_FLOAT_HIGH_CLAMP to specify the range\n         to clamp to on output, if that's important.\n\n      MAX/MIN SCALE FACTORS\n         The input pixel resolutions are in integers, and we do the internal pointer\n         resolution in size_t sized integers. However, the scale ratio from input\n         resolution to output resolution is calculated in float form. This means\n         the effective possible scale ratio is limited to 24 bits (or 16 million\n         to 1). As you get close to the size of the float resolution (again, 16\n         million pixels wide or high), you might start seeing float inaccuracy\n         issues in general in the pipeline. If you have to do extreme resizes,\n         you can usually do this is multiple stages (using float intermediate\n         buffers).\n\n      FLIPPED IMAGES\n         Stride is just the delta from one scanline to the next. This means you can\n         use a negative stride to handle inverted images (point to the final\n         scanline and use a negative stride). You can invert the input or output,\n         using negative strides.\n\n      DEFAULT FILTERS\n         For functions which don't provide explicit control over what filters to\n         use, you can change the compile-time defaults with:\n\n            #define STBIR_DEFAULT_FILTER_UPSAMPLE     STBIR_FILTER_something\n            #define STBIR_DEFAULT_FILTER_DOWNSAMPLE   STBIR_FILTER_something\n\n         See stbir_filter in the header-file section for the list of filters.\n\n      NEW FILTERS\n         A number of 1D filter kernels are supplied. For a list of supported\n         filters, see the stbir_filter enum. You can install your own filters by\n         using the stbir_set_filter_callbacks function.\n\n      PROGRESS\n         For interactive use with slow resize operations, you can use the \n         scanline callbacks in the extended API. It would have to be a *very* large\n         image resample to need progress though - we're very fast.\n\n      CEIL and FLOOR\n         In scalar mode, the only functions we use from math.h are ceilf and floorf,\n         but if you have your own versions, you can define the STBIR_CEILF(v) and\n         STBIR_FLOORF(v) macros and we'll use them instead. In SIMD, we just use\n         our own versions.\n\n      ASSERT\n         Define STBIR_ASSERT(boolval) to override assert() and not use assert.h\n\n     PORTING FROM VERSION 1\n        The API has changed. You can continue to use the old version of stb_image_resize.h,\n        which is available in the \"deprecated/\" directory.\n\n        If you're using the old simple-to-use API, porting is straightforward.\n        (For more advanced APIs, read the documentation.)\n\n          stbir_resize_uint8():\n            - call `stbir_resize_uint8_linear`, cast channel count to `stbir_pixel_layout`\n\n          stbir_resize_float():\n            - call `stbir_resize_float_linear`, cast channel count to `stbir_pixel_layout`\n\n          stbir_resize_uint8_srgb():\n            - function name is unchanged\n            - cast channel count to `stbir_pixel_layout`\n            - above is sufficient unless your image has alpha and it's not RGBA/BGRA\n              - in that case, follow the below instructions for stbir_resize_uint8_srgb_edgemode\n\n          stbir_resize_uint8_srgb_edgemode()\n            - switch to the \"medium complexity\" API\n            - stbir_resize(), very similar API but a few more parameters:\n              - pixel_layout: cast channel count to `stbir_pixel_layout`\n              - data_type:    STBIR_TYPE_UINT8_SRGB\n              - edge:         unchanged (STBIR_EDGE_WRAP, etc.)\n              - filter:       STBIR_FILTER_DEFAULT\n            - which channel is alpha is specified in stbir_pixel_layout, see enum for details\n\n      FUTURE TODOS\n        *  For polyphase integral filters, we just memcpy the coeffs to dupe\n           them, but we should indirect and use the same coeff memory.\n        *  Add pixel layout conversions for sensible different channel counts\n           (maybe, 1->3/4, 3->4, 4->1, 3->1).\n         * For SIMD encode and decode scanline routines, do any pre-aligning\n           for bad input/output buffer alignments and pitch?\n         * For very wide scanlines, we should we do vertical strips to stay within\n           L2 cache. Maybe do chunks of 1K pixels at a time. There would be\n           some pixel reconversion, but probably dwarfed by things falling out\n           of cache. Probably also something possible with alternating between\n           scattering and gathering at high resize scales?\n         * Should we have a multiple MIPs at the same time function (could keep\n           more memory in cache during multiple resizes)?\n         * Rewrite the coefficient generator to do many at once.\n         * AVX-512 vertical kernels - worried about downclocking here.\n         * Convert the reincludes to macros when we know they aren't changing.\n         * Experiment with pivoting the horizontal and always using the\n           vertical filters (which are faster, but perhaps not enough to overcome\n           the pivot cost and the extra memory touches). Need to buffer the whole\n           image so have to balance memory use.\n         * Most of our code is internally function pointers, should we compile\n           all the SIMD stuff always and dynamically dispatch?\n\n   CONTRIBUTORS\n      Jeff Roberts: 2.0 implementation, optimizations, SIMD\n      Martins Mozeiko: NEON simd, WASM simd, clang and GCC whisperer\n      Fabian Giesen: half float and srgb converters\n      Sean Barrett: API design, optimizations\n      Jorge L Rodriguez: Original 1.0 implementation\n      Aras Pranckevicius: bugfixes\n      Nathan Reed: warning fixes for 1.0\n\n   REVISIONS\n      2.18 (2026-03-25) fixed coefficient calculation when skipping a coefficient off \n                          the left side of the window, added non-aligned access safe \n                          memcpy mode for scalar path, fixed various typos, and fixed \n                          define error in the float clamp output mode. \n      2.17 (2025-10-25) silly format bug in easy-to-use APIs.\n      2.16 (2025-10-21) fixed the easy-to-use APIs to allow inverted bitmaps (negative\n                          strides), fix vertical filter kernel callback, fix threaded\n                          gather buffer priming (and assert).\n                          (thanks adipose, TainZerL, and Harrison Green)\n      2.15 (2025-07-17) fixed an assert in debug mode when using floats with input\n                          callbacks, work around GCC warning when adding to null ptr\n                          (thanks Johannes Spohr and Pyry Kovanen).\n      2.14 (2025-05-09) fixed a bug using downsampling gather horizontal first, and \n                          scatter with vertical first.\n      2.13 (2025-02-27) fixed a bug when using input callbacks, turned off simd for \n                          tiny-c, fixed some variables that should have been static,\n                          fixes a bug when calculating temp memory with resizes that\n                          exceed 2GB of temp memory (very large resizes).\n      2.12 (2024-10-18) fix incorrect use of user_data with STBIR_FREE\n      2.11 (2024-09-08) fix harmless asan warnings in 2-channel and 3-channel mode\n                          with AVX-2, fix some weird scaling edge conditions with\n                          point sample mode.\n      2.10 (2024-07-27) fix the defines GCC and mingw for loop unroll control,\n                          fix MSVC 32-bit arm half float routines.\n      2.09 (2024-06-19) fix the defines for 32-bit ARM GCC builds (was selecting\n                          hardware half floats).\n      2.08 (2024-06-10) fix for RGB->BGR three channel flips and add SIMD (thanks\n                          to Ryan Salsbury), fix for sub-rect resizes, use the\n                          pragmas to control unrolling when they are available.\n      2.07 (2024-05-24) fix for slow final split during threaded conversions of very \n                          wide scanlines when downsampling (caused by extra input \n                          converting), fix for wide scanline resamples with many \n                          splits (int overflow), fix GCC warning.\n      2.06 (2024-02-10) fix for identical width/height 3x or more down-scaling \n                          undersampling a single row on rare resize ratios (about 1%).\n      2.05 (2024-02-07) fix for 2 pixel to 1 pixel resizes with wrap (thanks Aras),\n                        fix for output callback (thanks Julien Koenen).\n      2.04 (2023-11-17) fix for rare AVX bug, shadowed symbol (thanks Nikola Smiljanic).\n      2.03 (2023-11-01) ASAN and TSAN warnings fixed, minor tweaks.\n      2.00 (2023-10-10) mostly new source: new api, optimizations, simd, vertical-first, etc\n                          2x-5x faster without simd, 4x-12x faster with simd,\n                          in some cases, 20x to 40x faster esp resizing large to very small.\n      0.96 (2019-03-04) fixed warnings\n      0.95 (2017-07-23) fixed warnings\n      0.94 (2017-03-18) fixed warnings\n      0.93 (2017-03-03) fixed bug with certain combinations of heights\n      0.92 (2017-01-02) fix integer overflow on large (>2GB) images\n      0.91 (2016-04-02) fix warnings; fix handling of subpixel regions\n      0.90 (2014-09-17) first released version\n\n   LICENSE\n     See end of file for license information.\n*/\n\n#if !defined(STB_IMAGE_RESIZE_DO_HORIZONTALS) && !defined(STB_IMAGE_RESIZE_DO_VERTICALS) && !defined(STB_IMAGE_RESIZE_DO_CODERS)   // for internal re-includes\n\n#ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE2_H\n#define STBIR_INCLUDE_STB_IMAGE_RESIZE2_H\n\n#include <stddef.h>\n#ifdef _MSC_VER\ntypedef unsigned char    stbir_uint8;\ntypedef unsigned short   stbir_uint16;\ntypedef unsigned int     stbir_uint32;\ntypedef unsigned __int64 stbir_uint64;\n#else\n#include <stdint.h>\ntypedef uint8_t  stbir_uint8;\ntypedef uint16_t stbir_uint16;\ntypedef uint32_t stbir_uint32;\ntypedef uint64_t stbir_uint64;\n#endif\n\n#ifndef STBIRDEF\n#ifdef STB_IMAGE_RESIZE_STATIC\n#define STBIRDEF static\n#else\n#ifdef __cplusplus\n#define STBIRDEF extern \"C\"\n#else\n#define STBIRDEF extern\n#endif\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n////   start \"header file\" ///////////////////////////////////////////////////\n//\n// Easy-to-use API:\n//\n//     * stride is the offset between successive rows of image data\n//        in memory, in bytes. specify 0 for packed continuously in memory\n//     * colorspace is linear or sRGB as specified by function name\n//     * Uses the default filters\n//     * Uses edge mode clamped\n//     * returned result is 1 for success or 0 in case of an error.\n\n\n// stbir_pixel_layout specifies:\n//   number of channels\n//   order of channels\n//   whether color is premultiplied by alpha\n// for back compatibility, you can cast the old channel count to an stbir_pixel_layout\ntypedef enum\n{\n  STBIR_1CHANNEL = 1,\n  STBIR_2CHANNEL = 2,\n  STBIR_RGB      = 3,               // 3-chan, with order specified (for channel flipping)\n  STBIR_BGR      = 0,               // 3-chan, with order specified (for channel flipping)\n  STBIR_4CHANNEL = 5,\n\n  STBIR_RGBA = 4,                   // alpha formats, where alpha is NOT premultiplied into color channels\n  STBIR_BGRA = 6,\n  STBIR_ARGB = 7,\n  STBIR_ABGR = 8,\n  STBIR_RA   = 9,\n  STBIR_AR   = 10,\n\n  STBIR_RGBA_PM = 11,               // alpha formats, where alpha is premultiplied into color channels\n  STBIR_BGRA_PM = 12,\n  STBIR_ARGB_PM = 13,\n  STBIR_ABGR_PM = 14,\n  STBIR_RA_PM   = 15,\n  STBIR_AR_PM   = 16,\n\n  STBIR_RGBA_NO_AW = 11,            // alpha formats, where NO alpha weighting is applied at all!\n  STBIR_BGRA_NO_AW = 12,            //   these are just synonyms for the _PM flags (which also do\n  STBIR_ARGB_NO_AW = 13,            //   no alpha weighting). These names just make it more clear\n  STBIR_ABGR_NO_AW = 14,            //   for some folks).\n  STBIR_RA_NO_AW   = 15,\n  STBIR_AR_NO_AW   = 16,\n\n} stbir_pixel_layout;\n\n//===============================================================\n//  Simple-complexity API\n//\n//    If output_pixels is NULL (0), then we will allocate the buffer and return it to you.\n//--------------------------------\n\nSTBIRDEF unsigned char * stbir_resize_uint8_srgb( const unsigned char *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                                        unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                                        stbir_pixel_layout pixel_type );\n\nSTBIRDEF unsigned char * stbir_resize_uint8_linear( const unsigned char *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                                          unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                                          stbir_pixel_layout pixel_type );\n\nSTBIRDEF float * stbir_resize_float_linear( const float *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                                  float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                                  stbir_pixel_layout pixel_type );\n//===============================================================\n\n//===============================================================\n// Medium-complexity API\n//\n// This extends the easy-to-use API as follows:\n//\n//     * Can specify the datatype - U8, U8_SRGB, U16, FLOAT, HALF_FLOAT\n//     * Edge wrap can selected explicitly\n//     * Filter can be selected explicitly\n//--------------------------------\n\ntypedef enum\n{\n  STBIR_EDGE_CLAMP   = 0,\n  STBIR_EDGE_REFLECT = 1,\n  STBIR_EDGE_WRAP    = 2,  // this edge mode is slower and uses more memory\n  STBIR_EDGE_ZERO    = 3,\n} stbir_edge;\n\ntypedef enum\n{\n  STBIR_FILTER_DEFAULT      = 0,  // use same filter type that easy-to-use API chooses\n  STBIR_FILTER_BOX          = 1,  // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios\n  STBIR_FILTER_TRIANGLE     = 2,  // On upsampling, produces same results as bilinear texture filtering\n  STBIR_FILTER_CUBICBSPLINE = 3,  // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque\n  STBIR_FILTER_CATMULLROM   = 4,  // An interpolating cubic spline\n  STBIR_FILTER_MITCHELL     = 5,  // Mitchell-Netrevalli filter with B=1/3, C=1/3\n  STBIR_FILTER_POINT_SAMPLE = 6,  // Simple point sampling\n  STBIR_FILTER_OTHER        = 7,  // User callback specified\n} stbir_filter;\n\ntypedef enum\n{\n  STBIR_TYPE_UINT8            = 0,\n  STBIR_TYPE_UINT8_SRGB       = 1,\n  STBIR_TYPE_UINT8_SRGB_ALPHA = 2,  // alpha channel, when present, should also be SRGB (this is very unusual)\n  STBIR_TYPE_UINT16           = 3,\n  STBIR_TYPE_FLOAT            = 4,\n  STBIR_TYPE_HALF_FLOAT       = 5\n} stbir_datatype;\n\n// medium api\nSTBIRDEF void *  stbir_resize( const void *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                     void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                               stbir_pixel_layout pixel_layout, stbir_datatype data_type,\n                               stbir_edge edge, stbir_filter filter );\n//===============================================================\n\n\n\n//===============================================================\n// Extended-complexity API\n//\n// This API exposes all resize functionality.\n//\n//     * Separate filter types for each axis\n//     * Separate edge modes for each axis\n//     * Separate input and output data types\n//     * Can specify regions with subpixel correctness\n//     * Can specify alpha flags\n//     * Can specify a memory callback\n//     * Can specify a callback data type for pixel input and output\n//     * Can be threaded for a single resize\n//     * Can be used to resize many frames without recalculating the sampler info\n//\n//  Use this API as follows:\n//     1) Call the stbir_resize_init function on a local STBIR_RESIZE structure\n//     2) Call any of the stbir_set functions\n//     3) Optionally call stbir_build_samplers() if you are going to resample multiple times\n//        with the same input and output dimensions (like resizing video frames)\n//     4) Resample by calling stbir_resize_extended().\n//     5) Call stbir_free_samplers() if you called stbir_build_samplers()\n//--------------------------------\n\n\n// Types:\n\n// INPUT CALLBACK: this callback is used for input scanlines\ntypedef void const * stbir_input_callback( void * optional_output, void const * input_ptr, int num_pixels, int x, int y, void * context );\n\n// OUTPUT CALLBACK: this callback is used for output scanlines\ntypedef void stbir_output_callback( void const * output_ptr, int num_pixels, int y, void * context );\n\n// callbacks for user installed filters\ntypedef float stbir__kernel_callback( float x, float scale, void * user_data ); // centered at zero\ntypedef float stbir__support_callback( float scale, void * user_data );\n\n// internal structure with precomputed scaling\ntypedef struct stbir__info stbir__info;\n\ntypedef struct STBIR_RESIZE  // use the stbir_resize_init and stbir_override functions to set these values for future compatibility\n{\n  void * user_data;\n  void const * input_pixels;\n  int input_w, input_h;\n  double input_s0, input_t0, input_s1, input_t1;\n  stbir_input_callback * input_cb;\n  void * output_pixels;\n  int output_w, output_h;\n  int output_subx, output_suby, output_subw, output_subh;\n  stbir_output_callback * output_cb;\n  int input_stride_in_bytes;\n  int output_stride_in_bytes;\n  int splits;\n  int fast_alpha;\n  int needs_rebuild;\n  int called_alloc;\n  stbir_pixel_layout input_pixel_layout_public;\n  stbir_pixel_layout output_pixel_layout_public;\n  stbir_datatype input_data_type;\n  stbir_datatype output_data_type;\n  stbir_filter horizontal_filter, vertical_filter;\n  stbir_edge horizontal_edge, vertical_edge;\n  stbir__kernel_callback * horizontal_filter_kernel; stbir__support_callback * horizontal_filter_support;\n  stbir__kernel_callback * vertical_filter_kernel; stbir__support_callback * vertical_filter_support;\n  stbir__info * samplers;\n} STBIR_RESIZE;\n\n// extended complexity api\n\n\n// First off, you must ALWAYS call stbir_resize_init on your resize structure before any of the other calls!\nSTBIRDEF void stbir_resize_init( STBIR_RESIZE * resize,\n                                 const void *input_pixels,  int input_w,  int input_h, int input_stride_in_bytes, // stride can be zero\n                                       void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, // stride can be zero\n                                 stbir_pixel_layout pixel_layout, stbir_datatype data_type );\n\n//===============================================================\n// You can update these parameters any time after resize_init and there is no cost\n//--------------------------------\n\nSTBIRDEF void stbir_set_datatypes( STBIR_RESIZE * resize, stbir_datatype input_type, stbir_datatype output_type );\nSTBIRDEF void stbir_set_pixel_callbacks( STBIR_RESIZE * resize, stbir_input_callback * input_cb, stbir_output_callback * output_cb );   // no callbacks by default\nSTBIRDEF void stbir_set_user_data( STBIR_RESIZE * resize, void * user_data );                                               // pass back STBIR_RESIZE* by default\nSTBIRDEF void stbir_set_buffer_ptrs( STBIR_RESIZE * resize, const void * input_pixels, int input_stride_in_bytes, void * output_pixels, int output_stride_in_bytes );\n\n//===============================================================\n\n\n//===============================================================\n// If you call any of these functions, you will trigger a sampler rebuild!\n//--------------------------------\n\nSTBIRDEF int stbir_set_pixel_layouts( STBIR_RESIZE * resize, stbir_pixel_layout input_pixel_layout, stbir_pixel_layout output_pixel_layout );  // sets new buffer layouts\nSTBIRDEF int stbir_set_edgemodes( STBIR_RESIZE * resize, stbir_edge horizontal_edge, stbir_edge vertical_edge );       // CLAMP by default\n\nSTBIRDEF int stbir_set_filters( STBIR_RESIZE * resize, stbir_filter horizontal_filter, stbir_filter vertical_filter ); // STBIR_DEFAULT_FILTER_UPSAMPLE/DOWNSAMPLE by default\nSTBIRDEF int stbir_set_filter_callbacks( STBIR_RESIZE * resize, stbir__kernel_callback * horizontal_filter, stbir__support_callback * horizontal_support, stbir__kernel_callback * vertical_filter, stbir__support_callback * vertical_support );\n\nSTBIRDEF int stbir_set_pixel_subrect( STBIR_RESIZE * resize, int subx, int suby, int subw, int subh );        // sets both sub-regions (full regions by default)\nSTBIRDEF int stbir_set_input_subrect( STBIR_RESIZE * resize, double s0, double t0, double s1, double t1 );    // sets input sub-region (full region by default)\nSTBIRDEF int stbir_set_output_pixel_subrect( STBIR_RESIZE * resize, int subx, int suby, int subw, int subh ); // sets output sub-region (full region by default)\n\n// when inputting AND outputting non-premultiplied alpha pixels, we use a slower but higher quality technique\n//   that fills the zero alpha pixel's RGB values with something plausible.  If you don't care about areas of\n//   zero alpha, you can call this function to get about a 25% speed improvement for STBIR_RGBA to STBIR_RGBA\n//   types of resizes.\nSTBIRDEF int stbir_set_non_pm_alpha_speed_over_quality( STBIR_RESIZE * resize, int non_pma_alpha_speed_over_quality );\n//===============================================================\n\n\n//===============================================================\n// You can call build_samplers to prebuild all the internal data we need to resample.\n//   Then, if you call resize_extended many times with the same resize, you only pay the\n//   cost once.\n// If you do call build_samplers, you MUST call free_samplers eventually.\n//--------------------------------\n\n// This builds the samplers and does one allocation\nSTBIRDEF int stbir_build_samplers( STBIR_RESIZE * resize );\n\n// You MUST call this, if you call stbir_build_samplers or stbir_build_samplers_with_splits\nSTBIRDEF void stbir_free_samplers( STBIR_RESIZE * resize );\n//===============================================================\n\n\n// And this is the main function to perform the resize synchronously on one thread.\nSTBIRDEF int stbir_resize_extended( STBIR_RESIZE * resize );\n\n\n//===============================================================\n// Use these functions for multithreading.\n//   1) You call stbir_build_samplers_with_splits first on the main thread\n//   2) Then stbir_resize_with_split on each thread\n//   3) stbir_free_samplers when done on the main thread\n//--------------------------------\n\n// This will build samplers for threading.\n//   You can pass in the number of threads you'd like to use (try_splits).\n//   It returns the number of splits (threads) that you can call it with.\n///  It might be less if the image resize can't be split up that many ways.\n\nSTBIRDEF int stbir_build_samplers_with_splits( STBIR_RESIZE * resize, int try_splits );\n\n// This function does a split of the resizing (you call this fuction for each\n// split, on multiple threads). A split is a piece of the output resize pixel space.\n\n// Note that you MUST call stbir_build_samplers_with_splits before stbir_resize_extended_split!\n\n// Usually, you will always call stbir_resize_split with split_start as the thread_index\n//   and \"1\" for the split_count.\n// But, if you have a weird situation where you MIGHT want 8 threads, but sometimes\n//   only 4 threads, you can use 0,2,4,6 for the split_start's and use \"2\" for the\n//   split_count each time to turn in into a 4 thread resize. (This is unusual).\n\nSTBIRDEF int stbir_resize_extended_split( STBIR_RESIZE * resize, int split_start, int split_count );\n//===============================================================\n\n\n//===============================================================\n// Pixel Callbacks info:\n//--------------------------------\n\n//   The input callback is super flexible - it calls you with the input address\n//   (based on the stride and base pointer), it gives you an optional_output\n//   pointer that you can fill, or you can just return your own pointer into\n//   your own data.\n//\n//   You can also do conversion from non-supported data types if necessary - in\n//   this case, you ignore the input_ptr and just use the x and y parameters to\n//   calculate your own input_ptr based on the size of each non-supported pixel.\n//   (Something like the third example below.)\n//\n//   You can also install just an input or just an output callback by setting the\n//   callback that you don't want to zero.\n//\n//     First example, progress: (getting a callback that you can monitor the progress):\n//        void const * my_callback( void * optional_output, void const * input_ptr, int num_pixels, int x, int y, void * context )\n//        {\n//           percentage_done = y / input_height;\n//           return input_ptr;  // use buffer from call\n//        }\n//\n//     Next example, copying: (copy from some other buffer or stream):\n//        void const * my_callback( void * optional_output, void const * input_ptr, int num_pixels, int x, int y, void * context )\n//        {\n//           CopyOrStreamData( optional_output, other_data_src, num_pixels * pixel_width_in_bytes );\n//           return optional_output;  // return the optional buffer that we filled\n//        }\n//\n//     Third example, input another buffer without copying: (zero-copy from other buffer):\n//        void const * my_callback( void * optional_output, void const * input_ptr, int num_pixels, int x, int y, void * context )\n//        {\n//           void * pixels = ( (char*) other_image_base ) + ( y * other_image_stride ) + ( x * other_pixel_width_in_bytes );\n//           return pixels;       // return pointer to your data without copying\n//        }\n//\n//\n//   The output callback is considerably simpler - it just calls you so that you can dump\n//   out each scanline. You could even directly copy out to disk if you have a simple format\n//   like TGA or BMP. You can also convert to other output types here if you want.\n//\n//   Simple example:\n//        void const * my_output( void * output_ptr, int num_pixels, int y, void * context )\n//        {\n//           percentage_done = y / output_height;\n//           fwrite( output_ptr, pixel_width_in_bytes, num_pixels, output_file );\n//        }\n//===============================================================\n\n\n\n\n//===============================================================\n// optional built-in profiling API\n//--------------------------------\n\n#ifdef STBIR_PROFILE\n\ntypedef struct STBIR_PROFILE_INFO\n{\n  stbir_uint64 total_clocks;\n\n  // how many clocks spent (of total_clocks) in the various resize routines, along with a string description\n  //    there are \"resize_count\" number of zones\n  stbir_uint64 clocks[ 8 ];\n  char const ** descriptions;\n\n  // count of clocks and descriptions\n  stbir_uint32 count;\n} STBIR_PROFILE_INFO;\n\n// use after calling stbir_resize_extended (or stbir_build_samplers or stbir_build_samplers_with_splits)\nSTBIRDEF void stbir_resize_build_profile_info( STBIR_PROFILE_INFO * out_info, STBIR_RESIZE const * resize );\n\n// use after calling stbir_resize_extended\nSTBIRDEF void stbir_resize_extended_profile_info( STBIR_PROFILE_INFO * out_info, STBIR_RESIZE const * resize );\n\n// use after calling stbir_resize_extended_split\nSTBIRDEF void stbir_resize_split_profile_info( STBIR_PROFILE_INFO * out_info, STBIR_RESIZE const * resize, int split_start, int split_num );\n\n//===============================================================\n\n#endif\n\n\n////   end header file   /////////////////////////////////////////////////////\n#endif // STBIR_INCLUDE_STB_IMAGE_RESIZE2_H\n\n#if defined(STB_IMAGE_RESIZE_IMPLEMENTATION) || defined(STB_IMAGE_RESIZE2_IMPLEMENTATION)\n\n#ifndef STBIR_ASSERT\n#include <assert.h>\n#define STBIR_ASSERT(x) assert(x)\n#endif\n\n#ifndef STBIR_MALLOC\n#include <stdlib.h>\n#define STBIR_MALLOC(size,user_data) ((void)(user_data), malloc(size))\n#define STBIR_FREE(ptr,user_data)    ((void)(user_data), free(ptr))\n// (we used the comma operator to evaluate user_data, to avoid \"unused parameter\" warnings)\n#endif\n\n#ifdef _MSC_VER\n\n#define stbir__inline __forceinline\n\n#else\n\n#define stbir__inline __inline__\n\n// Clang address sanitizer\n#if defined(__has_feature)\n  #if __has_feature(address_sanitizer) || __has_feature(memory_sanitizer)\n    #ifndef STBIR__SEPARATE_ALLOCATIONS\n      #define STBIR__SEPARATE_ALLOCATIONS\n    #endif\n  #endif\n#endif\n\n#endif\n\n// GCC and MSVC\n#if defined(__SANITIZE_ADDRESS__)\n  #ifndef STBIR__SEPARATE_ALLOCATIONS\n    #define STBIR__SEPARATE_ALLOCATIONS\n  #endif\n#endif\n\n// Always turn off automatic FMA use - use STBIR_USE_FMA if you want.\n// Otherwise, this is a determinism disaster.\n#ifndef STBIR_DONT_CHANGE_FP_CONTRACT  // override in case you don't want this behavior\n#if defined(_MSC_VER) && !defined(__clang__)\n#if _MSC_VER > 1200\n#pragma fp_contract(off)\n#endif\n#elif defined(__GNUC__) &&  !defined(__clang__)\n#pragma GCC optimize(\"fp-contract=off\")\n#else\n#pragma STDC FP_CONTRACT OFF\n#endif\n#endif\n\n#ifdef _MSC_VER\n#define STBIR__UNUSED(v)  (void)(v)\n#else\n#define STBIR__UNUSED(v)  (void)sizeof(v)\n#endif\n\n#define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0]))\n\n\n#ifndef STBIR_DEFAULT_FILTER_UPSAMPLE\n#define STBIR_DEFAULT_FILTER_UPSAMPLE    STBIR_FILTER_CATMULLROM\n#endif\n\n#ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE\n#define STBIR_DEFAULT_FILTER_DOWNSAMPLE  STBIR_FILTER_MITCHELL\n#endif\n\n\n#ifndef STBIR__HEADER_FILENAME\n#define STBIR__HEADER_FILENAME \"stb_image_resize2.h\"\n#endif\n\n// the internal pixel layout enums are in a different order, so we can easily do range comparisons of types\n//   the public pixel layout is ordered in a way that if you cast num_channels (1-4) to the enum, you get something sensible\ntypedef enum\n{\n  STBIRI_1CHANNEL = 0,\n  STBIRI_2CHANNEL = 1,\n  STBIRI_RGB      = 2,\n  STBIRI_BGR      = 3,\n  STBIRI_4CHANNEL = 4,\n\n  STBIRI_RGBA = 5,\n  STBIRI_BGRA = 6,\n  STBIRI_ARGB = 7,\n  STBIRI_ABGR = 8,\n  STBIRI_RA   = 9,\n  STBIRI_AR   = 10,\n\n  STBIRI_RGBA_PM = 11,\n  STBIRI_BGRA_PM = 12,\n  STBIRI_ARGB_PM = 13,\n  STBIRI_ABGR_PM = 14,\n  STBIRI_RA_PM   = 15,\n  STBIRI_AR_PM   = 16,\n} stbir_internal_pixel_layout;\n\n// define the public pixel layouts to not compile inside the implementation (to avoid accidental use)\n#define STBIR_BGR bad_dont_use_in_implementation\n#define STBIR_1CHANNEL STBIR_BGR\n#define STBIR_2CHANNEL STBIR_BGR\n#define STBIR_RGB STBIR_BGR\n#define STBIR_RGBA STBIR_BGR\n#define STBIR_4CHANNEL STBIR_BGR\n#define STBIR_BGRA STBIR_BGR\n#define STBIR_ARGB STBIR_BGR\n#define STBIR_ABGR STBIR_BGR\n#define STBIR_RA STBIR_BGR\n#define STBIR_AR STBIR_BGR\n#define STBIR_RGBA_PM STBIR_BGR\n#define STBIR_BGRA_PM STBIR_BGR\n#define STBIR_ARGB_PM STBIR_BGR\n#define STBIR_ABGR_PM STBIR_BGR\n#define STBIR_RA_PM STBIR_BGR\n#define STBIR_AR_PM STBIR_BGR\n\n// must match stbir_datatype\nstatic unsigned char stbir__type_size[] = {\n  1,1,1,2,4,2 // STBIR_TYPE_UINT8,STBIR_TYPE_UINT8_SRGB,STBIR_TYPE_UINT8_SRGB_ALPHA,STBIR_TYPE_UINT16,STBIR_TYPE_FLOAT,STBIR_TYPE_HALF_FLOAT\n};\n\n// When gathering, the contributors are which source pixels contribute.\n// When scattering, the contributors are which destination pixels are contributed to.\ntypedef struct\n{\n  int n0; // First contributing pixel\n  int n1; // Last contributing pixel\n} stbir__contributors;\n\ntypedef struct\n{\n  int lowest;    // First sample index for whole filter\n  int highest;   // Last sample index for whole filter\n  int widest;    // widest single set of samples for an output\n} stbir__filter_extent_info;\n\ntypedef struct\n{\n  int n0; // First pixel of decode buffer to write to\n  int n1; // Last pixel of decode that will be written to\n  int pixel_offset_for_input;  // Pixel offset into input_scanline\n} stbir__span;\n\ntypedef struct stbir__scale_info\n{\n  int input_full_size;\n  int output_sub_size;\n  float scale;\n  float inv_scale;\n  float pixel_shift; // starting shift in output pixel space (in pixels)\n  int scale_is_rational;\n  stbir_uint32 scale_numerator, scale_denominator;\n} stbir__scale_info;\n\ntypedef struct\n{\n  stbir__contributors * contributors;\n  float* coefficients;\n  stbir__contributors * gather_prescatter_contributors;\n  float * gather_prescatter_coefficients;\n  stbir__scale_info scale_info;\n  float support;\n  stbir_filter filter_enum;\n  stbir__kernel_callback * filter_kernel;\n  stbir__support_callback * filter_support;\n  stbir_edge edge;\n  int coefficient_width;\n  int filter_pixel_width;\n  int filter_pixel_margin;\n  int num_contributors;\n  int contributors_size;\n  int coefficients_size;\n  stbir__filter_extent_info extent_info;\n  int is_gather;  // 0 = scatter, 1 = gather with scale >= 1, 2 = gather with scale < 1\n  int gather_prescatter_num_contributors;\n  int gather_prescatter_coefficient_width;\n  int gather_prescatter_contributors_size;\n  int gather_prescatter_coefficients_size;\n} stbir__sampler;\n\ntypedef struct\n{\n  stbir__contributors conservative;\n  int edge_sizes[2];    // this can be less than filter_pixel_margin, if the filter and scaling falls off\n  stbir__span spans[2]; // can be two spans, if doing input subrect with clamp mode WRAP\n} stbir__extents;\n\ntypedef struct\n{\n#ifdef STBIR_PROFILE\n  union\n  {\n    struct { stbir_uint64 total, looping, vertical, horizontal, decode, encode, alpha, unalpha; } named;\n    stbir_uint64 array[8];\n  } profile;\n  stbir_uint64 * current_zone_excluded_ptr;\n#endif\n  float* decode_buffer;\n\n  int ring_buffer_first_scanline;\n  int ring_buffer_last_scanline;\n  int ring_buffer_begin_index;    // first_scanline is at this index in the ring buffer\n  int start_output_y, end_output_y;\n  int start_input_y, end_input_y;  // used in scatter only\n\n  #ifdef STBIR__SEPARATE_ALLOCATIONS\n    float** ring_buffers; // one pointer for each ring buffer\n  #else\n    float* ring_buffer;  // one big buffer that we index into\n  #endif\n\n  float* vertical_buffer;\n\n  char no_cache_straddle[64];\n} stbir__per_split_info;\n\ntypedef float * stbir__decode_pixels_func( float * decode, int width_times_channels, void const * input );\ntypedef void stbir__alpha_weight_func( float * decode_buffer, int width_times_channels );\ntypedef void stbir__horizontal_gather_channels_func( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer,\n  stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width );\ntypedef void stbir__alpha_unweight_func(float * encode_buffer, int width_times_channels );\ntypedef void stbir__encode_pixels_func( void * output, int width_times_channels, float const * encode );\n\nstruct stbir__info\n{\n#ifdef STBIR_PROFILE\n  union\n  {\n    struct { stbir_uint64 total, build, alloc, horizontal, vertical, cleanup, pivot; } named;\n    stbir_uint64 array[7];\n  } profile;\n  stbir_uint64 * current_zone_excluded_ptr;\n#endif\n  stbir__sampler horizontal;\n  stbir__sampler vertical;\n\n  void const * input_data;\n  void * output_data;\n\n  int input_stride_bytes;\n  int output_stride_bytes;\n  int ring_buffer_length_bytes;   // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter)\n  int ring_buffer_num_entries;    // Total number of entries in the ring buffer.\n\n  stbir_datatype input_type;\n  stbir_datatype output_type;\n\n  stbir_input_callback * in_pixels_cb;\n  void * user_data;\n  stbir_output_callback * out_pixels_cb;\n\n  stbir__extents scanline_extents;\n\n  void * alloced_mem;\n  stbir__per_split_info * split_info;  // by default 1, but there will be N of these allocated based on the thread init you did\n\n  stbir__decode_pixels_func * decode_pixels;\n  stbir__alpha_weight_func * alpha_weight;\n  stbir__horizontal_gather_channels_func * horizontal_gather_channels;\n  stbir__alpha_unweight_func * alpha_unweight;\n  stbir__encode_pixels_func * encode_pixels;\n\n  int alloc_ring_buffer_num_entries;    // Number of entries in the ring buffer that will be allocated\n  int splits; // count of splits\n\n  stbir_internal_pixel_layout input_pixel_layout_internal;\n  stbir_internal_pixel_layout output_pixel_layout_internal;\n\n  int input_color_and_type;\n  int offset_x, offset_y; // offset within output_data\n  int vertical_first;\n  int channels;\n  int effective_channels; // same as channels, except on RGBA/ARGB (7), or XA/AX (3)\n  size_t alloced_total;\n};\n\n\n#define stbir__max_uint8_as_float             255.0f\n#define stbir__max_uint16_as_float            65535.0f\n#define stbir__max_uint8_as_float_inverted    3.9215689e-03f     // (1.0f/255.0f)\n#define stbir__max_uint16_as_float_inverted   1.5259022e-05f     // (1.0f/65535.0f)\n#define stbir__small_float ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20))\n\n// min/max friendly\n#define STBIR_CLAMP(x, xmin, xmax) for(;;) { \\\n  if ( (x) < (xmin) ) (x) = (xmin);     \\\n  if ( (x) > (xmax) ) (x) = (xmax);     \\\n  break;                                \\\n}\n\nstatic stbir__inline int stbir__min(int a, int b)\n{\n  return a < b ? a : b;\n}\n\nstatic stbir__inline int stbir__max(int a, int b)\n{\n  return a > b ? a : b;\n}\n\nstatic float stbir__srgb_uchar_to_linear_float[256] = {\n  0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f,\n  0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f,\n  0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f,\n  0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f,\n  0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f,\n  0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f,\n  0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f,\n  0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f,\n  0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f,\n  0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f,\n  0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f,\n  0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f,\n  0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f,\n  0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f,\n  0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f,\n  0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f,\n  0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f,\n  0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f,\n  0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f,\n  0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f,\n  0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f,\n  0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f,\n  0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f,\n  0.982251f, 0.991102f, 1.0f\n};\n\ntypedef union\n{\n  unsigned int u;\n  float f;\n} stbir__FP32;\n\n// From https://gist.github.com/rygorous/2203834\n\nstatic const stbir_uint32 fp32_to_srgb8_tab4[104] = {\n  0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d,\n  0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a,\n  0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033,\n  0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067,\n  0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5,\n  0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2,\n  0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143,\n  0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af,\n  0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240,\n  0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300,\n  0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401,\n  0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559,\n  0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723,\n};\n\nstatic stbir__inline stbir_uint8 stbir__linear_to_srgb_uchar(float in)\n{\n  static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps\n  static const stbir__FP32 minval = { (127-13) << 23 };\n  stbir_uint32 tab,bias,scale,t;\n  stbir__FP32 f;\n\n  // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively.\n  // The tests are carefully written so that NaNs map to 0, same as in the reference\n  // implementation.\n  if (!(in > minval.f)) // written this way to catch NaNs\n      return 0;\n  if (in > almostone.f)\n      return 255;\n\n  // Do the table lookup and unpack bias, scale\n  f.f = in;\n  tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20];\n  bias = (tab >> 16) << 9;\n  scale = tab & 0xffff;\n\n  // Grab next-highest mantissa bits and perform linear interpolation\n  t = (f.u >> 12) & 0xff;\n  return (unsigned char) ((bias + scale*t) >> 16);\n}\n\n#ifndef STBIR_FORCE_GATHER_FILTER_SCANLINES_AMOUNT\n#define STBIR_FORCE_GATHER_FILTER_SCANLINES_AMOUNT 32 // when downsampling and <= 32 scanlines of buffering, use gather. gather used down to 1/8th scaling for 25% win.\n#endif\n\n#ifndef STBIR_FORCE_MINIMUM_SCANLINES_FOR_SPLITS\n#define STBIR_FORCE_MINIMUM_SCANLINES_FOR_SPLITS 4 // when threading, what is the minimum number of scanlines for a split?\n#endif\n\n#define STBIR_INPUT_CALLBACK_PADDING 3\n\n#ifdef _M_IX86_FP\n#if ( _M_IX86_FP >= 1 )\n#ifndef STBIR_SSE\n#define STBIR_SSE\n#endif\n#endif\n#endif\n\n#ifdef __TINYC__\n  // tiny c has no intrinsics yet - this can become a version check if they add them\n  #define STBIR_NO_SIMD\n#endif\n\n#if defined(_x86_64) || defined( __x86_64__ ) || defined( _M_X64 ) || defined(__x86_64) || defined(_M_AMD64) || defined(__SSE2__) || defined(STBIR_SSE) || defined(STBIR_SSE2)\n  #ifndef STBIR_SSE2\n    #define STBIR_SSE2\n  #endif\n  #if defined(__AVX__) || defined(STBIR_AVX2)\n    #ifndef STBIR_AVX\n      #ifndef STBIR_NO_AVX\n        #define STBIR_AVX\n      #endif\n    #endif\n  #endif\n  #if defined(__AVX2__) || defined(STBIR_AVX2)\n    #ifndef STBIR_NO_AVX2\n      #ifndef STBIR_AVX2\n        #define STBIR_AVX2\n      #endif\n      #if defined( _MSC_VER ) && !defined(__clang__)\n        #ifndef STBIR_FP16C  // FP16C instructions are on all AVX2 cpus, so we can autoselect it here on microsoft - clang needs -mf16c\n          #define STBIR_FP16C\n        #endif\n      #endif\n    #endif\n  #endif\n  #ifdef __F16C__\n    #ifndef STBIR_FP16C  // turn on FP16C instructions if the define is set (for clang and gcc)\n      #define STBIR_FP16C\n    #endif\n  #endif\n#endif\n\n#if defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ ) || ((__ARM_NEON_FP & 4) != 0) || defined(__ARM_NEON__)\n#ifndef STBIR_NEON\n#define STBIR_NEON\n#endif\n#endif\n\n#if defined(_M_ARM) || defined(__arm__)\n#ifdef STBIR_USE_FMA\n#undef STBIR_USE_FMA // no FMA for 32-bit arm on MSVC\n#endif\n#endif\n\n#if defined(__wasm__) && defined(__wasm_simd128__)\n#ifndef STBIR_WASM\n#define STBIR_WASM\n#endif\n#endif\n\n// restrict pointers for the output pointers, other loop and unroll control\n#if defined( _MSC_VER ) && !defined(__clang__)\n  #define STBIR_STREAMOUT_PTR( star ) star __restrict\n  #define STBIR_NO_UNROLL( ptr ) __assume(ptr) // this oddly keeps msvc from unrolling a loop\n  #if _MSC_VER >= 1900\n    #define STBIR_NO_UNROLL_LOOP_START __pragma(loop( no_vector )) \n  #else\n    #define STBIR_NO_UNROLL_LOOP_START \n  #endif\n#elif defined( __clang__ )\n  #define STBIR_STREAMOUT_PTR( star ) star __restrict__\n  #define STBIR_NO_UNROLL( ptr ) __asm__ (\"\"::\"r\"(ptr)) \n  #if ( __clang_major__ >= 4 ) || ( ( __clang_major__ >= 3 ) && ( __clang_minor__ >= 5 ) )\n    #define STBIR_NO_UNROLL_LOOP_START _Pragma(\"clang loop unroll(disable)\") _Pragma(\"clang loop vectorize(disable)\")\n  #else\n    #define STBIR_NO_UNROLL_LOOP_START\n  #endif \n#elif defined( __GNUC__ )\n  #define STBIR_STREAMOUT_PTR( star ) star __restrict__\n  #define STBIR_NO_UNROLL( ptr ) __asm__ (\"\"::\"r\"(ptr))\n  #if __GNUC__ >= 14\n    #define STBIR_NO_UNROLL_LOOP_START _Pragma(\"GCC unroll 0\") _Pragma(\"GCC novector\")\n  #else\n    #define STBIR_NO_UNROLL_LOOP_START\n  #endif\n  #define STBIR_NO_UNROLL_LOOP_START_INF_FOR\n#else\n  #define STBIR_STREAMOUT_PTR( star ) star\n  #define STBIR_NO_UNROLL( ptr )\n  #define STBIR_NO_UNROLL_LOOP_START\n#endif\n\n#ifndef STBIR_NO_UNROLL_LOOP_START_INF_FOR\n#define STBIR_NO_UNROLL_LOOP_START_INF_FOR STBIR_NO_UNROLL_LOOP_START\n#endif\n\n#ifdef STBIR_NO_SIMD // force simd off for whatever reason\n\n// force simd off overrides everything else, so clear it all\n\n#ifdef STBIR_SSE2\n#undef STBIR_SSE2\n#endif\n\n#ifdef STBIR_AVX\n#undef STBIR_AVX\n#endif\n\n#ifdef STBIR_NEON\n#undef STBIR_NEON\n#endif\n\n#ifdef STBIR_AVX2\n#undef STBIR_AVX2\n#endif\n\n#ifdef STBIR_FP16C\n#undef STBIR_FP16C\n#endif\n\n#ifdef STBIR_WASM\n#undef STBIR_WASM\n#endif\n\n#ifdef STBIR_SIMD\n#undef STBIR_SIMD\n#endif\n\n#else // STBIR_SIMD\n\n#ifdef STBIR_SSE2\n  #include <emmintrin.h>\n\n  #define stbir__simdf __m128\n  #define stbir__simdi __m128i\n\n  #define stbir_simdi_castf( reg ) _mm_castps_si128(reg)\n  #define stbir_simdf_casti( reg ) _mm_castsi128_ps(reg)\n\n  #define stbir__simdf_load( reg, ptr ) (reg) = _mm_loadu_ps( (float const*)(ptr) )\n  #define stbir__simdi_load( reg, ptr ) (reg) = _mm_loadu_si128 ( (stbir__simdi const*)(ptr) )\n  #define stbir__simdf_load1( out, ptr ) (out) = _mm_load_ss( (float const*)(ptr) )  // top values can be random (not denormal or nan for perf)\n  #define stbir__simdi_load1( out, ptr ) (out) = _mm_castps_si128( _mm_load_ss( (float const*)(ptr) ))\n  #define stbir__simdf_load1z( out, ptr ) (out) = _mm_load_ss( (float const*)(ptr) )  // top values must be zero\n  #define stbir__simdf_frep4( fvar ) _mm_set_ps1( fvar )\n  #define stbir__simdf_load1frep4( out, fvar ) (out) = _mm_set_ps1( fvar )\n  #define stbir__simdf_load2( out, ptr ) (out) = _mm_castsi128_ps( _mm_loadl_epi64( (__m128i*)(ptr)) ) // top values can be random (not denormal or nan for perf)\n  #define stbir__simdf_load2z( out, ptr ) (out) = _mm_castsi128_ps( _mm_loadl_epi64( (__m128i*)(ptr)) ) // top values must be zero\n  #define stbir__simdf_load2hmerge( out, reg, ptr ) (out) = _mm_castpd_ps(_mm_loadh_pd( _mm_castps_pd(reg), (double*)(ptr) ))\n\n  #define stbir__simdf_zeroP() _mm_setzero_ps()\n  #define stbir__simdf_zero( reg ) (reg) = _mm_setzero_ps()\n\n  #define stbir__simdf_store( ptr, reg )  _mm_storeu_ps( (float*)(ptr), reg )\n  #define stbir__simdf_store1( ptr, reg ) _mm_store_ss( (float*)(ptr), reg )\n  #define stbir__simdf_store2( ptr, reg ) _mm_storel_epi64( (__m128i*)(ptr), _mm_castps_si128(reg) )\n  #define stbir__simdf_store2h( ptr, reg ) _mm_storeh_pd( (double*)(ptr), _mm_castps_pd(reg) )\n\n  #define stbir__simdi_store( ptr, reg )  _mm_storeu_si128( (__m128i*)(ptr), reg )\n  #define stbir__simdi_store1( ptr, reg ) _mm_store_ss( (float*)(ptr), _mm_castsi128_ps(reg) )\n  #define stbir__simdi_store2( ptr, reg ) _mm_storel_epi64( (__m128i*)(ptr), (reg) )\n\n  #define stbir__prefetch( ptr ) _mm_prefetch((char*)(ptr), _MM_HINT_T0 )\n\n  #define stbir__simdi_expand_u8_to_u32(out0,out1,out2,out3,ireg) \\\n  { \\\n    stbir__simdi zero = _mm_setzero_si128(); \\\n    out2 = _mm_unpacklo_epi8( ireg, zero ); \\\n    out3 = _mm_unpackhi_epi8( ireg, zero ); \\\n    out0 = _mm_unpacklo_epi16( out2, zero ); \\\n    out1 = _mm_unpackhi_epi16( out2, zero ); \\\n    out2 = _mm_unpacklo_epi16( out3, zero ); \\\n    out3 = _mm_unpackhi_epi16( out3, zero ); \\\n  }\n\n#define stbir__simdi_expand_u8_to_1u32(out,ireg) \\\n  { \\\n    stbir__simdi zero = _mm_setzero_si128(); \\\n    out = _mm_unpacklo_epi8( ireg, zero ); \\\n    out = _mm_unpacklo_epi16( out, zero ); \\\n  }\n\n  #define stbir__simdi_expand_u16_to_u32(out0,out1,ireg) \\\n  { \\\n    stbir__simdi zero = _mm_setzero_si128(); \\\n    out0 = _mm_unpacklo_epi16( ireg, zero ); \\\n    out1 = _mm_unpackhi_epi16( ireg, zero ); \\\n  }\n\n  #define stbir__simdf_convert_float_to_i32( i, f ) (i) = _mm_cvttps_epi32(f)\n  #define stbir__simdf_convert_float_to_int( f ) _mm_cvtt_ss2si(f)\n  #define stbir__simdf_convert_float_to_uint8( f ) ((unsigned char)_mm_cvtsi128_si32(_mm_cvttps_epi32(_mm_max_ps(_mm_min_ps(f,STBIR__CONSTF(STBIR_max_uint8_as_float)),_mm_setzero_ps()))))\n  #define stbir__simdf_convert_float_to_short( f ) ((unsigned short)_mm_cvtsi128_si32(_mm_cvttps_epi32(_mm_max_ps(_mm_min_ps(f,STBIR__CONSTF(STBIR_max_uint16_as_float)),_mm_setzero_ps()))))\n\n  #define stbir__simdi_to_int( i ) _mm_cvtsi128_si32(i)\n  #define stbir__simdi_convert_i32_to_float(out, ireg) (out) = _mm_cvtepi32_ps( ireg )\n  #define stbir__simdf_add( out, reg0, reg1 ) (out) = _mm_add_ps( reg0, reg1 )\n  #define stbir__simdf_mult( out, reg0, reg1 ) (out) = _mm_mul_ps( reg0, reg1 )\n  #define stbir__simdf_mult_mem( out, reg, ptr ) (out) = _mm_mul_ps( reg, _mm_loadu_ps( (float const*)(ptr) ) )\n  #define stbir__simdf_mult1_mem( out, reg, ptr ) (out) = _mm_mul_ss( reg, _mm_load_ss( (float const*)(ptr) ) )\n  #define stbir__simdf_add_mem( out, reg, ptr ) (out) = _mm_add_ps( reg, _mm_loadu_ps( (float const*)(ptr) ) )\n  #define stbir__simdf_add1_mem( out, reg, ptr ) (out) = _mm_add_ss( reg, _mm_load_ss( (float const*)(ptr) ) )\n\n  #ifdef STBIR_USE_FMA           // not on by default to maintain bit identical simd to non-simd\n  #include <immintrin.h>\n  #define stbir__simdf_madd( out, add, mul1, mul2 ) (out) = _mm_fmadd_ps( mul1, mul2, add )\n  #define stbir__simdf_madd1( out, add, mul1, mul2 ) (out) = _mm_fmadd_ss( mul1, mul2, add )\n  #define stbir__simdf_madd_mem( out, add, mul, ptr ) (out) = _mm_fmadd_ps( mul, _mm_loadu_ps( (float const*)(ptr) ), add )\n  #define stbir__simdf_madd1_mem( out, add, mul, ptr ) (out) = _mm_fmadd_ss( mul, _mm_load_ss( (float const*)(ptr) ), add )\n  #else\n  #define stbir__simdf_madd( out, add, mul1, mul2 ) (out) = _mm_add_ps( add, _mm_mul_ps( mul1, mul2 ) )\n  #define stbir__simdf_madd1( out, add, mul1, mul2 ) (out) = _mm_add_ss( add, _mm_mul_ss( mul1, mul2 ) )\n  #define stbir__simdf_madd_mem( out, add, mul, ptr ) (out) = _mm_add_ps( add, _mm_mul_ps( mul, _mm_loadu_ps( (float const*)(ptr) ) ) )\n  #define stbir__simdf_madd1_mem( out, add, mul, ptr ) (out) = _mm_add_ss( add, _mm_mul_ss( mul, _mm_load_ss( (float const*)(ptr) ) ) )\n  #endif\n\n  #define stbir__simdf_add1( out, reg0, reg1 ) (out) = _mm_add_ss( reg0, reg1 )\n  #define stbir__simdf_mult1( out, reg0, reg1 ) (out) = _mm_mul_ss( reg0, reg1 )\n\n  #define stbir__simdf_and( out, reg0, reg1 ) (out) = _mm_and_ps( reg0, reg1 )\n  #define stbir__simdf_or( out, reg0, reg1 ) (out) = _mm_or_ps( reg0, reg1 )\n\n  #define stbir__simdf_min( out, reg0, reg1 ) (out) = _mm_min_ps( reg0, reg1 )\n  #define stbir__simdf_max( out, reg0, reg1 ) (out) = _mm_max_ps( reg0, reg1 )\n  #define stbir__simdf_min1( out, reg0, reg1 ) (out) = _mm_min_ss( reg0, reg1 )\n  #define stbir__simdf_max1( out, reg0, reg1 ) (out) = _mm_max_ss( reg0, reg1 )\n\n  #define stbir__simdf_0123ABCDto3ABx( out, reg0, reg1 ) (out)=_mm_castsi128_ps( _mm_shuffle_epi32( _mm_castps_si128( _mm_shuffle_ps( reg1,reg0, (0<<0) + (1<<2) + (2<<4) + (3<<6) )), (3<<0) + (0<<2) + (1<<4) + (2<<6) ) )\n  #define stbir__simdf_0123ABCDto23Ax( out, reg0, reg1 ) (out)=_mm_castsi128_ps( _mm_shuffle_epi32( _mm_castps_si128( _mm_shuffle_ps( reg1,reg0, (0<<0) + (1<<2) + (2<<4) + (3<<6) )), (2<<0) + (3<<2) + (0<<4) + (1<<6) ) )\n\n  static const stbir__simdf STBIR_zeroones = { 0.0f,1.0f,0.0f,1.0f };\n  static const stbir__simdf STBIR_onezeros = { 1.0f,0.0f,1.0f,0.0f };\n  #define stbir__simdf_aaa1( out, alp, ones ) (out)=_mm_castsi128_ps( _mm_shuffle_epi32( _mm_castps_si128( _mm_movehl_ps( ones, alp ) ), (1<<0) + (1<<2) + (1<<4) + (2<<6) ) )\n  #define stbir__simdf_1aaa( out, alp, ones ) (out)=_mm_castsi128_ps( _mm_shuffle_epi32( _mm_castps_si128( _mm_movelh_ps( ones, alp ) ), (0<<0) + (2<<2) + (2<<4) + (2<<6) ) )\n  #define stbir__simdf_a1a1( out, alp, ones) (out) = _mm_or_ps( _mm_castsi128_ps( _mm_srli_epi64( _mm_castps_si128(alp), 32 ) ), STBIR_zeroones )\n  #define stbir__simdf_1a1a( out, alp, ones) (out) = _mm_or_ps( _mm_castsi128_ps( _mm_slli_epi64( _mm_castps_si128(alp), 32 ) ), STBIR_onezeros )\n\n  #define stbir__simdf_swiz( reg, one, two, three, four ) _mm_castsi128_ps( _mm_shuffle_epi32( _mm_castps_si128( reg ), (one<<0) + (two<<2) + (three<<4) + (four<<6) ) )\n\n  #define stbir__simdi_and( out, reg0, reg1 ) (out) = _mm_and_si128( reg0, reg1 )\n  #define stbir__simdi_or( out, reg0, reg1 ) (out) = _mm_or_si128( reg0, reg1 )\n  #define stbir__simdi_16madd( out, reg0, reg1 ) (out) = _mm_madd_epi16( reg0, reg1 )\n\n  #define stbir__simdf_pack_to_8bytes(out,aa,bb) \\\n  { \\\n    stbir__simdf af,bf; \\\n    stbir__simdi a,b; \\\n    af = _mm_min_ps( aa, STBIR_max_uint8_as_float ); \\\n    bf = _mm_min_ps( bb, STBIR_max_uint8_as_float ); \\\n    af = _mm_max_ps( af, _mm_setzero_ps() ); \\\n    bf = _mm_max_ps( bf, _mm_setzero_ps() ); \\\n    a = _mm_cvttps_epi32( af ); \\\n    b = _mm_cvttps_epi32( bf ); \\\n    a = _mm_packs_epi32( a, b ); \\\n    out = _mm_packus_epi16( a, a ); \\\n  }\n\n  #define stbir__simdf_load4_transposed( o0, o1, o2, o3, ptr ) \\\n      stbir__simdf_load( o0, (ptr) );    \\\n      stbir__simdf_load( o1, (ptr)+4 );  \\\n      stbir__simdf_load( o2, (ptr)+8 );  \\\n      stbir__simdf_load( o3, (ptr)+12 ); \\\n      {                                  \\\n        __m128 tmp0, tmp1, tmp2, tmp3;   \\\n        tmp0 = _mm_unpacklo_ps(o0, o1);  \\\n        tmp2 = _mm_unpacklo_ps(o2, o3);  \\\n        tmp1 = _mm_unpackhi_ps(o0, o1);  \\\n        tmp3 = _mm_unpackhi_ps(o2, o3);  \\\n        o0 = _mm_movelh_ps(tmp0, tmp2);  \\\n        o1 = _mm_movehl_ps(tmp2, tmp0);  \\\n        o2 = _mm_movelh_ps(tmp1, tmp3);  \\\n        o3 = _mm_movehl_ps(tmp3, tmp1);  \\\n      }\n\n  #define stbir__interleave_pack_and_store_16_u8( ptr, r0, r1, r2, r3 ) \\\n      r0 = _mm_packs_epi32( r0, r1 ); \\\n      r2 = _mm_packs_epi32( r2, r3 ); \\\n      r1 = _mm_unpacklo_epi16( r0, r2 ); \\\n      r3 = _mm_unpackhi_epi16( r0, r2 ); \\\n      r0 = _mm_unpacklo_epi16( r1, r3 ); \\\n      r2 = _mm_unpackhi_epi16( r1, r3 ); \\\n      r0 = _mm_packus_epi16( r0, r2 ); \\\n      stbir__simdi_store( ptr, r0 ); \\\n\n  #define stbir__simdi_32shr( out, reg, imm ) out = _mm_srli_epi32( reg, imm )\n\n  #if defined(_MSC_VER) && !defined(__clang__)\n    // msvc inits with 8 bytes\n    #define STBIR__CONST_32_TO_8( v ) (char)(unsigned char)((v)&255),(char)(unsigned char)(((v)>>8)&255),(char)(unsigned char)(((v)>>16)&255),(char)(unsigned char)(((v)>>24)&255)\n    #define STBIR__CONST_4_32i( v ) STBIR__CONST_32_TO_8( v ), STBIR__CONST_32_TO_8( v ), STBIR__CONST_32_TO_8( v ), STBIR__CONST_32_TO_8( v )\n    #define STBIR__CONST_4d_32i( v0, v1, v2, v3 ) STBIR__CONST_32_TO_8( v0 ), STBIR__CONST_32_TO_8( v1 ), STBIR__CONST_32_TO_8( v2 ), STBIR__CONST_32_TO_8( v3 )\n  #else\n    // everything else inits with long long's\n    #define STBIR__CONST_4_32i( v ) (long long)((((stbir_uint64)(stbir_uint32)(v))<<32)|((stbir_uint64)(stbir_uint32)(v))),(long long)((((stbir_uint64)(stbir_uint32)(v))<<32)|((stbir_uint64)(stbir_uint32)(v)))\n    #define STBIR__CONST_4d_32i( v0, v1, v2, v3 ) (long long)((((stbir_uint64)(stbir_uint32)(v1))<<32)|((stbir_uint64)(stbir_uint32)(v0))),(long long)((((stbir_uint64)(stbir_uint32)(v3))<<32)|((stbir_uint64)(stbir_uint32)(v2)))\n  #endif\n\n  #define STBIR__SIMDF_CONST(var, x) stbir__simdf var = { x, x, x, x }\n  #define STBIR__SIMDI_CONST(var, x) stbir__simdi var = { STBIR__CONST_4_32i(x) }\n  #define STBIR__CONSTF(var) (var)\n  #define STBIR__CONSTI(var) (var)\n\n  #if defined(STBIR_AVX) || defined(__SSE4_1__)\n    #include <smmintrin.h>\n    #define stbir__simdf_pack_to_8words(out,reg0,reg1) out = _mm_packus_epi32(_mm_cvttps_epi32(_mm_max_ps(_mm_min_ps(reg0,STBIR__CONSTF(STBIR_max_uint16_as_float)),_mm_setzero_ps())), _mm_cvttps_epi32(_mm_max_ps(_mm_min_ps(reg1,STBIR__CONSTF(STBIR_max_uint16_as_float)),_mm_setzero_ps())))\n  #else\n    static STBIR__SIMDI_CONST(stbir__s32_32768, 32768);\n    static STBIR__SIMDI_CONST(stbir__s16_32768, ((32768<<16)|32768));\n\n    #define stbir__simdf_pack_to_8words(out,reg0,reg1) \\\n      { \\\n        stbir__simdi tmp0,tmp1; \\\n        tmp0 = _mm_cvttps_epi32(_mm_max_ps(_mm_min_ps(reg0,STBIR__CONSTF(STBIR_max_uint16_as_float)),_mm_setzero_ps())); \\\n        tmp1 = _mm_cvttps_epi32(_mm_max_ps(_mm_min_ps(reg1,STBIR__CONSTF(STBIR_max_uint16_as_float)),_mm_setzero_ps())); \\\n        tmp0 = _mm_sub_epi32( tmp0, stbir__s32_32768 ); \\\n        tmp1 = _mm_sub_epi32( tmp1, stbir__s32_32768 ); \\\n        out = _mm_packs_epi32( tmp0, tmp1 ); \\\n        out = _mm_sub_epi16( out, stbir__s16_32768 ); \\\n      }\n\n  #endif\n\n  #define STBIR_SIMD\n\n  // if we detect AVX, set the simd8 defines\n  #ifdef STBIR_AVX\n    #include <immintrin.h>\n    #define STBIR_SIMD8\n    #define stbir__simdf8 __m256\n    #define stbir__simdi8 __m256i\n    #define stbir__simdf8_load( out, ptr ) (out) = _mm256_loadu_ps( (float const *)(ptr) )\n    #define stbir__simdi8_load( out, ptr ) (out) = _mm256_loadu_si256( (__m256i const *)(ptr) )\n    #define stbir__simdf8_mult( out, a, b ) (out) = _mm256_mul_ps( (a), (b) )\n    #define stbir__simdf8_store( ptr, out ) _mm256_storeu_ps( (float*)(ptr), out )\n    #define stbir__simdi8_store( ptr, reg )  _mm256_storeu_si256( (__m256i*)(ptr), reg )\n    #define stbir__simdf8_frep8( fval ) _mm256_set1_ps( fval )\n\n    #define stbir__simdf8_min( out, reg0, reg1 ) (out) = _mm256_min_ps( reg0, reg1 )\n    #define stbir__simdf8_max( out, reg0, reg1 ) (out) = _mm256_max_ps( reg0, reg1 )\n\n    #define stbir__simdf8_add4halves( out, bot4, top8 ) (out) = _mm_add_ps( bot4, _mm256_extractf128_ps( top8, 1 ) )\n    #define stbir__simdf8_mult_mem( out, reg, ptr ) (out) = _mm256_mul_ps( reg, _mm256_loadu_ps( (float const*)(ptr) ) )\n    #define stbir__simdf8_add_mem( out, reg, ptr ) (out) = _mm256_add_ps( reg, _mm256_loadu_ps( (float const*)(ptr) ) )\n    #define stbir__simdf8_add( out, a, b ) (out) = _mm256_add_ps( a, b )\n    #define stbir__simdf8_load1b( out, ptr ) (out) = _mm256_broadcast_ss( ptr )\n    #define stbir__simdf_load1rep4( out, ptr ) (out) = _mm_broadcast_ss( ptr )  // avx load instruction\n\n    #define stbir__simdi8_convert_i32_to_float(out, ireg) (out) = _mm256_cvtepi32_ps( ireg )\n    #define stbir__simdf8_convert_float_to_i32( i, f ) (i) = _mm256_cvttps_epi32(f)\n\n    #define stbir__simdf8_bot4s( out, a, b ) (out) = _mm256_permute2f128_ps(a,b, (0<<0)+(2<<4) )\n    #define stbir__simdf8_top4s( out, a, b ) (out) = _mm256_permute2f128_ps(a,b, (1<<0)+(3<<4) )\n\n    #define stbir__simdf8_gettop4( reg ) _mm256_extractf128_ps(reg,1)\n\n    #ifdef STBIR_AVX2\n\n    #define stbir__simdi8_expand_u8_to_u32(out0,out1,ireg) \\\n    { \\\n      stbir__simdi8 a, zero  =_mm256_setzero_si256();\\\n      a = _mm256_permute4x64_epi64( _mm256_unpacklo_epi8( _mm256_permute4x64_epi64(_mm256_castsi128_si256(ireg),(0<<0)+(2<<2)+(1<<4)+(3<<6)), zero ),(0<<0)+(2<<2)+(1<<4)+(3<<6)); \\\n      out0 = _mm256_unpacklo_epi16( a, zero ); \\\n      out1 = _mm256_unpackhi_epi16( a, zero ); \\\n    }\n\n    #define stbir__simdf8_pack_to_16bytes(out,aa,bb) \\\n    { \\\n      stbir__simdi8 t; \\\n      stbir__simdf8 af,bf; \\\n      stbir__simdi8 a,b; \\\n      af = _mm256_min_ps( aa, STBIR_max_uint8_as_floatX ); \\\n      bf = _mm256_min_ps( bb, STBIR_max_uint8_as_floatX ); \\\n      af = _mm256_max_ps( af, _mm256_setzero_ps() ); \\\n      bf = _mm256_max_ps( bf, _mm256_setzero_ps() ); \\\n      a = _mm256_cvttps_epi32( af ); \\\n      b = _mm256_cvttps_epi32( bf ); \\\n      t = _mm256_permute4x64_epi64( _mm256_packs_epi32( a, b ), (0<<0)+(2<<2)+(1<<4)+(3<<6) ); \\\n      out = _mm256_castsi256_si128( _mm256_permute4x64_epi64( _mm256_packus_epi16( t, t ), (0<<0)+(2<<2)+(1<<4)+(3<<6) ) ); \\\n    }\n\n    #define stbir__simdi8_expand_u16_to_u32(out,ireg) out = _mm256_unpacklo_epi16( _mm256_permute4x64_epi64(_mm256_castsi128_si256(ireg),(0<<0)+(2<<2)+(1<<4)+(3<<6)), _mm256_setzero_si256() );\n\n    #define stbir__simdf8_pack_to_16words(out,aa,bb) \\\n      { \\\n        stbir__simdf8 af,bf; \\\n        stbir__simdi8 a,b; \\\n        af = _mm256_min_ps( aa, STBIR_max_uint16_as_floatX ); \\\n        bf = _mm256_min_ps( bb, STBIR_max_uint16_as_floatX ); \\\n        af = _mm256_max_ps( af, _mm256_setzero_ps() ); \\\n        bf = _mm256_max_ps( bf, _mm256_setzero_ps() ); \\\n        a = _mm256_cvttps_epi32( af ); \\\n        b = _mm256_cvttps_epi32( bf ); \\\n        (out) = _mm256_permute4x64_epi64( _mm256_packus_epi32(a, b), (0<<0)+(2<<2)+(1<<4)+(3<<6) ); \\\n      }\n\n    #else\n\n    #define stbir__simdi8_expand_u8_to_u32(out0,out1,ireg) \\\n    { \\\n      stbir__simdi a,zero = _mm_setzero_si128(); \\\n      a = _mm_unpacklo_epi8( ireg, zero ); \\\n      out0 = _mm256_setr_m128i( _mm_unpacklo_epi16( a, zero ), _mm_unpackhi_epi16( a, zero ) ); \\\n      a = _mm_unpackhi_epi8( ireg, zero ); \\\n      out1 = _mm256_setr_m128i( _mm_unpacklo_epi16( a, zero ), _mm_unpackhi_epi16( a, zero ) ); \\\n    }\n\n    #define stbir__simdf8_pack_to_16bytes(out,aa,bb) \\\n    { \\\n      stbir__simdi t; \\\n      stbir__simdf8 af,bf; \\\n      stbir__simdi8 a,b; \\\n      af = _mm256_min_ps( aa, STBIR_max_uint8_as_floatX ); \\\n      bf = _mm256_min_ps( bb, STBIR_max_uint8_as_floatX ); \\\n      af = _mm256_max_ps( af, _mm256_setzero_ps() ); \\\n      bf = _mm256_max_ps( bf, _mm256_setzero_ps() ); \\\n      a = _mm256_cvttps_epi32( af ); \\\n      b = _mm256_cvttps_epi32( bf ); \\\n      out = _mm_packs_epi32( _mm256_castsi256_si128(a), _mm256_extractf128_si256( a, 1 ) ); \\\n      out = _mm_packus_epi16( out, out ); \\\n      t = _mm_packs_epi32( _mm256_castsi256_si128(b), _mm256_extractf128_si256( b, 1 ) ); \\\n      t = _mm_packus_epi16( t, t ); \\\n      out = _mm_castps_si128( _mm_shuffle_ps( _mm_castsi128_ps(out), _mm_castsi128_ps(t), (0<<0)+(1<<2)+(0<<4)+(1<<6) ) ); \\\n    }\n\n    #define stbir__simdi8_expand_u16_to_u32(out,ireg) \\\n    { \\\n      stbir__simdi a,b,zero = _mm_setzero_si128(); \\\n      a = _mm_unpacklo_epi16( ireg, zero ); \\\n      b = _mm_unpackhi_epi16( ireg, zero ); \\\n      out = _mm256_insertf128_si256( _mm256_castsi128_si256( a ), b, 1 ); \\\n    }\n\n    #define stbir__simdf8_pack_to_16words(out,aa,bb) \\\n      { \\\n        stbir__simdi t0,t1; \\\n        stbir__simdf8 af,bf; \\\n        stbir__simdi8 a,b; \\\n        af = _mm256_min_ps( aa, STBIR_max_uint16_as_floatX ); \\\n        bf = _mm256_min_ps( bb, STBIR_max_uint16_as_floatX ); \\\n        af = _mm256_max_ps( af, _mm256_setzero_ps() ); \\\n        bf = _mm256_max_ps( bf, _mm256_setzero_ps() ); \\\n        a = _mm256_cvttps_epi32( af ); \\\n        b = _mm256_cvttps_epi32( bf ); \\\n        t0 = _mm_packus_epi32( _mm256_castsi256_si128(a), _mm256_extractf128_si256( a, 1 ) ); \\\n        t1 = _mm_packus_epi32( _mm256_castsi256_si128(b), _mm256_extractf128_si256( b, 1 ) ); \\\n        out = _mm256_setr_m128i( t0, t1 ); \\\n      }\n\n    #endif\n\n    static __m256i stbir_00001111 = { STBIR__CONST_4d_32i( 0, 0, 0, 0 ), STBIR__CONST_4d_32i( 1, 1, 1, 1 ) };\n    #define stbir__simdf8_0123to00001111( out, in ) (out) = _mm256_permutevar_ps ( in, stbir_00001111 )\n\n    static __m256i stbir_22223333 = { STBIR__CONST_4d_32i( 2, 2, 2, 2 ), STBIR__CONST_4d_32i( 3, 3, 3, 3 ) };\n    #define stbir__simdf8_0123to22223333( out, in ) (out) = _mm256_permutevar_ps ( in, stbir_22223333 )\n\n    #define stbir__simdf8_0123to2222( out, in ) (out) = stbir__simdf_swiz(_mm256_castps256_ps128(in), 2,2,2,2 )\n\n    #define stbir__simdf8_load4b( out, ptr ) (out) = _mm256_broadcast_ps( (__m128 const *)(ptr) )\n\n    static __m256i stbir_00112233 = { STBIR__CONST_4d_32i( 0, 0, 1, 1 ), STBIR__CONST_4d_32i( 2, 2, 3, 3 ) };\n    #define stbir__simdf8_0123to00112233( out, in ) (out) = _mm256_permutevar_ps ( in, stbir_00112233 )\n    #define stbir__simdf8_add4( out, a8, b ) (out) = _mm256_add_ps( a8,  _mm256_castps128_ps256( b ) )\n\n    static __m256i stbir_load6 = { STBIR__CONST_4_32i( 0x80000000 ), STBIR__CONST_4d_32i(  0x80000000,  0x80000000, 0, 0 ) };\n    #define stbir__simdf8_load6z( out, ptr ) (out) = _mm256_maskload_ps( ptr, stbir_load6 )\n\n    #define stbir__simdf8_0123to00000000( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (0<<0)+(0<<2)+(0<<4)+(0<<6) )\n    #define stbir__simdf8_0123to11111111( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (1<<0)+(1<<2)+(1<<4)+(1<<6) )\n    #define stbir__simdf8_0123to22222222( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (2<<0)+(2<<2)+(2<<4)+(2<<6) )\n    #define stbir__simdf8_0123to33333333( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (3<<0)+(3<<2)+(3<<4)+(3<<6) )\n    #define stbir__simdf8_0123to21032103( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (2<<0)+(1<<2)+(0<<4)+(3<<6) )\n    #define stbir__simdf8_0123to32103210( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (3<<0)+(2<<2)+(1<<4)+(0<<6) )\n    #define stbir__simdf8_0123to12301230( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (1<<0)+(2<<2)+(3<<4)+(0<<6) )\n    #define stbir__simdf8_0123to10321032( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (1<<0)+(0<<2)+(3<<4)+(2<<6) )\n    #define stbir__simdf8_0123to30123012( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (3<<0)+(0<<2)+(1<<4)+(2<<6) )\n\n    #define stbir__simdf8_0123to11331133( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (1<<0)+(1<<2)+(3<<4)+(3<<6) )\n    #define stbir__simdf8_0123to00220022( out, in ) (out) =  _mm256_shuffle_ps ( in, in, (0<<0)+(0<<2)+(2<<4)+(2<<6) )\n\n    #define stbir__simdf8_aaa1( out, alp, ones ) (out) = _mm256_blend_ps( alp, ones, (1<<0)+(1<<1)+(1<<2)+(0<<3)+(1<<4)+(1<<5)+(1<<6)+(0<<7)); (out)=_mm256_shuffle_ps( out,out, (3<<0) + (3<<2) + (3<<4) + (0<<6) )\n    #define stbir__simdf8_1aaa( out, alp, ones ) (out) = _mm256_blend_ps( alp, ones, (0<<0)+(1<<1)+(1<<2)+(1<<3)+(0<<4)+(1<<5)+(1<<6)+(1<<7)); (out)=_mm256_shuffle_ps( out,out, (1<<0) + (0<<2) + (0<<4) + (0<<6) )\n    #define stbir__simdf8_a1a1( out, alp, ones) (out) = _mm256_blend_ps( alp, ones, (1<<0)+(0<<1)+(1<<2)+(0<<3)+(1<<4)+(0<<5)+(1<<6)+(0<<7)); (out)=_mm256_shuffle_ps( out,out, (1<<0) + (0<<2) + (3<<4) + (2<<6) )\n    #define stbir__simdf8_1a1a( out, alp, ones) (out) = _mm256_blend_ps( alp, ones, (0<<0)+(1<<1)+(0<<2)+(1<<3)+(0<<4)+(1<<5)+(0<<6)+(1<<7)); (out)=_mm256_shuffle_ps( out,out, (1<<0) + (0<<2) + (3<<4) + (2<<6) )\n\n    #define stbir__simdf8_zero( reg ) (reg) = _mm256_setzero_ps()\n\n    #ifdef STBIR_USE_FMA           // not on by default to maintain bit identical simd to non-simd\n    #define stbir__simdf8_madd( out, add, mul1, mul2 ) (out) = _mm256_fmadd_ps( mul1, mul2, add )\n    #define stbir__simdf8_madd_mem( out, add, mul, ptr ) (out) = _mm256_fmadd_ps( mul, _mm256_loadu_ps( (float const*)(ptr) ), add )\n    #define stbir__simdf8_madd_mem4( out, add, mul, ptr )(out) = _mm256_fmadd_ps( _mm256_setr_m128( mul, _mm_setzero_ps() ), _mm256_setr_m128( _mm_loadu_ps( (float const*)(ptr) ), _mm_setzero_ps() ), add )\n    #else\n    #define stbir__simdf8_madd( out, add, mul1, mul2 ) (out) = _mm256_add_ps( add, _mm256_mul_ps( mul1, mul2 ) )\n    #define stbir__simdf8_madd_mem( out, add, mul, ptr ) (out) = _mm256_add_ps( add, _mm256_mul_ps( mul, _mm256_loadu_ps( (float const*)(ptr) ) ) )\n    #define stbir__simdf8_madd_mem4( out, add, mul, ptr )  (out) = _mm256_add_ps( add, _mm256_setr_m128( _mm_mul_ps( mul, _mm_loadu_ps( (float const*)(ptr) ) ), _mm_setzero_ps() ) )\n    #endif\n    #define stbir__if_simdf8_cast_to_simdf4( val ) _mm256_castps256_ps128( val )\n\n  #endif\n\n  #ifdef STBIR_FLOORF\n  #undef STBIR_FLOORF\n  #endif\n  #define STBIR_FLOORF stbir_simd_floorf\n  static stbir__inline float stbir_simd_floorf(float x)  // martins floorf\n  {\n    #if defined(STBIR_AVX) || defined(__SSE4_1__) || defined(STBIR_SSE41)\n    __m128 t = _mm_set_ss(x);\n    return _mm_cvtss_f32( _mm_floor_ss(t, t) );\n    #else\n    __m128 f = _mm_set_ss(x);\n    __m128 t = _mm_cvtepi32_ps(_mm_cvttps_epi32(f));\n    __m128 r = _mm_add_ss(t, _mm_and_ps(_mm_cmplt_ss(f, t), _mm_set_ss(-1.0f)));\n    return _mm_cvtss_f32(r);\n    #endif\n  }\n\n  #ifdef STBIR_CEILF\n  #undef STBIR_CEILF\n  #endif\n  #define STBIR_CEILF stbir_simd_ceilf\n  static stbir__inline float stbir_simd_ceilf(float x)  // martins ceilf\n  {\n    #if defined(STBIR_AVX) || defined(__SSE4_1__) || defined(STBIR_SSE41)\n    __m128 t = _mm_set_ss(x);\n    return _mm_cvtss_f32( _mm_ceil_ss(t, t) );\n    #else\n    __m128 f = _mm_set_ss(x);\n    __m128 t = _mm_cvtepi32_ps(_mm_cvttps_epi32(f));\n    __m128 r = _mm_add_ss(t, _mm_and_ps(_mm_cmplt_ss(t, f), _mm_set_ss(1.0f)));\n    return _mm_cvtss_f32(r);\n    #endif\n  }\n\n#elif defined(STBIR_NEON)\n\n  #include <arm_neon.h>\n\n  #define stbir__simdf float32x4_t\n  #define stbir__simdi uint32x4_t\n\n  #define stbir_simdi_castf( reg ) vreinterpretq_u32_f32(reg)\n  #define stbir_simdf_casti( reg ) vreinterpretq_f32_u32(reg)\n\n  #define stbir__simdf_load( reg, ptr ) (reg) = vld1q_f32( (float const*)(ptr) )\n  #define stbir__simdi_load( reg, ptr ) (reg) = vld1q_u32( (uint32_t const*)(ptr) )\n  #define stbir__simdf_load1( out, ptr ) (out) = vld1q_dup_f32( (float const*)(ptr) ) // top values can be random (not denormal or nan for perf)\n  #define stbir__simdi_load1( out, ptr ) (out) = vld1q_dup_u32( (uint32_t const*)(ptr) )\n  #define stbir__simdf_load1z( out, ptr ) (out) = vld1q_lane_f32( (float const*)(ptr), vdupq_n_f32(0), 0 ) // top values must be zero\n  #define stbir__simdf_frep4( fvar ) vdupq_n_f32( fvar )\n  #define stbir__simdf_load1frep4( out, fvar ) (out) = vdupq_n_f32( fvar )\n  #define stbir__simdf_load2( out, ptr ) (out) = vcombine_f32( vld1_f32( (float const*)(ptr) ), vcreate_f32(0) ) // top values can be random (not denormal or nan for perf)\n  #define stbir__simdf_load2z( out, ptr ) (out) = vcombine_f32( vld1_f32( (float const*)(ptr) ), vcreate_f32(0) )  // top values must be zero\n  #define stbir__simdf_load2hmerge( out, reg, ptr ) (out) = vcombine_f32( vget_low_f32(reg), vld1_f32( (float const*)(ptr) ) )\n\n  #define stbir__simdf_zeroP() vdupq_n_f32(0)\n  #define stbir__simdf_zero( reg ) (reg) = vdupq_n_f32(0)\n\n  #define stbir__simdf_store( ptr, reg )  vst1q_f32( (float*)(ptr), reg )\n  #define stbir__simdf_store1( ptr, reg ) vst1q_lane_f32( (float*)(ptr), reg, 0)\n  #define stbir__simdf_store2( ptr, reg ) vst1_f32( (float*)(ptr), vget_low_f32(reg) )\n  #define stbir__simdf_store2h( ptr, reg ) vst1_f32( (float*)(ptr), vget_high_f32(reg) )\n\n  #define stbir__simdi_store( ptr, reg )  vst1q_u32( (uint32_t*)(ptr), reg )\n  #define stbir__simdi_store1( ptr, reg ) vst1q_lane_u32( (uint32_t*)(ptr), reg, 0 )\n  #define stbir__simdi_store2( ptr, reg ) vst1_u32( (uint32_t*)(ptr), vget_low_u32(reg) )\n\n  #define stbir__prefetch( ptr )\n\n  #define stbir__simdi_expand_u8_to_u32(out0,out1,out2,out3,ireg) \\\n  { \\\n    uint16x8_t l = vmovl_u8( vget_low_u8 ( vreinterpretq_u8_u32(ireg) ) ); \\\n    uint16x8_t h = vmovl_u8( vget_high_u8( vreinterpretq_u8_u32(ireg) ) ); \\\n    out0 = vmovl_u16( vget_low_u16 ( l ) ); \\\n    out1 = vmovl_u16( vget_high_u16( l ) ); \\\n    out2 = vmovl_u16( vget_low_u16 ( h ) ); \\\n    out3 = vmovl_u16( vget_high_u16( h ) ); \\\n  }\n\n  #define stbir__simdi_expand_u8_to_1u32(out,ireg) \\\n  { \\\n    uint16x8_t tmp = vmovl_u8( vget_low_u8( vreinterpretq_u8_u32(ireg) ) ); \\\n    out = vmovl_u16( vget_low_u16( tmp ) ); \\\n  }\n\n  #define stbir__simdi_expand_u16_to_u32(out0,out1,ireg) \\\n  { \\\n    uint16x8_t tmp = vreinterpretq_u16_u32(ireg); \\\n    out0 = vmovl_u16( vget_low_u16 ( tmp ) ); \\\n    out1 = vmovl_u16( vget_high_u16( tmp ) ); \\\n  }\n\n  #define stbir__simdf_convert_float_to_i32( i, f ) (i) = vreinterpretq_u32_s32( vcvtq_s32_f32(f) )\n  #define stbir__simdf_convert_float_to_int( f ) vgetq_lane_s32(vcvtq_s32_f32(f), 0)\n  #define stbir__simdi_to_int( i ) (int)vgetq_lane_u32(i, 0)\n  #define stbir__simdf_convert_float_to_uint8( f ) ((unsigned char)vgetq_lane_s32(vcvtq_s32_f32(vmaxq_f32(vminq_f32(f,STBIR__CONSTF(STBIR_max_uint8_as_float)),vdupq_n_f32(0))), 0))\n  #define stbir__simdf_convert_float_to_short( f ) ((unsigned short)vgetq_lane_s32(vcvtq_s32_f32(vmaxq_f32(vminq_f32(f,STBIR__CONSTF(STBIR_max_uint16_as_float)),vdupq_n_f32(0))), 0))\n  #define stbir__simdi_convert_i32_to_float(out, ireg) (out) = vcvtq_f32_s32( vreinterpretq_s32_u32(ireg) )\n  #define stbir__simdf_add( out, reg0, reg1 ) (out) = vaddq_f32( reg0, reg1 )\n  #define stbir__simdf_mult( out, reg0, reg1 ) (out) = vmulq_f32( reg0, reg1 )\n  #define stbir__simdf_mult_mem( out, reg, ptr ) (out) = vmulq_f32( reg, vld1q_f32( (float const*)(ptr) ) )\n  #define stbir__simdf_mult1_mem( out, reg, ptr ) (out) = vmulq_f32( reg, vld1q_dup_f32( (float const*)(ptr) ) )\n  #define stbir__simdf_add_mem( out, reg, ptr ) (out) = vaddq_f32( reg, vld1q_f32( (float const*)(ptr) ) )\n  #define stbir__simdf_add1_mem( out, reg, ptr ) (out) = vaddq_f32( reg, vld1q_dup_f32( (float const*)(ptr) ) )\n\n  #ifdef STBIR_USE_FMA           // not on by default to maintain bit identical simd to non-simd (and also x64 no madd to arm madd)\n  #define stbir__simdf_madd( out, add, mul1, mul2 ) (out) = vfmaq_f32( add, mul1, mul2 )\n  #define stbir__simdf_madd1( out, add, mul1, mul2 ) (out) = vfmaq_f32( add, mul1, mul2 )\n  #define stbir__simdf_madd_mem( out, add, mul, ptr ) (out) = vfmaq_f32( add, mul, vld1q_f32( (float const*)(ptr) ) )\n  #define stbir__simdf_madd1_mem( out, add, mul, ptr ) (out) = vfmaq_f32( add, mul, vld1q_dup_f32( (float const*)(ptr) ) )\n  #else\n  #define stbir__simdf_madd( out, add, mul1, mul2 ) (out) = vaddq_f32( add, vmulq_f32( mul1, mul2 ) )\n  #define stbir__simdf_madd1( out, add, mul1, mul2 ) (out) = vaddq_f32( add, vmulq_f32( mul1, mul2 ) )\n  #define stbir__simdf_madd_mem( out, add, mul, ptr ) (out) = vaddq_f32( add, vmulq_f32( mul, vld1q_f32( (float const*)(ptr) ) ) )\n  #define stbir__simdf_madd1_mem( out, add, mul, ptr ) (out) = vaddq_f32( add, vmulq_f32( mul, vld1q_dup_f32( (float const*)(ptr) ) ) )\n  #endif\n\n  #define stbir__simdf_add1( out, reg0, reg1 ) (out) = vaddq_f32( reg0, reg1 )\n  #define stbir__simdf_mult1( out, reg0, reg1 ) (out) = vmulq_f32( reg0, reg1 )\n\n  #define stbir__simdf_and( out, reg0, reg1 ) (out) = vreinterpretq_f32_u32( vandq_u32( vreinterpretq_u32_f32(reg0), vreinterpretq_u32_f32(reg1) ) )\n  #define stbir__simdf_or( out, reg0, reg1 ) (out) = vreinterpretq_f32_u32( vorrq_u32( vreinterpretq_u32_f32(reg0), vreinterpretq_u32_f32(reg1) ) )\n\n  #define stbir__simdf_min( out, reg0, reg1 ) (out) = vminq_f32( reg0, reg1 )\n  #define stbir__simdf_max( out, reg0, reg1 ) (out) = vmaxq_f32( reg0, reg1 )\n  #define stbir__simdf_min1( out, reg0, reg1 ) (out) = vminq_f32( reg0, reg1 )\n  #define stbir__simdf_max1( out, reg0, reg1 ) (out) = vmaxq_f32( reg0, reg1 )\n\n  #define stbir__simdf_0123ABCDto3ABx( out, reg0, reg1 ) (out) = vextq_f32( reg0, reg1, 3 )\n  #define stbir__simdf_0123ABCDto23Ax( out, reg0, reg1 ) (out) = vextq_f32( reg0, reg1, 2 )\n\n  #define stbir__simdf_a1a1( out, alp, ones ) (out) = vzipq_f32(vuzpq_f32(alp, alp).val[1], ones).val[0]\n  #define stbir__simdf_1a1a( out, alp, ones ) (out) = vzipq_f32(ones, vuzpq_f32(alp, alp).val[0]).val[0]\n\n  #if defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ )\n\n    #define stbir__simdf_aaa1( out, alp, ones ) (out) = vcopyq_laneq_f32(vdupq_n_f32(vgetq_lane_f32(alp, 3)), 3, ones, 3)\n    #define stbir__simdf_1aaa( out, alp, ones ) (out) = vcopyq_laneq_f32(vdupq_n_f32(vgetq_lane_f32(alp, 0)), 0, ones, 0)\n\n    #if defined( _MSC_VER ) && !defined(__clang__)\n      #define stbir_make16(a,b,c,d) vcombine_u8( \\\n        vcreate_u8( (4*a+0) | ((4*a+1)<<8) | ((4*a+2)<<16) | ((4*a+3)<<24) | \\\n          ((stbir_uint64)(4*b+0)<<32) | ((stbir_uint64)(4*b+1)<<40) | ((stbir_uint64)(4*b+2)<<48) | ((stbir_uint64)(4*b+3)<<56)), \\\n        vcreate_u8( (4*c+0) | ((4*c+1)<<8) | ((4*c+2)<<16) | ((4*c+3)<<24) | \\\n          ((stbir_uint64)(4*d+0)<<32) | ((stbir_uint64)(4*d+1)<<40) | ((stbir_uint64)(4*d+2)<<48) | ((stbir_uint64)(4*d+3)<<56) ) )\n\n      static stbir__inline uint8x16x2_t stbir_make16x2(float32x4_t rega,float32x4_t regb)\n      {\n        uint8x16x2_t r = { vreinterpretq_u8_f32(rega), vreinterpretq_u8_f32(regb) };\n        return r;\n      }\n    #else\n      #define stbir_make16(a,b,c,d) (uint8x16_t){4*a+0,4*a+1,4*a+2,4*a+3,4*b+0,4*b+1,4*b+2,4*b+3,4*c+0,4*c+1,4*c+2,4*c+3,4*d+0,4*d+1,4*d+2,4*d+3}\n      #define stbir_make16x2(a,b) (uint8x16x2_t){{vreinterpretq_u8_f32(a),vreinterpretq_u8_f32(b)}}\n    #endif\n\n    #define stbir__simdf_swiz( reg, one, two, three, four ) vreinterpretq_f32_u8( vqtbl1q_u8( vreinterpretq_u8_f32(reg), stbir_make16(one, two, three, four) ) )\n    #define stbir__simdf_swiz2( rega, regb, one, two, three, four ) vreinterpretq_f32_u8( vqtbl2q_u8( stbir_make16x2(rega,regb), stbir_make16(one, two, three, four) ) )\n\n    #define stbir__simdi_16madd( out, reg0, reg1 ) \\\n    { \\\n      int16x8_t r0 = vreinterpretq_s16_u32(reg0); \\\n      int16x8_t r1 = vreinterpretq_s16_u32(reg1); \\\n      int32x4_t tmp0 = vmull_s16( vget_low_s16(r0), vget_low_s16(r1) ); \\\n      int32x4_t tmp1 = vmull_s16( vget_high_s16(r0), vget_high_s16(r1) ); \\\n      (out) = vreinterpretq_u32_s32( vpaddq_s32(tmp0, tmp1) ); \\\n    }\n\n  #else\n\n    #define stbir__simdf_aaa1( out, alp, ones ) (out) = vsetq_lane_f32(1.0f, vdupq_n_f32(vgetq_lane_f32(alp, 3)), 3)\n    #define stbir__simdf_1aaa( out, alp, ones ) (out) = vsetq_lane_f32(1.0f, vdupq_n_f32(vgetq_lane_f32(alp, 0)), 0)\n\n    #if defined( _MSC_VER ) && !defined(__clang__)\n      static stbir__inline uint8x8x2_t stbir_make8x2(float32x4_t reg)\n      {\n        uint8x8x2_t r = { { vget_low_u8(vreinterpretq_u8_f32(reg)), vget_high_u8(vreinterpretq_u8_f32(reg)) } };\n        return r;\n      }\n      #define stbir_make8(a,b) vcreate_u8( \\\n        (4*a+0) | ((4*a+1)<<8) | ((4*a+2)<<16) | ((4*a+3)<<24) | \\\n        ((stbir_uint64)(4*b+0)<<32) | ((stbir_uint64)(4*b+1)<<40) | ((stbir_uint64)(4*b+2)<<48) | ((stbir_uint64)(4*b+3)<<56) )\n    #else\n      #define stbir_make8x2(reg) (uint8x8x2_t){ { vget_low_u8(vreinterpretq_u8_f32(reg)), vget_high_u8(vreinterpretq_u8_f32(reg)) } }\n      #define stbir_make8(a,b) (uint8x8_t){4*a+0,4*a+1,4*a+2,4*a+3,4*b+0,4*b+1,4*b+2,4*b+3}\n    #endif\n\n    #define stbir__simdf_swiz( reg, one, two, three, four ) vreinterpretq_f32_u8( vcombine_u8( \\\n        vtbl2_u8( stbir_make8x2( reg ), stbir_make8( one, two ) ), \\\n        vtbl2_u8( stbir_make8x2( reg ), stbir_make8( three, four ) ) ) )\n\n    #define stbir__simdi_16madd( out, reg0, reg1 ) \\\n    { \\\n      int16x8_t r0 = vreinterpretq_s16_u32(reg0); \\\n      int16x8_t r1 = vreinterpretq_s16_u32(reg1); \\\n      int32x4_t tmp0 = vmull_s16( vget_low_s16(r0), vget_low_s16(r1) ); \\\n      int32x4_t tmp1 = vmull_s16( vget_high_s16(r0), vget_high_s16(r1) ); \\\n      int32x2_t out0 = vpadd_s32( vget_low_s32(tmp0), vget_high_s32(tmp0) ); \\\n      int32x2_t out1 = vpadd_s32( vget_low_s32(tmp1), vget_high_s32(tmp1) ); \\\n      (out) = vreinterpretq_u32_s32( vcombine_s32(out0, out1) ); \\\n    }\n\n  #endif\n\n  #define stbir__simdi_and( out, reg0, reg1 ) (out) = vandq_u32( reg0, reg1 )\n  #define stbir__simdi_or( out, reg0, reg1 ) (out) = vorrq_u32( reg0, reg1 )\n\n  #define stbir__simdf_pack_to_8bytes(out,aa,bb) \\\n  { \\\n    float32x4_t af = vmaxq_f32( vminq_f32(aa,STBIR__CONSTF(STBIR_max_uint8_as_float) ), vdupq_n_f32(0) ); \\\n    float32x4_t bf = vmaxq_f32( vminq_f32(bb,STBIR__CONSTF(STBIR_max_uint8_as_float) ), vdupq_n_f32(0) ); \\\n    int16x4_t ai = vqmovn_s32( vcvtq_s32_f32( af ) ); \\\n    int16x4_t bi = vqmovn_s32( vcvtq_s32_f32( bf ) ); \\\n    uint8x8_t out8 = vqmovun_s16( vcombine_s16(ai, bi) ); \\\n    out = vreinterpretq_u32_u8( vcombine_u8(out8, out8) ); \\\n  }\n\n  #define stbir__simdf_pack_to_8words(out,aa,bb) \\\n  { \\\n    float32x4_t af = vmaxq_f32( vminq_f32(aa,STBIR__CONSTF(STBIR_max_uint16_as_float) ), vdupq_n_f32(0) ); \\\n    float32x4_t bf = vmaxq_f32( vminq_f32(bb,STBIR__CONSTF(STBIR_max_uint16_as_float) ), vdupq_n_f32(0) ); \\\n    int32x4_t ai = vcvtq_s32_f32( af ); \\\n    int32x4_t bi = vcvtq_s32_f32( bf ); \\\n    out = vreinterpretq_u32_u16( vcombine_u16(vqmovun_s32(ai), vqmovun_s32(bi)) ); \\\n  }\n\n  #define stbir__interleave_pack_and_store_16_u8( ptr, r0, r1, r2, r3 ) \\\n  { \\\n    int16x4x2_t tmp0 = vzip_s16( vqmovn_s32(vreinterpretq_s32_u32(r0)), vqmovn_s32(vreinterpretq_s32_u32(r2)) ); \\\n    int16x4x2_t tmp1 = vzip_s16( vqmovn_s32(vreinterpretq_s32_u32(r1)), vqmovn_s32(vreinterpretq_s32_u32(r3)) ); \\\n    uint8x8x2_t out = \\\n    { { \\\n      vqmovun_s16( vcombine_s16(tmp0.val[0], tmp0.val[1]) ), \\\n      vqmovun_s16( vcombine_s16(tmp1.val[0], tmp1.val[1]) ), \\\n    } }; \\\n    vst2_u8(ptr, out); \\\n  }\n\n  #define stbir__simdf_load4_transposed( o0, o1, o2, o3, ptr ) \\\n  { \\\n    float32x4x4_t tmp = vld4q_f32(ptr); \\\n    o0 = tmp.val[0]; \\\n    o1 = tmp.val[1]; \\\n    o2 = tmp.val[2]; \\\n    o3 = tmp.val[3]; \\\n  }\n\n  #define stbir__simdi_32shr( out, reg, imm ) out = vshrq_n_u32( reg, imm )\n\n  #if defined( _MSC_VER ) && !defined(__clang__)\n    #define STBIR__SIMDF_CONST(var, x) __declspec(align(8)) float var[] = { x, x, x, x }\n    #define STBIR__SIMDI_CONST(var, x) __declspec(align(8)) uint32_t var[] = { x, x, x, x }\n    #define STBIR__CONSTF(var) (*(const float32x4_t*)var)\n    #define STBIR__CONSTI(var) (*(const uint32x4_t*)var)\n  #else\n    #define STBIR__SIMDF_CONST(var, x) stbir__simdf var = { x, x, x, x }\n    #define STBIR__SIMDI_CONST(var, x) stbir__simdi var = { x, x, x, x }\n    #define STBIR__CONSTF(var) (var)\n    #define STBIR__CONSTI(var) (var)\n  #endif\n\n  #ifdef STBIR_FLOORF\n  #undef STBIR_FLOORF\n  #endif\n  #define STBIR_FLOORF stbir_simd_floorf\n  static stbir__inline float stbir_simd_floorf(float x)\n  {\n    #if defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ )\n    return vget_lane_f32( vrndm_f32( vdup_n_f32(x) ), 0);\n    #else\n    float32x2_t f = vdup_n_f32(x);\n    float32x2_t t = vcvt_f32_s32(vcvt_s32_f32(f));\n    uint32x2_t a = vclt_f32(f, t);\n    uint32x2_t b = vreinterpret_u32_f32(vdup_n_f32(-1.0f));\n    float32x2_t r = vadd_f32(t, vreinterpret_f32_u32(vand_u32(a, b)));\n    return vget_lane_f32(r, 0);\n    #endif\n  }\n\n  #ifdef STBIR_CEILF\n  #undef STBIR_CEILF\n  #endif\n  #define STBIR_CEILF stbir_simd_ceilf\n  static stbir__inline float stbir_simd_ceilf(float x)\n  {\n    #if defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ )\n    return vget_lane_f32( vrndp_f32( vdup_n_f32(x) ), 0);\n    #else\n    float32x2_t f = vdup_n_f32(x);\n    float32x2_t t = vcvt_f32_s32(vcvt_s32_f32(f));\n    uint32x2_t a = vclt_f32(t, f);\n    uint32x2_t b = vreinterpret_u32_f32(vdup_n_f32(1.0f));\n    float32x2_t r = vadd_f32(t, vreinterpret_f32_u32(vand_u32(a, b)));\n    return vget_lane_f32(r, 0);\n    #endif\n  }\n\n  #define STBIR_SIMD\n\n#elif defined(STBIR_WASM)\n\n  #include <wasm_simd128.h>\n\n  #define stbir__simdf v128_t\n  #define stbir__simdi v128_t\n\n  #define stbir_simdi_castf( reg ) (reg)\n  #define stbir_simdf_casti( reg ) (reg)\n\n  #define stbir__simdf_load( reg, ptr )             (reg) = wasm_v128_load( (void const*)(ptr) )\n  #define stbir__simdi_load( reg, ptr )             (reg) = wasm_v128_load( (void const*)(ptr) )\n  #define stbir__simdf_load1( out, ptr )            (out) = wasm_v128_load32_splat( (void const*)(ptr) ) // top values can be random (not denormal or nan for perf)\n  #define stbir__simdi_load1( out, ptr )            (out) = wasm_v128_load32_splat( (void const*)(ptr) )\n  #define stbir__simdf_load1z( out, ptr )           (out) = wasm_v128_load32_zero( (void const*)(ptr) ) // top values must be zero\n  #define stbir__simdf_frep4( fvar )                wasm_f32x4_splat( fvar )\n  #define stbir__simdf_load1frep4( out, fvar )      (out) = wasm_f32x4_splat( fvar )\n  #define stbir__simdf_load2( out, ptr )            (out) = wasm_v128_load64_splat( (void const*)(ptr) ) // top values can be random (not denormal or nan for perf)\n  #define stbir__simdf_load2z( out, ptr )           (out) = wasm_v128_load64_zero( (void const*)(ptr) ) // top values must be zero\n  #define stbir__simdf_load2hmerge( out, reg, ptr ) (out) = wasm_v128_load64_lane( (void const*)(ptr), reg, 1 )\n\n  #define stbir__simdf_zeroP() wasm_f32x4_const_splat(0)\n  #define stbir__simdf_zero( reg ) (reg) = wasm_f32x4_const_splat(0)\n\n  #define stbir__simdf_store( ptr, reg )   wasm_v128_store( (void*)(ptr), reg )\n  #define stbir__simdf_store1( ptr, reg )  wasm_v128_store32_lane( (void*)(ptr), reg, 0 )\n  #define stbir__simdf_store2( ptr, reg )  wasm_v128_store64_lane( (void*)(ptr), reg, 0 )\n  #define stbir__simdf_store2h( ptr, reg ) wasm_v128_store64_lane( (void*)(ptr), reg, 1 )\n\n  #define stbir__simdi_store( ptr, reg )  wasm_v128_store( (void*)(ptr), reg )\n  #define stbir__simdi_store1( ptr, reg ) wasm_v128_store32_lane( (void*)(ptr), reg, 0 )\n  #define stbir__simdi_store2( ptr, reg ) wasm_v128_store64_lane( (void*)(ptr), reg, 0 )\n\n  #define stbir__prefetch( ptr )\n\n  #define stbir__simdi_expand_u8_to_u32(out0,out1,out2,out3,ireg) \\\n  { \\\n    v128_t l = wasm_u16x8_extend_low_u8x16 ( ireg ); \\\n    v128_t h = wasm_u16x8_extend_high_u8x16( ireg ); \\\n    out0 = wasm_u32x4_extend_low_u16x8 ( l ); \\\n    out1 = wasm_u32x4_extend_high_u16x8( l ); \\\n    out2 = wasm_u32x4_extend_low_u16x8 ( h ); \\\n    out3 = wasm_u32x4_extend_high_u16x8( h ); \\\n  }\n\n  #define stbir__simdi_expand_u8_to_1u32(out,ireg) \\\n  { \\\n    v128_t tmp = wasm_u16x8_extend_low_u8x16(ireg); \\\n    out = wasm_u32x4_extend_low_u16x8(tmp); \\\n  }\n\n  #define stbir__simdi_expand_u16_to_u32(out0,out1,ireg) \\\n  { \\\n    out0 = wasm_u32x4_extend_low_u16x8 ( ireg ); \\\n    out1 = wasm_u32x4_extend_high_u16x8( ireg ); \\\n  }\n\n  #define stbir__simdf_convert_float_to_i32( i, f )    (i) = wasm_i32x4_trunc_sat_f32x4(f)\n  #define stbir__simdf_convert_float_to_int( f )       wasm_i32x4_extract_lane(wasm_i32x4_trunc_sat_f32x4(f), 0)\n  #define stbir__simdi_to_int( i )                     wasm_i32x4_extract_lane(i, 0)\n  #define stbir__simdf_convert_float_to_uint8( f )     ((unsigned char)wasm_i32x4_extract_lane(wasm_i32x4_trunc_sat_f32x4(wasm_f32x4_max(wasm_f32x4_min(f,STBIR_max_uint8_as_float),wasm_f32x4_const_splat(0))), 0))\n  #define stbir__simdf_convert_float_to_short( f )     ((unsigned short)wasm_i32x4_extract_lane(wasm_i32x4_trunc_sat_f32x4(wasm_f32x4_max(wasm_f32x4_min(f,STBIR_max_uint16_as_float),wasm_f32x4_const_splat(0))), 0))\n  #define stbir__simdi_convert_i32_to_float(out, ireg) (out) = wasm_f32x4_convert_i32x4(ireg)\n  #define stbir__simdf_add( out, reg0, reg1 )          (out) = wasm_f32x4_add( reg0, reg1 )\n  #define stbir__simdf_mult( out, reg0, reg1 )         (out) = wasm_f32x4_mul( reg0, reg1 )\n  #define stbir__simdf_mult_mem( out, reg, ptr )       (out) = wasm_f32x4_mul( reg, wasm_v128_load( (void const*)(ptr) ) )\n  #define stbir__simdf_mult1_mem( out, reg, ptr )      (out) = wasm_f32x4_mul( reg, wasm_v128_load32_splat( (void const*)(ptr) ) )\n  #define stbir__simdf_add_mem( out, reg, ptr )        (out) = wasm_f32x4_add( reg, wasm_v128_load( (void const*)(ptr) ) )\n  #define stbir__simdf_add1_mem( out, reg, ptr )       (out) = wasm_f32x4_add( reg, wasm_v128_load32_splat( (void const*)(ptr) ) )\n\n  #define stbir__simdf_madd( out, add, mul1, mul2 )    (out) = wasm_f32x4_add( add, wasm_f32x4_mul( mul1, mul2 ) )\n  #define stbir__simdf_madd1( out, add, mul1, mul2 )   (out) = wasm_f32x4_add( add, wasm_f32x4_mul( mul1, mul2 ) )\n  #define stbir__simdf_madd_mem( out, add, mul, ptr )  (out) = wasm_f32x4_add( add, wasm_f32x4_mul( mul, wasm_v128_load( (void const*)(ptr) ) ) )\n  #define stbir__simdf_madd1_mem( out, add, mul, ptr ) (out) = wasm_f32x4_add( add, wasm_f32x4_mul( mul, wasm_v128_load32_splat( (void const*)(ptr) ) ) )\n\n  #define stbir__simdf_add1( out, reg0, reg1 )  (out) = wasm_f32x4_add( reg0, reg1 )\n  #define stbir__simdf_mult1( out, reg0, reg1 ) (out) = wasm_f32x4_mul( reg0, reg1 )\n\n  #define stbir__simdf_and( out, reg0, reg1 ) (out) = wasm_v128_and( reg0, reg1 )\n  #define stbir__simdf_or( out, reg0, reg1 )  (out) = wasm_v128_or( reg0, reg1 )\n\n  #define stbir__simdf_min( out, reg0, reg1 ) (out) = wasm_f32x4_min( reg0, reg1 )\n  #define stbir__simdf_max( out, reg0, reg1 ) (out) = wasm_f32x4_max( reg0, reg1 )\n  #define stbir__simdf_min1( out, reg0, reg1 ) (out) = wasm_f32x4_min( reg0, reg1 )\n  #define stbir__simdf_max1( out, reg0, reg1 ) (out) = wasm_f32x4_max( reg0, reg1 )\n\n  #define stbir__simdf_0123ABCDto3ABx( out, reg0, reg1 ) (out) = wasm_i32x4_shuffle( reg0, reg1, 3, 4, 5, -1 )\n  #define stbir__simdf_0123ABCDto23Ax( out, reg0, reg1 ) (out) = wasm_i32x4_shuffle( reg0, reg1, 2, 3, 4, -1 )\n\n  #define stbir__simdf_aaa1(out,alp,ones) (out) = wasm_i32x4_shuffle(alp, ones, 3, 3, 3, 4)\n  #define stbir__simdf_1aaa(out,alp,ones) (out) = wasm_i32x4_shuffle(alp, ones, 4, 0, 0, 0)\n  #define stbir__simdf_a1a1(out,alp,ones) (out) = wasm_i32x4_shuffle(alp, ones, 1, 4, 3, 4)\n  #define stbir__simdf_1a1a(out,alp,ones) (out) = wasm_i32x4_shuffle(alp, ones, 4, 0, 4, 2)\n\n  #define stbir__simdf_swiz( reg, one, two, three, four ) wasm_i32x4_shuffle(reg, reg, one, two, three, four)\n\n  #define stbir__simdi_and( out, reg0, reg1 )    (out) = wasm_v128_and( reg0, reg1 )\n  #define stbir__simdi_or( out, reg0, reg1 )     (out) = wasm_v128_or( reg0, reg1 )\n  #define stbir__simdi_16madd( out, reg0, reg1 ) (out) = wasm_i32x4_dot_i16x8( reg0, reg1 )\n\n  #define stbir__simdf_pack_to_8bytes(out,aa,bb) \\\n  { \\\n    v128_t af = wasm_f32x4_max( wasm_f32x4_min(aa, STBIR_max_uint8_as_float), wasm_f32x4_const_splat(0) ); \\\n    v128_t bf = wasm_f32x4_max( wasm_f32x4_min(bb, STBIR_max_uint8_as_float), wasm_f32x4_const_splat(0) ); \\\n    v128_t ai = wasm_i32x4_trunc_sat_f32x4( af ); \\\n    v128_t bi = wasm_i32x4_trunc_sat_f32x4( bf ); \\\n    v128_t out16 = wasm_i16x8_narrow_i32x4( ai, bi ); \\\n    out = wasm_u8x16_narrow_i16x8( out16, out16 ); \\\n  }\n\n  #define stbir__simdf_pack_to_8words(out,aa,bb) \\\n  { \\\n    v128_t af = wasm_f32x4_max( wasm_f32x4_min(aa, STBIR_max_uint16_as_float), wasm_f32x4_const_splat(0)); \\\n    v128_t bf = wasm_f32x4_max( wasm_f32x4_min(bb, STBIR_max_uint16_as_float), wasm_f32x4_const_splat(0)); \\\n    v128_t ai = wasm_i32x4_trunc_sat_f32x4( af ); \\\n    v128_t bi = wasm_i32x4_trunc_sat_f32x4( bf ); \\\n    out = wasm_u16x8_narrow_i32x4( ai, bi ); \\\n  }\n\n  #define stbir__interleave_pack_and_store_16_u8( ptr, r0, r1, r2, r3 ) \\\n  { \\\n    v128_t tmp0 = wasm_i16x8_narrow_i32x4(r0, r1); \\\n    v128_t tmp1 = wasm_i16x8_narrow_i32x4(r2, r3); \\\n    v128_t tmp = wasm_u8x16_narrow_i16x8(tmp0, tmp1); \\\n    tmp = wasm_i8x16_shuffle(tmp, tmp, 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); \\\n    wasm_v128_store( (void*)(ptr), tmp); \\\n  }\n\n  #define stbir__simdf_load4_transposed( o0, o1, o2, o3, ptr ) \\\n  { \\\n    v128_t t0 = wasm_v128_load( ptr    ); \\\n    v128_t t1 = wasm_v128_load( ptr+4  ); \\\n    v128_t t2 = wasm_v128_load( ptr+8  ); \\\n    v128_t t3 = wasm_v128_load( ptr+12 ); \\\n    v128_t s0 = wasm_i32x4_shuffle(t0, t1, 0, 4, 2, 6); \\\n    v128_t s1 = wasm_i32x4_shuffle(t0, t1, 1, 5, 3, 7); \\\n    v128_t s2 = wasm_i32x4_shuffle(t2, t3, 0, 4, 2, 6); \\\n    v128_t s3 = wasm_i32x4_shuffle(t2, t3, 1, 5, 3, 7); \\\n    o0 = wasm_i32x4_shuffle(s0, s2, 0, 1, 4, 5); \\\n    o1 = wasm_i32x4_shuffle(s1, s3, 0, 1, 4, 5); \\\n    o2 = wasm_i32x4_shuffle(s0, s2, 2, 3, 6, 7); \\\n    o3 = wasm_i32x4_shuffle(s1, s3, 2, 3, 6, 7); \\\n  }\n\n  #define stbir__simdi_32shr( out, reg, imm ) out = wasm_u32x4_shr( reg, imm )\n\n  typedef float stbir__f32x4 __attribute__((__vector_size__(16), __aligned__(16)));\n  #define STBIR__SIMDF_CONST(var, x) stbir__simdf var = (v128_t)(stbir__f32x4){ x, x, x, x }\n  #define STBIR__SIMDI_CONST(var, x) stbir__simdi var = { x, x, x, x }\n  #define STBIR__CONSTF(var) (var)\n  #define STBIR__CONSTI(var) (var)\n\n  #ifdef STBIR_FLOORF\n  #undef STBIR_FLOORF\n  #endif\n  #define STBIR_FLOORF stbir_simd_floorf\n  static stbir__inline float stbir_simd_floorf(float x)\n  {\n    return wasm_f32x4_extract_lane( wasm_f32x4_floor( wasm_f32x4_splat(x) ), 0);\n  }\n\n  #ifdef STBIR_CEILF\n  #undef STBIR_CEILF\n  #endif\n  #define STBIR_CEILF stbir_simd_ceilf\n  static stbir__inline float stbir_simd_ceilf(float x)\n  {\n    return wasm_f32x4_extract_lane( wasm_f32x4_ceil( wasm_f32x4_splat(x) ), 0);\n  }\n\n  #define STBIR_SIMD\n\n#endif  // SSE2/NEON/WASM\n\n#endif // NO SIMD\n\n#ifdef STBIR_SIMD8\n  #define stbir__simdfX stbir__simdf8\n  #define stbir__simdiX stbir__simdi8\n  #define stbir__simdfX_load stbir__simdf8_load\n  #define stbir__simdiX_load stbir__simdi8_load\n  #define stbir__simdfX_mult stbir__simdf8_mult\n  #define stbir__simdfX_add_mem stbir__simdf8_add_mem\n  #define stbir__simdfX_madd_mem stbir__simdf8_madd_mem\n  #define stbir__simdfX_store stbir__simdf8_store\n  #define stbir__simdiX_store stbir__simdi8_store\n  #define stbir__simdf_frepX  stbir__simdf8_frep8\n  #define stbir__simdfX_madd stbir__simdf8_madd\n  #define stbir__simdfX_min stbir__simdf8_min\n  #define stbir__simdfX_max stbir__simdf8_max\n  #define stbir__simdfX_aaa1 stbir__simdf8_aaa1\n  #define stbir__simdfX_1aaa stbir__simdf8_1aaa\n  #define stbir__simdfX_a1a1 stbir__simdf8_a1a1\n  #define stbir__simdfX_1a1a stbir__simdf8_1a1a\n  #define stbir__simdfX_convert_float_to_i32 stbir__simdf8_convert_float_to_i32\n  #define stbir__simdfX_pack_to_words stbir__simdf8_pack_to_16words\n  #define stbir__simdfX_zero stbir__simdf8_zero\n  #define STBIR_onesX STBIR_ones8\n  #define STBIR_max_uint8_as_floatX STBIR_max_uint8_as_float8\n  #define STBIR_max_uint16_as_floatX STBIR_max_uint16_as_float8\n  #define STBIR_simd_point5X STBIR_simd_point58\n  #define stbir__simdfX_float_count 8\n  #define stbir__simdfX_0123to1230 stbir__simdf8_0123to12301230\n  #define stbir__simdfX_0123to2103 stbir__simdf8_0123to21032103\n  static const stbir__simdf8 STBIR_max_uint16_as_float_inverted8 = { stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted,stbir__max_uint16_as_float_inverted };\n  static const stbir__simdf8 STBIR_max_uint8_as_float_inverted8 = { stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted,stbir__max_uint8_as_float_inverted };\n  static const stbir__simdf8 STBIR_ones8 = { 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0 };\n  static const stbir__simdf8 STBIR_simd_point58 = { 0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5 };\n  static const stbir__simdf8 STBIR_max_uint8_as_float8 = { stbir__max_uint8_as_float,stbir__max_uint8_as_float,stbir__max_uint8_as_float,stbir__max_uint8_as_float, stbir__max_uint8_as_float,stbir__max_uint8_as_float,stbir__max_uint8_as_float,stbir__max_uint8_as_float };\n  static const stbir__simdf8 STBIR_max_uint16_as_float8 = { stbir__max_uint16_as_float,stbir__max_uint16_as_float,stbir__max_uint16_as_float,stbir__max_uint16_as_float, stbir__max_uint16_as_float,stbir__max_uint16_as_float,stbir__max_uint16_as_float,stbir__max_uint16_as_float };\n#else\n  #define stbir__simdfX stbir__simdf\n  #define stbir__simdiX stbir__simdi\n  #define stbir__simdfX_load stbir__simdf_load\n  #define stbir__simdiX_load stbir__simdi_load\n  #define stbir__simdfX_mult stbir__simdf_mult\n  #define stbir__simdfX_add_mem stbir__simdf_add_mem\n  #define stbir__simdfX_madd_mem stbir__simdf_madd_mem\n  #define stbir__simdfX_store stbir__simdf_store\n  #define stbir__simdiX_store stbir__simdi_store\n  #define stbir__simdf_frepX  stbir__simdf_frep4\n  #define stbir__simdfX_madd stbir__simdf_madd\n  #define stbir__simdfX_min stbir__simdf_min\n  #define stbir__simdfX_max stbir__simdf_max\n  #define stbir__simdfX_aaa1 stbir__simdf_aaa1\n  #define stbir__simdfX_1aaa stbir__simdf_1aaa\n  #define stbir__simdfX_a1a1 stbir__simdf_a1a1\n  #define stbir__simdfX_1a1a stbir__simdf_1a1a\n  #define stbir__simdfX_convert_float_to_i32 stbir__simdf_convert_float_to_i32\n  #define stbir__simdfX_pack_to_words stbir__simdf_pack_to_8words\n  #define stbir__simdfX_zero stbir__simdf_zero\n  #define STBIR_onesX STBIR__CONSTF(STBIR_ones)\n  #define STBIR_simd_point5X STBIR__CONSTF(STBIR_simd_point5)\n  #define STBIR_max_uint8_as_floatX STBIR__CONSTF(STBIR_max_uint8_as_float)\n  #define STBIR_max_uint16_as_floatX STBIR__CONSTF(STBIR_max_uint16_as_float)\n  #define stbir__simdfX_float_count 4\n  #define stbir__if_simdf8_cast_to_simdf4( val ) ( val )\n  #define stbir__simdfX_0123to1230 stbir__simdf_0123to1230\n  #define stbir__simdfX_0123to2103 stbir__simdf_0123to2103\n#endif\n\n\n#if defined(STBIR_NEON) && !defined(_M_ARM) && !defined(__arm__)\n\n  #if defined( _MSC_VER ) && !defined(__clang__)\n  typedef __int16 stbir__FP16;\n  #else\n  typedef float16_t stbir__FP16;\n  #endif\n\n#else // no NEON, or 32-bit ARM for MSVC\n\n  typedef union stbir__FP16\n  {\n    unsigned short u;\n  } stbir__FP16;\n\n#endif\n\n#if (!defined(STBIR_NEON) && !defined(STBIR_FP16C)) || (defined(STBIR_NEON) && defined(_M_ARM)) || (defined(STBIR_NEON) && defined(__arm__))\n\n  // Fabian's half float routines, see: https://gist.github.com/rygorous/2156668\n\n  static stbir__inline float stbir__half_to_float( stbir__FP16 h )\n  {\n    static const stbir__FP32 magic = { (254 - 15) << 23 };\n    static const stbir__FP32 was_infnan = { (127 + 16) << 23 };\n    stbir__FP32 o;\n\n    o.u = (h.u & 0x7fff) << 13;     // exponent/mantissa bits\n    o.f *= magic.f;                 // exponent adjust\n    if (o.f >= was_infnan.f)        // make sure Inf/NaN survive\n      o.u |= 255 << 23;\n    o.u |= (h.u & 0x8000) << 16;    // sign bit\n    return o.f;\n  }\n\n  static stbir__inline stbir__FP16 stbir__float_to_half(float val)\n  {\n    stbir__FP32 f32infty = { 255 << 23 };\n    stbir__FP32 f16max   = { (127 + 16) << 23 };\n    stbir__FP32 denorm_magic = { ((127 - 15) + (23 - 10) + 1) << 23 };\n    unsigned int sign_mask = 0x80000000u;\n    stbir__FP16 o = { 0 };\n    stbir__FP32 f;\n    unsigned int sign;\n\n    f.f = val;\n    sign = f.u & sign_mask;\n    f.u ^= sign;\n\n    if (f.u >= f16max.u) // result is Inf or NaN (all exponent bits set)\n      o.u = (f.u > f32infty.u) ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf\n    else // (De)normalized number or zero\n    {\n      if (f.u < (113 << 23)) // resulting FP16 is subnormal or zero\n      {\n        // use a magic value to align our 10 mantissa bits at the bottom of\n        // the float. as long as FP addition is round-to-nearest-even this\n        // just works.\n        f.f += denorm_magic.f;\n        // and one integer subtract of the bias later, we have our final float!\n        o.u = (unsigned short) ( f.u - denorm_magic.u );\n      }\n      else\n      {\n        unsigned int mant_odd = (f.u >> 13) & 1; // resulting mantissa is odd\n        // update exponent, rounding bias part 1\n        f.u = f.u + ((15u - 127) << 23) + 0xfff;\n        // rounding bias part 2\n        f.u += mant_odd;\n        // take the bits!\n        o.u = (unsigned short) ( f.u >> 13 );\n      }\n    }\n\n    o.u |= sign >> 16;\n    return o;\n  }\n\n#endif\n\n\n#if defined(STBIR_FP16C)\n\n  #include <immintrin.h>\n\n  static stbir__inline void stbir__half_to_float_SIMD(float * output, stbir__FP16 const * input)\n  {\n    _mm256_storeu_ps( (float*)output, _mm256_cvtph_ps( _mm_loadu_si128( (__m128i const* )input ) ) );\n  }\n\n  static stbir__inline void stbir__float_to_half_SIMD(stbir__FP16 * output, float const * input)\n  {\n    _mm_storeu_si128( (__m128i*)output, _mm256_cvtps_ph( _mm256_loadu_ps( input ), 0 ) );\n  }\n\n  static stbir__inline float stbir__half_to_float( stbir__FP16 h )\n  {\n    return _mm_cvtss_f32( _mm_cvtph_ps( _mm_cvtsi32_si128( (int)h.u ) ) );\n  }\n\n  static stbir__inline stbir__FP16 stbir__float_to_half( float f )\n  {\n    stbir__FP16 h;\n    h.u = (unsigned short) _mm_cvtsi128_si32( _mm_cvtps_ph( _mm_set_ss( f ), 0 ) );\n    return h;\n  }\n\n#elif defined(STBIR_SSE2)\n\n  // Fabian's half float routines, see: https://gist.github.com/rygorous/2156668\n  stbir__inline static void stbir__half_to_float_SIMD(float * output, void const * input)\n  {\n    static const STBIR__SIMDI_CONST(mask_nosign,      0x7fff);\n    static const STBIR__SIMDI_CONST(smallest_normal,  0x0400);\n    static const STBIR__SIMDI_CONST(infinity,         0x7c00);\n    static const STBIR__SIMDI_CONST(expadjust_normal, (127 - 15) << 23);\n    static const STBIR__SIMDI_CONST(magic_denorm,     113 << 23);\n\n    __m128i i = _mm_loadu_si128 ( (__m128i const*)(input) );\n    __m128i h = _mm_unpacklo_epi16 ( i, _mm_setzero_si128() );\n    __m128i mnosign     = STBIR__CONSTI(mask_nosign);\n    __m128i eadjust     = STBIR__CONSTI(expadjust_normal);\n    __m128i smallest    = STBIR__CONSTI(smallest_normal);\n    __m128i infty       = STBIR__CONSTI(infinity);\n    __m128i expmant     = _mm_and_si128(mnosign, h);\n    __m128i justsign    = _mm_xor_si128(h, expmant);\n    __m128i b_notinfnan = _mm_cmpgt_epi32(infty, expmant);\n    __m128i b_isdenorm  = _mm_cmpgt_epi32(smallest, expmant);\n    __m128i shifted     = _mm_slli_epi32(expmant, 13);\n    __m128i adj_infnan  = _mm_andnot_si128(b_notinfnan, eadjust);\n    __m128i adjusted    = _mm_add_epi32(eadjust, shifted);\n    __m128i den1        = _mm_add_epi32(shifted, STBIR__CONSTI(magic_denorm));\n    __m128i adjusted2   = _mm_add_epi32(adjusted, adj_infnan);\n    __m128  den2        = _mm_sub_ps(_mm_castsi128_ps(den1), *(const __m128 *)&magic_denorm);\n    __m128  adjusted3   = _mm_and_ps(den2, _mm_castsi128_ps(b_isdenorm));\n    __m128  adjusted4   = _mm_andnot_ps(_mm_castsi128_ps(b_isdenorm), _mm_castsi128_ps(adjusted2));\n    __m128  adjusted5   = _mm_or_ps(adjusted3, adjusted4);\n    __m128i sign        = _mm_slli_epi32(justsign, 16);\n    __m128  final       = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));\n    stbir__simdf_store( output + 0,  final );\n\n    h = _mm_unpackhi_epi16 ( i, _mm_setzero_si128() );\n    expmant     = _mm_and_si128(mnosign, h);\n    justsign    = _mm_xor_si128(h, expmant);\n    b_notinfnan = _mm_cmpgt_epi32(infty, expmant);\n    b_isdenorm  = _mm_cmpgt_epi32(smallest, expmant);\n    shifted     = _mm_slli_epi32(expmant, 13);\n    adj_infnan  = _mm_andnot_si128(b_notinfnan, eadjust);\n    adjusted    = _mm_add_epi32(eadjust, shifted);\n    den1        = _mm_add_epi32(shifted, STBIR__CONSTI(magic_denorm));\n    adjusted2   = _mm_add_epi32(adjusted, adj_infnan);\n    den2        = _mm_sub_ps(_mm_castsi128_ps(den1), *(const __m128 *)&magic_denorm);\n    adjusted3   = _mm_and_ps(den2, _mm_castsi128_ps(b_isdenorm));\n    adjusted4   = _mm_andnot_ps(_mm_castsi128_ps(b_isdenorm), _mm_castsi128_ps(adjusted2));\n    adjusted5   = _mm_or_ps(adjusted3, adjusted4);\n    sign        = _mm_slli_epi32(justsign, 16);\n    final       = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));\n    stbir__simdf_store( output + 4,  final );\n\n    // ~38 SSE2 ops for 8 values\n  }\n\n  // Fabian's round-to-nearest-even float to half\n  // ~48 SSE2 ops for 8 output\n  stbir__inline static void stbir__float_to_half_SIMD(void * output, float const * input)\n  {\n    static const STBIR__SIMDI_CONST(mask_sign,      0x80000000u);\n    static const STBIR__SIMDI_CONST(c_f16max,       (127 + 16) << 23); // all FP32 values >=this round to +inf\n    static const STBIR__SIMDI_CONST(c_nanbit,        0x200);\n    static const STBIR__SIMDI_CONST(c_infty_as_fp16, 0x7c00);\n    static const STBIR__SIMDI_CONST(c_min_normal,    (127 - 14) << 23); // smallest FP32 that yields a normalized FP16\n    static const STBIR__SIMDI_CONST(c_subnorm_magic, ((127 - 15) + (23 - 10) + 1) << 23);\n    static const STBIR__SIMDI_CONST(c_normal_bias,    0xfff - ((127 - 15) << 23)); // adjust exponent and add mantissa rounding\n\n    __m128  f           =  _mm_loadu_ps(input);\n    __m128  msign       = _mm_castsi128_ps(STBIR__CONSTI(mask_sign));\n    __m128  justsign    = _mm_and_ps(msign, f);\n    __m128  absf        = _mm_xor_ps(f, justsign);\n    __m128i absf_int    = _mm_castps_si128(absf); // the cast is \"free\" (extra bypass latency, but no thruput hit)\n    __m128i f16max      = STBIR__CONSTI(c_f16max);\n    __m128  b_isnan     = _mm_cmpunord_ps(absf, absf); // is this a NaN?\n    __m128i b_isregular = _mm_cmpgt_epi32(f16max, absf_int); // (sub)normalized or special?\n    __m128i nanbit      = _mm_and_si128(_mm_castps_si128(b_isnan), STBIR__CONSTI(c_nanbit));\n    __m128i inf_or_nan  = _mm_or_si128(nanbit, STBIR__CONSTI(c_infty_as_fp16)); // output for specials\n\n    __m128i min_normal  = STBIR__CONSTI(c_min_normal);\n    __m128i b_issub     = _mm_cmpgt_epi32(min_normal, absf_int);\n\n    // \"result is subnormal\" path\n    __m128  subnorm1    = _mm_add_ps(absf, _mm_castsi128_ps(STBIR__CONSTI(c_subnorm_magic))); // magic value to round output mantissa\n    __m128i subnorm2    = _mm_sub_epi32(_mm_castps_si128(subnorm1), STBIR__CONSTI(c_subnorm_magic)); // subtract out bias\n\n    // \"result is normal\" path\n    __m128i mantoddbit  = _mm_slli_epi32(absf_int, 31 - 13); // shift bit 13 (mantissa LSB) to sign\n    __m128i mantodd     = _mm_srai_epi32(mantoddbit, 31); // -1 if FP16 mantissa odd, else 0\n\n    __m128i round1      = _mm_add_epi32(absf_int, STBIR__CONSTI(c_normal_bias));\n    __m128i round2      = _mm_sub_epi32(round1, mantodd); // if mantissa LSB odd, bias towards rounding up (RTNE)\n    __m128i normal      = _mm_srli_epi32(round2, 13); // rounded result\n\n    // combine the two non-specials\n    __m128i nonspecial  = _mm_or_si128(_mm_and_si128(subnorm2, b_issub), _mm_andnot_si128(b_issub, normal));\n\n    // merge in specials as well\n    __m128i joined      = _mm_or_si128(_mm_and_si128(nonspecial, b_isregular), _mm_andnot_si128(b_isregular, inf_or_nan));\n\n    __m128i sign_shift  = _mm_srai_epi32(_mm_castps_si128(justsign), 16);\n    __m128i final2, final= _mm_or_si128(joined, sign_shift);\n\n    f           =  _mm_loadu_ps(input+4);\n    justsign    = _mm_and_ps(msign, f);\n    absf        = _mm_xor_ps(f, justsign);\n    absf_int    = _mm_castps_si128(absf); // the cast is \"free\" (extra bypass latency, but no thruput hit)\n    b_isnan     = _mm_cmpunord_ps(absf, absf); // is this a NaN?\n    b_isregular = _mm_cmpgt_epi32(f16max, absf_int); // (sub)normalized or special?\n    nanbit      = _mm_and_si128(_mm_castps_si128(b_isnan), c_nanbit);\n    inf_or_nan  = _mm_or_si128(nanbit, STBIR__CONSTI(c_infty_as_fp16)); // output for specials\n\n    b_issub     = _mm_cmpgt_epi32(min_normal, absf_int);\n\n    // \"result is subnormal\" path\n    subnorm1    = _mm_add_ps(absf, _mm_castsi128_ps(STBIR__CONSTI(c_subnorm_magic))); // magic value to round output mantissa\n    subnorm2    = _mm_sub_epi32(_mm_castps_si128(subnorm1), STBIR__CONSTI(c_subnorm_magic)); // subtract out bias\n\n    // \"result is normal\" path\n    mantoddbit  = _mm_slli_epi32(absf_int, 31 - 13); // shift bit 13 (mantissa LSB) to sign\n    mantodd     = _mm_srai_epi32(mantoddbit, 31); // -1 if FP16 mantissa odd, else 0\n\n    round1      = _mm_add_epi32(absf_int, STBIR__CONSTI(c_normal_bias));\n    round2      = _mm_sub_epi32(round1, mantodd); // if mantissa LSB odd, bias towards rounding up (RTNE)\n    normal      = _mm_srli_epi32(round2, 13); // rounded result\n\n    // combine the two non-specials\n    nonspecial  = _mm_or_si128(_mm_and_si128(subnorm2, b_issub), _mm_andnot_si128(b_issub, normal));\n\n    // merge in specials as well\n    joined      = _mm_or_si128(_mm_and_si128(nonspecial, b_isregular), _mm_andnot_si128(b_isregular, inf_or_nan));\n\n    sign_shift  = _mm_srai_epi32(_mm_castps_si128(justsign), 16);\n    final2      = _mm_or_si128(joined, sign_shift);\n    final       = _mm_packs_epi32(final, final2);\n    stbir__simdi_store( output,final );\n  }\n\n#elif defined(STBIR_NEON) && defined(_MSC_VER) && defined(_M_ARM64) && !defined(__clang__) // 64-bit ARM on MSVC (not clang)\n\n  static stbir__inline void stbir__half_to_float_SIMD(float * output, stbir__FP16 const * input)\n  {\n    float16x4_t in0 = vld1_f16(input + 0);\n    float16x4_t in1 = vld1_f16(input + 4);\n    vst1q_f32(output + 0, vcvt_f32_f16(in0));\n    vst1q_f32(output + 4, vcvt_f32_f16(in1));\n  }\n\n  static stbir__inline void stbir__float_to_half_SIMD(stbir__FP16 * output, float const * input)\n  {\n    float16x4_t out0 = vcvt_f16_f32(vld1q_f32(input + 0));\n    float16x4_t out1 = vcvt_f16_f32(vld1q_f32(input + 4));\n    vst1_f16(output+0, out0);\n    vst1_f16(output+4, out1);\n  }\n\n  static stbir__inline float stbir__half_to_float( stbir__FP16 h )\n  {\n    return vgetq_lane_f32(vcvt_f32_f16(vld1_dup_f16(&h)), 0);\n  }\n\n  static stbir__inline stbir__FP16 stbir__float_to_half( float f )\n  {\n    return vget_lane_f16(vcvt_f16_f32(vdupq_n_f32(f)), 0).n16_u16[0];\n  }\n\n#elif defined(STBIR_NEON) && ( defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ ) ) // 64-bit ARM\n\n  static stbir__inline void stbir__half_to_float_SIMD(float * output, stbir__FP16 const * input)\n  {\n    float16x8_t in = vld1q_f16(input);\n    vst1q_f32(output + 0, vcvt_f32_f16(vget_low_f16(in)));\n    vst1q_f32(output + 4, vcvt_f32_f16(vget_high_f16(in)));\n  }\n\n  static stbir__inline void stbir__float_to_half_SIMD(stbir__FP16 * output, float const * input)\n  {\n    float16x4_t out0 = vcvt_f16_f32(vld1q_f32(input + 0));\n    float16x4_t out1 = vcvt_f16_f32(vld1q_f32(input + 4));\n    vst1q_f16(output, vcombine_f16(out0, out1));\n  }\n\n  static stbir__inline float stbir__half_to_float( stbir__FP16 h )\n  {\n    return vgetq_lane_f32(vcvt_f32_f16(vdup_n_f16(h)), 0);\n  }\n\n  static stbir__inline stbir__FP16 stbir__float_to_half( float f )\n  {\n    return vget_lane_f16(vcvt_f16_f32(vdupq_n_f32(f)), 0);\n  }\n\n#elif defined(STBIR_WASM) || (defined(STBIR_NEON) && (defined(_MSC_VER) || defined(_M_ARM) || defined(__arm__))) // WASM or 32-bit ARM on MSVC/clang\n\n  static stbir__inline void stbir__half_to_float_SIMD(float * output, stbir__FP16 const * input)\n  {\n    for (int i=0; i<8; i++)\n    {\n      output[i] = stbir__half_to_float(input[i]);\n    }\n  }\n  static stbir__inline void stbir__float_to_half_SIMD(stbir__FP16 * output, float const * input)\n  {\n    for (int i=0; i<8; i++)\n    {\n      output[i] = stbir__float_to_half(input[i]);\n    }\n  }\n\n#endif\n\n\n#ifdef STBIR_SIMD\n\n#define stbir__simdf_0123to3333( out, reg ) (out) = stbir__simdf_swiz( reg, 3,3,3,3 )\n#define stbir__simdf_0123to2222( out, reg ) (out) = stbir__simdf_swiz( reg, 2,2,2,2 )\n#define stbir__simdf_0123to1111( out, reg ) (out) = stbir__simdf_swiz( reg, 1,1,1,1 )\n#define stbir__simdf_0123to0000( out, reg ) (out) = stbir__simdf_swiz( reg, 0,0,0,0 )\n#define stbir__simdf_0123to0003( out, reg ) (out) = stbir__simdf_swiz( reg, 0,0,0,3 )\n#define stbir__simdf_0123to0001( out, reg ) (out) = stbir__simdf_swiz( reg, 0,0,0,1 )\n#define stbir__simdf_0123to1122( out, reg ) (out) = stbir__simdf_swiz( reg, 1,1,2,2 )\n#define stbir__simdf_0123to2333( out, reg ) (out) = stbir__simdf_swiz( reg, 2,3,3,3 )\n#define stbir__simdf_0123to0023( out, reg ) (out) = stbir__simdf_swiz( reg, 0,0,2,3 )\n#define stbir__simdf_0123to1230( out, reg ) (out) = stbir__simdf_swiz( reg, 1,2,3,0 )\n#define stbir__simdf_0123to2103( out, reg ) (out) = stbir__simdf_swiz( reg, 2,1,0,3 )\n#define stbir__simdf_0123to3210( out, reg ) (out) = stbir__simdf_swiz( reg, 3,2,1,0 )\n#define stbir__simdf_0123to2301( out, reg ) (out) = stbir__simdf_swiz( reg, 2,3,0,1 )\n#define stbir__simdf_0123to3012( out, reg ) (out) = stbir__simdf_swiz( reg, 3,0,1,2 )\n#define stbir__simdf_0123to0011( out, reg ) (out) = stbir__simdf_swiz( reg, 0,0,1,1 )\n#define stbir__simdf_0123to1100( out, reg ) (out) = stbir__simdf_swiz( reg, 1,1,0,0 )\n#define stbir__simdf_0123to2233( out, reg ) (out) = stbir__simdf_swiz( reg, 2,2,3,3 )\n#define stbir__simdf_0123to1133( out, reg ) (out) = stbir__simdf_swiz( reg, 1,1,3,3 )\n#define stbir__simdf_0123to0022( out, reg ) (out) = stbir__simdf_swiz( reg, 0,0,2,2 )\n#define stbir__simdf_0123to1032( out, reg ) (out) = stbir__simdf_swiz( reg, 1,0,3,2 )\n\ntypedef union stbir__simdi_u32\n{\n  stbir_uint32 m128i_u32[4];\n  int m128i_i32[4];\n  stbir__simdi m128i_i128;\n} stbir__simdi_u32;\n\nstatic const int STBIR_mask[9] = { 0,0,0,-1,-1,-1,0,0,0 };\n\nstatic const STBIR__SIMDF_CONST(STBIR_max_uint8_as_float,           stbir__max_uint8_as_float);\nstatic const STBIR__SIMDF_CONST(STBIR_max_uint16_as_float,          stbir__max_uint16_as_float);\nstatic const STBIR__SIMDF_CONST(STBIR_max_uint8_as_float_inverted,  stbir__max_uint8_as_float_inverted);\nstatic const STBIR__SIMDF_CONST(STBIR_max_uint16_as_float_inverted, stbir__max_uint16_as_float_inverted);\n\nstatic const STBIR__SIMDF_CONST(STBIR_simd_point5,   0.5f);\nstatic const STBIR__SIMDF_CONST(STBIR_ones,          1.0f);\nstatic const STBIR__SIMDI_CONST(STBIR_almost_zero,   (127 - 13) << 23);\nstatic const STBIR__SIMDI_CONST(STBIR_almost_one,    0x3f7fffff);\nstatic const STBIR__SIMDI_CONST(STBIR_mantissa_mask, 0xff);\nstatic const STBIR__SIMDI_CONST(STBIR_topscale,      0x02000000);\n\n//   Basically, in simd mode, we unroll the proper amount, and we don't want\n//   the non-simd remnant loops to be unroll because they only run a few times\n//   Adding this switch saves about 5K on clang which is Captain Unroll the 3rd.\n#define STBIR_SIMD_STREAMOUT_PTR( star )  STBIR_STREAMOUT_PTR( star )\n#define STBIR_SIMD_NO_UNROLL(ptr) STBIR_NO_UNROLL(ptr)\n#define STBIR_SIMD_NO_UNROLL_LOOP_START STBIR_NO_UNROLL_LOOP_START\n#define STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR STBIR_NO_UNROLL_LOOP_START_INF_FOR\n\n#ifdef STBIR_MEMCPY\n#undef STBIR_MEMCPY\n#endif\n#define STBIR_MEMCPY stbir_simd_memcpy\n\n// override normal use of memcpy with much simpler copy (faster and smaller with our sized copies)\nstatic void stbir_simd_memcpy( void * dest, void const * src, size_t bytes )\n{\n  char STBIR_SIMD_STREAMOUT_PTR (*) d = (char*) dest;\n  char STBIR_SIMD_STREAMOUT_PTR( * ) d_end = ((char*) dest) + bytes;\n  ptrdiff_t ofs_to_src = (char*)src - (char*)dest;\n\n  // check overlaps\n  STBIR_ASSERT( ( ( d >= ( (char*)src) + bytes ) ) || ( ( d + bytes ) <= (char*)src ) );\n\n  if ( bytes < (16*stbir__simdfX_float_count) )\n  {\n    if ( bytes < 16 )\n    {\n      if ( bytes )\n      {\n        STBIR_SIMD_NO_UNROLL_LOOP_START\n        do\n        {\n          STBIR_SIMD_NO_UNROLL(d);\n          d[ 0 ] = d[ ofs_to_src ];\n          ++d;\n        } while ( d < d_end );\n      }\n    }\n    else\n    {\n      stbir__simdf x;\n      // do one unaligned to get us aligned for the stream out below\n      stbir__simdf_load( x, ( d + ofs_to_src ) );\n      stbir__simdf_store( d, x );\n      d = (char*)( ( ( (size_t)d ) + 16 ) & ~15 );\n\n      STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n      for(;;)\n      {\n        STBIR_SIMD_NO_UNROLL(d);\n\n        if ( d > ( d_end - 16 ) )\n        {\n          if ( d == d_end )\n            return;\n          d = d_end - 16;\n        }\n\n        stbir__simdf_load( x, ( d + ofs_to_src ) );\n        stbir__simdf_store( d, x );\n        d += 16;\n      }\n    }\n  }\n  else\n  {\n    stbir__simdfX x0,x1,x2,x3;\n\n    // do one unaligned to get us aligned for the stream out below\n    stbir__simdfX_load( x0, ( d + ofs_to_src ) +  0*stbir__simdfX_float_count );\n    stbir__simdfX_load( x1, ( d + ofs_to_src ) +  4*stbir__simdfX_float_count );\n    stbir__simdfX_load( x2, ( d + ofs_to_src ) +  8*stbir__simdfX_float_count );\n    stbir__simdfX_load( x3, ( d + ofs_to_src ) + 12*stbir__simdfX_float_count );\n    stbir__simdfX_store( d +  0*stbir__simdfX_float_count, x0 );\n    stbir__simdfX_store( d +  4*stbir__simdfX_float_count, x1 );\n    stbir__simdfX_store( d +  8*stbir__simdfX_float_count, x2 );\n    stbir__simdfX_store( d + 12*stbir__simdfX_float_count, x3 );\n    d = (char*)( ( ( (size_t)d ) + (16*stbir__simdfX_float_count) ) & ~((16*stbir__simdfX_float_count)-1) );\n\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      STBIR_SIMD_NO_UNROLL(d);\n\n      if ( d > ( d_end - (16*stbir__simdfX_float_count) ) )\n      {\n        if ( d == d_end )\n          return;\n        d = d_end - (16*stbir__simdfX_float_count);\n      }\n\n      stbir__simdfX_load( x0, ( d + ofs_to_src ) +  0*stbir__simdfX_float_count );\n      stbir__simdfX_load( x1, ( d + ofs_to_src ) +  4*stbir__simdfX_float_count );\n      stbir__simdfX_load( x2, ( d + ofs_to_src ) +  8*stbir__simdfX_float_count );\n      stbir__simdfX_load( x3, ( d + ofs_to_src ) + 12*stbir__simdfX_float_count );\n      stbir__simdfX_store( d +  0*stbir__simdfX_float_count, x0 );\n      stbir__simdfX_store( d +  4*stbir__simdfX_float_count, x1 );\n      stbir__simdfX_store( d +  8*stbir__simdfX_float_count, x2 );\n      stbir__simdfX_store( d + 12*stbir__simdfX_float_count, x3 );\n      d += (16*stbir__simdfX_float_count);\n    }\n  }\n}\n\n// memcpy that is specically intentionally overlapping (src is smaller then dest, so can be\n//   a normal forward copy, bytes is divisible by 4 and bytes is greater than or equal to\n//   the diff between dest and src)\nstatic void stbir_overlapping_memcpy( void * dest, void const * src, size_t bytes )\n{\n  char STBIR_SIMD_STREAMOUT_PTR (*) sd = (char*) src;\n  char STBIR_SIMD_STREAMOUT_PTR( * ) s_end = ((char*) src) + bytes;\n  ptrdiff_t ofs_to_dest = (char*)dest - (char*)src;\n\n  if ( ofs_to_dest >= 16 ) // is the overlap more than 16 away?\n  {\n    char STBIR_SIMD_STREAMOUT_PTR( * ) s_end16 = ((char*) src) + (bytes&~15);\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    do\n    {\n      stbir__simdf x;\n      STBIR_SIMD_NO_UNROLL(sd);\n      stbir__simdf_load( x, sd );\n      stbir__simdf_store(  ( sd + ofs_to_dest ), x );\n      sd += 16;\n    } while ( sd < s_end16 );\n\n    if ( sd == s_end )\n      return;\n  }\n\n  do\n  {\n    STBIR_SIMD_NO_UNROLL(sd);\n    *(int*)( sd + ofs_to_dest ) = *(int*) sd;\n    sd += 4;\n  } while ( sd < s_end );\n}\n\n#else // no SSE2\n\n// when in scalar mode, we let unrolling happen, so this macro just does the __restrict\n#define STBIR_SIMD_STREAMOUT_PTR( star ) STBIR_STREAMOUT_PTR( star )\n#define STBIR_SIMD_NO_UNROLL(ptr)\n#define STBIR_SIMD_NO_UNROLL_LOOP_START\n#define STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n\n#endif // SSE2\n\n\n#ifdef STBIR_PROFILE\n\n#ifndef STBIR_PROFILE_FUNC\n\n#if defined(_x86_64) || defined( __x86_64__ ) || defined( _M_X64 ) || defined(__x86_64) || defined(__SSE2__) || defined(STBIR_SSE) || defined( _M_IX86_FP ) || defined(__i386) || defined( __i386__ ) || defined( _M_IX86 ) || defined( _X86_ )\n\n#ifdef _MSC_VER\n\n  STBIRDEF stbir_uint64 __rdtsc();\n  #define STBIR_PROFILE_FUNC() __rdtsc()\n\n#else // non msvc\n\n  static stbir__inline stbir_uint64 STBIR_PROFILE_FUNC()\n  {\n    stbir_uint32 lo, hi;\n    asm volatile (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi) );\n    return ( ( (stbir_uint64) hi ) << 32 ) | ( (stbir_uint64) lo );\n  }\n\n#endif  // msvc\n\n#elif defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ ) || defined(__ARM_NEON__)\n\n#if defined( _MSC_VER ) && !defined(__clang__)\n\n  #define STBIR_PROFILE_FUNC() _ReadStatusReg(ARM64_CNTVCT)\n\n#else\n\n  static stbir__inline stbir_uint64 STBIR_PROFILE_FUNC()\n  {\n    stbir_uint64 tsc;\n    asm volatile(\"mrs %0, cntvct_el0\" : \"=r\" (tsc));\n    return tsc;\n  }\n\n#endif\n\n#else // x64, arm\n\n#error Unknown platform for profiling.\n\n#endif  // x64, arm\n\n#endif // STBIR_PROFILE_FUNC\n\n#define STBIR_ONLY_PROFILE_GET_SPLIT_INFO ,stbir__per_split_info * split_info\n#define STBIR_ONLY_PROFILE_SET_SPLIT_INFO ,split_info\n\n#define STBIR_ONLY_PROFILE_BUILD_GET_INFO ,stbir__info * profile_info\n#define STBIR_ONLY_PROFILE_BUILD_SET_INFO ,profile_info\n\n// super light-weight micro profiler\n#define STBIR_PROFILE_START_ll( info, wh ) { stbir_uint64 wh##thiszonetime = STBIR_PROFILE_FUNC(); stbir_uint64 * wh##save_parent_excluded_ptr = info->current_zone_excluded_ptr; stbir_uint64 wh##current_zone_excluded = 0; info->current_zone_excluded_ptr = &wh##current_zone_excluded;\n#define STBIR_PROFILE_END_ll( info, wh ) wh##thiszonetime = STBIR_PROFILE_FUNC() - wh##thiszonetime; info->profile.named.wh += wh##thiszonetime - wh##current_zone_excluded; *wh##save_parent_excluded_ptr += wh##thiszonetime; info->current_zone_excluded_ptr = wh##save_parent_excluded_ptr; }\n#define STBIR_PROFILE_FIRST_START_ll( info, wh ) { int i; info->current_zone_excluded_ptr = &info->profile.named.total; for(i=0;i<STBIR__ARRAY_SIZE(info->profile.array);i++) info->profile.array[i]=0; } STBIR_PROFILE_START_ll( info, wh );\n#define STBIR_PROFILE_CLEAR_EXTRAS_ll( info, num ) { int extra; for(extra=1;extra<(num);extra++) { int i; for(i=0;i<STBIR__ARRAY_SIZE((info)->profile.array);i++) (info)[extra].profile.array[i]=0; } }\n\n// for thread data\n#define STBIR_PROFILE_START( wh ) STBIR_PROFILE_START_ll( split_info, wh )\n#define STBIR_PROFILE_END( wh ) STBIR_PROFILE_END_ll( split_info, wh )\n#define STBIR_PROFILE_FIRST_START( wh ) STBIR_PROFILE_FIRST_START_ll( split_info, wh )\n#define STBIR_PROFILE_CLEAR_EXTRAS() STBIR_PROFILE_CLEAR_EXTRAS_ll( split_info, split_count )\n\n// for build data\n#define STBIR_PROFILE_BUILD_START( wh ) STBIR_PROFILE_START_ll( profile_info, wh )\n#define STBIR_PROFILE_BUILD_END( wh ) STBIR_PROFILE_END_ll( profile_info, wh )\n#define STBIR_PROFILE_BUILD_FIRST_START( wh ) STBIR_PROFILE_FIRST_START_ll( profile_info, wh )\n#define STBIR_PROFILE_BUILD_CLEAR( info ) { int i; for(i=0;i<STBIR__ARRAY_SIZE(info->profile.array);i++) info->profile.array[i]=0; }\n\n#else  // no profile\n\n#define STBIR_ONLY_PROFILE_GET_SPLIT_INFO\n#define STBIR_ONLY_PROFILE_SET_SPLIT_INFO\n\n#define STBIR_ONLY_PROFILE_BUILD_GET_INFO\n#define STBIR_ONLY_PROFILE_BUILD_SET_INFO\n\n#define STBIR_PROFILE_START( wh )\n#define STBIR_PROFILE_END( wh )\n#define STBIR_PROFILE_FIRST_START( wh )\n#define STBIR_PROFILE_CLEAR_EXTRAS( )\n\n#define STBIR_PROFILE_BUILD_START( wh )\n#define STBIR_PROFILE_BUILD_END( wh )\n#define STBIR_PROFILE_BUILD_FIRST_START( wh )\n#define STBIR_PROFILE_BUILD_CLEAR( info )\n\n#endif  // stbir_profile\n\n#ifndef STBIR_CEILF\n#include <math.h>\n#if _MSC_VER <= 1200 // support VC6 for Sean\n#define STBIR_CEILF(x) ((float)ceil((float)(x)))\n#define STBIR_FLOORF(x) ((float)floor((float)(x)))\n#else\n#define STBIR_CEILF(x) ceilf(x)\n#define STBIR_FLOORF(x) floorf(x)\n#endif\n#endif\n\n#ifndef STBIR_MEMCPY\n// For memcpy\n#include <string.h>\n#define STBIR_MEMCPY( dest, src, len ) memcpy( dest, src, len )\n#endif\n\n#ifndef STBIR_SIMD\n\n// memcpy that is specifically intentionally overlapping (src is smaller then dest, so can be\n//   a normal forward copy, bytes is divisible by 4 and bytes is greater than or equal to\n//   the diff between dest and src)\nstatic void stbir_overlapping_memcpy( void * dest, void const * src, size_t bytes )\n{\n  char STBIR_SIMD_STREAMOUT_PTR (*) sd = (char*) src;\n  char STBIR_SIMD_STREAMOUT_PTR( * ) s_end = ((char*) src) + bytes;\n  ptrdiff_t ofs_to_dest = (char*)dest - (char*)src;\n\n  if ( ofs_to_dest >= 8 ) // is the overlap more than 8 away\n  {\n    char STBIR_SIMD_STREAMOUT_PTR( * ) s_end8 = ((char*) src) + (bytes&~7);\n\n    if ( ( ( ((ptrdiff_t)dest)|((ptrdiff_t)src) ) & 7 ) == 0 ) // is it 8byte aligned?\n    {\n      STBIR_NO_UNROLL_LOOP_START\n      do\n      {\n        STBIR_NO_UNROLL(sd);\n        *(stbir_uint64*)( sd + ofs_to_dest ) = *(stbir_uint64*) sd;\n        sd += 8;\n      } while ( sd < s_end8 );\n    }\n    else\n    {\n      STBIR_NO_UNROLL_LOOP_START\n      do\n      {\n        int a,b;\n        STBIR_NO_UNROLL(sd);\n        a = ((int*)sd)[0];\n        b = ((int*)sd)[1];\n        ((int*)( sd + ofs_to_dest ))[0] = a;\n        ((int*)( sd + ofs_to_dest ))[1] = b;\n        sd += 8;\n      } while ( sd < s_end8 );\n    }\n\n    if ( sd == s_end )\n      return;\n  }\n\n  STBIR_NO_UNROLL_LOOP_START\n  do\n  {\n    STBIR_NO_UNROLL(sd);\n    *(int*)( sd + ofs_to_dest ) = *(int*) sd;\n    sd += 4;\n  } while ( sd < s_end );\n}\n\n#endif\n\nstatic float stbir__filter_trapezoid(float x, float scale, void * user_data)\n{\n  float halfscale = scale / 2;\n  float t = 0.5f + halfscale;\n  STBIR_ASSERT(scale <= 1);\n  STBIR__UNUSED(user_data);\n\n  if ( x < 0.0f ) x = -x;\n\n  if (x >= t)\n    return 0.0f;\n  else\n  {\n    float r = 0.5f - halfscale;\n    if (x <= r)\n      return 1.0f;\n    else\n      return (t - x) / scale;\n  }\n}\n\nstatic float stbir__support_trapezoid(float scale, void * user_data)\n{\n  STBIR__UNUSED(user_data);\n  return 0.5f + scale / 2.0f;\n}\n\nstatic float stbir__filter_triangle(float x, float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n\n  if ( x < 0.0f ) x = -x;\n\n  if (x <= 1.0f)\n    return 1.0f - x;\n  else\n    return 0.0f;\n}\n\nstatic float stbir__filter_point(float x, float s, void * user_data)\n{\n  STBIR__UNUSED(x);\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n\n  return 1.0f;\n}\n\nstatic float stbir__filter_cubic(float x, float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n\n  if ( x < 0.0f ) x = -x;\n\n  if (x < 1.0f)\n    return (4.0f + x*x*(3.0f*x - 6.0f))/6.0f;\n  else if (x < 2.0f)\n    return (8.0f + x*(-12.0f + x*(6.0f - x)))/6.0f;\n\n  return (0.0f);\n}\n\nstatic float stbir__filter_catmullrom(float x, float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n\n  if ( x < 0.0f ) x = -x;\n\n  if (x < 1.0f)\n    return 1.0f - x*x*(2.5f - 1.5f*x);\n  else if (x < 2.0f)\n    return 2.0f - x*(4.0f + x*(0.5f*x - 2.5f));\n\n  return (0.0f);\n}\n\nstatic float stbir__filter_mitchell(float x, float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n\n  if ( x < 0.0f ) x = -x;\n\n  if (x < 1.0f)\n    return (16.0f + x*x*(21.0f * x - 36.0f))/18.0f;\n  else if (x < 2.0f)\n    return (32.0f + x*(-60.0f + x*(36.0f - 7.0f*x)))/18.0f;\n\n  return (0.0f);\n}\n\nstatic float stbir__support_zeropoint5(float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n  return 0.5f;\n}\n\nstatic float stbir__support_one(float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n  return 1;\n}\n\nstatic float stbir__support_two(float s, void * user_data)\n{\n  STBIR__UNUSED(s);\n  STBIR__UNUSED(user_data);\n  return 2;\n}\n\n// This is the maximum number of input samples that can affect an output sample\n// with the given filter from the output pixel's perspective\nstatic int stbir__get_filter_pixel_width(stbir__support_callback * support, float scale, void * user_data)\n{\n  STBIR_ASSERT(support != 0);\n\n  if ( scale >= ( 1.0f-stbir__small_float ) ) // upscale\n    return (int)STBIR_CEILF(support(1.0f/scale,user_data) * 2.0f);\n  else\n    return (int)STBIR_CEILF(support(scale,user_data) * 2.0f / scale);\n}\n\n// this is how many coefficents per run of the filter (which is different\n//   from the filter_pixel_width depending on if we are scattering or gathering)\nstatic int stbir__get_coefficient_width(stbir__sampler * samp, int is_gather, void * user_data)\n{\n  float scale = samp->scale_info.scale;\n  stbir__support_callback * support = samp->filter_support;\n\n  switch( is_gather )\n  {\n    case 1:\n      return (int)STBIR_CEILF(support(1.0f / scale, user_data) * 2.0f);\n    case 2:\n      return (int)STBIR_CEILF(support(scale, user_data) * 2.0f / scale);\n    case 0:\n      return (int)STBIR_CEILF(support(scale, user_data) * 2.0f);\n    default:\n      STBIR_ASSERT( (is_gather >= 0 ) && (is_gather <= 2 ) );\n      return 0;\n  }\n}\n\nstatic int stbir__get_contributors(stbir__sampler * samp, int is_gather)\n{\n  if (is_gather)\n      return samp->scale_info.output_sub_size;\n  else\n      return (samp->scale_info.input_full_size + samp->filter_pixel_margin * 2);\n}\n\nstatic int stbir__edge_zero_full( int n, int max )\n{\n  STBIR__UNUSED(n);\n  STBIR__UNUSED(max);\n  return 0; // NOTREACHED\n}\n\nstatic int stbir__edge_clamp_full( int n, int max )\n{\n  if (n < 0)\n    return 0;\n\n  if (n >= max)\n    return max - 1;\n\n  return n; // NOTREACHED\n}\n\nstatic int stbir__edge_reflect_full( int n, int max )\n{\n  if (n < 0)\n  {\n    if (n > -max)\n      return -n;\n    else\n      return max - 1;\n  }\n\n  if (n >= max)\n  {\n    int max2 = max * 2;\n    if (n >= max2)\n      return 0;\n    else\n      return max2 - n - 1;\n  }\n\n  return n; // NOTREACHED\n}\n\nstatic int stbir__edge_wrap_full( int n, int max )\n{\n  if (n >= 0)\n    return (n % max);\n  else\n  {\n    int m = (-n) % max;\n\n    if (m != 0)\n      m = max - m;\n\n    return (m);\n  }\n}\n\ntypedef int stbir__edge_wrap_func( int n, int max );\nstatic stbir__edge_wrap_func * stbir__edge_wrap_slow[] =\n{\n  stbir__edge_clamp_full,    // STBIR_EDGE_CLAMP\n  stbir__edge_reflect_full,  // STBIR_EDGE_REFLECT\n  stbir__edge_wrap_full,     // STBIR_EDGE_WRAP\n  stbir__edge_zero_full,     // STBIR_EDGE_ZERO\n};\n\nstbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max)\n{\n  // avoid per-pixel switch\n  if (n >= 0 && n < max)\n      return n;\n  return stbir__edge_wrap_slow[edge]( n, max );\n}\n\n#define STBIR__MERGE_RUNS_PIXEL_THRESHOLD 16\n\n// get information on the extents of a sampler\nstatic void stbir__get_extents( stbir__sampler * samp, stbir__extents * scanline_extents )\n{\n  int j, stop;\n  int left_margin, right_margin;\n  int min_n = 0x7fffffff, max_n = -0x7fffffff;\n  int min_left = 0x7fffffff, max_left = -0x7fffffff;\n  int min_right = 0x7fffffff, max_right = -0x7fffffff;\n  stbir_edge edge = samp->edge;\n  stbir__contributors* contributors = samp->contributors;\n  int output_sub_size = samp->scale_info.output_sub_size;\n  int input_full_size = samp->scale_info.input_full_size;\n  int filter_pixel_margin = samp->filter_pixel_margin;\n\n  STBIR_ASSERT( samp->is_gather );\n\n  stop = output_sub_size;\n  for (j = 0; j < stop; j++ )\n  {\n    STBIR_ASSERT( contributors[j].n1 >= contributors[j].n0 );\n    if ( contributors[j].n0 < min_n )\n    {\n      min_n = contributors[j].n0;\n      stop = j + filter_pixel_margin;  // if we find a new min, only scan another filter width\n      if ( stop > output_sub_size ) stop = output_sub_size;\n    }\n  }\n\n  stop = 0;\n  for (j = output_sub_size - 1; j >= stop; j-- )\n  {\n    STBIR_ASSERT( contributors[j].n1 >= contributors[j].n0 );\n    if ( contributors[j].n1 > max_n )\n    {\n      max_n = contributors[j].n1;\n      stop = j - filter_pixel_margin;  // if we find a new max, only scan another filter width\n      if (stop<0) stop = 0;\n    }\n  }\n\n  STBIR_ASSERT( scanline_extents->conservative.n0 <= min_n );\n  STBIR_ASSERT( scanline_extents->conservative.n1 >= max_n );\n\n  // now calculate how much into the margins we really read\n  left_margin = 0;\n  if ( min_n < 0 )\n  {\n    left_margin = -min_n;\n    min_n = 0;\n  }\n\n  right_margin = 0;\n  if ( max_n >= input_full_size )\n  {\n    right_margin = max_n - input_full_size + 1;\n    max_n = input_full_size - 1;\n  }\n\n  // index 1 is margin pixel extents (how many pixels we hang over the edge)\n  scanline_extents->edge_sizes[0] = left_margin;\n  scanline_extents->edge_sizes[1] = right_margin;\n\n  // index 2 is pixels read from the input\n  scanline_extents->spans[0].n0 = min_n;\n  scanline_extents->spans[0].n1 = max_n;\n  scanline_extents->spans[0].pixel_offset_for_input = min_n;\n\n  // default to no other input range\n  scanline_extents->spans[1].n0 = 0;\n  scanline_extents->spans[1].n1 = -1;\n  scanline_extents->spans[1].pixel_offset_for_input = 0;\n\n  // don't have to do edge calc for zero clamp\n  if ( edge == STBIR_EDGE_ZERO )\n    return;\n\n  // convert margin pixels to the pixels within the input (min and max)\n  for( j = -left_margin ; j < 0 ; j++ )\n  {\n      int p = stbir__edge_wrap( edge, j, input_full_size );\n      if ( p < min_left )\n        min_left = p;\n      if ( p > max_left )\n        max_left = p;\n  }\n\n  for( j = input_full_size ; j < (input_full_size + right_margin) ; j++ )\n  {\n      int p = stbir__edge_wrap( edge, j, input_full_size );\n      if ( p < min_right )\n        min_right = p;\n      if ( p > max_right )\n        max_right = p;\n  }\n\n  // merge the left margin pixel region if it connects within 4 pixels of main pixel region\n  if ( min_left != 0x7fffffff )\n  {\n    if ( ( ( min_left <= min_n ) && ( ( max_left  + STBIR__MERGE_RUNS_PIXEL_THRESHOLD ) >= min_n ) ) ||\n         ( ( min_n <= min_left ) && ( ( max_n  + STBIR__MERGE_RUNS_PIXEL_THRESHOLD ) >= max_left ) ) )\n    {\n      scanline_extents->spans[0].n0 = min_n = stbir__min( min_n, min_left );\n      scanline_extents->spans[0].n1 = max_n = stbir__max( max_n, max_left );\n      scanline_extents->spans[0].pixel_offset_for_input = min_n;\n      left_margin = 0;\n    }\n  }\n\n  // merge the right margin pixel region if it connects within 4 pixels of main pixel region\n  if ( min_right != 0x7fffffff )\n  {\n    if ( ( ( min_right <= min_n ) && ( ( max_right  + STBIR__MERGE_RUNS_PIXEL_THRESHOLD ) >= min_n ) ) ||\n         ( ( min_n <= min_right ) && ( ( max_n  + STBIR__MERGE_RUNS_PIXEL_THRESHOLD ) >= max_right ) ) )\n    {\n      scanline_extents->spans[0].n0 = min_n = stbir__min( min_n, min_right );\n      scanline_extents->spans[0].n1 = max_n = stbir__max( max_n, max_right );\n      scanline_extents->spans[0].pixel_offset_for_input = min_n;\n      right_margin = 0;\n    }\n  }\n\n  STBIR_ASSERT( scanline_extents->conservative.n0 <= min_n );\n  STBIR_ASSERT( scanline_extents->conservative.n1 >= max_n );\n\n  // you get two ranges when you have the WRAP edge mode and you are doing just the a piece of the resize\n  //   so you need to get a second run of pixels from the opposite side of the scanline (which you\n  //   wouldn't need except for WRAP)\n\n\n  // if we can't merge the min_left range, add it as a second range\n  if ( ( left_margin ) && ( min_left != 0x7fffffff ) )\n  {\n    stbir__span * newspan = scanline_extents->spans + 1;\n    STBIR_ASSERT( right_margin == 0 );\n    if ( min_left < scanline_extents->spans[0].n0 )\n    {\n      scanline_extents->spans[1].pixel_offset_for_input = scanline_extents->spans[0].n0;\n      scanline_extents->spans[1].n0 = scanline_extents->spans[0].n0;\n      scanline_extents->spans[1].n1 = scanline_extents->spans[0].n1;\n      --newspan;\n    }\n    newspan->pixel_offset_for_input = min_left;\n    newspan->n0 = -left_margin;\n    newspan->n1 = ( max_left - min_left ) - left_margin;\n    scanline_extents->edge_sizes[0] = 0;  // don't need to copy the left margin, since we are directly decoding into the margin\n  }\n  // if we can't merge the min_right range, add it as a second range\n  else  \n  if ( ( right_margin ) && ( min_right != 0x7fffffff ) )\n  {\n    stbir__span * newspan = scanline_extents->spans + 1;\n    if ( min_right < scanline_extents->spans[0].n0 )\n    {\n      scanline_extents->spans[1].pixel_offset_for_input = scanline_extents->spans[0].n0;\n      scanline_extents->spans[1].n0 = scanline_extents->spans[0].n0;\n      scanline_extents->spans[1].n1 = scanline_extents->spans[0].n1;\n      --newspan;\n    }\n    newspan->pixel_offset_for_input = min_right;\n    newspan->n0 = scanline_extents->spans[1].n1 + 1;\n    newspan->n1 = scanline_extents->spans[1].n1 + 1 + ( max_right - min_right );\n    scanline_extents->edge_sizes[1] = 0;  // don't need to copy the right margin, since we are directly decoding into the margin\n  }\n\n  // sort the spans into write output order\n  if ( ( scanline_extents->spans[1].n1 > scanline_extents->spans[1].n0 ) && ( scanline_extents->spans[0].n0 > scanline_extents->spans[1].n0 ) )\n  {\n    stbir__span tspan = scanline_extents->spans[0];\n    scanline_extents->spans[0] = scanline_extents->spans[1];\n    scanline_extents->spans[1] = tspan;\n  }\n}\n\nstatic void stbir__calculate_in_pixel_range( int * first_pixel, int * last_pixel, float out_pixel_center, float out_filter_radius, float inv_scale, float out_shift, int input_size, stbir_edge edge )\n{\n  int first, last;\n  float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius;\n  float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius;\n\n  float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) * inv_scale;\n  float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) * inv_scale;\n\n  first = (int)(STBIR_FLOORF(in_pixel_influence_lowerbound + 0.5f));\n  last = (int)(STBIR_FLOORF(in_pixel_influence_upperbound - 0.5f));\n  if ( last < first ) last = first; // point sample mode can span a value *right* at 0.5, and cause these to cross\n\n  if ( edge == STBIR_EDGE_WRAP )\n  {\n    if ( first < -input_size )\n      first = -input_size;\n    if ( last >= (input_size*2))\n      last = (input_size*2) - 1;\n  }\n\n  *first_pixel = first;\n  *last_pixel = last;\n}\n\nstatic void stbir__calculate_coefficients_for_gather_upsample( float out_filter_radius, stbir__kernel_callback * kernel, stbir__scale_info * scale_info, int num_contributors, stbir__contributors* contributors, float* coefficient_group, int coefficient_width, stbir_edge edge, void * user_data )\n{\n  int n, end;\n  float inv_scale = scale_info->inv_scale;\n  float out_shift = scale_info->pixel_shift;\n  int input_size  = scale_info->input_full_size;\n  int numerator = scale_info->scale_numerator;\n  int polyphase = ( ( scale_info->scale_is_rational ) && ( numerator < num_contributors ) );\n\n  // Looping through out pixels\n  end = num_contributors; if ( polyphase ) end = numerator;\n  for (n = 0; n < end; n++)\n  {\n    int i;\n    int last_non_zero;\n    float out_pixel_center = (float)n + 0.5f;\n    float in_center_of_out = (out_pixel_center + out_shift) * inv_scale;\n\n    int in_first_pixel, in_last_pixel;\n\n    stbir__calculate_in_pixel_range( &in_first_pixel, &in_last_pixel, out_pixel_center, out_filter_radius, inv_scale, out_shift, input_size, edge );\n\n    // make sure we never generate a range larger than our precalculated coeff width\n    //   this only happens in point sample mode, but it's a good safe thing to do anyway\n    if ( ( in_last_pixel - in_first_pixel + 1 ) > coefficient_width )\n      in_last_pixel = in_first_pixel + coefficient_width - 1;\n\n    last_non_zero = -1;\n    for (i = 0; i <= in_last_pixel - in_first_pixel; i++)\n    {\n      float in_pixel_center = (float)(i + in_first_pixel) + 0.5f;\n      float coeff = kernel(in_center_of_out - in_pixel_center, inv_scale, user_data);\n\n      // kill denormals\n      if ( ( ( coeff < stbir__small_float ) && ( coeff > -stbir__small_float ) ) )\n      {\n        if ( i == 0 )  // if we're at the front, just eat zero contributors\n        {\n          STBIR_ASSERT ( ( in_last_pixel - in_first_pixel ) != 0 ); // there should be at least one contrib\n          ++in_first_pixel;\n          i--;\n          continue;\n        }\n        coeff = 0;  // make sure is fully zero (should keep denormals away)\n      }\n      else\n        last_non_zero = i;\n\n      coefficient_group[i] = coeff;\n    }\n\n    in_last_pixel = last_non_zero+in_first_pixel; // kills trailing zeros\n    contributors->n0 = in_first_pixel;\n    contributors->n1 = in_last_pixel;\n\n    STBIR_ASSERT(contributors->n1 >= contributors->n0);\n\n    ++contributors;\n    coefficient_group += coefficient_width;\n  }\n}\n\nstatic void stbir__insert_coeff( stbir__contributors * contribs, float * coeffs, int new_pixel, float new_coeff, int max_width )\n{\n  if ( contribs->n1 < contribs->n0 ) // this first clause should never happen, but handle in case\n  {\n    contribs->n0 = contribs->n1 = new_pixel;\n    coeffs[0] = new_coeff;\n  }\n  else if ( new_pixel <= contribs->n1 )  // before the end\n  {\n    if ( new_pixel < contribs->n0 ) // before the front?\n    {\n      if ( ( contribs->n1 - new_pixel + 1 ) <= max_width )\n      { \n        int j, o = contribs->n0 - new_pixel;\n        for ( j = contribs->n1 - contribs->n0 ; j >= 0 ; j-- )\n          coeffs[ j + o ] = coeffs[ j ];\n        for ( j = 1 ; j < o ; j++ )\n          coeffs[ j ] = 0;\n        coeffs[ 0 ] = new_coeff;\n        contribs->n0 = new_pixel;\n      }\n    }\n    else\n    {\n      // add new weight to existing coeff if already there\n      coeffs[ new_pixel - contribs->n0 ] += new_coeff;\n    }\n  }\n  else\n  {\n    if ( ( new_pixel - contribs->n0 + 1 ) <= max_width )\n    {\n      int j, e = new_pixel - contribs->n0;\n      for( j = ( contribs->n1 - contribs->n0 ) + 1 ; j < e ; j++ ) // clear in-betweens coeffs if there are any\n        coeffs[j] = 0;\n\n      coeffs[ e ] = new_coeff;\n      contribs->n1 = new_pixel;\n    }\n  }\n}\n\nstatic void stbir__calculate_out_pixel_range( int * first_pixel, int * last_pixel, float in_pixel_center, float in_pixels_radius, float scale, float out_shift, int out_size )\n{\n  float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius;\n  float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius;\n  float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale - out_shift;\n  float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale - out_shift;\n  int out_first_pixel = (int)(STBIR_FLOORF(out_pixel_influence_lowerbound + 0.5f));\n  int out_last_pixel = (int)(STBIR_FLOORF(out_pixel_influence_upperbound - 0.5f));\n\n  if ( out_first_pixel < 0 )\n    out_first_pixel = 0;\n  if ( out_last_pixel >= out_size )\n    out_last_pixel = out_size - 1;\n  *first_pixel = out_first_pixel;\n  *last_pixel = out_last_pixel;\n}\n\nstatic void stbir__calculate_coefficients_for_gather_downsample( int start, int end, float in_pixels_radius, stbir__kernel_callback * kernel, stbir__scale_info * scale_info, int coefficient_width, int num_contributors, stbir__contributors * contributors, float * coefficient_group, void * user_data )\n{\n  int in_pixel;\n  int i;\n  int first_out_inited = -1;\n  float scale = scale_info->scale;\n  float out_shift = scale_info->pixel_shift;\n  int out_size = scale_info->output_sub_size;\n  int numerator = scale_info->scale_numerator;\n  int polyphase = ( ( scale_info->scale_is_rational ) && ( numerator < out_size ) );\n\n  STBIR__UNUSED(num_contributors);\n\n  // Loop through the input pixels\n  for (in_pixel = start; in_pixel < end; in_pixel++)\n  {\n    float in_pixel_center = (float)in_pixel + 0.5f;\n    float out_center_of_in = in_pixel_center * scale - out_shift;\n    int out_first_pixel, out_last_pixel;\n\n    stbir__calculate_out_pixel_range( &out_first_pixel, &out_last_pixel, in_pixel_center, in_pixels_radius, scale, out_shift, out_size );\n\n    if ( out_first_pixel > out_last_pixel )\n      continue;\n\n    // clamp or exit if we are using polyphase filtering, and the limit is up\n    if ( polyphase )\n    {\n      // when polyphase, you only have to do coeffs up to the numerator count\n      if ( out_first_pixel == numerator )\n        break;\n\n      // don't do any extra work, clamp last pixel at numerator too\n      if ( out_last_pixel >= numerator )\n        out_last_pixel = numerator - 1;\n    }\n\n    for (i = 0; i <= out_last_pixel - out_first_pixel; i++)\n    {\n      float out_pixel_center = (float)(i + out_first_pixel) + 0.5f;\n      float x = out_pixel_center - out_center_of_in;\n      float coeff = kernel(x, scale, user_data) * scale;\n\n      // kill the coeff if it's too small (avoid denormals)\n      if ( ( ( coeff < stbir__small_float ) && ( coeff > -stbir__small_float ) ) )\n        coeff = 0.0f;\n\n      {\n        int out = i + out_first_pixel;\n        float * coeffs = coefficient_group + out * coefficient_width;\n        stbir__contributors * contribs = contributors + out;\n\n        // is this the first time this output pixel has been seen?  Init it.\n        if ( out > first_out_inited )\n        {\n          STBIR_ASSERT( out == ( first_out_inited + 1 ) ); // ensure we have only advanced one at time\n          first_out_inited = out;\n          contribs->n0 = in_pixel;\n          contribs->n1 = in_pixel;\n          coeffs[0]  = coeff;\n        }\n        else\n        {\n          // insert on end (always in order)\n          if ( coeffs[0] == 0.0f )  // if the first coefficent is zero, then zap it for this coeffs\n          {\n            STBIR_ASSERT( ( in_pixel - contribs->n0 ) == 1 ); // ensure that when we zap, we're at the 2nd pos\n            contribs->n0 = in_pixel;\n          }\n          contribs->n1 = in_pixel;\n          STBIR_ASSERT( ( in_pixel - contribs->n0 ) < coefficient_width );\n          coeffs[in_pixel - contribs->n0]  = coeff;\n        }\n      }\n    }\n  }\n}\n\n#ifdef STBIR_RENORMALIZE_IN_FLOAT\n#define STBIR_RENORM_TYPE float\n#else\n#define STBIR_RENORM_TYPE double\n#endif\n\nstatic void stbir__cleanup_gathered_coefficients( stbir_edge edge, stbir__filter_extent_info* filter_info, stbir__scale_info * scale_info, int num_contributors, stbir__contributors* contributors, float * coefficient_group, int coefficient_width )\n{\n  int input_size = scale_info->input_full_size;\n  int input_last_n1 = input_size - 1;\n  int n, end;\n  int lowest = 0x7fffffff;\n  int highest = -0x7fffffff;\n  int widest = -1;\n  int numerator = scale_info->scale_numerator;\n  int denominator = scale_info->scale_denominator;\n  int polyphase = ( ( scale_info->scale_is_rational ) && ( numerator < num_contributors ) );\n  float * coeffs;\n  stbir__contributors * contribs;\n\n  // weight all the coeffs for each sample\n  coeffs = coefficient_group;\n  contribs = contributors;\n  end = num_contributors; if ( polyphase ) end = numerator;\n  for (n = 0; n < end; n++)\n  {\n    int i;\n    STBIR_RENORM_TYPE filter_scale, total_filter = 0;\n    int e;\n\n    // add all contribs\n    e = contribs->n1 - contribs->n0;\n    for( i = 0 ; i <= e ; i++ )\n    {\n      total_filter += (STBIR_RENORM_TYPE) coeffs[i];\n      STBIR_ASSERT( ( coeffs[i] >= -2.0f ) && ( coeffs[i] <= 2.0f )  ); // check for wonky weights\n    }\n\n    // rescale\n    if ( ( total_filter < stbir__small_float ) && ( total_filter > -stbir__small_float ) )\n    {\n      // all coeffs are extremely small, just zero it\n      contribs->n1 = contribs->n0;\n      coeffs[0] = 0.0f;\n    }\n    else\n    {\n      // if the total isn't 1.0, rescale everything\n      if ( ( total_filter < (1.0f-stbir__small_float) ) || ( total_filter > (1.0f+stbir__small_float) ) )\n      {\n        filter_scale = ((STBIR_RENORM_TYPE)1.0) / total_filter;\n\n        // scale them all\n        for (i = 0; i <= e; i++)\n          coeffs[i] = (float) ( coeffs[i] * filter_scale );\n      }\n    }\n    ++contribs;\n    coeffs += coefficient_width;\n  }\n\n  // if we have a rational for the scale, we can exploit the polyphaseness to not calculate\n  //   most of the coefficients, so we copy them here\n  if ( polyphase )\n  {\n    stbir__contributors * prev_contribs = contributors;\n    stbir__contributors * cur_contribs = contributors + numerator;\n\n    for( n = numerator ; n < num_contributors ; n++ )\n    {\n      cur_contribs->n0 = prev_contribs->n0 + denominator;\n      cur_contribs->n1 = prev_contribs->n1 + denominator;\n      ++cur_contribs;\n      ++prev_contribs;\n    }\n    stbir_overlapping_memcpy( coefficient_group + numerator * coefficient_width, coefficient_group, ( num_contributors - numerator ) * coefficient_width * sizeof( coeffs[ 0 ] ) );\n  }\n\n  coeffs = coefficient_group;\n  contribs = contributors;\n\n  for (n = 0; n < num_contributors; n++)\n  {\n    int i;\n\n    // in zero edge mode, just remove out of bounds contribs completely (since their weights are accounted for now)\n    if ( edge == STBIR_EDGE_ZERO )\n    {\n      // shrink the right side if necessary\n      if ( contribs->n1 > input_last_n1 )\n        contribs->n1 = input_last_n1;\n\n      // shrink the left side\n      if ( contribs->n0 < 0 )\n      {\n        int j, left, skips = 0;\n\n        skips = -contribs->n0;\n        contribs->n0 = 0;\n\n        // now move down the weights\n        left = contribs->n1 - contribs->n0 + 1;\n        if ( left > 0 )\n        {\n          for( j = 0 ; j < left ; j++ )\n            coeffs[ j ] = coeffs[ j + skips ];\n        }\n      }\n    }\n    else if ( ( edge == STBIR_EDGE_CLAMP ) || ( edge == STBIR_EDGE_REFLECT ) )\n    {\n      // for clamp and reflect, calculate the true inbounds position (based on edge type) and just add that to the existing weight\n\n      // right hand side first\n      if ( contribs->n1 > input_last_n1 )\n      {\n        int start = contribs->n0;\n        int endi = contribs->n1;\n        contribs->n1 = input_last_n1;\n        for( i = input_size; i <= endi; i++ )\n          stbir__insert_coeff( contribs, coeffs, stbir__edge_wrap_slow[edge]( i, input_size ), coeffs[i-start], coefficient_width );\n      }\n\n      // now check left hand edge\n      if ( contribs->n0 < 0 )\n      {\n        int save_n0;\n        float save_n0_coeff;\n        float * c = coeffs - ( contribs->n0 + 1 );\n\n        // reinsert the coeffs with it reflected or clamped (insert accumulates, if the coeffs exist)\n        for( i = -1 ; i > contribs->n0 ; i-- )\n          stbir__insert_coeff( contribs, coeffs, stbir__edge_wrap_slow[edge]( i, input_size ), *c--, coefficient_width );\n        save_n0 = contribs->n0;\n        save_n0_coeff = c[0]; // save it, since we didn't do the final one (i==n0), because there might be too many coeffs to hold (before we resize)!\n\n        // now slide all the coeffs down (since we have accumulated them in the positive contribs) and reset the first contrib\n        contribs->n0 = 0;\n        for(i = 0 ; i <= contribs->n1 ; i++ )\n          coeffs[i] = coeffs[i-save_n0];\n\n        // now that we have shrunk down the contribs, we insert the first one safely\n        stbir__insert_coeff( contribs, coeffs, stbir__edge_wrap_slow[edge]( save_n0, input_size ), save_n0_coeff, coefficient_width );\n      }\n    }\n\n    if ( contribs->n0 <= contribs->n1 )\n    {\n      int diff = contribs->n1 - contribs->n0 + 1;\n      while ( diff && ( coeffs[ diff-1 ] == 0.0f ) )\n        --diff;\n\n      contribs->n1 = contribs->n0 + diff - 1;\n\n      if ( contribs->n0 <= contribs->n1 )\n      {\n        if ( contribs->n0 < lowest )\n          lowest = contribs->n0;\n        if ( contribs->n1 > highest )\n          highest = contribs->n1;\n        if ( diff > widest )\n          widest = diff;\n      }\n\n      // re-zero out unused coefficients (if any)\n      for( i = diff ; i < coefficient_width ; i++ )\n        coeffs[i] = 0.0f;\n    }\n\n    ++contribs;\n    coeffs += coefficient_width;\n  }\n  filter_info->lowest = lowest;\n  filter_info->highest = highest;\n  filter_info->widest = widest;\n}\n\n#undef STBIR_RENORM_TYPE \n\nstatic int stbir__pack_coefficients( int num_contributors, stbir__contributors* contributors, float * coefficents, int coefficient_width, int widest, int row0, int row1 ) \n{\n  #define STBIR_MOVE_1( dest, src ) { STBIR_NO_UNROLL(dest); ((stbir_uint32*)(dest))[0] = ((stbir_uint32*)(src))[0]; }\n  #define STBIR_MOVE_2( dest, src ) { STBIR_NO_UNROLL(dest); ((stbir_uint64*)(dest))[0] = ((stbir_uint64*)(src))[0]; }\n  #ifdef STBIR_SIMD\n  #define STBIR_MOVE_4( dest, src ) { stbir__simdf t; STBIR_NO_UNROLL(dest); stbir__simdf_load( t, src ); stbir__simdf_store( dest, t ); }\n  #else\n  #define STBIR_MOVE_4( dest, src ) { STBIR_NO_UNROLL(dest); ((stbir_uint64*)(dest))[0] = ((stbir_uint64*)(src))[0]; ((stbir_uint64*)(dest))[1] = ((stbir_uint64*)(src))[1]; }\n  #endif\n\n  int row_end = row1 + 1;\n  STBIR__UNUSED( row0 ); // only used in an assert\n\n  if ( coefficient_width != widest )\n  {\n    float * pc = coefficents;\n    float * coeffs = coefficents;\n    float * pc_end = coefficents + num_contributors * widest;\n    switch( widest )\n    {\n      case 1:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_1( pc, coeffs );\n          ++pc;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 2:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_2( pc, coeffs );\n          pc += 2;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 3:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_2( pc, coeffs );\n          STBIR_MOVE_1( pc+2, coeffs+2 );\n          pc += 3;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 4:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          pc += 4;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 5:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_1( pc+4, coeffs+4 );\n          pc += 5;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 6:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_2( pc+4, coeffs+4 );\n          pc += 6;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 7:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_2( pc+4, coeffs+4 );\n          STBIR_MOVE_1( pc+6, coeffs+6 );\n          pc += 7;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 8:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_4( pc+4, coeffs+4 );\n          pc += 8;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 9:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_4( pc+4, coeffs+4 );\n          STBIR_MOVE_1( pc+8, coeffs+8 );\n          pc += 9;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 10:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_4( pc+4, coeffs+4 );\n          STBIR_MOVE_2( pc+8, coeffs+8 );\n          pc += 10;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 11:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_4( pc+4, coeffs+4 );\n          STBIR_MOVE_2( pc+8, coeffs+8 );\n          STBIR_MOVE_1( pc+10, coeffs+10 );\n          pc += 11;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      case 12:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          STBIR_MOVE_4( pc, coeffs );\n          STBIR_MOVE_4( pc+4, coeffs+4 );\n          STBIR_MOVE_4( pc+8, coeffs+8 );\n          pc += 12;\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n      default:\n        STBIR_NO_UNROLL_LOOP_START\n        do {\n          float * copy_end = pc + widest - 4;\n          float * c = coeffs;\n          do {\n            STBIR_NO_UNROLL( pc );\n            STBIR_MOVE_4( pc, c );\n            pc += 4;\n            c += 4;\n          } while ( pc <= copy_end );\n          copy_end += 4;\n          STBIR_NO_UNROLL_LOOP_START\n          while ( pc < copy_end )\n          {\n            STBIR_MOVE_1( pc, c );\n            ++pc; ++c;\n          }\n          coeffs += coefficient_width;\n        } while ( pc < pc_end );\n        break;\n    }\n  }\n\n  // some horizontal routines read one float off the end (which is then masked off), so put in a sentinel so we don't read an snan or denormal\n  coefficents[ widest * num_contributors ] = 8888.0f;\n\n  // the minimum we might read for unrolled filters widths is 12. So, we need to\n  //   make sure we never read outside the decode buffer, by possibly moving\n  //   the sample area back into the scanline, and putting zeros weights first.\n  // we start on the right edge and check until we're well past the possible\n  //   clip area (2*widest).\n  {\n    stbir__contributors * contribs = contributors + num_contributors - 1;\n    float * coeffs = coefficents + widest * ( num_contributors - 1 );\n\n    // go until no chance of clipping (this is usually less than 8 lops)\n    while ( ( contribs >= contributors ) && ( ( contribs->n0 + widest*2 ) >= row_end ) )\n    {\n      // might we clip??\n      if ( ( contribs->n0 + widest ) > row_end )\n      {\n        int stop_range = widest;\n\n        // if range is larger than 12, it will be handled by generic loops that can terminate on the exact length\n        //   of this contrib n1, instead of a fixed widest amount - so calculate this\n        if ( widest > 12 )\n        {\n          int mod;\n\n          // how far will be read in the n_coeff loop (which depends on the widest count mod4);\n          mod = widest & 3;\n          stop_range = ( ( ( contribs->n1 - contribs->n0 + 1 ) - mod + 3 ) & ~3 ) + mod;\n\n          // the n_coeff loops do a minimum amount of coeffs, so factor that in!\n          if ( stop_range < ( 8 + mod ) ) stop_range = 8 + mod;\n        }\n\n        // now see if we still clip with the refined range\n        if ( ( contribs->n0 + stop_range ) > row_end )\n        {\n          int new_n0 = row_end - stop_range;\n          int num = contribs->n1 - contribs->n0 + 1;\n          int backup = contribs->n0 - new_n0;\n          float * from_co = coeffs + num - 1;\n          float * to_co = from_co + backup;\n\n          STBIR_ASSERT( ( new_n0 >= row0 ) && ( new_n0 < contribs->n0 ) );\n\n          // move the coeffs over\n          while( num )\n          {\n            *to_co-- = *from_co--;\n            --num;\n          }\n          // zero new positions\n          while ( to_co >= coeffs )\n            *to_co-- = 0;\n          // set new start point\n          contribs->n0 = new_n0;\n          if ( widest > 12 )\n          {\n            int mod;\n\n            // how far will be read in the n_coeff loop (which depends on the widest count mod4);\n            mod = widest & 3;\n            stop_range = ( ( ( contribs->n1 - contribs->n0 + 1 ) - mod + 3 ) & ~3 ) + mod;\n\n            // the n_coeff loops do a minimum amount of coeffs, so factor that in!\n            if ( stop_range < ( 8 + mod ) ) stop_range = 8 + mod;\n          }\n        }\n      }\n      --contribs;\n      coeffs -= widest;\n    }\n  }\n\n  return widest;\n  #undef STBIR_MOVE_1\n  #undef STBIR_MOVE_2\n  #undef STBIR_MOVE_4\n}\n\nstatic void stbir__calculate_filters( stbir__sampler * samp, stbir__sampler * other_axis_for_pivot, void * user_data STBIR_ONLY_PROFILE_BUILD_GET_INFO )\n{\n  int n;\n  float scale = samp->scale_info.scale;\n  stbir__kernel_callback * kernel = samp->filter_kernel;\n  stbir__support_callback * support = samp->filter_support;\n  float inv_scale = samp->scale_info.inv_scale;\n  int input_full_size = samp->scale_info.input_full_size;\n  int gather_num_contributors = samp->num_contributors;\n  stbir__contributors* gather_contributors = samp->contributors;\n  float * gather_coeffs = samp->coefficients;\n  int gather_coefficient_width = samp->coefficient_width;\n\n  switch ( samp->is_gather )\n  {\n    case 1: // gather upsample\n    {\n      float out_pixels_radius = support(inv_scale,user_data) * scale;\n\n      stbir__calculate_coefficients_for_gather_upsample( out_pixels_radius, kernel, &samp->scale_info, gather_num_contributors, gather_contributors, gather_coeffs, gather_coefficient_width, samp->edge, user_data );\n\n      STBIR_PROFILE_BUILD_START( cleanup );\n      stbir__cleanup_gathered_coefficients( samp->edge, &samp->extent_info, &samp->scale_info, gather_num_contributors, gather_contributors, gather_coeffs, gather_coefficient_width );\n      STBIR_PROFILE_BUILD_END( cleanup );\n    }\n    break;\n\n    case 0: // scatter downsample (only on vertical)\n    case 2: // gather downsample\n    {\n      float in_pixels_radius = support(scale,user_data) * inv_scale;\n      int filter_pixel_margin = samp->filter_pixel_margin;\n      int input_end = input_full_size + filter_pixel_margin;\n\n      // if this is a scatter, we do a downsample gather to get the coeffs, and then pivot after\n      if ( !samp->is_gather )\n      {\n        // check if we are using the same gather downsample on the horizontal as this vertical,\n        //   if so, then we don't have to generate them, we can just pivot from the horizontal.\n        if ( other_axis_for_pivot )\n        {\n          gather_contributors = other_axis_for_pivot->contributors;\n          gather_coeffs = other_axis_for_pivot->coefficients;\n          gather_coefficient_width = other_axis_for_pivot->coefficient_width;\n          gather_num_contributors = other_axis_for_pivot->num_contributors;\n          samp->extent_info.lowest = other_axis_for_pivot->extent_info.lowest;\n          samp->extent_info.highest = other_axis_for_pivot->extent_info.highest;\n          samp->extent_info.widest = other_axis_for_pivot->extent_info.widest;\n          goto jump_right_to_pivot;\n        }\n\n        gather_contributors = samp->gather_prescatter_contributors;\n        gather_coeffs = samp->gather_prescatter_coefficients;\n        gather_coefficient_width = samp->gather_prescatter_coefficient_width;\n        gather_num_contributors = samp->gather_prescatter_num_contributors;\n      }\n\n      stbir__calculate_coefficients_for_gather_downsample( -filter_pixel_margin, input_end, in_pixels_radius, kernel, &samp->scale_info, gather_coefficient_width, gather_num_contributors, gather_contributors, gather_coeffs, user_data );\n\n      STBIR_PROFILE_BUILD_START( cleanup );\n      stbir__cleanup_gathered_coefficients( samp->edge, &samp->extent_info, &samp->scale_info, gather_num_contributors, gather_contributors, gather_coeffs, gather_coefficient_width );\n      STBIR_PROFILE_BUILD_END( cleanup );\n\n      if ( !samp->is_gather )\n      {\n        // if this is a scatter (vertical only), then we need to pivot the coeffs\n        stbir__contributors * scatter_contributors;\n        int highest_set;\n\n        jump_right_to_pivot:\n\n        STBIR_PROFILE_BUILD_START( pivot );\n\n        highest_set = (-filter_pixel_margin) - 1;\n        for (n = 0; n < gather_num_contributors; n++)\n        {\n          int k;\n          int gn0 = gather_contributors->n0, gn1 = gather_contributors->n1;\n          int scatter_coefficient_width = samp->coefficient_width;\n          float * scatter_coeffs = samp->coefficients + ( gn0 + filter_pixel_margin ) * scatter_coefficient_width;\n          float * g_coeffs = gather_coeffs;\n          scatter_contributors = samp->contributors + ( gn0 + filter_pixel_margin );\n\n          for (k = gn0 ; k <= gn1 ; k++ )\n          {\n            float gc = *g_coeffs++;\n            \n            // skip zero and denormals - must skip zeros to avoid adding coeffs beyond scatter_coefficient_width\n            //   (which happens when pivoting from horizontal, which might have dummy zeros)\n            if ( ( ( gc >= stbir__small_float ) || ( gc <= -stbir__small_float ) ) )\n            {\n              if ( ( k > highest_set ) || ( scatter_contributors->n0 > scatter_contributors->n1 ) )\n              {\n                {\n                  // if we are skipping over several contributors, we need to clear the skipped ones\n                  stbir__contributors * clear_contributors = samp->contributors + ( highest_set + filter_pixel_margin + 1);\n                  while ( clear_contributors < scatter_contributors )\n                  {\n                    clear_contributors->n0 = 0;\n                    clear_contributors->n1 = -1;\n                    ++clear_contributors;\n                  }\n                }\n                scatter_contributors->n0 = n;\n                scatter_contributors->n1 = n;\n                scatter_coeffs[0]  = gc;\n                highest_set = k;\n              }\n              else\n              {\n                stbir__insert_coeff( scatter_contributors, scatter_coeffs, n, gc, scatter_coefficient_width );\n              }\n              STBIR_ASSERT( ( scatter_contributors->n1 - scatter_contributors->n0 + 1 ) <= scatter_coefficient_width );\n            }\n            ++scatter_contributors;\n            scatter_coeffs += scatter_coefficient_width;\n          }\n\n          ++gather_contributors;\n          gather_coeffs += gather_coefficient_width;\n        }\n\n        // now clear any unset contribs\n        {\n          stbir__contributors * clear_contributors = samp->contributors + ( highest_set + filter_pixel_margin + 1);\n          stbir__contributors * end_contributors = samp->contributors + samp->num_contributors;\n          while ( clear_contributors < end_contributors )\n          {\n            clear_contributors->n0 = 0;\n            clear_contributors->n1 = -1;\n            ++clear_contributors;\n          }\n        }\n\n        STBIR_PROFILE_BUILD_END( pivot );\n      }\n    }\n    break;\n  }\n}\n\n\n//========================================================================================================\n// scanline decoders and encoders\n\n#define stbir__coder_min_num 1\n#define STB_IMAGE_RESIZE_DO_CODERS\n#include STBIR__HEADER_FILENAME\n\n#define stbir__decode_suffix BGRA\n#define stbir__decode_swizzle\n#define stbir__decode_order0  2\n#define stbir__decode_order1  1\n#define stbir__decode_order2  0\n#define stbir__decode_order3  3\n#define stbir__encode_order0  2\n#define stbir__encode_order1  1\n#define stbir__encode_order2  0\n#define stbir__encode_order3  3\n#define stbir__coder_min_num 4\n#define STB_IMAGE_RESIZE_DO_CODERS\n#include STBIR__HEADER_FILENAME\n\n#define stbir__decode_suffix ARGB\n#define stbir__decode_swizzle\n#define stbir__decode_order0  1\n#define stbir__decode_order1  2\n#define stbir__decode_order2  3\n#define stbir__decode_order3  0\n#define stbir__encode_order0  3\n#define stbir__encode_order1  0\n#define stbir__encode_order2  1\n#define stbir__encode_order3  2\n#define stbir__coder_min_num 4\n#define STB_IMAGE_RESIZE_DO_CODERS\n#include STBIR__HEADER_FILENAME\n\n#define stbir__decode_suffix ABGR\n#define stbir__decode_swizzle\n#define stbir__decode_order0  3\n#define stbir__decode_order1  2\n#define stbir__decode_order2  1\n#define stbir__decode_order3  0\n#define stbir__encode_order0  3\n#define stbir__encode_order1  2\n#define stbir__encode_order2  1\n#define stbir__encode_order3  0\n#define stbir__coder_min_num 4\n#define STB_IMAGE_RESIZE_DO_CODERS\n#include STBIR__HEADER_FILENAME\n\n#define stbir__decode_suffix AR\n#define stbir__decode_swizzle\n#define stbir__decode_order0  1\n#define stbir__decode_order1  0\n#define stbir__decode_order2  3\n#define stbir__decode_order3  2\n#define stbir__encode_order0  1\n#define stbir__encode_order1  0\n#define stbir__encode_order2  3\n#define stbir__encode_order3  2\n#define stbir__coder_min_num 2\n#define STB_IMAGE_RESIZE_DO_CODERS\n#include STBIR__HEADER_FILENAME\n\n\n// fancy alpha means we expand to keep both premultipied and non-premultiplied color channels\nstatic void stbir__fancy_alpha_weight_4ch( float * out_buffer, int width_times_channels )\n{\n  float STBIR_STREAMOUT_PTR(*) out = out_buffer;\n  float const * end_decode = out_buffer + ( width_times_channels / 4 ) * 7;  // decode buffer aligned to end of out_buffer\n  float STBIR_STREAMOUT_PTR(*) decode = (float*)end_decode - width_times_channels;\n\n  // fancy alpha is stored internally as R G B A Rpm Gpm Bpm\n\n  #ifdef STBIR_SIMD\n\n  #ifdef STBIR_SIMD8\n  decode += 16;\n  STBIR_NO_UNROLL_LOOP_START\n  while ( decode <= end_decode )\n  {\n    stbir__simdf8 d0,d1,a0,a1,p0,p1;\n    STBIR_NO_UNROLL(decode);\n    stbir__simdf8_load( d0, decode-16 );\n    stbir__simdf8_load( d1, decode-16+8 );\n    stbir__simdf8_0123to33333333( a0, d0 );\n    stbir__simdf8_0123to33333333( a1, d1 );\n    stbir__simdf8_mult( p0, a0, d0 );\n    stbir__simdf8_mult( p1, a1, d1 );\n    stbir__simdf8_bot4s( a0, d0, p0 );\n    stbir__simdf8_bot4s( a1, d1, p1 );\n    stbir__simdf8_top4s( d0, d0, p0 );\n    stbir__simdf8_top4s( d1, d1, p1 );\n    stbir__simdf8_store ( out, a0 );\n    stbir__simdf8_store ( out+7, d0 );\n    stbir__simdf8_store ( out+14, a1 );\n    stbir__simdf8_store ( out+21, d1 );\n    decode += 16;\n    out += 28;\n  }\n  decode -= 16;\n  #else\n  decode += 8;\n  STBIR_NO_UNROLL_LOOP_START\n  while ( decode <= end_decode )\n  {\n    stbir__simdf d0,a0,d1,a1,p0,p1;\n    STBIR_NO_UNROLL(decode);\n    stbir__simdf_load( d0, decode-8 );\n    stbir__simdf_load( d1, decode-8+4 );\n    stbir__simdf_0123to3333( a0, d0 );\n    stbir__simdf_0123to3333( a1, d1 );\n    stbir__simdf_mult( p0, a0, d0 );\n    stbir__simdf_mult( p1, a1, d1 );\n    stbir__simdf_store ( out, d0 );\n    stbir__simdf_store ( out+4, p0 );\n    stbir__simdf_store ( out+7, d1 );\n    stbir__simdf_store ( out+7+4, p1 );\n    decode += 8;\n    out += 14;\n  }\n  decode -= 8;\n  #endif\n\n  // might be one last odd pixel\n  #ifdef STBIR_SIMD8\n  STBIR_NO_UNROLL_LOOP_START\n  while ( decode < end_decode )\n  #else\n  if ( decode < end_decode )\n  #endif\n  {\n    stbir__simdf d,a,p;\n    STBIR_NO_UNROLL(decode);\n    stbir__simdf_load( d, decode );\n    stbir__simdf_0123to3333( a, d );\n    stbir__simdf_mult( p, a, d );\n    stbir__simdf_store ( out, d );\n    stbir__simdf_store ( out+4, p );\n    decode += 4;\n    out += 7;\n  }\n\n  #else\n\n  while( decode < end_decode )\n  {\n    float r = decode[0], g = decode[1], b = decode[2], alpha = decode[3];\n    out[0] = r;\n    out[1] = g;\n    out[2] = b;\n    out[3] = alpha;\n    out[4] = r * alpha;\n    out[5] = g * alpha;\n    out[6] = b * alpha;\n    out += 7;\n    decode += 4;\n  }\n\n  #endif\n}\n\nstatic void stbir__fancy_alpha_weight_2ch( float * out_buffer, int width_times_channels )\n{\n  float STBIR_STREAMOUT_PTR(*) out = out_buffer;\n  float const * end_decode = out_buffer + ( width_times_channels / 2 ) * 3;\n  float STBIR_STREAMOUT_PTR(*) decode = (float*)end_decode - width_times_channels;\n\n  //  for fancy alpha, turns into: [X A Xpm][X A Xpm],etc\n\n  #ifdef STBIR_SIMD\n\n  decode += 8;\n  if ( decode <= end_decode )\n  {\n    STBIR_NO_UNROLL_LOOP_START\n    do {\n      #ifdef STBIR_SIMD8\n      stbir__simdf8 d0,a0,p0;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdf8_load( d0, decode-8 );\n      stbir__simdf8_0123to11331133( p0, d0 );\n      stbir__simdf8_0123to00220022( a0, d0 );\n      stbir__simdf8_mult( p0, p0, a0 );\n\n      stbir__simdf_store2( out, stbir__if_simdf8_cast_to_simdf4( d0 ) );\n      stbir__simdf_store( out+2, stbir__if_simdf8_cast_to_simdf4( p0 ) );\n      stbir__simdf_store2h( out+3, stbir__if_simdf8_cast_to_simdf4( d0 ) );\n\n      stbir__simdf_store2( out+6, stbir__simdf8_gettop4( d0 ) );\n      stbir__simdf_store( out+8, stbir__simdf8_gettop4( p0 ) );\n      stbir__simdf_store2h( out+9, stbir__simdf8_gettop4( d0 ) );\n      #else\n      stbir__simdf d0,a0,d1,a1,p0,p1;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdf_load( d0, decode-8 );\n      stbir__simdf_load( d1, decode-8+4 );\n      stbir__simdf_0123to1133( p0, d0 );\n      stbir__simdf_0123to1133( p1, d1 );\n      stbir__simdf_0123to0022( a0, d0 );\n      stbir__simdf_0123to0022( a1, d1 );\n      stbir__simdf_mult( p0, p0, a0 );\n      stbir__simdf_mult( p1, p1, a1 );\n\n      stbir__simdf_store2( out, d0 );\n      stbir__simdf_store( out+2, p0 );\n      stbir__simdf_store2h( out+3, d0 );\n\n      stbir__simdf_store2( out+6, d1 );\n      stbir__simdf_store( out+8, p1 );\n      stbir__simdf_store2h( out+9, d1 );\n      #endif\n      decode += 8;\n      out += 12;\n    } while ( decode <= end_decode );\n  }\n  decode -= 8;\n  #endif\n\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode < end_decode )\n  {\n    float x = decode[0], y = decode[1];\n    STBIR_SIMD_NO_UNROLL(decode);\n    out[0] = x;\n    out[1] = y;\n    out[2] = x * y;\n    out += 3;\n    decode += 2;\n  }\n}\n\nstatic void stbir__fancy_alpha_unweight_4ch( float * encode_buffer, int width_times_channels )\n{\n  float STBIR_SIMD_STREAMOUT_PTR(*) encode = encode_buffer;\n  float STBIR_SIMD_STREAMOUT_PTR(*) input = encode_buffer;\n  float const * end_output = encode_buffer + width_times_channels;\n\n  // fancy RGBA is stored internally as R G B A Rpm Gpm Bpm\n\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float alpha = input[3];\n#ifdef STBIR_SIMD\n    stbir__simdf i,ia;\n    STBIR_SIMD_NO_UNROLL(encode);\n    if ( alpha < stbir__small_float )\n    {\n      stbir__simdf_load( i, input );\n      stbir__simdf_store( encode, i );\n    }\n    else\n    {\n      stbir__simdf_load1frep4( ia, 1.0f / alpha );\n      stbir__simdf_load( i, input+4 );\n      stbir__simdf_mult( i, i, ia );\n      stbir__simdf_store( encode, i );\n      encode[3] = alpha;\n    }\n#else\n    if ( alpha < stbir__small_float )\n    {\n      encode[0] = input[0];\n      encode[1] = input[1];\n      encode[2] = input[2];\n    }\n    else\n    {\n      float ialpha = 1.0f / alpha;\n      encode[0] = input[4] * ialpha;\n      encode[1] = input[5] * ialpha;\n      encode[2] = input[6] * ialpha;\n    }\n    encode[3] = alpha;\n#endif\n\n    input += 7;\n    encode += 4;\n  } while ( encode < end_output );\n}\n\n//  format: [X A Xpm][X A Xpm] etc\nstatic void stbir__fancy_alpha_unweight_2ch( float * encode_buffer, int width_times_channels )\n{\n  float STBIR_SIMD_STREAMOUT_PTR(*) encode = encode_buffer;\n  float STBIR_SIMD_STREAMOUT_PTR(*) input = encode_buffer;\n  float const * end_output = encode_buffer + width_times_channels;\n\n  do {\n    float alpha = input[1];\n    encode[0] = input[0];\n    if ( alpha >= stbir__small_float )\n      encode[0] = input[2] / alpha;\n    encode[1] = alpha;\n\n    input += 3;\n    encode += 2;\n  } while ( encode < end_output );\n}\n\nstatic void stbir__simple_alpha_weight_4ch( float * decode_buffer, int width_times_channels )\n{\n  float STBIR_STREAMOUT_PTR(*) decode = decode_buffer;\n  float const * end_decode = decode_buffer + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  {\n    decode += 2 * stbir__simdfX_float_count;\n    STBIR_NO_UNROLL_LOOP_START\n    while ( decode <= end_decode )\n    {\n      stbir__simdfX d0,a0,d1,a1;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdfX_load( d0, decode-2*stbir__simdfX_float_count );\n      stbir__simdfX_load( d1, decode-2*stbir__simdfX_float_count+stbir__simdfX_float_count );\n      stbir__simdfX_aaa1( a0, d0, STBIR_onesX );\n      stbir__simdfX_aaa1( a1, d1, STBIR_onesX );\n      stbir__simdfX_mult( d0, d0, a0 );\n      stbir__simdfX_mult( d1, d1, a1 );\n      stbir__simdfX_store ( decode-2*stbir__simdfX_float_count, d0 );\n      stbir__simdfX_store ( decode-2*stbir__simdfX_float_count+stbir__simdfX_float_count, d1 );\n      decode += 2 * stbir__simdfX_float_count;\n    }\n    decode -= 2 * stbir__simdfX_float_count;\n\n    // few last pixels remnants\n    #ifdef STBIR_SIMD8\n    STBIR_NO_UNROLL_LOOP_START\n    while ( decode < end_decode )\n    #else\n    if ( decode < end_decode )\n    #endif\n    {\n      stbir__simdf d,a;\n      stbir__simdf_load( d, decode );\n      stbir__simdf_aaa1( a, d, STBIR__CONSTF(STBIR_ones) );\n      stbir__simdf_mult( d, d, a );\n      stbir__simdf_store ( decode, d );\n      decode += 4;\n    }\n  }\n\n  #else\n\n  while( decode < end_decode )\n  {\n    float alpha = decode[3];\n    decode[0] *= alpha;\n    decode[1] *= alpha;\n    decode[2] *= alpha;\n    decode += 4;\n  }\n\n  #endif\n}\n\nstatic void stbir__simple_alpha_weight_2ch( float * decode_buffer, int width_times_channels )\n{\n  float STBIR_STREAMOUT_PTR(*) decode = decode_buffer;\n  float const * end_decode = decode_buffer + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  decode += 2 * stbir__simdfX_float_count;\n  STBIR_NO_UNROLL_LOOP_START\n  while ( decode <= end_decode )\n  {\n    stbir__simdfX d0,a0,d1,a1;\n    STBIR_NO_UNROLL(decode);\n    stbir__simdfX_load( d0, decode-2*stbir__simdfX_float_count );\n    stbir__simdfX_load( d1, decode-2*stbir__simdfX_float_count+stbir__simdfX_float_count );\n    stbir__simdfX_a1a1( a0, d0, STBIR_onesX );\n    stbir__simdfX_a1a1( a1, d1, STBIR_onesX );\n    stbir__simdfX_mult( d0, d0, a0 );\n    stbir__simdfX_mult( d1, d1, a1 );\n    stbir__simdfX_store ( decode-2*stbir__simdfX_float_count, d0 );\n    stbir__simdfX_store ( decode-2*stbir__simdfX_float_count+stbir__simdfX_float_count, d1 );\n    decode += 2 * stbir__simdfX_float_count;\n  }\n  decode -= 2 * stbir__simdfX_float_count;\n  #endif\n\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode < end_decode )\n  {\n    float alpha = decode[1];\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0] *= alpha;\n    decode += 2;\n  }\n}\n\nstatic void stbir__simple_alpha_unweight_4ch( float * encode_buffer, int width_times_channels )\n{\n  float STBIR_SIMD_STREAMOUT_PTR(*) encode = encode_buffer;\n  float const * end_output = encode_buffer + width_times_channels;\n\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float alpha = encode[3];\n\n#ifdef STBIR_SIMD\n    stbir__simdf i,ia;\n    STBIR_SIMD_NO_UNROLL(encode);\n    if ( alpha >= stbir__small_float )\n    {\n      stbir__simdf_load1frep4( ia, 1.0f / alpha );\n      stbir__simdf_load( i, encode );\n      stbir__simdf_mult( i, i, ia );\n      stbir__simdf_store( encode, i );\n      encode[3] = alpha;\n    }\n#else\n    if ( alpha >= stbir__small_float )\n    {\n      float ialpha = 1.0f / alpha;\n      encode[0] *= ialpha;\n      encode[1] *= ialpha;\n      encode[2] *= ialpha;\n    }\n#endif\n    encode += 4;\n  } while ( encode < end_output );\n}\n\nstatic void stbir__simple_alpha_unweight_2ch( float * encode_buffer, int width_times_channels )\n{\n  float STBIR_SIMD_STREAMOUT_PTR(*) encode = encode_buffer;\n  float const * end_output = encode_buffer + width_times_channels;\n\n  do {\n    float alpha = encode[1];\n    if ( alpha >= stbir__small_float )\n      encode[0] /= alpha;\n    encode += 2;\n  } while ( encode < end_output );\n}\n\n\n// only used in RGB->BGR or BGR->RGB\nstatic void stbir__simple_flip_3ch( float * decode_buffer, int width_times_channels )\n{\n  float STBIR_STREAMOUT_PTR(*) decode = decode_buffer;\n  float const * end_decode = decode_buffer + width_times_channels;\n\n#ifdef STBIR_SIMD\n    #ifdef stbir__simdf_swiz2 // do we have two argument swizzles?\n      end_decode -= 12; \n      STBIR_NO_UNROLL_LOOP_START\n      while( decode <= end_decode )\n      {\n        // on arm64 8 instructions, no overlapping stores\n        stbir__simdf a,b,c,na,nb;\n        STBIR_SIMD_NO_UNROLL(decode);\n        stbir__simdf_load( a, decode );\n        stbir__simdf_load( b, decode+4 );\n        stbir__simdf_load( c, decode+8 );\n\n        na = stbir__simdf_swiz2( a, b, 2, 1, 0, 5 );   \n        b  = stbir__simdf_swiz2( a, b, 4, 3, 6, 7 );   \n        nb = stbir__simdf_swiz2( b, c, 0, 1, 4, 3 );   \n        c  = stbir__simdf_swiz2( b, c, 2, 7, 6, 5 );   \n\n        stbir__simdf_store( decode, na );\n        stbir__simdf_store( decode+4, nb ); \n        stbir__simdf_store( decode+8, c );\n        decode += 12;\n      }\n      end_decode += 12;\n    #else\n      end_decode -= 24;\n      STBIR_NO_UNROLL_LOOP_START\n      while( decode <= end_decode )\n      {\n        // 26 instructions on x64\n        stbir__simdf a,b,c,d,e,f,g;\n        float i21, i23;\n        STBIR_SIMD_NO_UNROLL(decode);\n        stbir__simdf_load( a, decode );\n        stbir__simdf_load( b, decode+3 );\n        stbir__simdf_load( c, decode+6 );\n        stbir__simdf_load( d, decode+9 );\n        stbir__simdf_load( e, decode+12 );\n        stbir__simdf_load( f, decode+15 );\n        stbir__simdf_load( g, decode+18 );\n\n        a = stbir__simdf_swiz( a, 2, 1, 0, 3 );   \n        b = stbir__simdf_swiz( b, 2, 1, 0, 3 );   \n        c = stbir__simdf_swiz( c, 2, 1, 0, 3 );   \n        d = stbir__simdf_swiz( d, 2, 1, 0, 3 );   \n        e = stbir__simdf_swiz( e, 2, 1, 0, 3 );   \n        f = stbir__simdf_swiz( f, 2, 1, 0, 3 );   \n        g = stbir__simdf_swiz( g, 2, 1, 0, 3 );   \n\n        // stores overlap, need to be in order, \n        stbir__simdf_store( decode,    a );\n        i21 = decode[21];\n        stbir__simdf_store( decode+3,  b ); \n        i23 = decode[23];\n        stbir__simdf_store( decode+6,  c );\n        stbir__simdf_store( decode+9,  d );\n        stbir__simdf_store( decode+12, e );\n        stbir__simdf_store( decode+15, f );\n        stbir__simdf_store( decode+18, g );\n        decode[21] = i23;\n        decode[23] = i21;\n        decode += 24;\n      }\n      end_decode += 24;\n    #endif\n#else\n  end_decode -= 12;\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode <= end_decode )\n  {\n    // 16 instructions\n    float t0,t1,t2,t3;\n    STBIR_NO_UNROLL(decode);\n    t0 = decode[0]; t1 = decode[3]; t2 = decode[6]; t3 = decode[9];\n    decode[0] = decode[2]; decode[3] = decode[5]; decode[6] = decode[8]; decode[9] = decode[11];\n    decode[2] = t0; decode[5] = t1; decode[8] = t2; decode[11] = t3;\n    decode += 12;\n  }\n  end_decode += 12;\n#endif\n\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < end_decode )\n  {\n    float t = decode[0];\n    STBIR_NO_UNROLL(decode);\n    decode[0] = decode[2];\n    decode[2] = t;\n    decode += 3;\n  }\n}\n\n\n\nstatic void stbir__decode_scanline(stbir__info const * stbir_info, int n, float * output_buffer STBIR_ONLY_PROFILE_GET_SPLIT_INFO )\n{\n  int channels = stbir_info->channels;\n  int effective_channels = stbir_info->effective_channels;\n  int input_sample_in_bytes = stbir__type_size[stbir_info->input_type] * channels;\n  stbir_edge edge_horizontal = stbir_info->horizontal.edge;\n  stbir_edge edge_vertical = stbir_info->vertical.edge;\n  int row = stbir__edge_wrap(edge_vertical, n, stbir_info->vertical.scale_info.input_full_size);\n  const void* input_plane_data = ( (char *) stbir_info->input_data ) + (size_t)row * (size_t) stbir_info->input_stride_bytes;\n  stbir__span const * spans = stbir_info->scanline_extents.spans;\n  float * full_decode_buffer = output_buffer - stbir_info->scanline_extents.conservative.n0 * effective_channels;\n  float * last_decoded = 0;\n\n  // if we are on edge_zero, and we get in here with an out of bounds n, then the calculate filters has failed\n  STBIR_ASSERT( !(edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->vertical.scale_info.input_full_size)) );\n\n  do\n  {\n    float * decode_buffer;\n    void const * input_data;\n    float * end_decode;\n    int width_times_channels;\n    int width;\n\n    if ( spans->n1 < spans->n0 )\n      break;\n\n    width = spans->n1 + 1 - spans->n0;\n    decode_buffer = full_decode_buffer + spans->n0 * effective_channels;\n    end_decode = full_decode_buffer + ( spans->n1 + 1 ) * effective_channels;\n    width_times_channels = width * channels;\n\n    // read directly out of input plane by default\n    input_data = ( (char*)input_plane_data ) + spans->pixel_offset_for_input * input_sample_in_bytes;\n\n    // if we have an input callback, call it to get the input data\n    if ( stbir_info->in_pixels_cb )\n    {\n      // call the callback with a temp buffer (that they can choose to use or not).  the temp is just right aligned memory in the decode_buffer itself\n      input_data = stbir_info->in_pixels_cb( ( (char*) end_decode ) - ( width * input_sample_in_bytes ) + ( ( stbir_info->input_type != STBIR_TYPE_FLOAT ) ? ( sizeof(float)*STBIR_INPUT_CALLBACK_PADDING ) : 0 ), input_plane_data, width, spans->pixel_offset_for_input, row, stbir_info->user_data );\n    }\n\n    STBIR_PROFILE_START( decode );\n    // convert the pixels info the float decode_buffer, (we index from end_decode, so that when channels<effective_channels, we are right justified in the buffer)\n    last_decoded = stbir_info->decode_pixels( (float*)end_decode - width_times_channels, width_times_channels, input_data );\n    STBIR_PROFILE_END( decode );\n\n    if (stbir_info->alpha_weight)\n    {\n      STBIR_PROFILE_START( alpha );\n      stbir_info->alpha_weight( decode_buffer, width_times_channels );\n      STBIR_PROFILE_END( alpha );\n    }\n\n    ++spans;\n  } while ( spans <= ( &stbir_info->scanline_extents.spans[1] ) );\n\n  // handle the edge_wrap filter (all other types are handled back out at the calculate_filter stage)\n  // basically the idea here is that if we have the whole scanline in memory, we don't redecode the\n  //   wrapped edge pixels, and instead just memcpy them from the scanline into the edge positions\n  if ( ( edge_horizontal == STBIR_EDGE_WRAP ) && ( stbir_info->scanline_extents.edge_sizes[0] | stbir_info->scanline_extents.edge_sizes[1] ) )\n  {\n    // this code only runs if we're in edge_wrap, and we're doing the entire scanline\n    int e, start_x[2];\n    int input_full_size = stbir_info->horizontal.scale_info.input_full_size;\n\n    start_x[0] = -stbir_info->scanline_extents.edge_sizes[0];  // left edge start x\n    start_x[1] =  input_full_size;                             // right edge\n\n    for( e = 0; e < 2 ; e++ )\n    {\n      // do each margin\n      int margin = stbir_info->scanline_extents.edge_sizes[e];\n      if ( margin )\n      {\n        int x = start_x[e];\n        float * marg = full_decode_buffer + x * effective_channels;\n        float const * src = full_decode_buffer + stbir__edge_wrap(edge_horizontal, x, input_full_size) * effective_channels;\n        STBIR_MEMCPY( marg, src, margin * effective_channels * sizeof(float) );\n        if ( e == 1 ) last_decoded = marg + margin * effective_channels;\n      }\n    }\n  }\n  \n  // some of the horizontal gathers read one float off the edge (which is masked out), but we force a zero here to make sure no NaNs leak in\n  //   (we can't pre-zero it, because the input callback can use that area as padding)\n  last_decoded[0] = 0.0f; \n\n  // we clear this extra float, because the final output pixel filter kernel might have used one less coeff than the max filter width\n  //   when this happens, we do read that pixel from the input, so it too could be Nan, so just zero an extra one.\n  //   this fits because each scanline is padded by three floats (STBIR_INPUT_CALLBACK_PADDING)\n  last_decoded[1] = 0.0f;\n}\n\n\n//=================\n// Do 1 channel horizontal routines\n\n#ifdef STBIR_SIMD\n\n#define stbir__1_coeff_only()          \\\n    stbir__simdf tot,c;                \\\n    STBIR_SIMD_NO_UNROLL(decode);      \\\n    stbir__simdf_load1( c, hc );       \\\n    stbir__simdf_mult1_mem( tot, c, decode );\n\n#define stbir__2_coeff_only()          \\\n    stbir__simdf tot,c,d;              \\\n    STBIR_SIMD_NO_UNROLL(decode);      \\\n    stbir__simdf_load2z( c, hc );      \\\n    stbir__simdf_load2( d, decode );   \\\n    stbir__simdf_mult( tot, c, d );    \\\n    stbir__simdf_0123to1230( c, tot ); \\\n    stbir__simdf_add1( tot, tot, c );\n\n#define stbir__3_coeff_only()                  \\\n    stbir__simdf tot,c,t;                      \\\n    STBIR_SIMD_NO_UNROLL(decode);              \\\n    stbir__simdf_load( c, hc );                \\\n    stbir__simdf_mult_mem( tot, c, decode );   \\\n    stbir__simdf_0123to1230( c, tot );         \\\n    stbir__simdf_0123to2301( t, tot );         \\\n    stbir__simdf_add1( tot, tot, c );          \\\n    stbir__simdf_add1( tot, tot, t );\n\n#define stbir__store_output_tiny()                \\\n    stbir__simdf_store1( output, tot );           \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 1;\n\n#define stbir__4_coeff_start()                 \\\n    stbir__simdf tot,c;                        \\\n    STBIR_SIMD_NO_UNROLL(decode);              \\\n    stbir__simdf_load( c, hc );                \\\n    stbir__simdf_mult_mem( tot, c, decode );   \\\n\n#define stbir__4_coeff_continue_from_4( ofs )  \\\n    STBIR_SIMD_NO_UNROLL(decode);              \\\n    stbir__simdf_load( c, hc + (ofs) );        \\\n    stbir__simdf_madd_mem( tot, tot, c, decode+(ofs) );\n\n#define stbir__1_coeff_remnant( ofs )          \\\n    { stbir__simdf d;                          \\\n    stbir__simdf_load1z( c, hc + (ofs) );      \\\n    stbir__simdf_load1( d, decode + (ofs) );   \\\n    stbir__simdf_madd( tot, tot, d, c ); }\n\n#define stbir__2_coeff_remnant( ofs )          \\\n    { stbir__simdf d;                          \\\n    stbir__simdf_load2z( c, hc+(ofs) );        \\\n    stbir__simdf_load2( d, decode+(ofs) );     \\\n    stbir__simdf_madd( tot, tot, d, c ); }\n\n#define stbir__3_coeff_setup()                 \\\n    stbir__simdf mask;                         \\\n    stbir__simdf_load( mask, STBIR_mask + 3 );\n\n#define stbir__3_coeff_remnant( ofs )                  \\\n    stbir__simdf_load( c, hc+(ofs) );                  \\\n    stbir__simdf_and( c, c, mask );                    \\\n    stbir__simdf_madd_mem( tot, tot, c, decode+(ofs) );\n\n#define stbir__store_output()                     \\\n    stbir__simdf_0123to2301( c, tot );            \\\n    stbir__simdf_add( tot, tot, c );              \\\n    stbir__simdf_0123to1230( c, tot );            \\\n    stbir__simdf_add1( tot, tot, c );             \\\n    stbir__simdf_store1( output, tot );           \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 1;\n\n#else\n\n#define stbir__1_coeff_only()  \\\n    float tot;                 \\\n    tot = decode[0]*hc[0];\n\n#define stbir__2_coeff_only()  \\\n    float tot;                 \\\n    tot = decode[0] * hc[0];   \\\n    tot += decode[1] * hc[1];\n\n#define stbir__3_coeff_only()  \\\n    float tot;                 \\\n    tot = decode[0] * hc[0];   \\\n    tot += decode[1] * hc[1];  \\\n    tot += decode[2] * hc[2];\n\n#define stbir__store_output_tiny()                \\\n    output[0] = tot;                              \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 1;\n\n#define stbir__4_coeff_start()  \\\n    float tot0,tot1,tot2,tot3;  \\\n    tot0 = decode[0] * hc[0];   \\\n    tot1 = decode[1] * hc[1];   \\\n    tot2 = decode[2] * hc[2];   \\\n    tot3 = decode[3] * hc[3];\n\n#define stbir__4_coeff_continue_from_4( ofs )  \\\n    tot0 += decode[0+(ofs)] * hc[0+(ofs)];     \\\n    tot1 += decode[1+(ofs)] * hc[1+(ofs)];     \\\n    tot2 += decode[2+(ofs)] * hc[2+(ofs)];     \\\n    tot3 += decode[3+(ofs)] * hc[3+(ofs)];\n\n#define stbir__1_coeff_remnant( ofs )        \\\n    tot0 += decode[0+(ofs)] * hc[0+(ofs)];\n\n#define stbir__2_coeff_remnant( ofs )        \\\n    tot0 += decode[0+(ofs)] * hc[0+(ofs)];   \\\n    tot1 += decode[1+(ofs)] * hc[1+(ofs)];   \\\n\n#define stbir__3_coeff_remnant( ofs )        \\\n    tot0 += decode[0+(ofs)] * hc[0+(ofs)];   \\\n    tot1 += decode[1+(ofs)] * hc[1+(ofs)];   \\\n    tot2 += decode[2+(ofs)] * hc[2+(ofs)];\n\n#define stbir__store_output()                     \\\n    output[0] = (tot0+tot2)+(tot1+tot3);          \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 1;\n\n#endif\n\n#define STBIR__horizontal_channels 1\n#define STB_IMAGE_RESIZE_DO_HORIZONTALS\n#include STBIR__HEADER_FILENAME\n\n\n//=================\n// Do 2 channel horizontal routines\n\n#ifdef STBIR_SIMD\n\n#define stbir__1_coeff_only()         \\\n    stbir__simdf tot,c,d;             \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    stbir__simdf_load1z( c, hc );     \\\n    stbir__simdf_0123to0011( c, c );  \\\n    stbir__simdf_load2( d, decode );  \\\n    stbir__simdf_mult( tot, d, c );\n\n#define stbir__2_coeff_only()         \\\n    stbir__simdf tot,c;               \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    stbir__simdf_load2( c, hc );      \\\n    stbir__simdf_0123to0011( c, c );  \\\n    stbir__simdf_mult_mem( tot, c, decode );\n\n#define stbir__3_coeff_only()                \\\n    stbir__simdf tot,c,cs,d;                 \\\n    STBIR_SIMD_NO_UNROLL(decode);            \\\n    stbir__simdf_load( cs, hc );             \\\n    stbir__simdf_0123to0011( c, cs );        \\\n    stbir__simdf_mult_mem( tot, c, decode ); \\\n    stbir__simdf_0123to2222( c, cs );        \\\n    stbir__simdf_load2z( d, decode+4 );      \\\n    stbir__simdf_madd( tot, tot, d, c );\n\n#define stbir__store_output_tiny()                \\\n    stbir__simdf_0123to2301( c, tot );            \\\n    stbir__simdf_add( tot, tot, c );              \\\n    stbir__simdf_store2( output, tot );           \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 2;\n\n#ifdef STBIR_SIMD8\n\n#define stbir__4_coeff_start()                    \\\n    stbir__simdf8 tot0,c,cs;                      \\\n    STBIR_SIMD_NO_UNROLL(decode);                 \\\n    stbir__simdf8_load4b( cs, hc );               \\\n    stbir__simdf8_0123to00112233( c, cs );        \\\n    stbir__simdf8_mult_mem( tot0, c, decode );\n\n#define stbir__4_coeff_continue_from_4( ofs )        \\\n    STBIR_SIMD_NO_UNROLL(decode);                    \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );          \\\n    stbir__simdf8_0123to00112233( c, cs );           \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*2 );\n\n#define stbir__1_coeff_remnant( ofs )                \\\n    { stbir__simdf t,d;                              \\\n    stbir__simdf_load1z( t, hc + (ofs) );            \\\n    stbir__simdf_load2( d, decode + (ofs) * 2 );     \\\n    stbir__simdf_0123to0011( t, t );                 \\\n    stbir__simdf_mult( t, t, d );                    \\\n    stbir__simdf8_add4( tot0, tot0, t ); }\n \n#define stbir__2_coeff_remnant( ofs )                \\\n    { stbir__simdf t;                                \\\n    stbir__simdf_load2( t, hc + (ofs) );             \\\n    stbir__simdf_0123to0011( t, t );                 \\\n    stbir__simdf_mult_mem( t, t, decode+(ofs)*2 );   \\\n    stbir__simdf8_add4( tot0, tot0, t ); }\n\n#define stbir__3_coeff_remnant( ofs )                \\\n    { stbir__simdf8 d;                               \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );          \\\n    stbir__simdf8_0123to00112233( c, cs );           \\\n    stbir__simdf8_load6z( d, decode+(ofs)*2 );       \\\n    stbir__simdf8_madd( tot0, tot0, c, d ); }\n\n#define stbir__store_output()                     \\\n    { stbir__simdf t,d;                           \\\n    stbir__simdf8_add4halves( t, stbir__if_simdf8_cast_to_simdf4(tot0), tot0 );    \\\n    stbir__simdf_0123to2301( d, t );              \\\n    stbir__simdf_add( t, t, d );                  \\\n    stbir__simdf_store2( output, t );             \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 2; }\n\n#else\n\n#define stbir__4_coeff_start()                   \\\n    stbir__simdf tot0,tot1,c,cs;                 \\\n    STBIR_SIMD_NO_UNROLL(decode);                \\\n    stbir__simdf_load( cs, hc );                 \\\n    stbir__simdf_0123to0011( c, cs );            \\\n    stbir__simdf_mult_mem( tot0, c, decode );    \\\n    stbir__simdf_0123to2233( c, cs );            \\\n    stbir__simdf_mult_mem( tot1, c, decode+4 );\n\n#define stbir__4_coeff_continue_from_4( ofs )                \\\n    STBIR_SIMD_NO_UNROLL(decode);                            \\\n    stbir__simdf_load( cs, hc + (ofs) );                     \\\n    stbir__simdf_0123to0011( c, cs );                        \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*2 );  \\\n    stbir__simdf_0123to2233( c, cs );                        \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*2+4 );\n\n#define stbir__1_coeff_remnant( ofs )            \\\n    { stbir__simdf d;                            \\\n    stbir__simdf_load1z( cs, hc + (ofs) );       \\\n    stbir__simdf_0123to0011( c, cs );            \\\n    stbir__simdf_load2( d, decode + (ofs) * 2 ); \\\n    stbir__simdf_madd( tot0, tot0, d, c ); }\n\n#define stbir__2_coeff_remnant( ofs )                      \\\n    stbir__simdf_load2( cs, hc + (ofs) );                  \\\n    stbir__simdf_0123to0011( c, cs );                      \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*2 );\n\n#define stbir__3_coeff_remnant( ofs )                       \\\n    { stbir__simdf d;                                       \\\n    stbir__simdf_load( cs, hc + (ofs) );                    \\\n    stbir__simdf_0123to0011( c, cs );                       \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*2 ); \\\n    stbir__simdf_0123to2222( c, cs );                       \\\n    stbir__simdf_load2z( d, decode + (ofs) * 2 + 4 );       \\\n    stbir__simdf_madd( tot1, tot1, d, c ); }\n\n#define stbir__store_output()                     \\\n    stbir__simdf_add( tot0, tot0, tot1 );         \\\n    stbir__simdf_0123to2301( c, tot0 );           \\\n    stbir__simdf_add( tot0, tot0, c );            \\\n    stbir__simdf_store2( output, tot0 );          \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 2;\n\n#endif\n\n#else\n\n#define stbir__1_coeff_only()  \\\n    float tota,totb,c;         \\\n    c = hc[0];                 \\\n    tota = decode[0]*c;        \\\n    totb = decode[1]*c;\n\n#define stbir__2_coeff_only()  \\\n    float tota,totb,c;         \\\n    c = hc[0];                 \\\n    tota = decode[0]*c;        \\\n    totb = decode[1]*c;        \\\n    c = hc[1];                 \\\n    tota += decode[2]*c;       \\\n    totb += decode[3]*c;\n\n// this weird order of add matches the simd\n#define stbir__3_coeff_only()  \\\n    float tota,totb,c;         \\\n    c = hc[0];                 \\\n    tota = decode[0]*c;        \\\n    totb = decode[1]*c;        \\\n    c = hc[2];                 \\\n    tota += decode[4]*c;       \\\n    totb += decode[5]*c;       \\\n    c = hc[1];                 \\\n    tota += decode[2]*c;       \\\n    totb += decode[3]*c;\n\n#define stbir__store_output_tiny()                \\\n    output[0] = tota;                             \\\n    output[1] = totb;                             \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 2;\n\n#define stbir__4_coeff_start()      \\\n    float tota0,tota1,tota2,tota3,totb0,totb1,totb2,totb3,c;  \\\n    c = hc[0];                      \\\n    tota0 = decode[0]*c;            \\\n    totb0 = decode[1]*c;            \\\n    c = hc[1];                      \\\n    tota1 = decode[2]*c;            \\\n    totb1 = decode[3]*c;            \\\n    c = hc[2];                      \\\n    tota2 = decode[4]*c;            \\\n    totb2 = decode[5]*c;            \\\n    c = hc[3];                      \\\n    tota3 = decode[6]*c;            \\\n    totb3 = decode[7]*c;\n\n#define stbir__4_coeff_continue_from_4( ofs )  \\\n    c = hc[0+(ofs)];                           \\\n    tota0 += decode[0+(ofs)*2]*c;              \\\n    totb0 += decode[1+(ofs)*2]*c;              \\\n    c = hc[1+(ofs)];                           \\\n    tota1 += decode[2+(ofs)*2]*c;              \\\n    totb1 += decode[3+(ofs)*2]*c;              \\\n    c = hc[2+(ofs)];                           \\\n    tota2 += decode[4+(ofs)*2]*c;              \\\n    totb2 += decode[5+(ofs)*2]*c;              \\\n    c = hc[3+(ofs)];                           \\\n    tota3 += decode[6+(ofs)*2]*c;              \\\n    totb3 += decode[7+(ofs)*2]*c;\n\n#define stbir__1_coeff_remnant( ofs )  \\\n    c = hc[0+(ofs)];                   \\\n    tota0 += decode[0+(ofs)*2] * c;    \\\n    totb0 += decode[1+(ofs)*2] * c;\n\n#define stbir__2_coeff_remnant( ofs )  \\\n    c = hc[0+(ofs)];                   \\\n    tota0 += decode[0+(ofs)*2] * c;    \\\n    totb0 += decode[1+(ofs)*2] * c;    \\\n    c = hc[1+(ofs)];                   \\\n    tota1 += decode[2+(ofs)*2] * c;    \\\n    totb1 += decode[3+(ofs)*2] * c;\n\n#define stbir__3_coeff_remnant( ofs )  \\\n    c = hc[0+(ofs)];                   \\\n    tota0 += decode[0+(ofs)*2] * c;    \\\n    totb0 += decode[1+(ofs)*2] * c;    \\\n    c = hc[1+(ofs)];                   \\\n    tota1 += decode[2+(ofs)*2] * c;    \\\n    totb1 += decode[3+(ofs)*2] * c;    \\\n    c = hc[2+(ofs)];                   \\\n    tota2 += decode[4+(ofs)*2] * c;    \\\n    totb2 += decode[5+(ofs)*2] * c;\n\n#define stbir__store_output()                     \\\n    output[0] = (tota0+tota2)+(tota1+tota3);      \\\n    output[1] = (totb0+totb2)+(totb1+totb3);      \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 2;\n\n#endif\n\n#define STBIR__horizontal_channels 2\n#define STB_IMAGE_RESIZE_DO_HORIZONTALS\n#include STBIR__HEADER_FILENAME\n\n\n//=================\n// Do 3 channel horizontal routines\n\n#ifdef STBIR_SIMD\n\n#define stbir__1_coeff_only()         \\\n    stbir__simdf tot,c,d;             \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    stbir__simdf_load1z( c, hc );     \\\n    stbir__simdf_0123to0001( c, c );  \\\n    stbir__simdf_load( d, decode );   \\\n    stbir__simdf_mult( tot, d, c );\n\n#define stbir__2_coeff_only()         \\\n    stbir__simdf tot,c,cs,d;          \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    stbir__simdf_load2( cs, hc );     \\\n    stbir__simdf_0123to0000( c, cs ); \\\n    stbir__simdf_load( d, decode );   \\\n    stbir__simdf_mult( tot, d, c );   \\\n    stbir__simdf_0123to1111( c, cs ); \\\n    stbir__simdf_load( d, decode+3 ); \\\n    stbir__simdf_madd( tot, tot, d, c );\n\n#define stbir__3_coeff_only()            \\\n    stbir__simdf tot,c,d,cs;             \\\n    STBIR_SIMD_NO_UNROLL(decode);        \\\n    stbir__simdf_load( cs, hc );         \\\n    stbir__simdf_0123to0000( c, cs );    \\\n    stbir__simdf_load( d, decode );      \\\n    stbir__simdf_mult( tot, d, c );      \\\n    stbir__simdf_0123to1111( c, cs );    \\\n    stbir__simdf_load( d, decode+3 );    \\\n    stbir__simdf_madd( tot, tot, d, c ); \\\n    stbir__simdf_0123to2222( c, cs );    \\\n    stbir__simdf_load( d, decode+6 );    \\\n    stbir__simdf_madd( tot, tot, d, c );\n\n#define stbir__store_output_tiny()                \\\n    stbir__simdf_store2( output, tot );           \\\n    stbir__simdf_0123to2301( tot, tot );          \\\n    stbir__simdf_store1( output+2, tot );         \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 3;\n\n#ifdef STBIR_SIMD8\n\n// we're loading from the XXXYYY decode by -1 to get the XXXYYY into different halves of the AVX reg fyi\n#define stbir__4_coeff_start()                     \\\n    stbir__simdf8 tot0,tot1,c,cs; stbir__simdf t;  \\\n    STBIR_SIMD_NO_UNROLL(decode);                  \\\n    stbir__simdf8_load4b( cs, hc );                \\\n    stbir__simdf8_0123to00001111( c, cs );         \\\n    stbir__simdf8_mult_mem( tot0, c, decode - 1 ); \\\n    stbir__simdf8_0123to22223333( c, cs );         \\\n    stbir__simdf8_mult_mem( tot1, c, decode+6 - 1 );\n\n#define stbir__4_coeff_continue_from_4( ofs )      \\\n    STBIR_SIMD_NO_UNROLL(decode);                  \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );        \\\n    stbir__simdf8_0123to00001111( c, cs );         \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*3 - 1 ); \\\n    stbir__simdf8_0123to22223333( c, cs );         \\\n    stbir__simdf8_madd_mem( tot1, tot1, c, decode+(ofs)*3 + 6 - 1 );\n\n#define stbir__1_coeff_remnant( ofs )                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf_load1rep4( t, hc + (ofs) );                   \\\n    stbir__simdf8_madd_mem4( tot0, tot0, t, decode+(ofs)*3 - 1 );\n\n#define stbir__2_coeff_remnant( ofs )                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf8_load4b( cs, hc + (ofs) - 2 );                \\\n    stbir__simdf8_0123to22223333( c, cs );                     \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*3 - 1 );\n\n #define stbir__3_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                                \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );                      \\\n    stbir__simdf8_0123to00001111( c, cs );                       \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*3 - 1 ); \\\n    stbir__simdf8_0123to2222( t, cs );                           \\\n    stbir__simdf8_madd_mem4( tot1, tot1, t, decode+(ofs)*3 + 6 - 1 );\n\n#define stbir__store_output()                       \\\n    stbir__simdf8_add( tot0, tot0, tot1 );          \\\n    stbir__simdf_0123to1230( t, stbir__if_simdf8_cast_to_simdf4( tot0 ) ); \\\n    stbir__simdf8_add4halves( t, t, tot0 );         \\\n    horizontal_coefficients += coefficient_width;   \\\n    ++horizontal_contributors;                      \\\n    output += 3;                                    \\\n    if ( output < output_end )                      \\\n    {                                               \\\n      stbir__simdf_store( output-3, t );            \\\n      continue;                                     \\\n    }                                               \\\n    { stbir__simdf tt; stbir__simdf_0123to2301( tt, t ); \\\n    stbir__simdf_store2( output-3, t );             \\\n    stbir__simdf_store1( output+2-3, tt ); }        \\\n    break;\n\n\n#else\n\n#define stbir__4_coeff_start()                  \\\n    stbir__simdf tot0,tot1,tot2,c,cs;           \\\n    STBIR_SIMD_NO_UNROLL(decode);               \\\n    stbir__simdf_load( cs, hc );                \\\n    stbir__simdf_0123to0001( c, cs );           \\\n    stbir__simdf_mult_mem( tot0, c, decode );   \\\n    stbir__simdf_0123to1122( c, cs );           \\\n    stbir__simdf_mult_mem( tot1, c, decode+4 ); \\\n    stbir__simdf_0123to2333( c, cs );           \\\n    stbir__simdf_mult_mem( tot2, c, decode+8 );\n\n#define stbir__4_coeff_continue_from_4( ofs )                 \\\n    STBIR_SIMD_NO_UNROLL(decode);                             \\\n    stbir__simdf_load( cs, hc + (ofs) );                      \\\n    stbir__simdf_0123to0001( c, cs );                         \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*3 );   \\\n    stbir__simdf_0123to1122( c, cs );                         \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*3+4 ); \\\n    stbir__simdf_0123to2333( c, cs );                         \\\n    stbir__simdf_madd_mem( tot2, tot2, c, decode+(ofs)*3+8 );\n\n#define stbir__1_coeff_remnant( ofs )         \\\n    STBIR_SIMD_NO_UNROLL(decode);             \\\n    stbir__simdf_load1z( c, hc + (ofs) );     \\\n    stbir__simdf_0123to0001( c, c );          \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*3 );\n\n#define stbir__2_coeff_remnant( ofs )                       \\\n    { stbir__simdf d;                                       \\\n    STBIR_SIMD_NO_UNROLL(decode);                           \\\n    stbir__simdf_load2z( cs, hc + (ofs) );                  \\\n    stbir__simdf_0123to0001( c, cs );                       \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*3 ); \\\n    stbir__simdf_0123to1122( c, cs );                       \\\n    stbir__simdf_load2z( d, decode+(ofs)*3+4 );             \\\n    stbir__simdf_madd( tot1, tot1, c, d ); }\n\n#define stbir__3_coeff_remnant( ofs )                         \\\n    { stbir__simdf d;                                         \\\n    STBIR_SIMD_NO_UNROLL(decode);                             \\\n    stbir__simdf_load( cs, hc + (ofs) );                      \\\n    stbir__simdf_0123to0001( c, cs );                         \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*3 );   \\\n    stbir__simdf_0123to1122( c, cs );                         \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*3+4 ); \\\n    stbir__simdf_0123to2222( c, cs );                         \\\n    stbir__simdf_load1z( d, decode+(ofs)*3+8 );               \\\n    stbir__simdf_madd( tot2, tot2, c, d );  }\n\n#define stbir__store_output()                       \\\n    stbir__simdf_0123ABCDto3ABx( c, tot0, tot1 );   \\\n    stbir__simdf_0123ABCDto23Ax( cs, tot1, tot2 );  \\\n    stbir__simdf_0123to1230( tot2, tot2 );          \\\n    stbir__simdf_add( tot0, tot0, cs );             \\\n    stbir__simdf_add( c, c, tot2 );                 \\\n    stbir__simdf_add( tot0, tot0, c );              \\\n    horizontal_coefficients += coefficient_width;   \\\n    ++horizontal_contributors;                      \\\n    output += 3;                                    \\\n    if ( output < output_end )                      \\\n    {                                               \\\n      stbir__simdf_store( output-3, tot0 );         \\\n      continue;                                     \\\n    }                                               \\\n    stbir__simdf_0123to2301( tot1, tot0 );          \\\n    stbir__simdf_store2( output-3, tot0 );          \\\n    stbir__simdf_store1( output+2-3, tot1 );        \\\n    break;\n\n#endif\n\n#else\n\n#define stbir__1_coeff_only()  \\\n    float tot0, tot1, tot2, c; \\\n    c = hc[0];                 \\\n    tot0 = decode[0]*c;        \\\n    tot1 = decode[1]*c;        \\\n    tot2 = decode[2]*c;\n\n#define stbir__2_coeff_only()  \\\n    float tot0, tot1, tot2, c; \\\n    c = hc[0];                 \\\n    tot0 = decode[0]*c;        \\\n    tot1 = decode[1]*c;        \\\n    tot2 = decode[2]*c;        \\\n    c = hc[1];                 \\\n    tot0 += decode[3]*c;       \\\n    tot1 += decode[4]*c;       \\\n    tot2 += decode[5]*c;\n\n#define stbir__3_coeff_only()  \\\n    float tot0, tot1, tot2, c; \\\n    c = hc[0];                 \\\n    tot0 = decode[0]*c;        \\\n    tot1 = decode[1]*c;        \\\n    tot2 = decode[2]*c;        \\\n    c = hc[1];                 \\\n    tot0 += decode[3]*c;       \\\n    tot1 += decode[4]*c;       \\\n    tot2 += decode[5]*c;       \\\n    c = hc[2];                 \\\n    tot0 += decode[6]*c;       \\\n    tot1 += decode[7]*c;       \\\n    tot2 += decode[8]*c;\n\n#define stbir__store_output_tiny()                \\\n    output[0] = tot0;                             \\\n    output[1] = tot1;                             \\\n    output[2] = tot2;                             \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 3;\n\n#define stbir__4_coeff_start()      \\\n    float tota0,tota1,tota2,totb0,totb1,totb2,totc0,totc1,totc2,totd0,totd1,totd2,c;  \\\n    c = hc[0];                      \\\n    tota0 = decode[0]*c;            \\\n    tota1 = decode[1]*c;            \\\n    tota2 = decode[2]*c;            \\\n    c = hc[1];                      \\\n    totb0 = decode[3]*c;            \\\n    totb1 = decode[4]*c;            \\\n    totb2 = decode[5]*c;            \\\n    c = hc[2];                      \\\n    totc0 = decode[6]*c;            \\\n    totc1 = decode[7]*c;            \\\n    totc2 = decode[8]*c;            \\\n    c = hc[3];                      \\\n    totd0 = decode[9]*c;            \\\n    totd1 = decode[10]*c;           \\\n    totd2 = decode[11]*c;\n\n#define stbir__4_coeff_continue_from_4( ofs )  \\\n    c = hc[0+(ofs)];                           \\\n    tota0 += decode[0+(ofs)*3]*c;              \\\n    tota1 += decode[1+(ofs)*3]*c;              \\\n    tota2 += decode[2+(ofs)*3]*c;              \\\n    c = hc[1+(ofs)];                           \\\n    totb0 += decode[3+(ofs)*3]*c;              \\\n    totb1 += decode[4+(ofs)*3]*c;              \\\n    totb2 += decode[5+(ofs)*3]*c;              \\\n    c = hc[2+(ofs)];                           \\\n    totc0 += decode[6+(ofs)*3]*c;              \\\n    totc1 += decode[7+(ofs)*3]*c;              \\\n    totc2 += decode[8+(ofs)*3]*c;              \\\n    c = hc[3+(ofs)];                           \\\n    totd0 += decode[9+(ofs)*3]*c;              \\\n    totd1 += decode[10+(ofs)*3]*c;             \\\n    totd2 += decode[11+(ofs)*3]*c;\n\n#define stbir__1_coeff_remnant( ofs )  \\\n    c = hc[0+(ofs)];                   \\\n    tota0 += decode[0+(ofs)*3]*c;      \\\n    tota1 += decode[1+(ofs)*3]*c;      \\\n    tota2 += decode[2+(ofs)*3]*c;\n\n#define stbir__2_coeff_remnant( ofs )  \\\n    c = hc[0+(ofs)];                   \\\n    tota0 += decode[0+(ofs)*3]*c;      \\\n    tota1 += decode[1+(ofs)*3]*c;      \\\n    tota2 += decode[2+(ofs)*3]*c;      \\\n    c = hc[1+(ofs)];                   \\\n    totb0 += decode[3+(ofs)*3]*c;      \\\n    totb1 += decode[4+(ofs)*3]*c;      \\\n    totb2 += decode[5+(ofs)*3]*c;      \\\n\n#define stbir__3_coeff_remnant( ofs )  \\\n    c = hc[0+(ofs)];                   \\\n    tota0 += decode[0+(ofs)*3]*c;      \\\n    tota1 += decode[1+(ofs)*3]*c;      \\\n    tota2 += decode[2+(ofs)*3]*c;      \\\n    c = hc[1+(ofs)];                   \\\n    totb0 += decode[3+(ofs)*3]*c;      \\\n    totb1 += decode[4+(ofs)*3]*c;      \\\n    totb2 += decode[5+(ofs)*3]*c;      \\\n    c = hc[2+(ofs)];                   \\\n    totc0 += decode[6+(ofs)*3]*c;      \\\n    totc1 += decode[7+(ofs)*3]*c;      \\\n    totc2 += decode[8+(ofs)*3]*c;\n\n#define stbir__store_output()                     \\\n    output[0] = (tota0+totc0)+(totb0+totd0);      \\\n    output[1] = (tota1+totc1)+(totb1+totd1);      \\\n    output[2] = (tota2+totc2)+(totb2+totd2);      \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 3;\n\n#endif\n\n#define STBIR__horizontal_channels 3\n#define STB_IMAGE_RESIZE_DO_HORIZONTALS\n#include STBIR__HEADER_FILENAME\n\n//=================\n// Do 4 channel horizontal routines\n\n#ifdef STBIR_SIMD\n\n#define stbir__1_coeff_only()             \\\n    stbir__simdf tot,c;                   \\\n    STBIR_SIMD_NO_UNROLL(decode);         \\\n    stbir__simdf_load1( c, hc );          \\\n    stbir__simdf_0123to0000( c, c );      \\\n    stbir__simdf_mult_mem( tot, c, decode );\n\n#define stbir__2_coeff_only()                       \\\n    stbir__simdf tot,c,cs;                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                   \\\n    stbir__simdf_load2( cs, hc );                   \\\n    stbir__simdf_0123to0000( c, cs );               \\\n    stbir__simdf_mult_mem( tot, c, decode );        \\\n    stbir__simdf_0123to1111( c, cs );               \\\n    stbir__simdf_madd_mem( tot, tot, c, decode+4 );\n\n#define stbir__3_coeff_only()                       \\\n    stbir__simdf tot,c,cs;                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                   \\\n    stbir__simdf_load( cs, hc );                    \\\n    stbir__simdf_0123to0000( c, cs );               \\\n    stbir__simdf_mult_mem( tot, c, decode );        \\\n    stbir__simdf_0123to1111( c, cs );               \\\n    stbir__simdf_madd_mem( tot, tot, c, decode+4 ); \\\n    stbir__simdf_0123to2222( c, cs );               \\\n    stbir__simdf_madd_mem( tot, tot, c, decode+8 );\n\n#define stbir__store_output_tiny()                \\\n    stbir__simdf_store( output, tot );            \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 4;\n\n#ifdef STBIR_SIMD8\n\n#define stbir__4_coeff_start()                     \\\n    stbir__simdf8 tot0,c,cs; stbir__simdf t;  \\\n    STBIR_SIMD_NO_UNROLL(decode);                  \\\n    stbir__simdf8_load4b( cs, hc );                \\\n    stbir__simdf8_0123to00001111( c, cs );         \\\n    stbir__simdf8_mult_mem( tot0, c, decode );     \\\n    stbir__simdf8_0123to22223333( c, cs );         \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+8 );\n\n#define stbir__4_coeff_continue_from_4( ofs )                  \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );                    \\\n    stbir__simdf8_0123to00001111( c, cs );                     \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*4 );   \\\n    stbir__simdf8_0123to22223333( c, cs );                     \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*4+8 );\n\n#define stbir__1_coeff_remnant( ofs )                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf_load1rep4( t, hc + (ofs) );                   \\\n    stbir__simdf8_madd_mem4( tot0, tot0, t, decode+(ofs)*4 );\n\n#define stbir__2_coeff_remnant( ofs )                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf8_load4b( cs, hc + (ofs) - 2 );                \\\n    stbir__simdf8_0123to22223333( c, cs );                     \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*4 );\n\n #define stbir__3_coeff_remnant( ofs )                         \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );                    \\\n    stbir__simdf8_0123to00001111( c, cs );                     \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*4 );   \\\n    stbir__simdf8_0123to2222( t, cs );                         \\\n    stbir__simdf8_madd_mem4( tot0, tot0, t, decode+(ofs)*4+8 );\n\n#define stbir__store_output()                      \\\n    stbir__simdf8_add4halves( t, stbir__if_simdf8_cast_to_simdf4(tot0), tot0 );     \\\n    stbir__simdf_store( output, t );               \\\n    horizontal_coefficients += coefficient_width;  \\\n    ++horizontal_contributors;                     \\\n    output += 4;\n\n#else\n\n#define stbir__4_coeff_start()                        \\\n    stbir__simdf tot0,tot1,c,cs;                      \\\n    STBIR_SIMD_NO_UNROLL(decode);                     \\\n    stbir__simdf_load( cs, hc );                      \\\n    stbir__simdf_0123to0000( c, cs );                 \\\n    stbir__simdf_mult_mem( tot0, c, decode );         \\\n    stbir__simdf_0123to1111( c, cs );                 \\\n    stbir__simdf_mult_mem( tot1, c, decode+4 );       \\\n    stbir__simdf_0123to2222( c, cs );                 \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+8 ); \\\n    stbir__simdf_0123to3333( c, cs );                 \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+12 );\n\n#define stbir__4_coeff_continue_from_4( ofs )                  \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf_load( cs, hc + (ofs) );                       \\\n    stbir__simdf_0123to0000( c, cs );                          \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*4 );    \\\n    stbir__simdf_0123to1111( c, cs );                          \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*4+4 );  \\\n    stbir__simdf_0123to2222( c, cs );                          \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*4+8 );  \\\n    stbir__simdf_0123to3333( c, cs );                          \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*4+12 );\n\n#define stbir__1_coeff_remnant( ofs )                       \\\n    STBIR_SIMD_NO_UNROLL(decode);                           \\\n    stbir__simdf_load1( c, hc + (ofs) );                    \\\n    stbir__simdf_0123to0000( c, c );                        \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*4 );\n\n#define stbir__2_coeff_remnant( ofs )                         \\\n    STBIR_SIMD_NO_UNROLL(decode);                             \\\n    stbir__simdf_load2( cs, hc + (ofs) );                     \\\n    stbir__simdf_0123to0000( c, cs );                         \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*4 );   \\\n    stbir__simdf_0123to1111( c, cs );                         \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*4+4 );\n\n#define stbir__3_coeff_remnant( ofs )                          \\\n    STBIR_SIMD_NO_UNROLL(decode);                              \\\n    stbir__simdf_load( cs, hc + (ofs) );                       \\\n    stbir__simdf_0123to0000( c, cs );                          \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*4 );    \\\n    stbir__simdf_0123to1111( c, cs );                          \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*4+4 );  \\\n    stbir__simdf_0123to2222( c, cs );                          \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*4+8 );\n\n#define stbir__store_output()                     \\\n    stbir__simdf_add( tot0, tot0, tot1 );         \\\n    stbir__simdf_store( output, tot0 );           \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 4;\n\n#endif\n\n#else\n\n#define stbir__1_coeff_only()         \\\n    float p0,p1,p2,p3,c;              \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0];                        \\\n    p0 = decode[0] * c;               \\\n    p1 = decode[1] * c;               \\\n    p2 = decode[2] * c;               \\\n    p3 = decode[3] * c;\n\n#define stbir__2_coeff_only()         \\\n    float p0,p1,p2,p3,c;              \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0];                        \\\n    p0 = decode[0] * c;               \\\n    p1 = decode[1] * c;               \\\n    p2 = decode[2] * c;               \\\n    p3 = decode[3] * c;               \\\n    c = hc[1];                        \\\n    p0 += decode[4] * c;              \\\n    p1 += decode[5] * c;              \\\n    p2 += decode[6] * c;              \\\n    p3 += decode[7] * c;\n\n#define stbir__3_coeff_only()         \\\n    float p0,p1,p2,p3,c;              \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0];                        \\\n    p0 = decode[0] * c;               \\\n    p1 = decode[1] * c;               \\\n    p2 = decode[2] * c;               \\\n    p3 = decode[3] * c;               \\\n    c = hc[1];                        \\\n    p0 += decode[4] * c;              \\\n    p1 += decode[5] * c;              \\\n    p2 += decode[6] * c;              \\\n    p3 += decode[7] * c;              \\\n    c = hc[2];                        \\\n    p0 += decode[8] * c;              \\\n    p1 += decode[9] * c;              \\\n    p2 += decode[10] * c;             \\\n    p3 += decode[11] * c;\n\n#define stbir__store_output_tiny()                \\\n    output[0] = p0;                               \\\n    output[1] = p1;                               \\\n    output[2] = p2;                               \\\n    output[3] = p3;                               \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 4;\n\n#define stbir__4_coeff_start()        \\\n    float x0,x1,x2,x3,y0,y1,y2,y3,c;  \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0];                        \\\n    x0 = decode[0] * c;               \\\n    x1 = decode[1] * c;               \\\n    x2 = decode[2] * c;               \\\n    x3 = decode[3] * c;               \\\n    c = hc[1];                        \\\n    y0 = decode[4] * c;               \\\n    y1 = decode[5] * c;               \\\n    y2 = decode[6] * c;               \\\n    y3 = decode[7] * c;               \\\n    c = hc[2];                        \\\n    x0 += decode[8] * c;              \\\n    x1 += decode[9] * c;              \\\n    x2 += decode[10] * c;             \\\n    x3 += decode[11] * c;             \\\n    c = hc[3];                        \\\n    y0 += decode[12] * c;             \\\n    y1 += decode[13] * c;             \\\n    y2 += decode[14] * c;             \\\n    y3 += decode[15] * c;\n\n#define stbir__4_coeff_continue_from_4( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0+(ofs)];                  \\\n    x0 += decode[0+(ofs)*4] * c;      \\\n    x1 += decode[1+(ofs)*4] * c;      \\\n    x2 += decode[2+(ofs)*4] * c;      \\\n    x3 += decode[3+(ofs)*4] * c;      \\\n    c = hc[1+(ofs)];                  \\\n    y0 += decode[4+(ofs)*4] * c;      \\\n    y1 += decode[5+(ofs)*4] * c;      \\\n    y2 += decode[6+(ofs)*4] * c;      \\\n    y3 += decode[7+(ofs)*4] * c;      \\\n    c = hc[2+(ofs)];                  \\\n    x0 += decode[8+(ofs)*4] * c;      \\\n    x1 += decode[9+(ofs)*4] * c;      \\\n    x2 += decode[10+(ofs)*4] * c;     \\\n    x3 += decode[11+(ofs)*4] * c;     \\\n    c = hc[3+(ofs)];                  \\\n    y0 += decode[12+(ofs)*4] * c;     \\\n    y1 += decode[13+(ofs)*4] * c;     \\\n    y2 += decode[14+(ofs)*4] * c;     \\\n    y3 += decode[15+(ofs)*4] * c;\n\n#define stbir__1_coeff_remnant( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0+(ofs)];                  \\\n    x0 += decode[0+(ofs)*4] * c;      \\\n    x1 += decode[1+(ofs)*4] * c;      \\\n    x2 += decode[2+(ofs)*4] * c;      \\\n    x3 += decode[3+(ofs)*4] * c;\n\n#define stbir__2_coeff_remnant( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0+(ofs)];                  \\\n    x0 += decode[0+(ofs)*4] * c;      \\\n    x1 += decode[1+(ofs)*4] * c;      \\\n    x2 += decode[2+(ofs)*4] * c;      \\\n    x3 += decode[3+(ofs)*4] * c;      \\\n    c = hc[1+(ofs)];                  \\\n    y0 += decode[4+(ofs)*4] * c;      \\\n    y1 += decode[5+(ofs)*4] * c;      \\\n    y2 += decode[6+(ofs)*4] * c;      \\\n    y3 += decode[7+(ofs)*4] * c;\n\n#define stbir__3_coeff_remnant( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);     \\\n    c = hc[0+(ofs)];                  \\\n    x0 += decode[0+(ofs)*4] * c;      \\\n    x1 += decode[1+(ofs)*4] * c;      \\\n    x2 += decode[2+(ofs)*4] * c;      \\\n    x3 += decode[3+(ofs)*4] * c;      \\\n    c = hc[1+(ofs)];                  \\\n    y0 += decode[4+(ofs)*4] * c;      \\\n    y1 += decode[5+(ofs)*4] * c;      \\\n    y2 += decode[6+(ofs)*4] * c;      \\\n    y3 += decode[7+(ofs)*4] * c;      \\\n    c = hc[2+(ofs)];                  \\\n    x0 += decode[8+(ofs)*4] * c;      \\\n    x1 += decode[9+(ofs)*4] * c;      \\\n    x2 += decode[10+(ofs)*4] * c;     \\\n    x3 += decode[11+(ofs)*4] * c;\n\n#define stbir__store_output()                     \\\n    output[0] = x0 + y0;                          \\\n    output[1] = x1 + y1;                          \\\n    output[2] = x2 + y2;                          \\\n    output[3] = x3 + y3;                          \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 4;\n\n#endif\n\n#define STBIR__horizontal_channels 4\n#define STB_IMAGE_RESIZE_DO_HORIZONTALS\n#include STBIR__HEADER_FILENAME\n\n\n\n//=================\n// Do 7 channel horizontal routines\n\n#ifdef STBIR_SIMD\n\n#define stbir__1_coeff_only()                   \\\n    stbir__simdf tot0,tot1,c;                   \\\n    STBIR_SIMD_NO_UNROLL(decode);               \\\n    stbir__simdf_load1( c, hc );                \\\n    stbir__simdf_0123to0000( c, c );            \\\n    stbir__simdf_mult_mem( tot0, c, decode );   \\\n    stbir__simdf_mult_mem( tot1, c, decode+3 );\n\n#define stbir__2_coeff_only()                         \\\n    stbir__simdf tot0,tot1,c,cs;                      \\\n    STBIR_SIMD_NO_UNROLL(decode);                     \\\n    stbir__simdf_load2( cs, hc );                     \\\n    stbir__simdf_0123to0000( c, cs );                 \\\n    stbir__simdf_mult_mem( tot0, c, decode );         \\\n    stbir__simdf_mult_mem( tot1, c, decode+3 );       \\\n    stbir__simdf_0123to1111( c, cs );                 \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+7 ); \\\n    stbir__simdf_madd_mem( tot1, tot1, c,decode+10 );\n\n#define stbir__3_coeff_only()                           \\\n    stbir__simdf tot0,tot1,c,cs;                        \\\n    STBIR_SIMD_NO_UNROLL(decode);                       \\\n    stbir__simdf_load( cs, hc );                        \\\n    stbir__simdf_0123to0000( c, cs );                   \\\n    stbir__simdf_mult_mem( tot0, c, decode );           \\\n    stbir__simdf_mult_mem( tot1, c, decode+3 );         \\\n    stbir__simdf_0123to1111( c, cs );                   \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+7 );   \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+10 );  \\\n    stbir__simdf_0123to2222( c, cs );                   \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+14 );  \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+17 );\n\n#define stbir__store_output_tiny()                \\\n    stbir__simdf_store( output+3, tot1 );         \\\n    stbir__simdf_store( output, tot0 );           \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 7;\n\n#ifdef STBIR_SIMD8\n\n#define stbir__4_coeff_start()                     \\\n    stbir__simdf8 tot0,tot1,c,cs;                  \\\n    STBIR_SIMD_NO_UNROLL(decode);                  \\\n    stbir__simdf8_load4b( cs, hc );                \\\n    stbir__simdf8_0123to00000000( c, cs );         \\\n    stbir__simdf8_mult_mem( tot0, c, decode );     \\\n    stbir__simdf8_0123to11111111( c, cs );         \\\n    stbir__simdf8_mult_mem( tot1, c, decode+7 );   \\\n    stbir__simdf8_0123to22222222( c, cs );         \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+14 );  \\\n    stbir__simdf8_0123to33333333( c, cs );         \\\n    stbir__simdf8_madd_mem( tot1, tot1, c, decode+21 );\n\n#define stbir__4_coeff_continue_from_4( ofs )                   \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );                     \\\n    stbir__simdf8_0123to00000000( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*7 );    \\\n    stbir__simdf8_0123to11111111( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot1, tot1, c, decode+(ofs)*7+7 );  \\\n    stbir__simdf8_0123to22222222( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*7+14 ); \\\n    stbir__simdf8_0123to33333333( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot1, tot1, c, decode+(ofs)*7+21 );\n\n#define stbir__1_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf8_load1b( c, hc + (ofs) );                      \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*7 );\n\n#define stbir__2_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf8_load1b( c, hc + (ofs) );                      \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*7 );    \\\n    stbir__simdf8_load1b( c, hc + (ofs)+1 );                    \\\n    stbir__simdf8_madd_mem( tot1, tot1, c, decode+(ofs)*7+7 );\n\n#define stbir__3_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf8_load4b( cs, hc + (ofs) );                     \\\n    stbir__simdf8_0123to00000000( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*7 );    \\\n    stbir__simdf8_0123to11111111( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot1, tot1, c, decode+(ofs)*7+7 );  \\\n    stbir__simdf8_0123to22222222( c, cs );                      \\\n    stbir__simdf8_madd_mem( tot0, tot0, c, decode+(ofs)*7+14 );\n\n#define stbir__store_output()                     \\\n    stbir__simdf8_add( tot0, tot0, tot1 );        \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 7;                                  \\\n    if ( output < output_end )                    \\\n    {                                             \\\n      stbir__simdf8_store( output-7, tot0 );      \\\n      continue;                                   \\\n    }                                             \\\n    stbir__simdf_store( output-7+3, stbir__simdf_swiz(stbir__simdf8_gettop4(tot0),0,0,1,2) ); \\\n    stbir__simdf_store( output-7, stbir__if_simdf8_cast_to_simdf4(tot0) );           \\\n    break;\n\n#else\n\n#define stbir__4_coeff_start()                    \\\n    stbir__simdf tot0,tot1,tot2,tot3,c,cs;        \\\n    STBIR_SIMD_NO_UNROLL(decode);                 \\\n    stbir__simdf_load( cs, hc );                  \\\n    stbir__simdf_0123to0000( c, cs );             \\\n    stbir__simdf_mult_mem( tot0, c, decode );     \\\n    stbir__simdf_mult_mem( tot1, c, decode+3 );   \\\n    stbir__simdf_0123to1111( c, cs );             \\\n    stbir__simdf_mult_mem( tot2, c, decode+7 );   \\\n    stbir__simdf_mult_mem( tot3, c, decode+10 );  \\\n    stbir__simdf_0123to2222( c, cs );             \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+14 );  \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+17 );  \\\n    stbir__simdf_0123to3333( c, cs );                   \\\n    stbir__simdf_madd_mem( tot2, tot2, c, decode+21 );  \\\n    stbir__simdf_madd_mem( tot3, tot3, c, decode+24 );\n\n#define stbir__4_coeff_continue_from_4( ofs )                   \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf_load( cs, hc + (ofs) );                        \\\n    stbir__simdf_0123to0000( c, cs );                           \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*7 );     \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*7+3 );   \\\n    stbir__simdf_0123to1111( c, cs );                           \\\n    stbir__simdf_madd_mem( tot2, tot2, c, decode+(ofs)*7+7 );   \\\n    stbir__simdf_madd_mem( tot3, tot3, c, decode+(ofs)*7+10 );  \\\n    stbir__simdf_0123to2222( c, cs );                           \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*7+14 );  \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*7+17 );  \\\n    stbir__simdf_0123to3333( c, cs );                           \\\n    stbir__simdf_madd_mem( tot2, tot2, c, decode+(ofs)*7+21 );  \\\n    stbir__simdf_madd_mem( tot3, tot3, c, decode+(ofs)*7+24 );\n\n#define stbir__1_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf_load1( c, hc + (ofs) );                        \\\n    stbir__simdf_0123to0000( c, c );                            \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*7 );     \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*7+3 );   \\\n\n#define stbir__2_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf_load2( cs, hc + (ofs) );                       \\\n    stbir__simdf_0123to0000( c, cs );                           \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*7 );     \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*7+3 );   \\\n    stbir__simdf_0123to1111( c, cs );                           \\\n    stbir__simdf_madd_mem( tot2, tot2, c, decode+(ofs)*7+7 );   \\\n    stbir__simdf_madd_mem( tot3, tot3, c, decode+(ofs)*7+10 );\n\n#define stbir__3_coeff_remnant( ofs )                           \\\n    STBIR_SIMD_NO_UNROLL(decode);                               \\\n    stbir__simdf_load( cs, hc + (ofs) );                        \\\n    stbir__simdf_0123to0000( c, cs );                           \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*7 );     \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*7+3 );   \\\n    stbir__simdf_0123to1111( c, cs );                           \\\n    stbir__simdf_madd_mem( tot2, tot2, c, decode+(ofs)*7+7 );   \\\n    stbir__simdf_madd_mem( tot3, tot3, c, decode+(ofs)*7+10 );  \\\n    stbir__simdf_0123to2222( c, cs );                           \\\n    stbir__simdf_madd_mem( tot0, tot0, c, decode+(ofs)*7+14 );  \\\n    stbir__simdf_madd_mem( tot1, tot1, c, decode+(ofs)*7+17 );\n\n#define stbir__store_output()                     \\\n    stbir__simdf_add( tot0, tot0, tot2 );         \\\n    stbir__simdf_add( tot1, tot1, tot3 );         \\\n    stbir__simdf_store( output+3, tot1 );         \\\n    stbir__simdf_store( output, tot0 );           \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 7;\n\n#endif\n\n#else\n\n#define stbir__1_coeff_only()        \\\n    float tot0, tot1, tot2, tot3, tot4, tot5, tot6, c; \\\n    c = hc[0];                       \\\n    tot0 = decode[0]*c;              \\\n    tot1 = decode[1]*c;              \\\n    tot2 = decode[2]*c;              \\\n    tot3 = decode[3]*c;              \\\n    tot4 = decode[4]*c;              \\\n    tot5 = decode[5]*c;              \\\n    tot6 = decode[6]*c;\n\n#define stbir__2_coeff_only()        \\\n    float tot0, tot1, tot2, tot3, tot4, tot5, tot6, c; \\\n    c = hc[0];                       \\\n    tot0 = decode[0]*c;              \\\n    tot1 = decode[1]*c;              \\\n    tot2 = decode[2]*c;              \\\n    tot3 = decode[3]*c;              \\\n    tot4 = decode[4]*c;              \\\n    tot5 = decode[5]*c;              \\\n    tot6 = decode[6]*c;              \\\n    c = hc[1];                       \\\n    tot0 += decode[7]*c;             \\\n    tot1 += decode[8]*c;             \\\n    tot2 += decode[9]*c;             \\\n    tot3 += decode[10]*c;            \\\n    tot4 += decode[11]*c;            \\\n    tot5 += decode[12]*c;            \\\n    tot6 += decode[13]*c;            \\\n\n#define stbir__3_coeff_only()        \\\n    float tot0, tot1, tot2, tot3, tot4, tot5, tot6, c; \\\n    c = hc[0];                       \\\n    tot0 = decode[0]*c;              \\\n    tot1 = decode[1]*c;              \\\n    tot2 = decode[2]*c;              \\\n    tot3 = decode[3]*c;              \\\n    tot4 = decode[4]*c;              \\\n    tot5 = decode[5]*c;              \\\n    tot6 = decode[6]*c;              \\\n    c = hc[1];                       \\\n    tot0 += decode[7]*c;             \\\n    tot1 += decode[8]*c;             \\\n    tot2 += decode[9]*c;             \\\n    tot3 += decode[10]*c;            \\\n    tot4 += decode[11]*c;            \\\n    tot5 += decode[12]*c;            \\\n    tot6 += decode[13]*c;            \\\n    c = hc[2];                       \\\n    tot0 += decode[14]*c;            \\\n    tot1 += decode[15]*c;            \\\n    tot2 += decode[16]*c;            \\\n    tot3 += decode[17]*c;            \\\n    tot4 += decode[18]*c;            \\\n    tot5 += decode[19]*c;            \\\n    tot6 += decode[20]*c;            \\\n\n#define stbir__store_output_tiny()                \\\n    output[0] = tot0;                             \\\n    output[1] = tot1;                             \\\n    output[2] = tot2;                             \\\n    output[3] = tot3;                             \\\n    output[4] = tot4;                             \\\n    output[5] = tot5;                             \\\n    output[6] = tot6;                             \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 7;\n\n#define stbir__4_coeff_start()    \\\n    float x0,x1,x2,x3,x4,x5,x6,y0,y1,y2,y3,y4,y5,y6,c; \\\n    STBIR_SIMD_NO_UNROLL(decode); \\\n    c = hc[0];                    \\\n    x0 = decode[0] * c;           \\\n    x1 = decode[1] * c;           \\\n    x2 = decode[2] * c;           \\\n    x3 = decode[3] * c;           \\\n    x4 = decode[4] * c;           \\\n    x5 = decode[5] * c;           \\\n    x6 = decode[6] * c;           \\\n    c = hc[1];                    \\\n    y0 = decode[7] * c;           \\\n    y1 = decode[8] * c;           \\\n    y2 = decode[9] * c;           \\\n    y3 = decode[10] * c;          \\\n    y4 = decode[11] * c;          \\\n    y5 = decode[12] * c;          \\\n    y6 = decode[13] * c;          \\\n    c = hc[2];                    \\\n    x0 += decode[14] * c;         \\\n    x1 += decode[15] * c;         \\\n    x2 += decode[16] * c;         \\\n    x3 += decode[17] * c;         \\\n    x4 += decode[18] * c;         \\\n    x5 += decode[19] * c;         \\\n    x6 += decode[20] * c;         \\\n    c = hc[3];                    \\\n    y0 += decode[21] * c;         \\\n    y1 += decode[22] * c;         \\\n    y2 += decode[23] * c;         \\\n    y3 += decode[24] * c;         \\\n    y4 += decode[25] * c;         \\\n    y5 += decode[26] * c;         \\\n    y6 += decode[27] * c;\n\n#define stbir__4_coeff_continue_from_4( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);  \\\n    c = hc[0+(ofs)];               \\\n    x0 += decode[0+(ofs)*7] * c;   \\\n    x1 += decode[1+(ofs)*7] * c;   \\\n    x2 += decode[2+(ofs)*7] * c;   \\\n    x3 += decode[3+(ofs)*7] * c;   \\\n    x4 += decode[4+(ofs)*7] * c;   \\\n    x5 += decode[5+(ofs)*7] * c;   \\\n    x6 += decode[6+(ofs)*7] * c;   \\\n    c = hc[1+(ofs)];               \\\n    y0 += decode[7+(ofs)*7] * c;   \\\n    y1 += decode[8+(ofs)*7] * c;   \\\n    y2 += decode[9+(ofs)*7] * c;   \\\n    y3 += decode[10+(ofs)*7] * c;  \\\n    y4 += decode[11+(ofs)*7] * c;  \\\n    y5 += decode[12+(ofs)*7] * c;  \\\n    y6 += decode[13+(ofs)*7] * c;  \\\n    c = hc[2+(ofs)];               \\\n    x0 += decode[14+(ofs)*7] * c;  \\\n    x1 += decode[15+(ofs)*7] * c;  \\\n    x2 += decode[16+(ofs)*7] * c;  \\\n    x3 += decode[17+(ofs)*7] * c;  \\\n    x4 += decode[18+(ofs)*7] * c;  \\\n    x5 += decode[19+(ofs)*7] * c;  \\\n    x6 += decode[20+(ofs)*7] * c;  \\\n    c = hc[3+(ofs)];               \\\n    y0 += decode[21+(ofs)*7] * c;  \\\n    y1 += decode[22+(ofs)*7] * c;  \\\n    y2 += decode[23+(ofs)*7] * c;  \\\n    y3 += decode[24+(ofs)*7] * c;  \\\n    y4 += decode[25+(ofs)*7] * c;  \\\n    y5 += decode[26+(ofs)*7] * c;  \\\n    y6 += decode[27+(ofs)*7] * c;\n\n#define stbir__1_coeff_remnant( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);  \\\n    c = hc[0+(ofs)];               \\\n    x0 += decode[0+(ofs)*7] * c;   \\\n    x1 += decode[1+(ofs)*7] * c;   \\\n    x2 += decode[2+(ofs)*7] * c;   \\\n    x3 += decode[3+(ofs)*7] * c;   \\\n    x4 += decode[4+(ofs)*7] * c;   \\\n    x5 += decode[5+(ofs)*7] * c;   \\\n    x6 += decode[6+(ofs)*7] * c;   \\\n\n#define stbir__2_coeff_remnant( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);  \\\n    c = hc[0+(ofs)];               \\\n    x0 += decode[0+(ofs)*7] * c;   \\\n    x1 += decode[1+(ofs)*7] * c;   \\\n    x2 += decode[2+(ofs)*7] * c;   \\\n    x3 += decode[3+(ofs)*7] * c;   \\\n    x4 += decode[4+(ofs)*7] * c;   \\\n    x5 += decode[5+(ofs)*7] * c;   \\\n    x6 += decode[6+(ofs)*7] * c;   \\\n    c = hc[1+(ofs)];               \\\n    y0 += decode[7+(ofs)*7] * c;   \\\n    y1 += decode[8+(ofs)*7] * c;   \\\n    y2 += decode[9+(ofs)*7] * c;   \\\n    y3 += decode[10+(ofs)*7] * c;  \\\n    y4 += decode[11+(ofs)*7] * c;  \\\n    y5 += decode[12+(ofs)*7] * c;  \\\n    y6 += decode[13+(ofs)*7] * c;  \\\n\n#define stbir__3_coeff_remnant( ofs ) \\\n    STBIR_SIMD_NO_UNROLL(decode);  \\\n    c = hc[0+(ofs)];               \\\n    x0 += decode[0+(ofs)*7] * c;   \\\n    x1 += decode[1+(ofs)*7] * c;   \\\n    x2 += decode[2+(ofs)*7] * c;   \\\n    x3 += decode[3+(ofs)*7] * c;   \\\n    x4 += decode[4+(ofs)*7] * c;   \\\n    x5 += decode[5+(ofs)*7] * c;   \\\n    x6 += decode[6+(ofs)*7] * c;   \\\n    c = hc[1+(ofs)];               \\\n    y0 += decode[7+(ofs)*7] * c;   \\\n    y1 += decode[8+(ofs)*7] * c;   \\\n    y2 += decode[9+(ofs)*7] * c;   \\\n    y3 += decode[10+(ofs)*7] * c;  \\\n    y4 += decode[11+(ofs)*7] * c;  \\\n    y5 += decode[12+(ofs)*7] * c;  \\\n    y6 += decode[13+(ofs)*7] * c;  \\\n    c = hc[2+(ofs)];               \\\n    x0 += decode[14+(ofs)*7] * c;  \\\n    x1 += decode[15+(ofs)*7] * c;  \\\n    x2 += decode[16+(ofs)*7] * c;  \\\n    x3 += decode[17+(ofs)*7] * c;  \\\n    x4 += decode[18+(ofs)*7] * c;  \\\n    x5 += decode[19+(ofs)*7] * c;  \\\n    x6 += decode[20+(ofs)*7] * c;  \\\n\n#define stbir__store_output()                     \\\n    output[0] = x0 + y0;                          \\\n    output[1] = x1 + y1;                          \\\n    output[2] = x2 + y2;                          \\\n    output[3] = x3 + y3;                          \\\n    output[4] = x4 + y4;                          \\\n    output[5] = x5 + y5;                          \\\n    output[6] = x6 + y6;                          \\\n    horizontal_coefficients += coefficient_width; \\\n    ++horizontal_contributors;                    \\\n    output += 7;\n\n#endif\n\n#define STBIR__horizontal_channels 7\n#define STB_IMAGE_RESIZE_DO_HORIZONTALS\n#include STBIR__HEADER_FILENAME\n\n\n// include all of the vertical resamplers (both scatter and gather versions)\n\n#define STBIR__vertical_channels 1\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 1\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 2\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 2\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 3\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 3\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 4\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 4\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 5\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 5\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 6\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 6\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 7\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 7\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 8\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#include STBIR__HEADER_FILENAME\n\n#define STBIR__vertical_channels 8\n#define STB_IMAGE_RESIZE_DO_VERTICALS\n#define STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#include STBIR__HEADER_FILENAME\n\ntypedef void STBIR_VERTICAL_GATHERFUNC( float * output, float const * coeffs, float const ** inputs, float const * input0_end );\n\nstatic STBIR_VERTICAL_GATHERFUNC * stbir__vertical_gathers[ 8 ] =\n{\n  stbir__vertical_gather_with_1_coeffs,stbir__vertical_gather_with_2_coeffs,stbir__vertical_gather_with_3_coeffs,stbir__vertical_gather_with_4_coeffs,stbir__vertical_gather_with_5_coeffs,stbir__vertical_gather_with_6_coeffs,stbir__vertical_gather_with_7_coeffs,stbir__vertical_gather_with_8_coeffs\n};\n\nstatic STBIR_VERTICAL_GATHERFUNC * stbir__vertical_gathers_continues[ 8 ] =\n{\n  stbir__vertical_gather_with_1_coeffs_cont,stbir__vertical_gather_with_2_coeffs_cont,stbir__vertical_gather_with_3_coeffs_cont,stbir__vertical_gather_with_4_coeffs_cont,stbir__vertical_gather_with_5_coeffs_cont,stbir__vertical_gather_with_6_coeffs_cont,stbir__vertical_gather_with_7_coeffs_cont,stbir__vertical_gather_with_8_coeffs_cont\n};\n\ntypedef void STBIR_VERTICAL_SCATTERFUNC( float ** outputs, float const * coeffs, float const * input, float const * input_end );\n\nstatic STBIR_VERTICAL_SCATTERFUNC * stbir__vertical_scatter_sets[ 8 ] =\n{\n  stbir__vertical_scatter_with_1_coeffs,stbir__vertical_scatter_with_2_coeffs,stbir__vertical_scatter_with_3_coeffs,stbir__vertical_scatter_with_4_coeffs,stbir__vertical_scatter_with_5_coeffs,stbir__vertical_scatter_with_6_coeffs,stbir__vertical_scatter_with_7_coeffs,stbir__vertical_scatter_with_8_coeffs\n};\n\nstatic STBIR_VERTICAL_SCATTERFUNC * stbir__vertical_scatter_blends[ 8 ] =\n{\n  stbir__vertical_scatter_with_1_coeffs_cont,stbir__vertical_scatter_with_2_coeffs_cont,stbir__vertical_scatter_with_3_coeffs_cont,stbir__vertical_scatter_with_4_coeffs_cont,stbir__vertical_scatter_with_5_coeffs_cont,stbir__vertical_scatter_with_6_coeffs_cont,stbir__vertical_scatter_with_7_coeffs_cont,stbir__vertical_scatter_with_8_coeffs_cont\n};\n\n\nstatic void stbir__encode_scanline( stbir__info const * stbir_info, void *output_buffer_data, float * encode_buffer, int row  STBIR_ONLY_PROFILE_GET_SPLIT_INFO )\n{\n  int num_pixels = stbir_info->horizontal.scale_info.output_sub_size;\n  int channels = stbir_info->channels;\n  int width_times_channels = num_pixels * channels;\n  void * output_buffer;\n\n  // un-alpha weight if we need to\n  if ( stbir_info->alpha_unweight )\n  {\n    STBIR_PROFILE_START( unalpha );\n    stbir_info->alpha_unweight( encode_buffer, width_times_channels );\n    STBIR_PROFILE_END( unalpha );\n  }\n\n  // write directly into output by default\n  output_buffer = output_buffer_data;\n\n  // if we have an output callback, we first convert the decode buffer in place (and then hand that to the callback)\n  if ( stbir_info->out_pixels_cb )\n    output_buffer = encode_buffer;\n\n  STBIR_PROFILE_START( encode );\n  // convert into the output buffer\n  stbir_info->encode_pixels( output_buffer, width_times_channels, encode_buffer );\n  STBIR_PROFILE_END( encode );\n\n  // if we have an output callback, call it to send the data\n  if ( stbir_info->out_pixels_cb )\n    stbir_info->out_pixels_cb( output_buffer, num_pixels, row, stbir_info->user_data );\n}\n\n\n// Get the ring buffer pointer for an index\nstatic float* stbir__get_ring_buffer_entry(stbir__info const * stbir_info, stbir__per_split_info const * split_info, int index )\n{\n  STBIR_ASSERT( index < stbir_info->ring_buffer_num_entries );\n\n  #ifdef STBIR__SEPARATE_ALLOCATIONS\n    return split_info->ring_buffers[ index ];\n  #else\n    return (float*) ( ( (char*) split_info->ring_buffer ) + ( index * stbir_info->ring_buffer_length_bytes ) );\n  #endif\n}\n\n// Get the specified scan line from the ring buffer\nstatic float* stbir__get_ring_buffer_scanline(stbir__info const * stbir_info, stbir__per_split_info const * split_info, int get_scanline)\n{\n  int ring_buffer_index = (split_info->ring_buffer_begin_index + (get_scanline - split_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries;\n  return stbir__get_ring_buffer_entry( stbir_info, split_info, ring_buffer_index );\n}\n\nstatic void stbir__resample_horizontal_gather(stbir__info const * stbir_info, float* output_buffer, float const * input_buffer STBIR_ONLY_PROFILE_GET_SPLIT_INFO )\n{\n  float const * decode_buffer = input_buffer - ( stbir_info->scanline_extents.conservative.n0 * stbir_info->effective_channels );\n\n  STBIR_PROFILE_START( horizontal );\n  if ( ( stbir_info->horizontal.filter_enum == STBIR_FILTER_POINT_SAMPLE ) && ( stbir_info->horizontal.scale_info.scale == 1.0f ) )\n    STBIR_MEMCPY( output_buffer, input_buffer, stbir_info->horizontal.scale_info.output_sub_size * sizeof( float ) * stbir_info->effective_channels );\n  else\n    stbir_info->horizontal_gather_channels( output_buffer, stbir_info->horizontal.scale_info.output_sub_size, decode_buffer, stbir_info->horizontal.contributors, stbir_info->horizontal.coefficients, stbir_info->horizontal.coefficient_width );\n  STBIR_PROFILE_END( horizontal );\n}\n\nstatic void stbir__resample_vertical_gather(stbir__info const * stbir_info, stbir__per_split_info* split_info, int n, int contrib_n0, int contrib_n1, float const * vertical_coefficients )\n{\n  float* encode_buffer = split_info->vertical_buffer;\n  float* decode_buffer = split_info->decode_buffer;\n  int vertical_first = stbir_info->vertical_first;\n  int width = (vertical_first) ? ( stbir_info->scanline_extents.conservative.n1-stbir_info->scanline_extents.conservative.n0+1 ) : stbir_info->horizontal.scale_info.output_sub_size;\n  int width_times_channels = stbir_info->effective_channels * width;\n\n  STBIR_ASSERT( stbir_info->vertical.is_gather );\n\n  // loop over the contributing scanlines and scale into the buffer\n  STBIR_PROFILE_START( vertical );\n  {\n    int k = 0, total = contrib_n1 - contrib_n0 + 1;\n    STBIR_ASSERT( total > 0 );\n    do {\n      float const * inputs[8];\n      int i, cnt = total; if ( cnt > 8 ) cnt = 8;\n      for( i = 0 ; i < cnt ; i++ )\n        inputs[ i ] = stbir__get_ring_buffer_scanline(stbir_info, split_info, k+i+contrib_n0 );\n\n      // call the N scanlines at a time function (up to 8 scanlines of blending at once)\n      ((k==0)?stbir__vertical_gathers:stbir__vertical_gathers_continues)[cnt-1]( (vertical_first) ? decode_buffer : encode_buffer, vertical_coefficients + k, inputs, inputs[0] + width_times_channels );\n      k += cnt;\n      total -= cnt;\n    } while ( total );\n  }\n  STBIR_PROFILE_END( vertical );\n\n  if ( vertical_first )\n  {\n    // Now resample the gathered vertical data in the horizontal axis into the encode buffer\n    decode_buffer[ width_times_channels ] = 0.0f; // clear two over for horizontals with a remnant of 3\n    decode_buffer[ width_times_channels+1 ] = 0.0f; \n    stbir__resample_horizontal_gather(stbir_info, encode_buffer, decode_buffer  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n  }\n\n  stbir__encode_scanline( stbir_info, ( (char *) stbir_info->output_data ) + ((size_t)n * (size_t)stbir_info->output_stride_bytes),\n                          encode_buffer, n  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n}\n\nstatic void stbir__decode_and_resample_for_vertical_gather_loop(stbir__info const * stbir_info, stbir__per_split_info* split_info, int n)\n{\n  int ring_buffer_index;\n  float* ring_buffer;\n\n  // Decode the nth scanline from the source image into the decode buffer.\n  stbir__decode_scanline( stbir_info, n, split_info->decode_buffer  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n  // update new end scanline\n  split_info->ring_buffer_last_scanline = n;\n\n  // get ring buffer\n  ring_buffer_index = (split_info->ring_buffer_begin_index + (split_info->ring_buffer_last_scanline - split_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries;\n  ring_buffer = stbir__get_ring_buffer_entry(stbir_info, split_info, ring_buffer_index);\n\n  // Now resample it into the ring buffer.\n  stbir__resample_horizontal_gather( stbir_info, ring_buffer, split_info->decode_buffer  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n  // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling.\n}\n\nstatic void stbir__vertical_gather_loop( stbir__info const * stbir_info, stbir__per_split_info* split_info, int split_count )\n{\n  int y, start_output_y, end_output_y;\n  stbir__contributors* vertical_contributors = stbir_info->vertical.contributors;\n  float const * vertical_coefficients = stbir_info->vertical.coefficients;\n\n  STBIR_ASSERT( stbir_info->vertical.is_gather );\n\n  start_output_y = split_info->start_output_y;\n  end_output_y = split_info[split_count-1].end_output_y;\n\n  vertical_contributors += start_output_y;\n  vertical_coefficients += start_output_y * stbir_info->vertical.coefficient_width;\n\n  // initialize the ring buffer for gathering\n  split_info->ring_buffer_begin_index = 0;\n  split_info->ring_buffer_first_scanline = vertical_contributors->n0;\n  split_info->ring_buffer_last_scanline = split_info->ring_buffer_first_scanline - 1; // means \"empty\"\n\n  for (y = start_output_y; y < end_output_y; y++)\n  {\n    int in_first_scanline, in_last_scanline;\n\n    in_first_scanline = vertical_contributors->n0;\n    in_last_scanline = vertical_contributors->n1;\n\n    // make sure the indexing hasn't broken\n    STBIR_ASSERT( in_first_scanline >= split_info->ring_buffer_first_scanline );\n\n    // Load in new scanlines\n    while (in_last_scanline > split_info->ring_buffer_last_scanline)\n    {\n      STBIR_ASSERT( ( split_info->ring_buffer_last_scanline - split_info->ring_buffer_first_scanline + 1 ) <= stbir_info->ring_buffer_num_entries );\n\n      // make sure there was room in the ring buffer when we add new scanlines\n      if ( ( split_info->ring_buffer_last_scanline - split_info->ring_buffer_first_scanline + 1 ) == stbir_info->ring_buffer_num_entries )\n      {\n        split_info->ring_buffer_first_scanline++;\n        split_info->ring_buffer_begin_index++;\n      }\n\n      if ( stbir_info->vertical_first )\n      {\n        float * ring_buffer = stbir__get_ring_buffer_scanline( stbir_info, split_info, ++split_info->ring_buffer_last_scanline );\n        // Decode the nth scanline from the source image into the decode buffer.\n        stbir__decode_scanline( stbir_info, split_info->ring_buffer_last_scanline, ring_buffer  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n      }\n      else\n      {\n        stbir__decode_and_resample_for_vertical_gather_loop(stbir_info, split_info, split_info->ring_buffer_last_scanline + 1);\n      }\n    }\n\n    // Now all buffers should be ready to write a row of vertical sampling, so do it.\n    stbir__resample_vertical_gather(stbir_info, split_info, y, in_first_scanline, in_last_scanline, vertical_coefficients );\n\n    ++vertical_contributors;\n    vertical_coefficients += stbir_info->vertical.coefficient_width;\n  }\n}\n\n#define STBIR__FLOAT_EMPTY_MARKER 3.0e+38F\n#define STBIR__FLOAT_BUFFER_IS_EMPTY(ptr) ((ptr)[0]==STBIR__FLOAT_EMPTY_MARKER)\n\nstatic void stbir__encode_first_scanline_from_scatter(stbir__info const * stbir_info, stbir__per_split_info* split_info)\n{\n  // evict a scanline out into the output buffer\n  float* ring_buffer_entry = stbir__get_ring_buffer_entry(stbir_info, split_info, split_info->ring_buffer_begin_index );\n\n  // dump the scanline out\n  stbir__encode_scanline( stbir_info, ( (char *)stbir_info->output_data ) + ( (size_t)split_info->ring_buffer_first_scanline * (size_t)stbir_info->output_stride_bytes ), ring_buffer_entry, split_info->ring_buffer_first_scanline  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n  // mark it as empty\n  ring_buffer_entry[ 0 ] = STBIR__FLOAT_EMPTY_MARKER;\n\n  // advance the first scanline\n  split_info->ring_buffer_first_scanline++;\n  if ( ++split_info->ring_buffer_begin_index == stbir_info->ring_buffer_num_entries )\n    split_info->ring_buffer_begin_index = 0;\n}\n\nstatic void stbir__horizontal_resample_and_encode_first_scanline_from_scatter(stbir__info const * stbir_info, stbir__per_split_info* split_info)\n{\n  // evict a scanline out into the output buffer\n\n  float* ring_buffer_entry = stbir__get_ring_buffer_entry(stbir_info, split_info, split_info->ring_buffer_begin_index );\n\n  // Now resample it into the buffer.\n  stbir__resample_horizontal_gather( stbir_info, split_info->vertical_buffer, ring_buffer_entry  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n  // dump the scanline out\n  stbir__encode_scanline( stbir_info, ( (char *)stbir_info->output_data ) + ( (size_t)split_info->ring_buffer_first_scanline * (size_t)stbir_info->output_stride_bytes ), split_info->vertical_buffer, split_info->ring_buffer_first_scanline  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n  // mark it as empty\n  ring_buffer_entry[ 0 ] = STBIR__FLOAT_EMPTY_MARKER;\n\n  // advance the first scanline\n  split_info->ring_buffer_first_scanline++;\n  if ( ++split_info->ring_buffer_begin_index == stbir_info->ring_buffer_num_entries )\n    split_info->ring_buffer_begin_index = 0;\n}\n\nstatic void stbir__resample_vertical_scatter(stbir__info const * stbir_info, stbir__per_split_info* split_info, int n0, int n1, float const * vertical_coefficients, float const * vertical_buffer, float const * vertical_buffer_end )\n{\n  STBIR_ASSERT( !stbir_info->vertical.is_gather );\n\n  STBIR_PROFILE_START( vertical );\n  {\n    int k = 0, total = n1 - n0 + 1;\n    STBIR_ASSERT( total > 0 );\n    do {\n      float * outputs[8];\n      int i, n = total; if ( n > 8 ) n = 8;\n      for( i = 0 ; i < n ; i++ )\n      {\n        outputs[ i ] = stbir__get_ring_buffer_scanline(stbir_info, split_info, k+i+n0 );\n        if ( ( i ) && ( STBIR__FLOAT_BUFFER_IS_EMPTY( outputs[i] ) != STBIR__FLOAT_BUFFER_IS_EMPTY( outputs[0] ) ) ) // make sure runs are of the same type\n        {\n          n = i;\n          break;\n        }\n      }\n      // call the scatter to N scanlines at a time function (up to 8 scanlines of scattering at once)\n      ((STBIR__FLOAT_BUFFER_IS_EMPTY( outputs[0] ))?stbir__vertical_scatter_sets:stbir__vertical_scatter_blends)[n-1]( outputs, vertical_coefficients + k, vertical_buffer, vertical_buffer_end );\n      k += n;\n      total -= n;\n    } while ( total );\n  }\n\n  STBIR_PROFILE_END( vertical );\n}\n\ntypedef void stbir__handle_scanline_for_scatter_func(stbir__info const * stbir_info, stbir__per_split_info* split_info);\n\nstatic void stbir__vertical_scatter_loop( stbir__info const * stbir_info, stbir__per_split_info* split_info, int split_count )\n{\n  int y, start_output_y, end_output_y, start_input_y, end_input_y;\n  stbir__contributors* vertical_contributors = stbir_info->vertical.contributors;\n  float const * vertical_coefficients = stbir_info->vertical.coefficients;\n  stbir__handle_scanline_for_scatter_func * handle_scanline_for_scatter;\n  void * scanline_scatter_buffer;\n  void * scanline_scatter_buffer_end;\n  int on_first_input_y, last_input_y;\n  int width = (stbir_info->vertical_first) ? ( stbir_info->scanline_extents.conservative.n1-stbir_info->scanline_extents.conservative.n0+1 ) : stbir_info->horizontal.scale_info.output_sub_size;\n  int width_times_channels = stbir_info->effective_channels * width;\n\n  STBIR_ASSERT( !stbir_info->vertical.is_gather );\n\n  start_output_y = split_info->start_output_y;\n  end_output_y = split_info[split_count-1].end_output_y;  // may do multiple split counts\n\n  start_input_y = split_info->start_input_y;\n  end_input_y = split_info[split_count-1].end_input_y;\n\n  // adjust for starting offset start_input_y\n  y = start_input_y + stbir_info->vertical.filter_pixel_margin;\n  vertical_contributors += y ;\n  vertical_coefficients += stbir_info->vertical.coefficient_width * y;\n\n  if ( stbir_info->vertical_first )\n  {\n    handle_scanline_for_scatter = stbir__horizontal_resample_and_encode_first_scanline_from_scatter;\n    scanline_scatter_buffer = split_info->decode_buffer;\n    scanline_scatter_buffer_end = ( (char*) scanline_scatter_buffer ) + sizeof( float ) * stbir_info->effective_channels * (stbir_info->scanline_extents.conservative.n1-stbir_info->scanline_extents.conservative.n0+1);\n  }\n  else\n  {\n    handle_scanline_for_scatter = stbir__encode_first_scanline_from_scatter;\n    scanline_scatter_buffer = split_info->vertical_buffer;\n    scanline_scatter_buffer_end = ( (char*) scanline_scatter_buffer ) + sizeof( float ) * stbir_info->effective_channels * stbir_info->horizontal.scale_info.output_sub_size;\n  }\n\n  // initialize the ring buffer for scattering\n  split_info->ring_buffer_first_scanline = start_output_y;\n  split_info->ring_buffer_last_scanline = -1;\n  split_info->ring_buffer_begin_index = -1;\n\n  // mark all the buffers as empty to start\n  for( y = 0 ; y < stbir_info->ring_buffer_num_entries ; y++ )\n  {\n    float * decode_buffer = stbir__get_ring_buffer_entry( stbir_info, split_info, y );\n    decode_buffer[ width_times_channels ] = 0.0f; // clear two over for horizontals with a remnant of 3\n    decode_buffer[ width_times_channels+1 ] = 0.0f; \n    decode_buffer[0] = STBIR__FLOAT_EMPTY_MARKER; // only used on scatter\n  }\n\n  // do the loop in input space\n  on_first_input_y = 1; last_input_y = start_input_y;\n  for (y = start_input_y ; y < end_input_y; y++)\n  {\n    int out_first_scanline, out_last_scanline;\n\n    out_first_scanline = vertical_contributors->n0;\n    out_last_scanline = vertical_contributors->n1;\n\n    STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);\n\n    if ( ( out_last_scanline >= out_first_scanline ) && ( ( ( out_first_scanline >= start_output_y ) && ( out_first_scanline < end_output_y ) ) || ( ( out_last_scanline >= start_output_y ) && ( out_last_scanline < end_output_y ) ) ) )\n    {\n      float const * vc = vertical_coefficients;\n\n      // keep track of the range actually seen for the next resize\n      last_input_y = y;\n      if ( ( on_first_input_y ) && ( y > start_input_y ) )\n        split_info->start_input_y = y;\n      on_first_input_y = 0;\n\n      // clip the region\n      if ( out_first_scanline < start_output_y )\n      {\n        vc += start_output_y - out_first_scanline;\n        out_first_scanline = start_output_y;\n      }\n\n      if ( out_last_scanline >= end_output_y )\n        out_last_scanline = end_output_y - 1;\n\n      // if very first scanline, init the index\n      if (split_info->ring_buffer_begin_index < 0)\n        split_info->ring_buffer_begin_index = out_first_scanline - start_output_y;\n\n      STBIR_ASSERT( split_info->ring_buffer_begin_index <= out_first_scanline );\n\n      // Decode the nth scanline from the source image into the decode buffer.\n      stbir__decode_scanline( stbir_info, y, split_info->decode_buffer  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n      // When horizontal first, we resample horizontally into the vertical buffer before we scatter it out\n      if ( !stbir_info->vertical_first )\n        stbir__resample_horizontal_gather( stbir_info, split_info->vertical_buffer, split_info->decode_buffer  STBIR_ONLY_PROFILE_SET_SPLIT_INFO );\n\n      // Now it's sitting in the buffer ready to be distributed into the ring buffers.\n\n      // evict from the ringbuffer, if we need are full\n      if ( ( ( split_info->ring_buffer_last_scanline - split_info->ring_buffer_first_scanline + 1 ) == stbir_info->ring_buffer_num_entries ) &&\n           ( out_last_scanline > split_info->ring_buffer_last_scanline ) )\n        handle_scanline_for_scatter( stbir_info, split_info );\n\n      // Now the horizontal buffer is ready to write to all ring buffer rows, so do it.\n      stbir__resample_vertical_scatter(stbir_info, split_info, out_first_scanline, out_last_scanline, vc, (float*)scanline_scatter_buffer, (float*)scanline_scatter_buffer_end );\n\n      // update the end of the buffer\n      if ( out_last_scanline > split_info->ring_buffer_last_scanline )\n        split_info->ring_buffer_last_scanline = out_last_scanline;\n    }\n    ++vertical_contributors;\n    vertical_coefficients += stbir_info->vertical.coefficient_width;\n  }\n\n  // now evict the scanlines that are left over in the ring buffer\n  while ( split_info->ring_buffer_first_scanline < end_output_y )\n    handle_scanline_for_scatter(stbir_info, split_info);\n\n  // update the end_input_y if we do multiple resizes with the same data\n  ++last_input_y;\n  for( y = 0 ; y < split_count; y++ )\n    if ( split_info[y].end_input_y > last_input_y )\n      split_info[y].end_input_y = last_input_y;\n}\n\n\nstatic stbir__kernel_callback * stbir__builtin_kernels[] =   { 0, stbir__filter_trapezoid,  stbir__filter_triangle, stbir__filter_cubic, stbir__filter_catmullrom, stbir__filter_mitchell, stbir__filter_point };\nstatic stbir__support_callback * stbir__builtin_supports[] = { 0, stbir__support_trapezoid, stbir__support_one,     stbir__support_two,  stbir__support_two,       stbir__support_two,     stbir__support_zeropoint5 };\n\nstatic void stbir__set_sampler(stbir__sampler * samp, stbir_filter filter, stbir__kernel_callback * kernel, stbir__support_callback * support, stbir_edge edge, stbir__scale_info * scale_info, int always_gather, void * user_data )\n{\n  // set filter\n  if (filter == 0)\n  {\n    filter = STBIR_DEFAULT_FILTER_DOWNSAMPLE; // default to downsample\n    if (scale_info->scale >= ( 1.0f - stbir__small_float ) )\n    {\n      if ( (scale_info->scale <= ( 1.0f + stbir__small_float ) ) && ( STBIR_CEILF(scale_info->pixel_shift) == scale_info->pixel_shift ) )\n        filter = STBIR_FILTER_POINT_SAMPLE;\n      else\n        filter = STBIR_DEFAULT_FILTER_UPSAMPLE;\n    }\n  }\n  samp->filter_enum = filter;\n\n  STBIR_ASSERT(samp->filter_enum != 0);\n  STBIR_ASSERT((unsigned)samp->filter_enum < STBIR_FILTER_OTHER);\n  samp->filter_kernel = stbir__builtin_kernels[ filter ];\n  samp->filter_support = stbir__builtin_supports[ filter ];\n\n  if ( kernel && support )\n  {\n    samp->filter_kernel = kernel;\n    samp->filter_support = support;\n    samp->filter_enum = STBIR_FILTER_OTHER;\n  }\n\n  samp->edge = edge;\n  samp->filter_pixel_width  = stbir__get_filter_pixel_width (samp->filter_support, scale_info->scale, user_data );\n  // Gather is always better, but in extreme downsamples, you have to most or all of the data in memory\n  //    For horizontal, we always have all the pixels, so we always use gather here (always_gather==1).\n  //    For vertical, we use gather if scaling up (which means we will have samp->filter_pixel_width\n  //    scanlines in memory at once).\n  samp->is_gather = 0;\n  if ( scale_info->scale >= ( 1.0f - stbir__small_float ) )\n    samp->is_gather = 1;\n  else if ( ( always_gather ) || ( samp->filter_pixel_width <= STBIR_FORCE_GATHER_FILTER_SCANLINES_AMOUNT ) )\n    samp->is_gather = 2;\n\n  // pre calculate stuff based on the above\n  samp->coefficient_width = stbir__get_coefficient_width(samp, samp->is_gather, user_data);\n\n  // filter_pixel_width is the conservative size in pixels of input that affect an output pixel.\n  //   In rare cases (only with 2 pix to 1 pix with the default filters), it's possible that the \n  //   filter will extend before or after the scanline beyond just one extra entire copy of the \n  //   scanline (we would hit the edge twice). We don't let you do that, so we clamp the total \n  //   width to 3x the total of input pixel (once for the scanline, once for the left side \n  //   overhang, and once for the right side). We only do this for edge mode, since the other \n  //   modes can just re-edge clamp back in again.\n  if ( edge == STBIR_EDGE_WRAP )\n    if ( samp->filter_pixel_width > ( scale_info->input_full_size * 3 ) )\n      samp->filter_pixel_width = scale_info->input_full_size * 3;\n\n  // This is how much to expand buffers to account for filters seeking outside\n  // the image boundaries.\n  samp->filter_pixel_margin = samp->filter_pixel_width / 2;\n  \n  // filter_pixel_margin is the amount that this filter can overhang on just one side of either \n  //   end of the scanline (left or the right). Since we only allow you to overhang 1 scanline's \n  //   worth of pixels, we clamp this one side of overhang to the input scanline size. Again, \n  //   this clamping only happens in rare cases with the default filters (2 pix to 1 pix). \n  if ( edge == STBIR_EDGE_WRAP )\n    if ( samp->filter_pixel_margin > scale_info->input_full_size )\n      samp->filter_pixel_margin = scale_info->input_full_size;\n\n  samp->num_contributors = stbir__get_contributors(samp, samp->is_gather);\n\n  samp->contributors_size = samp->num_contributors * sizeof(stbir__contributors);\n  samp->coefficients_size = samp->num_contributors * samp->coefficient_width * sizeof(float) + sizeof(float)*STBIR_INPUT_CALLBACK_PADDING; // extra sizeof(float) is padding\n\n  samp->gather_prescatter_contributors = 0;\n  samp->gather_prescatter_coefficients = 0;\n  if ( samp->is_gather == 0 )\n  {\n    samp->gather_prescatter_coefficient_width = samp->filter_pixel_width;\n    samp->gather_prescatter_num_contributors  = stbir__get_contributors(samp, 2);\n    samp->gather_prescatter_contributors_size = samp->gather_prescatter_num_contributors * sizeof(stbir__contributors);\n    samp->gather_prescatter_coefficients_size = samp->gather_prescatter_num_contributors * samp->gather_prescatter_coefficient_width * sizeof(float);\n  }\n}\n\nstatic void stbir__get_conservative_extents( stbir__sampler * samp, stbir__contributors * range, void * user_data )\n{\n  float scale = samp->scale_info.scale;\n  float out_shift = samp->scale_info.pixel_shift;\n  stbir__support_callback * support = samp->filter_support;\n  int input_full_size = samp->scale_info.input_full_size;\n  stbir_edge edge = samp->edge;\n  float inv_scale = samp->scale_info.inv_scale;\n\n  STBIR_ASSERT( samp->is_gather != 0 );\n\n  if ( samp->is_gather == 1 )\n  {\n    int in_first_pixel, in_last_pixel;\n    float out_filter_radius = support(inv_scale, user_data) * scale;\n\n    stbir__calculate_in_pixel_range( &in_first_pixel, &in_last_pixel, 0.5, out_filter_radius, inv_scale, out_shift, input_full_size, edge );\n    range->n0 = in_first_pixel;\n    stbir__calculate_in_pixel_range( &in_first_pixel, &in_last_pixel, ( (float)(samp->scale_info.output_sub_size-1) ) + 0.5f, out_filter_radius, inv_scale, out_shift, input_full_size, edge );\n    range->n1 = in_last_pixel;\n  }\n  else if ( samp->is_gather == 2 ) // downsample gather, refine\n  {\n    float in_pixels_radius = support(scale, user_data) * inv_scale;\n    int filter_pixel_margin = samp->filter_pixel_margin;\n    int output_sub_size = samp->scale_info.output_sub_size;\n    int input_end;\n    int n;\n    int in_first_pixel, in_last_pixel;\n\n    // get a conservative area of the input range\n    stbir__calculate_in_pixel_range( &in_first_pixel, &in_last_pixel, 0, 0, inv_scale, out_shift, input_full_size, edge );\n    range->n0 = in_first_pixel;\n    stbir__calculate_in_pixel_range( &in_first_pixel, &in_last_pixel, (float)output_sub_size, 0, inv_scale, out_shift, input_full_size, edge );\n    range->n1 = in_last_pixel;\n\n    // now go through the margin to the start of area to find bottom\n    n = range->n0 + 1;\n    input_end = -filter_pixel_margin;\n    while( n >= input_end )\n    {\n      int out_first_pixel, out_last_pixel;\n      stbir__calculate_out_pixel_range( &out_first_pixel, &out_last_pixel, ((float)n)+0.5f, in_pixels_radius, scale, out_shift, output_sub_size );\n      if ( out_first_pixel > out_last_pixel )\n        break;\n\n      if ( ( out_first_pixel < output_sub_size ) || ( out_last_pixel >= 0 ) )\n        range->n0 = n;\n      --n;\n    }\n\n    // now go through the end of the area through the margin to find top\n    n = range->n1 - 1;\n    input_end = n + 1 + filter_pixel_margin;\n    while( n <= input_end )\n    {\n      int out_first_pixel, out_last_pixel;\n      stbir__calculate_out_pixel_range( &out_first_pixel, &out_last_pixel, ((float)n)+0.5f, in_pixels_radius, scale, out_shift, output_sub_size );\n      if ( out_first_pixel > out_last_pixel )\n        break;\n      if ( ( out_first_pixel < output_sub_size ) || ( out_last_pixel >= 0 ) )\n        range->n1 = n;\n      ++n;\n    }\n  }\n\n  if ( samp->edge == STBIR_EDGE_WRAP )\n  {\n    // if we are wrapping, and we are very close to the image size (so the edges might merge), just use the scanline up to the edge\n    if ( ( range->n0 > 0 ) && ( range->n1 >= input_full_size ) )\n    {\n      int marg = range->n1 - input_full_size + 1;\n      if ( ( marg + STBIR__MERGE_RUNS_PIXEL_THRESHOLD ) >= range->n0 )\n        range->n0 = 0;\n    }\n    if ( ( range->n0 < 0 ) && ( range->n1 < (input_full_size-1) ) )\n    {\n      int marg = -range->n0;\n      if ( ( input_full_size - marg - STBIR__MERGE_RUNS_PIXEL_THRESHOLD - 1 ) <= range->n1 )\n        range->n1 = input_full_size - 1;\n    }\n  }\n  else\n  {\n    // for non-edge-wrap modes, we never read over the edge, so clamp\n    if ( range->n0 < 0 )\n      range->n0 = 0;\n    if ( range->n1 >= input_full_size )\n      range->n1 = input_full_size - 1;\n  }\n}\n\nstatic void stbir__get_split_info( stbir__per_split_info* split_info, int splits, int output_height, int vertical_pixel_margin, int input_full_height, int is_gather, stbir__contributors * contribs )\n{\n  int i, cur;\n  int left = output_height;\n\n  cur = 0;\n  for( i = 0 ; i < splits ; i++ )\n  {\n    int each;\n\n    split_info[i].start_output_y = cur;\n    each = left / ( splits - i );\n    split_info[i].end_output_y = cur + each;\n\n    // ok, when we are gathering, we need to make sure we are starting on a y offset that doesn't have\n    //   a \"special\" set of coefficients. Basically, with exactly the right filter at exactly the right\n    //   resize at exactly the right phase, some of the coefficents can be zero. When they are zero, we\n    //   don't process them at all.  But this leads to a tricky thing with the thread splits, where we\n    //   might have a set of two coeffs like this for example: (4,4) and (3,6).  The 4,4 means there was\n    //   just one single coeff because things worked out perfectly (normally, they all have 4 coeffs\n    //   like the range 3,6.  The problem is that if we start right on the (4,4) on a brand new thread,\n    //   then when we get to (3,6), we don't have the \"3\" sample in memory (because we didn't load\n    //   it on the initial (4,4) range because it didn't have a 3 (we only add new samples that are \n    //   larger than our existing samples - it's just how the eviction works). So, our solution here\n    //   is pretty simple, if we start right on a range that has samples that start earlier, then we \n    //   simply bump up our previous thread split range to include it, and then start this threads\n    //   range with the smaller sample. It just moves one scanline from one thread split to another,\n    //   so that we end with the unusual one, instead of start with it. To do this, we check 2-4 \n    //   sample at each thread split start and then occassionally move them.\n    \n    if ( ( is_gather ) && ( i ) )\n    {\n      stbir__contributors * small_contribs;\n      int j, smallest, stop, start_n0;\n      stbir__contributors * split_contribs = contribs + cur;\n\n      // scan for a max of 3x the filter width or until the next thread split\n      stop = vertical_pixel_margin * 3;\n      if ( each < stop )\n        stop = each;\n\n      // loops a few times before early out\n      smallest = 0;\n      small_contribs = split_contribs;\n      start_n0 = small_contribs->n0;\n      for( j = 1 ; j <= stop ; j++ )\n      {\n        ++split_contribs;\n        if ( split_contribs->n0 > start_n0 )\n          break;\n        if ( split_contribs->n0 < small_contribs->n0 )\n        {\n          small_contribs = split_contribs;\n          smallest = j;\n        }\n      }\n\n      split_info[i-1].end_output_y += smallest;\n      split_info[i].start_output_y += smallest;\n    }\n\n    cur += each;\n    left -= each;\n\n    // scatter range (updated to minimum as you run it)\n    split_info[i].start_input_y = -vertical_pixel_margin;\n    split_info[i].end_input_y = input_full_height + vertical_pixel_margin;\n  }\n}\n\nstatic void stbir__free_internal_mem( stbir__info *info )\n{\n  #define STBIR__FREE_AND_CLEAR( ptr ) { if ( ptr ) { void * p = (ptr); (ptr) = 0; STBIR_FREE( p, info->user_data); } }\n\n  if ( info )\n  {\n  #ifndef STBIR__SEPARATE_ALLOCATIONS\n    STBIR__FREE_AND_CLEAR( info->alloced_mem );\n  #else\n    int i,j;\n\n    if ( ( info->vertical.gather_prescatter_contributors ) && ( (void*)info->vertical.gather_prescatter_contributors != (void*)info->split_info[0].decode_buffer ) )\n    {\n      STBIR__FREE_AND_CLEAR( info->vertical.gather_prescatter_coefficients );\n      STBIR__FREE_AND_CLEAR( info->vertical.gather_prescatter_contributors );\n    }\n    for( i = 0 ; i < info->splits ; i++ )\n    {\n      for( j = 0 ; j < info->alloc_ring_buffer_num_entries ; j++ )\n      {\n        #ifdef STBIR_SIMD8\n        if ( info->effective_channels == 3 )\n          --info->split_info[i].ring_buffers[j]; // avx in 3 channel mode needs one float at the start of the buffer\n        #endif\n        STBIR__FREE_AND_CLEAR( info->split_info[i].ring_buffers[j] );\n      }\n\n      #ifdef STBIR_SIMD8\n      if ( info->effective_channels == 3 )\n        --info->split_info[i].decode_buffer; // avx in 3 channel mode needs one float at the start of the buffer\n      #endif\n      STBIR__FREE_AND_CLEAR( info->split_info[i].decode_buffer );\n      STBIR__FREE_AND_CLEAR( info->split_info[i].ring_buffers );\n      STBIR__FREE_AND_CLEAR( info->split_info[i].vertical_buffer );\n    }\n    STBIR__FREE_AND_CLEAR( info->split_info );\n    if ( info->vertical.coefficients != info->horizontal.coefficients )\n    {\n      STBIR__FREE_AND_CLEAR( info->vertical.coefficients );\n      STBIR__FREE_AND_CLEAR( info->vertical.contributors );\n    }\n    STBIR__FREE_AND_CLEAR( info->horizontal.coefficients );\n    STBIR__FREE_AND_CLEAR( info->horizontal.contributors );\n    STBIR__FREE_AND_CLEAR( info->alloced_mem );\n    STBIR_FREE( info, info->user_data );\n  #endif\n  }\n\n  #undef STBIR__FREE_AND_CLEAR\n}\n\nstatic int stbir__get_max_split( int splits, int height )\n{\n  int i;\n  int max = 0;\n\n  for( i = 0 ; i < splits ; i++ )\n  {\n    int each = height / ( splits - i );\n    if ( each > max )\n      max = each;\n    height -= each;\n  }\n  return max;\n}\n\nstatic stbir__horizontal_gather_channels_func ** stbir__horizontal_gather_n_coeffs_funcs[8] =\n{\n  0, stbir__horizontal_gather_1_channels_with_n_coeffs_funcs, stbir__horizontal_gather_2_channels_with_n_coeffs_funcs, stbir__horizontal_gather_3_channels_with_n_coeffs_funcs, stbir__horizontal_gather_4_channels_with_n_coeffs_funcs, 0,0, stbir__horizontal_gather_7_channels_with_n_coeffs_funcs\n};\n\nstatic stbir__horizontal_gather_channels_func ** stbir__horizontal_gather_channels_funcs[8] =\n{\n  0, stbir__horizontal_gather_1_channels_funcs, stbir__horizontal_gather_2_channels_funcs, stbir__horizontal_gather_3_channels_funcs, stbir__horizontal_gather_4_channels_funcs, 0,0, stbir__horizontal_gather_7_channels_funcs\n};\n\n// there are six resize classifications: 0 == vertical scatter, 1 == vertical gather < 1x scale, 2 == vertical gather 1x-2x scale, 4 == vertical gather < 3x scale, 4 == vertical gather > 3x scale, 5 == <=4 pixel height, 6 == <=4 pixel wide column\n#define STBIR_RESIZE_CLASSIFICATIONS 8\n\nstatic float stbir__compute_weights[5][STBIR_RESIZE_CLASSIFICATIONS][4]=  // 5 = 0=1chan, 1=2chan, 2=3chan, 3=4chan, 4=7chan\n{\n  {\n    { 1.00000f, 1.00000f, 0.31250f, 1.00000f },\n    { 0.56250f, 0.59375f, 0.00000f, 0.96875f },\n    { 1.00000f, 0.06250f, 0.00000f, 1.00000f },\n    { 0.00000f, 0.09375f, 1.00000f, 1.00000f },\n    { 1.00000f, 1.00000f, 0.31250f, 1.00000f },\n    { 0.03125f, 0.12500f, 1.00000f, 1.00000f },\n    { 1.00000f, 1.00000f, 0.06250f, 1.00000f },\n    { 0.00000f, 1.00000f, 0.00000f, 0.03125f },\n  }, {\n    { 0.00000f, 0.84375f, 0.00000f, 0.03125f },\n    { 0.09375f, 0.93750f, 0.00000f, 0.78125f },\n    { 0.87500f, 0.21875f, 0.00000f, 0.96875f },\n    { 0.09375f, 0.09375f, 1.00000f, 1.00000f },\n    { 0.00000f, 0.84375f, 0.00000f, 0.03125f },\n    { 0.03125f, 0.12500f, 1.00000f, 1.00000f },\n    { 1.00000f, 1.00000f, 0.06250f, 1.00000f },\n    { 0.00000f, 1.00000f, 0.00000f, 0.53125f },\n  }, {\n    { 0.00000f, 0.53125f, 0.00000f, 0.03125f },\n    { 0.06250f, 0.96875f, 0.00000f, 0.53125f },\n    { 0.87500f, 0.18750f, 0.00000f, 0.93750f },\n    { 0.00000f, 0.09375f, 1.00000f, 1.00000f },\n    { 0.00000f, 0.53125f, 0.00000f, 0.03125f },\n    { 0.03125f, 0.12500f, 1.00000f, 1.00000f },\n    { 1.00000f, 1.00000f, 0.06250f, 1.00000f },\n    { 0.00000f, 1.00000f, 0.00000f, 0.56250f },\n  }, {\n    { 0.00000f, 0.50000f, 0.00000f, 0.71875f },\n    { 0.06250f, 0.84375f, 0.00000f, 0.87500f },\n    { 1.00000f, 0.50000f, 0.50000f, 0.96875f },\n    { 1.00000f, 0.09375f, 0.31250f, 0.50000f },\n    { 0.00000f, 0.50000f, 0.00000f, 0.71875f },\n    { 1.00000f, 0.03125f, 0.03125f, 0.53125f },\n    { 1.00000f, 1.00000f, 0.06250f, 1.00000f },\n    { 0.00000f, 1.00000f, 0.03125f, 0.18750f },\n  }, {\n    { 0.00000f, 0.59375f, 0.00000f, 0.96875f },\n    { 0.06250f, 0.81250f, 0.06250f, 0.59375f },\n    { 0.75000f, 0.43750f, 0.12500f, 0.96875f },\n    { 0.87500f, 0.06250f, 0.18750f, 0.43750f },\n    { 0.00000f, 0.59375f, 0.00000f, 0.96875f },\n    { 0.15625f, 0.12500f, 1.00000f, 1.00000f },\n    { 1.00000f, 1.00000f, 0.06250f, 1.00000f },\n    { 0.00000f, 1.00000f, 0.03125f, 0.34375f },\n  }\n};\n\n// structure that allow us to query and override info for training the costs\ntypedef struct STBIR__V_FIRST_INFO\n{\n  double v_cost, h_cost;\n  int control_v_first; // 0 = no control, 1 = force hori, 2 = force vert\n  int v_first;\n  int v_resize_classification;\n  int is_gather;\n} STBIR__V_FIRST_INFO;\n\n#ifdef STBIR__V_FIRST_INFO_BUFFER\nstatic STBIR__V_FIRST_INFO STBIR__V_FIRST_INFO_BUFFER = {0};\n#define STBIR__V_FIRST_INFO_POINTER &STBIR__V_FIRST_INFO_BUFFER\n#else\n#define STBIR__V_FIRST_INFO_POINTER 0\n#endif\n\n// Figure out whether to scale along the horizontal or vertical first.\n//   This only *super* important when you are scaling by a massively\n//   different amount in the vertical vs the horizontal (for example, if\n//   you are scaling by 2x in the width, and 0.5x in the height, then you\n//   want to do the vertical scale first, because it's around 3x faster\n//   in that order.\n//\n//   In more normal circumstances, this makes a 20-40% differences, so\n//     it's good to get right, but not critical. The normal way that you\n//     decide which direction goes first is just figuring out which\n//     direction does more multiplies. But with modern CPUs with their\n//     fancy caches and SIMD and high IPC abilities, so there's just a lot\n//     more that goes into it.\n//\n//   My handwavy sort of solution is to have an app that does a whole\n//     bunch of timing for both vertical and horizontal first modes,\n//     and then another app that can read lots of these timing files\n//     and try to search for the best weights to use. Dotimings.c\n//     is the app that does a bunch of timings, and vf_train.c is the\n//     app that solves for the best weights (and shows how well it\n//     does currently).\n\nstatic int stbir__should_do_vertical_first( float weights_table[STBIR_RESIZE_CLASSIFICATIONS][4], int horizontal_filter_pixel_width, float horizontal_scale, int horizontal_output_size, int vertical_filter_pixel_width, float vertical_scale, int vertical_output_size, int is_gather, STBIR__V_FIRST_INFO * info )\n{\n  double v_cost, h_cost;\n  float * weights;\n  int vertical_first;\n  int v_classification;\n\n  // categorize the resize into buckets\n  if ( ( vertical_output_size <= 4 ) || ( horizontal_output_size <= 4 ) )\n    v_classification = ( vertical_output_size < horizontal_output_size ) ? 6 : 7;\n  else if ( ( !is_gather ) && ( ( vertical_output_size <= 16 ) || ( horizontal_output_size <= 16 ) ) )\n    v_classification = 4;\n  else if ( vertical_scale <= 1.0f )\n    v_classification = ( is_gather ) ? 1 : 0;\n  else if ( vertical_scale <= 2.0f)\n    v_classification = 2;\n  else if ( vertical_scale <= 3.0f)\n    v_classification = 3;\n  else \n    v_classification = 5; // everything bigger than 3x\n\n  // use the right weights\n  weights = weights_table[ v_classification ];\n\n  // this is the costs when you don't take into account modern CPUs with high ipc and simd and caches - wish we had a better estimate\n  h_cost = (float)horizontal_filter_pixel_width * weights[0] + horizontal_scale * (float)vertical_filter_pixel_width * weights[1];\n  v_cost = (float)vertical_filter_pixel_width  * weights[2] + vertical_scale * (float)horizontal_filter_pixel_width * weights[3];\n\n  // use computation estimate to decide vertical first or not\n  vertical_first = ( v_cost <= h_cost ) ? 1 : 0;\n\n  // save these, if requested\n  if ( info )\n  {\n    info->h_cost = h_cost;\n    info->v_cost = v_cost;\n    info->v_resize_classification = v_classification;\n    info->v_first = vertical_first;\n    info->is_gather = is_gather;\n  }\n\n  // and this allows us to override everything for testing (see dotiming.c)\n  if ( ( info ) && ( info->control_v_first ) )\n    vertical_first = ( info->control_v_first == 2 ) ? 1 : 0;\n\n  return vertical_first;\n}\n\n// layout lookups - must match stbir_internal_pixel_layout\nstatic unsigned char stbir__pixel_channels[] = {\n  1,2,3,3,4,   // 1ch, 2ch, rgb, bgr, 4ch\n  4,4,4,4,2,2, // RGBA,BGRA,ARGB,ABGR,RA,AR\n  4,4,4,4,2,2, // RGBA_PM,BGRA_PM,ARGB_PM,ABGR_PM,RA_PM,AR_PM\n};\n\n// the internal pixel layout enums are in a different order, so we can easily do range comparisons of types\n//   the public pixel layout is ordered in a way that if you cast num_channels (1-4) to the enum, you get something sensible\nstatic stbir_internal_pixel_layout stbir__pixel_layout_convert_public_to_internal[] = {\n  STBIRI_BGR, STBIRI_1CHANNEL, STBIRI_2CHANNEL, STBIRI_RGB, STBIRI_RGBA,\n  STBIRI_4CHANNEL, STBIRI_BGRA, STBIRI_ARGB, STBIRI_ABGR, STBIRI_RA, STBIRI_AR,\n  STBIRI_RGBA_PM, STBIRI_BGRA_PM, STBIRI_ARGB_PM, STBIRI_ABGR_PM, STBIRI_RA_PM, STBIRI_AR_PM,\n};\n\nstatic stbir__info * stbir__alloc_internal_mem_and_build_samplers( stbir__sampler * horizontal, stbir__sampler * vertical, stbir__contributors * conservative, stbir_pixel_layout input_pixel_layout_public, stbir_pixel_layout output_pixel_layout_public, int splits, int new_x, int new_y, int fast_alpha, void * user_data STBIR_ONLY_PROFILE_BUILD_GET_INFO )\n{\n  static char stbir_channel_count_index[8]={ 9,0,1,2, 3,9,9,4 };\n\n  stbir__info * info = 0;\n  void * alloced = 0;\n  size_t alloced_total = 0;\n  int vertical_first;\n  size_t decode_buffer_size, ring_buffer_length_bytes, ring_buffer_size, vertical_buffer_size;\n  int alloc_ring_buffer_num_entries;\n\n  int alpha_weighting_type = 0; // 0=none, 1=simple, 2=fancy\n  int conservative_split_output_size = stbir__get_max_split( splits, vertical->scale_info.output_sub_size );\n  stbir_internal_pixel_layout input_pixel_layout = stbir__pixel_layout_convert_public_to_internal[ input_pixel_layout_public ];\n  stbir_internal_pixel_layout output_pixel_layout = stbir__pixel_layout_convert_public_to_internal[ output_pixel_layout_public ];\n  int channels = stbir__pixel_channels[ input_pixel_layout ];\n  int effective_channels = channels;\n\n  // first figure out what type of alpha weighting to use (if any)\n  if ( ( horizontal->filter_enum != STBIR_FILTER_POINT_SAMPLE ) || ( vertical->filter_enum != STBIR_FILTER_POINT_SAMPLE ) ) // no alpha weighting on point sampling\n  {\n    if ( ( input_pixel_layout >= STBIRI_RGBA ) && ( input_pixel_layout <= STBIRI_AR ) && ( output_pixel_layout >= STBIRI_RGBA ) && ( output_pixel_layout <= STBIRI_AR ) )\n    {\n      if ( fast_alpha )\n      {\n        alpha_weighting_type = 4;\n      }\n      else\n      {\n        static int fancy_alpha_effective_cnts[6] = { 7, 7, 7, 7, 3, 3 };\n        alpha_weighting_type = 2;\n        effective_channels = fancy_alpha_effective_cnts[ input_pixel_layout - STBIRI_RGBA ];\n      }\n    }\n    else if ( ( input_pixel_layout >= STBIRI_RGBA_PM ) && ( input_pixel_layout <= STBIRI_AR_PM ) && ( output_pixel_layout >= STBIRI_RGBA ) && ( output_pixel_layout <= STBIRI_AR ) )\n    {\n      // input premult, output non-premult\n      alpha_weighting_type = 3;\n    }\n    else if ( ( input_pixel_layout >= STBIRI_RGBA ) && ( input_pixel_layout <= STBIRI_AR ) && ( output_pixel_layout >= STBIRI_RGBA_PM ) && ( output_pixel_layout <= STBIRI_AR_PM ) )\n    {\n      // input non-premult, output premult\n      alpha_weighting_type = 1;\n    }\n  }\n\n  // channel in and out count must match currently\n  if ( channels != stbir__pixel_channels[ output_pixel_layout ] )\n    return 0;\n\n  // get vertical first\n  vertical_first = stbir__should_do_vertical_first( stbir__compute_weights[ (int)stbir_channel_count_index[ effective_channels ] ], horizontal->filter_pixel_width, horizontal->scale_info.scale, horizontal->scale_info.output_sub_size, vertical->filter_pixel_width, vertical->scale_info.scale, vertical->scale_info.output_sub_size, vertical->is_gather, STBIR__V_FIRST_INFO_POINTER );\n\n  // sometimes read one float off in some of the unrolled loops (with a weight of zero coeff, so it doesn't have an effect)\n  //   we use a few extra floats instead of just 1, so that input callback buffer can overlap with the decode buffer without\n  //   the conversion routines overwriting the callback input data.\n  decode_buffer_size = ( conservative->n1 - conservative->n0 + 1 ) * effective_channels * sizeof(float) + sizeof(float)*STBIR_INPUT_CALLBACK_PADDING; // extra floats for input callback stagger\n\n#if defined( STBIR__SEPARATE_ALLOCATIONS ) && defined(STBIR_SIMD8)\n  if ( effective_channels == 3 )\n    decode_buffer_size += sizeof(float); // avx in 3 channel mode needs one float at the start of the buffer (only with separate allocations)\n#endif\n\n  ring_buffer_length_bytes = (size_t)horizontal->scale_info.output_sub_size * (size_t)effective_channels * sizeof(float) + sizeof(float)*STBIR_INPUT_CALLBACK_PADDING; // extra floats for padding\n\n  // if we do vertical first, the ring buffer holds a whole decoded line\n  if ( vertical_first )\n    ring_buffer_length_bytes = ( decode_buffer_size + 15 ) & ~15;\n\n  if ( ( ring_buffer_length_bytes & 4095 ) == 0 ) ring_buffer_length_bytes += 64*3; // avoid 4k alias\n\n  // One extra entry because floating point precision problems sometimes cause an extra to be necessary.\n  alloc_ring_buffer_num_entries = vertical->filter_pixel_width + 1;\n\n  // we never need more ring buffer entries than the scanlines we're outputting when in scatter mode\n  if ( ( !vertical->is_gather ) && ( alloc_ring_buffer_num_entries > conservative_split_output_size ) )\n    alloc_ring_buffer_num_entries = conservative_split_output_size;\n\n  ring_buffer_size = (size_t)alloc_ring_buffer_num_entries * (size_t)ring_buffer_length_bytes;\n\n  // The vertical buffer is used differently, depending on whether we are scattering\n  //   the vertical scanlines, or gathering them.\n  //   If scattering, it's used at the temp buffer to accumulate each output.\n  //   If gathering, it's just the output buffer.\n  vertical_buffer_size = (size_t)horizontal->scale_info.output_sub_size * (size_t)effective_channels * sizeof(float) + sizeof(float);  // extra float for padding\n\n  // we make two passes through this loop, 1st to add everything up, 2nd to allocate and init\n  for(;;)\n  {\n    int i;\n    void * advance_mem = alloced;\n    int copy_horizontal = 0;\n    stbir__sampler * possibly_use_horizontal_for_pivot = 0;\n\n#ifdef STBIR__SEPARATE_ALLOCATIONS\n    #define STBIR__NEXT_PTR( ptr, size, ntype ) if ( alloced ) { void * p = STBIR_MALLOC( size, user_data); if ( p == 0 ) { stbir__free_internal_mem( info ); return 0; } (ptr) = (ntype*)p; }\n#else\n    #define STBIR__NEXT_PTR( ptr, size, ntype ) advance_mem = (void*) ( ( ((size_t)advance_mem) + 15 ) & ~15 ); if ( alloced ) ptr = (ntype*)advance_mem; advance_mem = (char*)(((size_t)advance_mem) + (size));\n#endif\n\n    STBIR__NEXT_PTR( info, sizeof( stbir__info ), stbir__info );\n\n    STBIR__NEXT_PTR( info->split_info, sizeof( stbir__per_split_info ) * splits, stbir__per_split_info );\n\n    if ( info )\n    {\n      static stbir__alpha_weight_func * fancy_alpha_weights[6]  =    { stbir__fancy_alpha_weight_4ch,   stbir__fancy_alpha_weight_4ch,   stbir__fancy_alpha_weight_4ch,   stbir__fancy_alpha_weight_4ch,   stbir__fancy_alpha_weight_2ch,   stbir__fancy_alpha_weight_2ch };\n      static stbir__alpha_unweight_func * fancy_alpha_unweights[6] = { stbir__fancy_alpha_unweight_4ch, stbir__fancy_alpha_unweight_4ch, stbir__fancy_alpha_unweight_4ch, stbir__fancy_alpha_unweight_4ch, stbir__fancy_alpha_unweight_2ch, stbir__fancy_alpha_unweight_2ch };\n      static stbir__alpha_weight_func * simple_alpha_weights[6] = { stbir__simple_alpha_weight_4ch, stbir__simple_alpha_weight_4ch, stbir__simple_alpha_weight_4ch, stbir__simple_alpha_weight_4ch, stbir__simple_alpha_weight_2ch, stbir__simple_alpha_weight_2ch };\n      static stbir__alpha_unweight_func * simple_alpha_unweights[6] = { stbir__simple_alpha_unweight_4ch, stbir__simple_alpha_unweight_4ch, stbir__simple_alpha_unweight_4ch, stbir__simple_alpha_unweight_4ch, stbir__simple_alpha_unweight_2ch, stbir__simple_alpha_unweight_2ch };\n\n      // initialize info fields\n      info->alloced_mem = alloced;\n      info->alloced_total = alloced_total;\n\n      info->channels = channels;\n      info->effective_channels = effective_channels;\n\n      info->offset_x = new_x;\n      info->offset_y = new_y;\n      info->alloc_ring_buffer_num_entries = (int)alloc_ring_buffer_num_entries;\n      info->ring_buffer_num_entries = 0;\n      info->ring_buffer_length_bytes = (int)ring_buffer_length_bytes;\n      info->splits = splits;\n      info->vertical_first = vertical_first;\n\n      info->input_pixel_layout_internal = input_pixel_layout;\n      info->output_pixel_layout_internal = output_pixel_layout;\n\n      // setup alpha weight functions\n      info->alpha_weight = 0;\n      info->alpha_unweight = 0;\n\n      // handle alpha weighting functions and overrides\n      if ( alpha_weighting_type == 2 )\n      {\n        // high quality alpha multiplying on the way in, dividing on the way out\n        info->alpha_weight = fancy_alpha_weights[ input_pixel_layout - STBIRI_RGBA ];\n        info->alpha_unweight = fancy_alpha_unweights[ output_pixel_layout - STBIRI_RGBA ];\n      }\n      else if ( alpha_weighting_type == 4 )\n      {\n        // fast alpha multiplying on the way in, dividing on the way out\n        info->alpha_weight = simple_alpha_weights[ input_pixel_layout - STBIRI_RGBA ];\n        info->alpha_unweight = simple_alpha_unweights[ output_pixel_layout - STBIRI_RGBA ];\n      }\n      else if ( alpha_weighting_type == 1 )\n      {\n        // fast alpha on the way in, leave in premultiplied form on way out\n        info->alpha_weight = simple_alpha_weights[ input_pixel_layout - STBIRI_RGBA ];\n      }\n      else if ( alpha_weighting_type == 3 )\n      {\n        // incoming is premultiplied, fast alpha dividing on the way out - non-premultiplied output\n        info->alpha_unweight = simple_alpha_unweights[ output_pixel_layout - STBIRI_RGBA ];\n      }\n\n      // handle 3-chan color flipping, using the alpha weight path\n      if ( ( ( input_pixel_layout == STBIRI_RGB ) && ( output_pixel_layout == STBIRI_BGR ) ) ||\n           ( ( input_pixel_layout == STBIRI_BGR ) && ( output_pixel_layout == STBIRI_RGB ) ) )\n      {\n        // do the flipping on the smaller of the two ends\n        if ( horizontal->scale_info.scale < 1.0f )\n          info->alpha_unweight = stbir__simple_flip_3ch;\n        else\n          info->alpha_weight = stbir__simple_flip_3ch;\n      }\n\n    }\n\n    // get all the per-split buffers\n    for( i = 0 ; i < splits ; i++ )\n    {\n      STBIR__NEXT_PTR( info->split_info[i].decode_buffer, decode_buffer_size, float );\n\n#ifdef STBIR__SEPARATE_ALLOCATIONS\n\n      #ifdef STBIR_SIMD8\n      if ( ( info ) && ( effective_channels == 3 ) )\n        ++info->split_info[i].decode_buffer; // avx in 3 channel mode needs one float at the start of the buffer\n      #endif\n\n      STBIR__NEXT_PTR( info->split_info[i].ring_buffers, alloc_ring_buffer_num_entries * sizeof(float*), float* );\n      {\n        int j;\n        for( j = 0 ; j < alloc_ring_buffer_num_entries ; j++ )\n        {\n          STBIR__NEXT_PTR( info->split_info[i].ring_buffers[j], ring_buffer_length_bytes, float );\n          #ifdef STBIR_SIMD8\n          if ( ( info ) && ( effective_channels == 3 ) )\n            ++info->split_info[i].ring_buffers[j]; // avx in 3 channel mode needs one float at the start of the buffer\n          #endif\n        }\n      }\n#else\n      STBIR__NEXT_PTR( info->split_info[i].ring_buffer, ring_buffer_size, float );\n#endif\n      STBIR__NEXT_PTR( info->split_info[i].vertical_buffer, vertical_buffer_size, float );\n    }\n\n    // alloc memory for to-be-pivoted coeffs (if necessary)\n    if ( vertical->is_gather == 0 )\n    {\n      size_t both;\n      size_t temp_mem_amt;\n\n      // when in vertical scatter mode, we first build the coefficients in gather mode, and then pivot after,\n      //   that means we need two buffers, so we try to use the decode buffer and ring buffer for this. if that\n      //   is too small, we just allocate extra memory to use as this temp.\n\n      both = (size_t)vertical->gather_prescatter_contributors_size + (size_t)vertical->gather_prescatter_coefficients_size;\n\n#ifdef STBIR__SEPARATE_ALLOCATIONS\n      temp_mem_amt = decode_buffer_size;\n\n      #ifdef STBIR_SIMD8\n      if ( effective_channels == 3 )\n        --temp_mem_amt; // avx in 3 channel mode needs one float at the start of the buffer\n      #endif\n#else\n      temp_mem_amt = (size_t)( decode_buffer_size + ring_buffer_size + vertical_buffer_size ) * (size_t)splits;\n#endif\n      if ( temp_mem_amt >= both )\n      {\n        if ( info )\n        {\n          vertical->gather_prescatter_contributors = (stbir__contributors*)info->split_info[0].decode_buffer;\n          vertical->gather_prescatter_coefficients = (float*) ( ( (char*)info->split_info[0].decode_buffer ) + vertical->gather_prescatter_contributors_size );\n        }\n      }\n      else\n      {\n        // ring+decode memory is too small, so allocate temp memory\n        STBIR__NEXT_PTR( vertical->gather_prescatter_contributors, vertical->gather_prescatter_contributors_size, stbir__contributors );\n        STBIR__NEXT_PTR( vertical->gather_prescatter_coefficients, vertical->gather_prescatter_coefficients_size, float );\n      }\n    }\n\n    STBIR__NEXT_PTR( horizontal->contributors, horizontal->contributors_size, stbir__contributors );\n    STBIR__NEXT_PTR( horizontal->coefficients, horizontal->coefficients_size, float );\n\n    // are the two filters identical?? (happens a lot with mipmap generation)\n    if ( ( horizontal->filter_kernel == vertical->filter_kernel ) && ( horizontal->filter_support == vertical->filter_support ) && ( horizontal->edge == vertical->edge ) && ( horizontal->scale_info.output_sub_size == vertical->scale_info.output_sub_size ) )\n    {\n      float diff_scale = horizontal->scale_info.scale - vertical->scale_info.scale;\n      float diff_shift = horizontal->scale_info.pixel_shift - vertical->scale_info.pixel_shift;\n      if ( diff_scale < 0.0f ) diff_scale = -diff_scale;\n      if ( diff_shift < 0.0f ) diff_shift = -diff_shift;\n      if ( ( diff_scale <= stbir__small_float ) && ( diff_shift <= stbir__small_float ) )\n      {\n        if ( horizontal->is_gather == vertical->is_gather )\n        {\n          copy_horizontal = 1;\n          goto no_vert_alloc;\n        }\n        // everything matches, but vertical is scatter, horizontal is gather, use horizontal coeffs for vertical pivot coeffs\n        possibly_use_horizontal_for_pivot = horizontal;\n      }\n    }\n\n    STBIR__NEXT_PTR( vertical->contributors, vertical->contributors_size, stbir__contributors );\n    STBIR__NEXT_PTR( vertical->coefficients, vertical->coefficients_size, float );\n\n   no_vert_alloc:\n\n    if ( info )\n    {\n      STBIR_PROFILE_BUILD_START( horizontal );\n\n      stbir__calculate_filters( horizontal, 0, user_data STBIR_ONLY_PROFILE_BUILD_SET_INFO );\n\n      // setup the horizontal gather functions\n      // start with defaulting to the n_coeffs functions (specialized on channels and remnant leftover)\n      info->horizontal_gather_channels = stbir__horizontal_gather_n_coeffs_funcs[ effective_channels ][ horizontal->extent_info.widest & 3 ];\n      // but if the number of coeffs <= 12, use another set of special cases. <=12 coeffs is any enlarging resize, or shrinking resize down to about 1/3 size\n      if ( horizontal->extent_info.widest <= 12 )\n        info->horizontal_gather_channels = stbir__horizontal_gather_channels_funcs[ effective_channels ][ horizontal->extent_info.widest - 1 ];\n\n      info->scanline_extents.conservative.n0 = conservative->n0;\n      info->scanline_extents.conservative.n1 = conservative->n1;\n\n      // get exact extents\n      stbir__get_extents( horizontal, &info->scanline_extents );\n\n      // pack the horizontal coeffs\n      horizontal->coefficient_width = stbir__pack_coefficients(horizontal->num_contributors, horizontal->contributors, horizontal->coefficients, horizontal->coefficient_width, horizontal->extent_info.widest, info->scanline_extents.conservative.n0, info->scanline_extents.conservative.n1 );\n\n      STBIR_MEMCPY( &info->horizontal, horizontal, sizeof( stbir__sampler ) );\n\n      STBIR_PROFILE_BUILD_END( horizontal );\n\n      if ( copy_horizontal )\n      {\n        STBIR_MEMCPY( &info->vertical, horizontal, sizeof( stbir__sampler ) );\n      }\n      else\n      {\n        STBIR_PROFILE_BUILD_START( vertical );\n\n        stbir__calculate_filters( vertical, possibly_use_horizontal_for_pivot, user_data STBIR_ONLY_PROFILE_BUILD_SET_INFO );\n        STBIR_MEMCPY( &info->vertical, vertical, sizeof( stbir__sampler ) );\n\n        STBIR_PROFILE_BUILD_END( vertical );\n      }\n\n      // setup the vertical split ranges\n      stbir__get_split_info( info->split_info, info->splits, info->vertical.scale_info.output_sub_size, info->vertical.filter_pixel_margin, info->vertical.scale_info.input_full_size, info->vertical.is_gather, info->vertical.contributors );\n\n      // now we know precisely how many entries we need\n      info->ring_buffer_num_entries = info->vertical.extent_info.widest;\n\n      // we never need more ring buffer entries than the scanlines we're outputting\n      if ( ( !info->vertical.is_gather ) && ( info->ring_buffer_num_entries > conservative_split_output_size ) )\n        info->ring_buffer_num_entries = conservative_split_output_size;\n      STBIR_ASSERT( info->ring_buffer_num_entries <= info->alloc_ring_buffer_num_entries );\n    }\n    #undef STBIR__NEXT_PTR\n\n\n    // is this the first time through loop?\n    if ( info == 0 )\n    {\n      alloced_total = ( 15 + (size_t)advance_mem );\n      alloced = STBIR_MALLOC( alloced_total, user_data );\n      if ( alloced == 0 )\n        return 0;\n    }\n    else\n      return info;  // success\n  }\n}\n\nstatic int stbir__perform_resize( stbir__info const * info, int split_start, int split_count )\n{\n  stbir__per_split_info * split_info = info->split_info + split_start;\n\n  STBIR_PROFILE_CLEAR_EXTRAS();\n\n  STBIR_PROFILE_FIRST_START( looping );\n  if (info->vertical.is_gather)\n    stbir__vertical_gather_loop( info, split_info, split_count );\n  else\n    stbir__vertical_scatter_loop( info, split_info, split_count );\n  STBIR_PROFILE_END( looping );\n\n  return 1;\n}\n\nstatic void stbir__update_info_from_resize( stbir__info * info, STBIR_RESIZE * resize )\n{\n  static stbir__decode_pixels_func * decode_simple[STBIR_TYPE_HALF_FLOAT-STBIR_TYPE_UINT8_SRGB+1]=\n  {\n    /* 1ch-4ch */ stbir__decode_uint8_srgb, stbir__decode_uint8_srgb, 0, stbir__decode_float_linear, stbir__decode_half_float_linear,\n  };\n\n  static stbir__decode_pixels_func * decode_alphas[STBIRI_AR-STBIRI_RGBA+1][STBIR_TYPE_HALF_FLOAT-STBIR_TYPE_UINT8_SRGB+1]=\n  {\n    { /* RGBA */ stbir__decode_uint8_srgb4_linearalpha,      stbir__decode_uint8_srgb,      0, stbir__decode_float_linear,      stbir__decode_half_float_linear },\n    { /* BGRA */ stbir__decode_uint8_srgb4_linearalpha_BGRA, stbir__decode_uint8_srgb_BGRA, 0, stbir__decode_float_linear_BGRA, stbir__decode_half_float_linear_BGRA },\n    { /* ARGB */ stbir__decode_uint8_srgb4_linearalpha_ARGB, stbir__decode_uint8_srgb_ARGB, 0, stbir__decode_float_linear_ARGB, stbir__decode_half_float_linear_ARGB },\n    { /* ABGR */ stbir__decode_uint8_srgb4_linearalpha_ABGR, stbir__decode_uint8_srgb_ABGR, 0, stbir__decode_float_linear_ABGR, stbir__decode_half_float_linear_ABGR },\n    { /* RA   */ stbir__decode_uint8_srgb2_linearalpha,      stbir__decode_uint8_srgb,      0, stbir__decode_float_linear,      stbir__decode_half_float_linear },\n    { /* AR   */ stbir__decode_uint8_srgb2_linearalpha_AR,   stbir__decode_uint8_srgb_AR,   0, stbir__decode_float_linear_AR,   stbir__decode_half_float_linear_AR },\n  };\n\n  static stbir__decode_pixels_func * decode_simple_scaled_or_not[2][2]=\n  {\n    { stbir__decode_uint8_linear_scaled,  stbir__decode_uint8_linear }, { stbir__decode_uint16_linear_scaled, stbir__decode_uint16_linear },\n  };\n\n  static stbir__decode_pixels_func * decode_alphas_scaled_or_not[STBIRI_AR-STBIRI_RGBA+1][2][2]=\n  {\n    { /* RGBA */ { stbir__decode_uint8_linear_scaled,       stbir__decode_uint8_linear },      { stbir__decode_uint16_linear_scaled,      stbir__decode_uint16_linear } },\n    { /* BGRA */ { stbir__decode_uint8_linear_scaled_BGRA,  stbir__decode_uint8_linear_BGRA }, { stbir__decode_uint16_linear_scaled_BGRA, stbir__decode_uint16_linear_BGRA } },\n    { /* ARGB */ { stbir__decode_uint8_linear_scaled_ARGB,  stbir__decode_uint8_linear_ARGB }, { stbir__decode_uint16_linear_scaled_ARGB, stbir__decode_uint16_linear_ARGB } },\n    { /* ABGR */ { stbir__decode_uint8_linear_scaled_ABGR,  stbir__decode_uint8_linear_ABGR }, { stbir__decode_uint16_linear_scaled_ABGR, stbir__decode_uint16_linear_ABGR } },\n    { /* RA   */ { stbir__decode_uint8_linear_scaled,       stbir__decode_uint8_linear },      { stbir__decode_uint16_linear_scaled,      stbir__decode_uint16_linear } },\n    { /* AR   */ { stbir__decode_uint8_linear_scaled_AR,    stbir__decode_uint8_linear_AR },   { stbir__decode_uint16_linear_scaled_AR,   stbir__decode_uint16_linear_AR } }\n  };\n\n  static stbir__encode_pixels_func * encode_simple[STBIR_TYPE_HALF_FLOAT-STBIR_TYPE_UINT8_SRGB+1]=\n  {\n    /* 1ch-4ch */ stbir__encode_uint8_srgb, stbir__encode_uint8_srgb, 0, stbir__encode_float_linear, stbir__encode_half_float_linear,\n  };\n\n  static stbir__encode_pixels_func * encode_alphas[STBIRI_AR-STBIRI_RGBA+1][STBIR_TYPE_HALF_FLOAT-STBIR_TYPE_UINT8_SRGB+1]=\n  {\n    { /* RGBA */ stbir__encode_uint8_srgb4_linearalpha,      stbir__encode_uint8_srgb,      0, stbir__encode_float_linear,      stbir__encode_half_float_linear },\n    { /* BGRA */ stbir__encode_uint8_srgb4_linearalpha_BGRA, stbir__encode_uint8_srgb_BGRA, 0, stbir__encode_float_linear_BGRA, stbir__encode_half_float_linear_BGRA },\n    { /* ARGB */ stbir__encode_uint8_srgb4_linearalpha_ARGB, stbir__encode_uint8_srgb_ARGB, 0, stbir__encode_float_linear_ARGB, stbir__encode_half_float_linear_ARGB },\n    { /* ABGR */ stbir__encode_uint8_srgb4_linearalpha_ABGR, stbir__encode_uint8_srgb_ABGR, 0, stbir__encode_float_linear_ABGR, stbir__encode_half_float_linear_ABGR },\n    { /* RA   */ stbir__encode_uint8_srgb2_linearalpha,      stbir__encode_uint8_srgb,      0, stbir__encode_float_linear,      stbir__encode_half_float_linear },\n    { /* AR   */ stbir__encode_uint8_srgb2_linearalpha_AR,   stbir__encode_uint8_srgb_AR,   0, stbir__encode_float_linear_AR,   stbir__encode_half_float_linear_AR }\n  };\n\n  static stbir__encode_pixels_func * encode_simple_scaled_or_not[2][2]=\n  {\n    { stbir__encode_uint8_linear_scaled,  stbir__encode_uint8_linear }, { stbir__encode_uint16_linear_scaled, stbir__encode_uint16_linear },\n  };\n\n  static stbir__encode_pixels_func * encode_alphas_scaled_or_not[STBIRI_AR-STBIRI_RGBA+1][2][2]=\n  {\n    { /* RGBA */ { stbir__encode_uint8_linear_scaled,       stbir__encode_uint8_linear },       { stbir__encode_uint16_linear_scaled,      stbir__encode_uint16_linear } },\n    { /* BGRA */ { stbir__encode_uint8_linear_scaled_BGRA,  stbir__encode_uint8_linear_BGRA },  { stbir__encode_uint16_linear_scaled_BGRA, stbir__encode_uint16_linear_BGRA } },\n    { /* ARGB */ { stbir__encode_uint8_linear_scaled_ARGB,  stbir__encode_uint8_linear_ARGB },  { stbir__encode_uint16_linear_scaled_ARGB, stbir__encode_uint16_linear_ARGB } },\n    { /* ABGR */ { stbir__encode_uint8_linear_scaled_ABGR,  stbir__encode_uint8_linear_ABGR },  { stbir__encode_uint16_linear_scaled_ABGR, stbir__encode_uint16_linear_ABGR } },\n    { /* RA   */ { stbir__encode_uint8_linear_scaled,       stbir__encode_uint8_linear },       { stbir__encode_uint16_linear_scaled,      stbir__encode_uint16_linear } },\n    { /* AR   */ { stbir__encode_uint8_linear_scaled_AR,    stbir__encode_uint8_linear_AR },    { stbir__encode_uint16_linear_scaled_AR,   stbir__encode_uint16_linear_AR } }\n  };\n\n  stbir__decode_pixels_func * decode_pixels = 0;\n  stbir__encode_pixels_func * encode_pixels = 0;\n  stbir_datatype input_type, output_type;\n\n  input_type = resize->input_data_type;\n  output_type = resize->output_data_type;\n  info->input_data = resize->input_pixels;\n  info->input_stride_bytes = resize->input_stride_in_bytes;\n  info->output_stride_bytes = resize->output_stride_in_bytes;\n\n  // if we're completely point sampling, then we can turn off SRGB\n  if ( ( info->horizontal.filter_enum == STBIR_FILTER_POINT_SAMPLE ) && ( info->vertical.filter_enum == STBIR_FILTER_POINT_SAMPLE ) )\n  {\n    if ( ( ( input_type  == STBIR_TYPE_UINT8_SRGB ) || ( input_type  == STBIR_TYPE_UINT8_SRGB_ALPHA ) ) &&\n         ( ( output_type == STBIR_TYPE_UINT8_SRGB ) || ( output_type == STBIR_TYPE_UINT8_SRGB_ALPHA ) ) )\n    {\n      input_type = STBIR_TYPE_UINT8;\n      output_type = STBIR_TYPE_UINT8;\n    }\n  }\n\n  // recalc the output and input strides\n  if ( info->input_stride_bytes == 0 )\n    info->input_stride_bytes = info->channels * info->horizontal.scale_info.input_full_size * stbir__type_size[input_type];\n\n  if ( info->output_stride_bytes == 0 )\n    info->output_stride_bytes = info->channels * info->horizontal.scale_info.output_sub_size * stbir__type_size[output_type];\n\n  // calc offset\n  info->output_data = ( (char*) resize->output_pixels ) + ( (size_t) info->offset_y * (size_t) resize->output_stride_in_bytes ) + ( info->offset_x * info->channels * stbir__type_size[output_type] );\n\n  info->in_pixels_cb = resize->input_cb;\n  info->user_data = resize->user_data;\n  info->out_pixels_cb = resize->output_cb;\n\n  // setup the input format converters\n  if ( ( input_type == STBIR_TYPE_UINT8 ) || ( input_type == STBIR_TYPE_UINT16 ) )\n  {\n    int non_scaled = 0;\n\n    // check if we can run unscaled - 0-255.0/0-65535.0 instead of 0-1.0 (which is a tiny bit faster when doing linear 8->8 or 16->16)\n    if ( ( !info->alpha_weight ) && ( !info->alpha_unweight )  ) // don't short circuit when alpha weighting (get everything to 0-1.0 as usual)\n      if ( ( ( input_type == STBIR_TYPE_UINT8 ) && ( output_type == STBIR_TYPE_UINT8 ) ) || ( ( input_type == STBIR_TYPE_UINT16 ) && ( output_type == STBIR_TYPE_UINT16 ) ) )\n        non_scaled = 1;\n\n    if ( info->input_pixel_layout_internal <= STBIRI_4CHANNEL )\n      decode_pixels = decode_simple_scaled_or_not[ input_type == STBIR_TYPE_UINT16 ][ non_scaled ];\n    else\n      decode_pixels = decode_alphas_scaled_or_not[ ( info->input_pixel_layout_internal - STBIRI_RGBA ) % ( STBIRI_AR-STBIRI_RGBA+1 ) ][ input_type == STBIR_TYPE_UINT16 ][ non_scaled ];\n  }\n  else\n  {\n    if ( info->input_pixel_layout_internal <= STBIRI_4CHANNEL )\n      decode_pixels = decode_simple[ input_type - STBIR_TYPE_UINT8_SRGB ];\n    else\n      decode_pixels = decode_alphas[ ( info->input_pixel_layout_internal - STBIRI_RGBA ) % ( STBIRI_AR-STBIRI_RGBA+1 ) ][ input_type - STBIR_TYPE_UINT8_SRGB ];\n  }\n\n  // setup the output format converters\n  if ( ( output_type == STBIR_TYPE_UINT8 ) || ( output_type == STBIR_TYPE_UINT16 ) )\n  {\n    int non_scaled = 0;\n\n    // check if we can run unscaled - 0-255.0/0-65535.0 instead of 0-1.0 (which is a tiny bit faster when doing linear 8->8 or 16->16)\n    if ( ( !info->alpha_weight ) && ( !info->alpha_unweight ) ) // don't short circuit when alpha weighting (get everything to 0-1.0 as usual)\n      if ( ( ( input_type == STBIR_TYPE_UINT8 ) && ( output_type == STBIR_TYPE_UINT8 ) ) || ( ( input_type == STBIR_TYPE_UINT16 ) && ( output_type == STBIR_TYPE_UINT16 ) ) )\n        non_scaled = 1;\n\n    if ( info->output_pixel_layout_internal <= STBIRI_4CHANNEL )\n      encode_pixels = encode_simple_scaled_or_not[ output_type == STBIR_TYPE_UINT16 ][ non_scaled ];\n    else\n      encode_pixels = encode_alphas_scaled_or_not[ ( info->output_pixel_layout_internal - STBIRI_RGBA ) % ( STBIRI_AR-STBIRI_RGBA+1 ) ][ output_type == STBIR_TYPE_UINT16 ][ non_scaled ];\n  }\n  else\n  {\n    if ( info->output_pixel_layout_internal <= STBIRI_4CHANNEL )\n      encode_pixels = encode_simple[ output_type - STBIR_TYPE_UINT8_SRGB ];\n    else\n      encode_pixels = encode_alphas[ ( info->output_pixel_layout_internal - STBIRI_RGBA ) % ( STBIRI_AR-STBIRI_RGBA+1 ) ][ output_type - STBIR_TYPE_UINT8_SRGB ];\n  }\n\n  info->input_type = input_type;\n  info->output_type = output_type;\n  info->decode_pixels = decode_pixels;\n  info->encode_pixels = encode_pixels;\n}\n\nstatic void stbir__clip( int * outx, int * outsubw, int outw, double * u0, double * u1 )\n{\n  double per, adj;\n  int over;\n\n  // do left/top edge\n  if ( *outx < 0 )\n  {\n    per = ( (double)*outx ) / ( (double)*outsubw ); // is negative\n    adj = per * ( *u1 - *u0 );\n    *u0 -= adj; // increases u0\n    *outx = 0;\n  }\n\n  // do right/bot edge\n  over = outw - ( *outx + *outsubw );\n  if ( over < 0 )\n  {\n    per = ( (double)over ) / ( (double)*outsubw ); // is negative\n    adj = per * ( *u1 - *u0 );\n    *u1 += adj; // decrease u1\n    *outsubw = outw - *outx;\n  }\n}\n\n// converts a double to a rational that has less than one float bit of error (returns 0 if unable to do so)\nstatic int stbir__double_to_rational(double f, stbir_uint32 limit, stbir_uint32 *numer, stbir_uint32 *denom, int limit_denom ) // limit_denom (1) or limit numer (0)\n{\n  double err;\n  stbir_uint64 top, bot;\n  stbir_uint64 numer_last = 0;\n  stbir_uint64 denom_last = 1;\n  stbir_uint64 numer_estimate = 1;\n  stbir_uint64 denom_estimate = 0;\n\n  // scale to past float error range\n  top = (stbir_uint64)( f * (double)(1 << 25) );\n  bot = 1 << 25;\n\n  // keep refining, but usually stops in a few loops - usually 5 for bad cases\n  for(;;)\n  {\n    stbir_uint64 est, temp;\n\n    // hit limit, break out and do best full range estimate\n    if ( ( ( limit_denom ) ? denom_estimate : numer_estimate ) >= limit )\n      break;\n\n    // is the current error less than 1 bit of a float? if so, we're done\n    if ( denom_estimate )\n    {\n      err = ( (double)numer_estimate / (double)denom_estimate ) - f;\n      if ( err < 0.0 ) err = -err;\n      if ( err < ( 1.0 / (double)(1<<24) ) )\n      {\n        // yup, found it\n        *numer = (stbir_uint32) numer_estimate;\n        *denom = (stbir_uint32) denom_estimate;\n        return 1;\n      }\n    }\n\n    // no more refinement bits left? break out and do full range estimate\n    if ( bot == 0 )\n      break;\n\n    // gcd the estimate bits\n    est = top / bot;\n    temp = top % bot;\n    top = bot;\n    bot = temp;\n\n    // move remainders\n    temp = est * denom_estimate + denom_last;\n    denom_last = denom_estimate;\n    denom_estimate = temp;\n\n    // move remainders\n    temp = est * numer_estimate + numer_last;\n    numer_last = numer_estimate;\n    numer_estimate = temp;\n  }\n\n  // we didn't find anything good enough for float, use a full range estimate\n  if ( limit_denom )\n  {\n    numer_estimate= (stbir_uint64)( f * (double)limit + 0.5 );\n    denom_estimate = limit;\n  }\n  else\n  {\n    numer_estimate = limit;\n    denom_estimate = (stbir_uint64)( ( (double)limit / f ) + 0.5 );\n  }\n\n  *numer = (stbir_uint32) numer_estimate;\n  *denom = (stbir_uint32) denom_estimate;\n\n  err = ( denom_estimate ) ? ( ( (double)(stbir_uint32)numer_estimate / (double)(stbir_uint32)denom_estimate ) - f ) : 1.0;\n  if ( err < 0.0 ) err = -err;\n  return ( err < ( 1.0 / (double)(1<<24) ) ) ? 1 : 0;\n}\n\nstatic int stbir__calculate_region_transform( stbir__scale_info * scale_info, int output_full_range, int * output_offset, int output_sub_range, int input_full_range, double input_s0, double input_s1 )\n{\n  double output_range, input_range, output_s, input_s, ratio, scale;\n\n  input_s = input_s1 - input_s0;\n\n  // null area\n  if ( ( output_full_range == 0 ) || ( input_full_range == 0 ) ||\n       ( output_sub_range == 0 ) || ( input_s <= stbir__small_float ) )\n    return 0;\n\n  // are either of the ranges completely out of bounds?\n  if ( ( *output_offset >= output_full_range ) || ( ( *output_offset + output_sub_range ) <= 0 ) || ( input_s0 >= (1.0f-stbir__small_float) ) || ( input_s1 <= stbir__small_float ) )\n    return 0;\n\n  output_range = (double)output_full_range;\n  input_range = (double)input_full_range;\n\n  output_s = ( (double)output_sub_range) / output_range;\n\n  // figure out the scaling to use\n  ratio = output_s / input_s;\n\n  // save scale before clipping\n  scale = ( output_range / input_range ) * ratio;\n  scale_info->scale = (float)scale;\n  scale_info->inv_scale = (float)( 1.0 / scale );\n\n  // clip output area to left/right output edges (and adjust input area)\n  stbir__clip( output_offset, &output_sub_range, output_full_range, &input_s0, &input_s1 );\n\n  // recalc input area\n  input_s = input_s1 - input_s0;\n\n  // after clipping do we have zero input area?\n  if ( input_s <= stbir__small_float )\n    return 0;\n\n  // calculate and store the starting source offsets in output pixel space\n  scale_info->pixel_shift = (float) ( input_s0 * ratio * output_range );\n\n  scale_info->scale_is_rational = stbir__double_to_rational( scale, ( scale <= 1.0 ) ? output_full_range : input_full_range, &scale_info->scale_numerator, &scale_info->scale_denominator, ( scale >= 1.0 ) );\n\n  scale_info->input_full_size = input_full_range;\n  scale_info->output_sub_size = output_sub_range;\n\n  return 1;\n}\n\n\nstatic void stbir__init_and_set_layout( STBIR_RESIZE * resize, stbir_pixel_layout pixel_layout, stbir_datatype data_type )\n{\n  resize->input_cb = 0;\n  resize->output_cb = 0;\n  resize->user_data = resize;\n  resize->samplers = 0;\n  resize->called_alloc = 0;\n  resize->horizontal_filter = STBIR_FILTER_DEFAULT;\n  resize->horizontal_filter_kernel = 0; resize->horizontal_filter_support = 0;\n  resize->vertical_filter = STBIR_FILTER_DEFAULT;\n  resize->vertical_filter_kernel = 0; resize->vertical_filter_support = 0;\n  resize->horizontal_edge = STBIR_EDGE_CLAMP;\n  resize->vertical_edge = STBIR_EDGE_CLAMP;\n  resize->input_s0 = 0; resize->input_t0 = 0; resize->input_s1 = 1; resize->input_t1 = 1;\n  resize->output_subx = 0; resize->output_suby = 0; resize->output_subw = resize->output_w; resize->output_subh = resize->output_h;\n  resize->input_data_type = data_type;\n  resize->output_data_type = data_type;\n  resize->input_pixel_layout_public = pixel_layout;\n  resize->output_pixel_layout_public = pixel_layout;\n  resize->needs_rebuild = 1;\n}\n\nSTBIRDEF void stbir_resize_init( STBIR_RESIZE * resize,\n                                 const void *input_pixels,  int input_w,  int input_h, int input_stride_in_bytes, // stride can be zero\n                                       void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, // stride can be zero\n                                 stbir_pixel_layout pixel_layout, stbir_datatype data_type )\n{\n  resize->input_pixels = input_pixels;\n  resize->input_w = input_w;\n  resize->input_h = input_h;\n  resize->input_stride_in_bytes = input_stride_in_bytes;\n  resize->output_pixels = output_pixels;\n  resize->output_w = output_w;\n  resize->output_h = output_h;\n  resize->output_stride_in_bytes = output_stride_in_bytes;\n  resize->fast_alpha = 0;\n\n  stbir__init_and_set_layout( resize, pixel_layout, data_type );\n}\n\n// You can update parameters any time after resize_init\nSTBIRDEF void stbir_set_datatypes( STBIR_RESIZE * resize, stbir_datatype input_type, stbir_datatype output_type )  // by default, datatype from resize_init\n{\n  resize->input_data_type = input_type;\n  resize->output_data_type = output_type;\n  if ( ( resize->samplers ) && ( !resize->needs_rebuild ) )\n    stbir__update_info_from_resize( resize->samplers, resize );\n}\n\nSTBIRDEF void stbir_set_pixel_callbacks( STBIR_RESIZE * resize, stbir_input_callback * input_cb, stbir_output_callback * output_cb )   // no callbacks by default\n{\n  resize->input_cb = input_cb;\n  resize->output_cb = output_cb;\n\n  if ( ( resize->samplers ) && ( !resize->needs_rebuild ) )\n  {\n    resize->samplers->in_pixels_cb = input_cb;\n    resize->samplers->out_pixels_cb = output_cb;\n  }\n}\n\nSTBIRDEF void stbir_set_user_data( STBIR_RESIZE * resize, void * user_data )                                     // pass back STBIR_RESIZE* by default\n{\n  resize->user_data = user_data;\n  if ( ( resize->samplers ) && ( !resize->needs_rebuild ) )\n    resize->samplers->user_data = user_data;\n}\n\nSTBIRDEF void stbir_set_buffer_ptrs( STBIR_RESIZE * resize, const void * input_pixels, int input_stride_in_bytes, void * output_pixels, int output_stride_in_bytes )\n{\n  resize->input_pixels = input_pixels;\n  resize->input_stride_in_bytes = input_stride_in_bytes;\n  resize->output_pixels = output_pixels;\n  resize->output_stride_in_bytes = output_stride_in_bytes;\n  if ( ( resize->samplers ) && ( !resize->needs_rebuild ) )\n    stbir__update_info_from_resize( resize->samplers, resize );\n}\n\n\nSTBIRDEF int stbir_set_edgemodes( STBIR_RESIZE * resize, stbir_edge horizontal_edge, stbir_edge vertical_edge )       // CLAMP by default\n{\n  resize->horizontal_edge = horizontal_edge;\n  resize->vertical_edge = vertical_edge;\n  resize->needs_rebuild = 1;\n  return 1;\n}\n\nSTBIRDEF int stbir_set_filters( STBIR_RESIZE * resize, stbir_filter horizontal_filter, stbir_filter vertical_filter ) // STBIR_DEFAULT_FILTER_UPSAMPLE/DOWNSAMPLE by default\n{\n  resize->horizontal_filter = horizontal_filter;\n  resize->vertical_filter = vertical_filter;\n  resize->needs_rebuild = 1;\n  return 1;\n}\n\nSTBIRDEF int stbir_set_filter_callbacks( STBIR_RESIZE * resize, stbir__kernel_callback * horizontal_filter, stbir__support_callback * horizontal_support, stbir__kernel_callback * vertical_filter, stbir__support_callback * vertical_support )\n{\n  resize->horizontal_filter_kernel = horizontal_filter; resize->horizontal_filter_support = horizontal_support;\n  resize->vertical_filter_kernel = vertical_filter; resize->vertical_filter_support = vertical_support;\n  resize->needs_rebuild = 1;\n  return 1;\n}\n\nSTBIRDEF int stbir_set_pixel_layouts( STBIR_RESIZE * resize, stbir_pixel_layout input_pixel_layout, stbir_pixel_layout output_pixel_layout )   // sets new pixel layouts\n{\n  resize->input_pixel_layout_public = input_pixel_layout;\n  resize->output_pixel_layout_public = output_pixel_layout;\n  resize->needs_rebuild = 1;\n  return 1;\n}\n\n\nSTBIRDEF int stbir_set_non_pm_alpha_speed_over_quality( STBIR_RESIZE * resize, int non_pma_alpha_speed_over_quality )   // sets alpha speed\n{\n  resize->fast_alpha = non_pma_alpha_speed_over_quality;\n  resize->needs_rebuild = 1;\n  return 1;\n}\n\nSTBIRDEF int stbir_set_input_subrect( STBIR_RESIZE * resize, double s0, double t0, double s1, double t1 )                 // sets input region (full region by default)\n{\n  resize->input_s0 = s0;\n  resize->input_t0 = t0;\n  resize->input_s1 = s1;\n  resize->input_t1 = t1;\n  resize->needs_rebuild = 1;\n\n  // are we inbounds?\n  if ( ( s1 < stbir__small_float ) || ( (s1-s0) < stbir__small_float ) ||\n       ( t1 < stbir__small_float ) || ( (t1-t0) < stbir__small_float ) ||\n       ( s0 > (1.0f-stbir__small_float) ) ||\n       ( t0 > (1.0f-stbir__small_float) ) )\n    return 0;\n\n  return 1;\n}\n\nSTBIRDEF int stbir_set_output_pixel_subrect( STBIR_RESIZE * resize, int subx, int suby, int subw, int subh )          // sets input region (full region by default)\n{\n  resize->output_subx = subx;\n  resize->output_suby = suby;\n  resize->output_subw = subw;\n  resize->output_subh = subh;\n  resize->needs_rebuild = 1;\n\n  // are we inbounds?\n  if ( ( subx >= resize->output_w ) || ( ( subx + subw ) <= 0 ) || ( suby >= resize->output_h ) || ( ( suby + subh ) <= 0 ) || ( subw == 0 ) || ( subh == 0 ) )\n    return 0;\n\n  return 1;\n}\n\nSTBIRDEF int stbir_set_pixel_subrect( STBIR_RESIZE * resize, int subx, int suby, int subw, int subh )                 // sets both regions (full regions by default)\n{\n  double s0, t0, s1, t1;\n\n  s0 = ( (double)subx ) / ( (double)resize->output_w );\n  t0 = ( (double)suby ) / ( (double)resize->output_h );\n  s1 = ( (double)(subx+subw) ) / ( (double)resize->output_w );\n  t1 = ( (double)(suby+subh) ) / ( (double)resize->output_h );\n\n  resize->input_s0 = s0;\n  resize->input_t0 = t0;\n  resize->input_s1 = s1;\n  resize->input_t1 = t1;\n  resize->output_subx = subx;\n  resize->output_suby = suby;\n  resize->output_subw = subw;\n  resize->output_subh = subh;\n  resize->needs_rebuild = 1;\n\n  // are we inbounds?\n  if ( ( subx >= resize->output_w ) || ( ( subx + subw ) <= 0 ) || ( suby >= resize->output_h ) || ( ( suby + subh ) <= 0 ) || ( subw == 0 ) || ( subh == 0 ) )\n    return 0;\n\n  return 1;\n}\n\nstatic int stbir__perform_build( STBIR_RESIZE * resize, int splits )\n{\n  stbir__contributors conservative = { 0, 0 };\n  stbir__sampler horizontal, vertical;\n  int new_output_subx, new_output_suby;\n  stbir__info * out_info;\n  #ifdef STBIR_PROFILE\n  stbir__info profile_infod;  // used to contain building profile info before everything is allocated\n  stbir__info * profile_info = &profile_infod;\n  #endif\n\n  // have we already built the samplers?\n  if ( resize->samplers )\n    return 0;\n\n  #define STBIR_RETURN_ERROR_AND_ASSERT( exp )  STBIR_ASSERT( !(exp) ); if (exp) return 0;\n  STBIR_RETURN_ERROR_AND_ASSERT( (unsigned)resize->horizontal_filter >= STBIR_FILTER_OTHER)\n  STBIR_RETURN_ERROR_AND_ASSERT( (unsigned)resize->vertical_filter >= STBIR_FILTER_OTHER)\n  #undef STBIR_RETURN_ERROR_AND_ASSERT\n\n  if ( splits <= 0 )\n    return 0;\n\n  STBIR_PROFILE_BUILD_FIRST_START( build );\n\n  new_output_subx = resize->output_subx;\n  new_output_suby = resize->output_suby;\n\n  // do horizontal clip and scale calcs\n  if ( !stbir__calculate_region_transform( &horizontal.scale_info, resize->output_w, &new_output_subx, resize->output_subw, resize->input_w, resize->input_s0, resize->input_s1 ) )\n    return 0;\n\n  // do vertical clip and scale calcs\n  if ( !stbir__calculate_region_transform( &vertical.scale_info, resize->output_h, &new_output_suby, resize->output_subh, resize->input_h, resize->input_t0, resize->input_t1 ) )\n    return 0;\n\n  // if nothing to do, just return\n  if ( ( horizontal.scale_info.output_sub_size == 0 ) || ( vertical.scale_info.output_sub_size == 0 ) )\n    return 0;\n\n  stbir__set_sampler(&horizontal, resize->horizontal_filter, resize->horizontal_filter_kernel, resize->horizontal_filter_support, resize->horizontal_edge, &horizontal.scale_info, 1, resize->user_data );\n  stbir__get_conservative_extents( &horizontal, &conservative, resize->user_data );\n  stbir__set_sampler(&vertical, resize->vertical_filter, resize->vertical_filter_kernel, resize->vertical_filter_support, resize->vertical_edge, &vertical.scale_info, 0, resize->user_data );\n\n  if ( ( vertical.scale_info.output_sub_size / splits ) < STBIR_FORCE_MINIMUM_SCANLINES_FOR_SPLITS ) // each split should be a minimum of 4 scanlines (handwavey choice)\n  {\n    splits = vertical.scale_info.output_sub_size / STBIR_FORCE_MINIMUM_SCANLINES_FOR_SPLITS;\n    if ( splits == 0 ) splits = 1;\n  }\n\n  STBIR_PROFILE_BUILD_START( alloc );\n  out_info = stbir__alloc_internal_mem_and_build_samplers( &horizontal, &vertical, &conservative, resize->input_pixel_layout_public, resize->output_pixel_layout_public, splits, new_output_subx, new_output_suby, resize->fast_alpha, resize->user_data STBIR_ONLY_PROFILE_BUILD_SET_INFO );\n  STBIR_PROFILE_BUILD_END( alloc );\n  STBIR_PROFILE_BUILD_END( build );\n\n  if ( out_info )\n  {\n    resize->splits = splits;\n    resize->samplers = out_info;\n    resize->needs_rebuild = 0;\n    #ifdef STBIR_PROFILE\n      STBIR_MEMCPY( &out_info->profile, &profile_infod.profile, sizeof( out_info->profile ) );\n    #endif\n\n    // update anything that can be changed without recalcing samplers\n    stbir__update_info_from_resize( out_info, resize );\n\n    return splits;\n  }\n\n  return 0;\n}\n\nSTBIRDEF void stbir_free_samplers( STBIR_RESIZE * resize )\n{\n  if ( resize->samplers )\n  {\n    stbir__free_internal_mem( resize->samplers );\n    resize->samplers = 0;\n    resize->called_alloc = 0;\n  }\n}\n\nSTBIRDEF int stbir_build_samplers_with_splits( STBIR_RESIZE * resize, int splits )\n{\n  if ( ( resize->samplers == 0 ) || ( resize->needs_rebuild ) )\n  {\n    if ( resize->samplers )\n      stbir_free_samplers( resize );\n\n    resize->called_alloc = 1;\n    return stbir__perform_build( resize, splits );\n  }\n\n  STBIR_PROFILE_BUILD_CLEAR( resize->samplers );\n\n  return 1;\n}\n\nSTBIRDEF int stbir_build_samplers( STBIR_RESIZE * resize )\n{\n  return stbir_build_samplers_with_splits( resize, 1 );\n}\n\nSTBIRDEF int stbir_resize_extended( STBIR_RESIZE * resize )\n{\n  int result;\n\n  if ( ( resize->samplers == 0 ) || ( resize->needs_rebuild ) )\n  {\n    int alloc_state = resize->called_alloc;  // remember allocated state\n\n    if ( resize->samplers )\n    {\n      stbir__free_internal_mem( resize->samplers );\n      resize->samplers = 0;\n    }\n\n    if ( !stbir_build_samplers( resize ) )\n      return 0;\n\n    resize->called_alloc = alloc_state;\n\n    // if build_samplers succeeded (above), but there are no samplers set, then\n    //   the area to stretch into was zero pixels, so don't do anything and return\n    //   success\n    if ( resize->samplers == 0 )\n      return 1;\n  }\n  else\n  {\n    // didn't build anything - clear it\n    STBIR_PROFILE_BUILD_CLEAR( resize->samplers );\n  }\n\n  // do resize\n  result = stbir__perform_resize( resize->samplers, 0, resize->splits );\n\n  // if we alloced, then free\n  if ( !resize->called_alloc )\n  {\n    stbir_free_samplers( resize );\n    resize->samplers = 0;\n  }\n\n  return result;\n}\n\nSTBIRDEF int stbir_resize_extended_split( STBIR_RESIZE * resize, int split_start, int split_count )\n{\n  STBIR_ASSERT( resize->samplers );\n\n  // if we're just doing the whole thing, call full\n  if ( ( split_start == -1 ) || ( ( split_start == 0 ) && ( split_count == resize->splits ) ) )\n    return stbir_resize_extended( resize );\n\n  // you **must** build samplers first when using split resize\n  if ( ( resize->samplers == 0 ) || ( resize->needs_rebuild ) )\n    return 0;\n\n  if ( ( split_start >= resize->splits ) || ( split_start < 0 ) || ( ( split_start + split_count ) > resize->splits ) || ( split_count <= 0 ) )\n    return 0;\n\n  // do resize\n  return stbir__perform_resize( resize->samplers, split_start, split_count );\n}\n\n\nstatic void * stbir_quick_resize_helper( const void *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                               void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                               stbir_pixel_layout pixel_layout, stbir_datatype data_type, stbir_edge edge, stbir_filter filter )\n{\n  STBIR_RESIZE resize;\n  int scanline_output_in_bytes;\n  int positive_output_stride_in_bytes;\n  void * start_ptr;\n  void * free_ptr;\n\n  scanline_output_in_bytes = output_w * stbir__type_size[ data_type ] * stbir__pixel_channels[ stbir__pixel_layout_convert_public_to_internal[ pixel_layout ] ];\n  if ( scanline_output_in_bytes == 0 )\n    return 0;\n\n  // if zero stride, use scanline output\n  if ( output_stride_in_bytes == 0 )\n    output_stride_in_bytes = scanline_output_in_bytes;\n\n  // abs value for inverted images (negative pitches)\n  positive_output_stride_in_bytes = output_stride_in_bytes;\n  if ( positive_output_stride_in_bytes < 0 )\n    positive_output_stride_in_bytes = -positive_output_stride_in_bytes;\n\n  // is the requested stride smaller than the scanline output? if so, just fail\n  if ( positive_output_stride_in_bytes < scanline_output_in_bytes )\n    return 0;\n\n  start_ptr = output_pixels;\n  free_ptr = 0;  // no free pointer, since they passed buffer to use\n\n  // did they pass a zero for the dest? if so, allocate the buffer\n  if ( output_pixels == 0 )\n  {\n    size_t size;\n    char * ptr;\n  \n    size = (size_t)positive_output_stride_in_bytes * (size_t)output_h;\n    if ( size == 0 )\n      return 0;\n\n    ptr = (char*) STBIR_MALLOC( size, 0 );\n    if ( ptr == 0 )\n      return 0;\n\n    free_ptr = ptr;\n\n    // point at the last scanline, if they requested a flipped image\n    if ( output_stride_in_bytes < 0 )\n      start_ptr = ptr + ( (size_t)positive_output_stride_in_bytes * (size_t)( output_h - 1 ) );\n    else\n      start_ptr = ptr;\n  }\n\n  // ok, now do the resize\n  stbir_resize_init( &resize,\n                     input_pixels,  input_w,  input_h,  input_stride_in_bytes,\n                     start_ptr, output_w, output_h, output_stride_in_bytes,\n                     pixel_layout, data_type );\n\n  resize.horizontal_edge = edge;\n  resize.vertical_edge = edge;\n  resize.horizontal_filter = filter;\n  resize.vertical_filter = filter;\n\n  if ( !stbir_resize_extended( &resize ) )\n  {\n    if ( free_ptr )\n      STBIR_FREE( free_ptr, 0 );\n    return 0;\n  }\n\n  return (free_ptr) ? free_ptr : start_ptr;\n}\n\n\n\nSTBIRDEF unsigned char * stbir_resize_uint8_linear( const unsigned char *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                                          unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                                          stbir_pixel_layout pixel_layout )\n{\n  return (unsigned char *) stbir_quick_resize_helper( input_pixels , input_w , input_h, input_stride_in_bytes, \n                                                      output_pixels, output_w, output_h, output_stride_in_bytes, \n                                                      pixel_layout, STBIR_TYPE_UINT8, STBIR_EDGE_CLAMP, STBIR_FILTER_DEFAULT );\n}\n\nSTBIRDEF unsigned char * stbir_resize_uint8_srgb( const unsigned char *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                                        unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                                        stbir_pixel_layout pixel_layout )\n{\n  return (unsigned char *) stbir_quick_resize_helper( input_pixels , input_w , input_h, input_stride_in_bytes, \n                                                      output_pixels, output_w, output_h, output_stride_in_bytes, \n                                                      pixel_layout, STBIR_TYPE_UINT8_SRGB, STBIR_EDGE_CLAMP, STBIR_FILTER_DEFAULT );\n}\n\n\nSTBIRDEF float * stbir_resize_float_linear( const float *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                                  float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                                  stbir_pixel_layout pixel_layout )\n{\n  return (float *) stbir_quick_resize_helper( input_pixels , input_w , input_h, input_stride_in_bytes, \n                                              output_pixels, output_w, output_h, output_stride_in_bytes, \n                                              pixel_layout, STBIR_TYPE_FLOAT, STBIR_EDGE_CLAMP, STBIR_FILTER_DEFAULT  );\n}\n\n\nSTBIRDEF void * stbir_resize( const void *input_pixels , int input_w , int input_h, int input_stride_in_bytes,\n                                    void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                    stbir_pixel_layout pixel_layout, stbir_datatype data_type,\n                                    stbir_edge edge, stbir_filter filter )\n{\n  return (void *) stbir_quick_resize_helper( input_pixels , input_w , input_h, input_stride_in_bytes, \n                                             output_pixels, output_w, output_h, output_stride_in_bytes, \n                                             pixel_layout, data_type, edge, filter  );\n}\n\n#ifdef STBIR_PROFILE\n\nSTBIRDEF void stbir_resize_build_profile_info( STBIR_PROFILE_INFO * info, STBIR_RESIZE const * resize )\n{\n  static char const * bdescriptions[6] = { \"Building\", \"Allocating\", \"Horizontal sampler\", \"Vertical sampler\", \"Coefficient cleanup\", \"Coefficient pivot\" } ;\n  stbir__info* samp = resize->samplers;\n  int i;\n\n  typedef int testa[ (STBIR__ARRAY_SIZE( bdescriptions ) == (STBIR__ARRAY_SIZE( samp->profile.array )-1) )?1:-1];\n  typedef int testb[ (sizeof( samp->profile.array ) == (sizeof(samp->profile.named)) )?1:-1];\n  typedef int testc[ (sizeof( info->clocks ) >= (sizeof(samp->profile.named)) )?1:-1];\n\n  for( i = 0 ; i < STBIR__ARRAY_SIZE( bdescriptions ) ; i++)\n    info->clocks[i] = samp->profile.array[i+1];\n\n  info->total_clocks = samp->profile.named.total;\n  info->descriptions = bdescriptions;\n  info->count = STBIR__ARRAY_SIZE( bdescriptions );\n}\n\nSTBIRDEF void stbir_resize_split_profile_info( STBIR_PROFILE_INFO * info, STBIR_RESIZE const * resize, int split_start, int split_count )\n{\n  static char const * descriptions[7] = { \"Looping\", \"Vertical sampling\", \"Horizontal sampling\", \"Scanline input\", \"Scanline output\", \"Alpha weighting\", \"Alpha unweighting\" };\n  stbir__per_split_info * split_info;\n  int s, i;\n\n  typedef int testa[ (STBIR__ARRAY_SIZE( descriptions ) == (STBIR__ARRAY_SIZE( split_info->profile.array )-1) )?1:-1];\n  typedef int testb[ (sizeof( split_info->profile.array ) == (sizeof(split_info->profile.named)) )?1:-1];\n  typedef int testc[ (sizeof( info->clocks ) >= (sizeof(split_info->profile.named)) )?1:-1];\n\n  if ( split_start == -1 )\n  {\n    split_start = 0;\n    split_count = resize->samplers->splits;\n  }\n\n  if ( ( split_start >= resize->splits ) || ( split_start < 0 ) || ( ( split_start + split_count ) > resize->splits ) || ( split_count <= 0 ) )\n  {\n    info->total_clocks = 0;\n    info->descriptions = 0;\n    info->count = 0;\n    return;\n  }\n\n  split_info = resize->samplers->split_info + split_start;\n\n  // sum up the profile from all the splits\n  for( i = 0 ; i < STBIR__ARRAY_SIZE( descriptions ) ; i++ )\n  {\n    stbir_uint64 sum = 0;\n    for( s = 0 ; s < split_count ; s++ )\n      sum += split_info[s].profile.array[i+1];\n    info->clocks[i] = sum;\n  }\n\n  info->total_clocks = split_info->profile.named.total; \n  info->descriptions = descriptions;\n  info->count = STBIR__ARRAY_SIZE( descriptions );\n}\n\nSTBIRDEF void stbir_resize_extended_profile_info( STBIR_PROFILE_INFO * info, STBIR_RESIZE const * resize )\n{\n  stbir_resize_split_profile_info( info, resize, -1, 0 );\n}\n\n#endif // STBIR_PROFILE\n\n#undef STBIR_BGR\n#undef STBIR_1CHANNEL\n#undef STBIR_2CHANNEL\n#undef STBIR_RGB\n#undef STBIR_RGBA\n#undef STBIR_4CHANNEL\n#undef STBIR_BGRA\n#undef STBIR_ARGB\n#undef STBIR_ABGR\n#undef STBIR_RA\n#undef STBIR_AR\n#undef STBIR_RGBA_PM\n#undef STBIR_BGRA_PM\n#undef STBIR_ARGB_PM\n#undef STBIR_ABGR_PM\n#undef STBIR_RA_PM\n#undef STBIR_AR_PM\n\n#endif // STB_IMAGE_RESIZE_IMPLEMENTATION\n\n#else  // STB_IMAGE_RESIZE_HORIZONTALS&STB_IMAGE_RESIZE_DO_VERTICALS\n\n// we reinclude the header file to define all the horizontal functions\n//   specializing each function for the number of coeffs is 20-40% faster *OVERALL*\n\n// by including the header file again this way, we can still debug the functions\n\n#define STBIR_strs_join2( start, mid, end ) start##mid##end\n#define STBIR_strs_join1( start, mid, end ) STBIR_strs_join2( start, mid, end )\n\n#define STBIR_strs_join24( start, mid1, mid2, end ) start##mid1##mid2##end\n#define STBIR_strs_join14( start, mid1, mid2, end ) STBIR_strs_join24( start, mid1, mid2, end )\n\n#ifdef STB_IMAGE_RESIZE_DO_CODERS\n\n#ifdef stbir__decode_suffix\n#define STBIR__CODER_NAME( name ) STBIR_strs_join1( name, _, stbir__decode_suffix )\n#else\n#define STBIR__CODER_NAME( name ) name\n#endif\n\n#ifdef stbir__decode_swizzle\n#define stbir__decode_simdf8_flip(reg) STBIR_strs_join1( STBIR_strs_join1( STBIR_strs_join1( STBIR_strs_join1( stbir__simdf8_0123to,stbir__decode_order0,stbir__decode_order1),stbir__decode_order2,stbir__decode_order3),stbir__decode_order0,stbir__decode_order1),stbir__decode_order2,stbir__decode_order3)(reg, reg)\n#define stbir__decode_simdf4_flip(reg) STBIR_strs_join1( STBIR_strs_join1( stbir__simdf_0123to,stbir__decode_order0,stbir__decode_order1),stbir__decode_order2,stbir__decode_order3)(reg, reg)\n#define stbir__encode_simdf8_unflip(reg) STBIR_strs_join1( STBIR_strs_join1( STBIR_strs_join1( STBIR_strs_join1( stbir__simdf8_0123to,stbir__encode_order0,stbir__encode_order1),stbir__encode_order2,stbir__encode_order3),stbir__encode_order0,stbir__encode_order1),stbir__encode_order2,stbir__encode_order3)(reg, reg)\n#define stbir__encode_simdf4_unflip(reg) STBIR_strs_join1( STBIR_strs_join1( stbir__simdf_0123to,stbir__encode_order0,stbir__encode_order1),stbir__encode_order2,stbir__encode_order3)(reg, reg)\n#else\n#define stbir__decode_order0 0\n#define stbir__decode_order1 1\n#define stbir__decode_order2 2\n#define stbir__decode_order3 3\n#define stbir__encode_order0 0\n#define stbir__encode_order1 1\n#define stbir__encode_order2 2\n#define stbir__encode_order3 3\n#define stbir__decode_simdf8_flip(reg)\n#define stbir__decode_simdf4_flip(reg)\n#define stbir__encode_simdf8_unflip(reg)\n#define stbir__encode_simdf4_unflip(reg)\n#endif\n\n#ifdef STBIR_SIMD8\n#define stbir__encode_simdfX_unflip  stbir__encode_simdf8_unflip\n#else\n#define stbir__encode_simdfX_unflip  stbir__encode_simdf4_unflip\n#endif\n\nstatic float * STBIR__CODER_NAME( stbir__decode_uint8_linear_scaled )( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned char const * input = (unsigned char const*)inputp;\n\n  #ifdef STBIR_SIMD\n  unsigned char const * end_input_m16 = input + width_times_channels - 16;\n  if ( width_times_channels >= 16 )\n  {\n    decode_end -= 16;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      #ifdef STBIR_SIMD8\n      stbir__simdi i; stbir__simdi8 o0,o1;\n      stbir__simdf8 of0, of1;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi8_expand_u8_to_u32( o0, o1, i );\n      stbir__simdi8_convert_i32_to_float( of0, o0 );\n      stbir__simdi8_convert_i32_to_float( of1, o1 );\n      stbir__simdf8_mult( of0, of0, STBIR_max_uint8_as_float_inverted8);\n      stbir__simdf8_mult( of1, of1, STBIR_max_uint8_as_float_inverted8);\n      stbir__decode_simdf8_flip( of0 );\n      stbir__decode_simdf8_flip( of1 );\n      stbir__simdf8_store( decode + 0, of0 );\n      stbir__simdf8_store( decode + 8, of1 );\n      #else\n      stbir__simdi i, o0, o1, o2, o3;\n      stbir__simdf of0, of1, of2, of3;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi_expand_u8_to_u32( o0,o1,o2,o3,i);\n      stbir__simdi_convert_i32_to_float( of0, o0 );\n      stbir__simdi_convert_i32_to_float( of1, o1 );\n      stbir__simdi_convert_i32_to_float( of2, o2 );\n      stbir__simdi_convert_i32_to_float( of3, o3 );\n      stbir__simdf_mult( of0, of0, STBIR__CONSTF(STBIR_max_uint8_as_float_inverted) );\n      stbir__simdf_mult( of1, of1, STBIR__CONSTF(STBIR_max_uint8_as_float_inverted) );\n      stbir__simdf_mult( of2, of2, STBIR__CONSTF(STBIR_max_uint8_as_float_inverted) );\n      stbir__simdf_mult( of3, of3, STBIR__CONSTF(STBIR_max_uint8_as_float_inverted) );\n      stbir__decode_simdf4_flip( of0 );\n      stbir__decode_simdf4_flip( of1 );\n      stbir__decode_simdf4_flip( of2 );\n      stbir__decode_simdf4_flip( of3 );\n      stbir__simdf_store( decode + 0,  of0 );\n      stbir__simdf_store( decode + 4,  of1 );\n      stbir__simdf_store( decode + 8,  of2 );\n      stbir__simdf_store( decode + 12, of3 );\n      #endif\n      decode += 16;\n      input += 16;\n      if ( decode <= decode_end )\n        continue;\n      if ( decode == ( decode_end + 16 ) )\n        break;\n      decode = decode_end; // backup and do last couple\n      input = end_input_m16;\n    }\n    return decode_end + 16;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode <= decode_end )\n  {\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0-4] = ((float)(input[stbir__decode_order0])) * stbir__max_uint8_as_float_inverted;\n    decode[1-4] = ((float)(input[stbir__decode_order1])) * stbir__max_uint8_as_float_inverted;\n    decode[2-4] = ((float)(input[stbir__decode_order2])) * stbir__max_uint8_as_float_inverted;\n    decode[3-4] = ((float)(input[stbir__decode_order3])) * stbir__max_uint8_as_float_inverted;\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = ((float)(input[stbir__decode_order0])) * stbir__max_uint8_as_float_inverted;\n    #if stbir__coder_min_num >= 2\n    decode[1] = ((float)(input[stbir__decode_order1])) * stbir__max_uint8_as_float_inverted;\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = ((float)(input[stbir__decode_order2])) * stbir__max_uint8_as_float_inverted;\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n\n  return decode_end;\n}\n\nstatic void STBIR__CODER_NAME( stbir__encode_uint8_linear_scaled )( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned char STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned char *) outputp;\n  unsigned char * end_output = ( (unsigned char *) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  if ( width_times_channels >= stbir__simdfX_float_count*2 )\n  {\n    float const * end_encode_m8 = encode + width_times_channels - stbir__simdfX_float_count*2;\n    end_output -= stbir__simdfX_float_count*2;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      stbir__simdfX e0, e1;\n      stbir__simdi i;\n      STBIR_SIMD_NO_UNROLL(encode);\n      stbir__simdfX_madd_mem( e0, STBIR_simd_point5X, STBIR_max_uint8_as_floatX, encode );\n      stbir__simdfX_madd_mem( e1, STBIR_simd_point5X, STBIR_max_uint8_as_floatX, encode+stbir__simdfX_float_count );\n      stbir__encode_simdfX_unflip( e0 );\n      stbir__encode_simdfX_unflip( e1 );\n      #ifdef STBIR_SIMD8\n      stbir__simdf8_pack_to_16bytes( i, e0, e1 );\n      stbir__simdi_store( output, i );\n      #else\n      stbir__simdf_pack_to_8bytes( i, e0, e1 );\n      stbir__simdi_store2( output, i );\n      #endif\n      encode += stbir__simdfX_float_count*2;\n      output += stbir__simdfX_float_count*2;\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + stbir__simdfX_float_count*2 ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m8;\n    }\n    return;\n  }\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    stbir__simdf e0;\n    stbir__simdi i0;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_load( e0, encode );\n    stbir__simdf_madd( e0, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint8_as_float), e0 );\n    stbir__encode_simdf4_unflip( e0 );\n    stbir__simdf_pack_to_8bytes( i0, e0, e0 );  // only use first 4\n    *(int*)(output-4) = stbir__simdi_to_int( i0 );\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    stbir__simdf e0;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_madd1_mem( e0, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint8_as_float), encode+stbir__encode_order0 ); output[0] = stbir__simdf_convert_float_to_uint8( e0 );\n    #if stbir__coder_min_num >= 2\n    stbir__simdf_madd1_mem( e0, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint8_as_float), encode+stbir__encode_order1 ); output[1] = stbir__simdf_convert_float_to_uint8( e0 );\n    #endif\n    #if stbir__coder_min_num >= 3\n    stbir__simdf_madd1_mem( e0, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint8_as_float), encode+stbir__encode_order2 ); output[2] = stbir__simdf_convert_float_to_uint8( e0 );\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n\n  #else\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  while( output <= end_output )\n  {\n    float f;\n    f = encode[stbir__encode_order0] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[0-4] = (unsigned char)f;\n    f = encode[stbir__encode_order1] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[1-4] = (unsigned char)f;\n    f = encode[stbir__encode_order2] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[2-4] = (unsigned char)f;\n    f = encode[stbir__encode_order3] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[3-4] = (unsigned char)f;\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    float f;\n    STBIR_NO_UNROLL(encode);\n    f = encode[stbir__encode_order0] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[0] = (unsigned char)f;\n    #if stbir__coder_min_num >= 2\n    f = encode[stbir__encode_order1] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[1] = (unsigned char)f;\n    #endif\n    #if stbir__coder_min_num >= 3\n    f = encode[stbir__encode_order2] * stbir__max_uint8_as_float + 0.5f; STBIR_CLAMP(f, 0, 255); output[2] = (unsigned char)f;\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n  #endif\n}\n\nstatic float * STBIR__CODER_NAME(stbir__decode_uint8_linear)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned char const * input = (unsigned char const*)inputp;\n\n  #ifdef STBIR_SIMD\n  unsigned char const * end_input_m16 = input + width_times_channels - 16;\n  if ( width_times_channels >= 16 )\n  {\n    decode_end -= 16;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      #ifdef STBIR_SIMD8\n      stbir__simdi i; stbir__simdi8 o0,o1;\n      stbir__simdf8 of0, of1;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi8_expand_u8_to_u32( o0, o1, i );\n      stbir__simdi8_convert_i32_to_float( of0, o0 );\n      stbir__simdi8_convert_i32_to_float( of1, o1 );\n      stbir__decode_simdf8_flip( of0 );\n      stbir__decode_simdf8_flip( of1 );\n      stbir__simdf8_store( decode + 0, of0 );\n      stbir__simdf8_store( decode + 8, of1 );\n      #else\n      stbir__simdi i, o0, o1, o2, o3;\n      stbir__simdf of0, of1, of2, of3;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi_expand_u8_to_u32( o0,o1,o2,o3,i);\n      stbir__simdi_convert_i32_to_float( of0, o0 );\n      stbir__simdi_convert_i32_to_float( of1, o1 );\n      stbir__simdi_convert_i32_to_float( of2, o2 );\n      stbir__simdi_convert_i32_to_float( of3, o3 );\n      stbir__decode_simdf4_flip( of0 );\n      stbir__decode_simdf4_flip( of1 );\n      stbir__decode_simdf4_flip( of2 );\n      stbir__decode_simdf4_flip( of3 );\n      stbir__simdf_store( decode + 0,  of0 );\n      stbir__simdf_store( decode + 4,  of1 );\n      stbir__simdf_store( decode + 8,  of2 );\n      stbir__simdf_store( decode + 12, of3 );\n#endif\n      decode += 16;\n      input += 16;\n      if ( decode <= decode_end )\n        continue;\n      if ( decode == ( decode_end + 16 ) )\n        break;\n      decode = decode_end; // backup and do last couple\n      input = end_input_m16;\n    }\n    return decode_end + 16;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode <= decode_end )\n  {\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0-4] = ((float)(input[stbir__decode_order0]));\n    decode[1-4] = ((float)(input[stbir__decode_order1]));\n    decode[2-4] = ((float)(input[stbir__decode_order2]));\n    decode[3-4] = ((float)(input[stbir__decode_order3]));\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = ((float)(input[stbir__decode_order0]));\n    #if stbir__coder_min_num >= 2\n    decode[1] = ((float)(input[stbir__decode_order1]));\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = ((float)(input[stbir__decode_order2]));\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n  return decode_end;\n}\n\nstatic void STBIR__CODER_NAME( stbir__encode_uint8_linear )( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned char STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned char *) outputp;\n  unsigned char * end_output = ( (unsigned char *) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  if ( width_times_channels >= stbir__simdfX_float_count*2 )\n  {\n    float const * end_encode_m8 = encode + width_times_channels - stbir__simdfX_float_count*2;\n    end_output -= stbir__simdfX_float_count*2;\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      stbir__simdfX e0, e1;\n      stbir__simdi i;\n      STBIR_SIMD_NO_UNROLL(encode);\n      stbir__simdfX_add_mem( e0, STBIR_simd_point5X, encode );\n      stbir__simdfX_add_mem( e1, STBIR_simd_point5X, encode+stbir__simdfX_float_count );\n      stbir__encode_simdfX_unflip( e0 );\n      stbir__encode_simdfX_unflip( e1 );\n      #ifdef STBIR_SIMD8\n      stbir__simdf8_pack_to_16bytes( i, e0, e1 );\n      stbir__simdi_store( output, i );\n      #else\n      stbir__simdf_pack_to_8bytes( i, e0, e1 );\n      stbir__simdi_store2( output, i );\n      #endif\n      encode += stbir__simdfX_float_count*2;\n      output += stbir__simdfX_float_count*2;\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + stbir__simdfX_float_count*2 ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m8;\n    }\n    return;\n  }\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    stbir__simdf e0;\n    stbir__simdi i0;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_load( e0, encode );\n    stbir__simdf_add( e0, STBIR__CONSTF(STBIR_simd_point5), e0 );\n    stbir__encode_simdf4_unflip( e0 );\n    stbir__simdf_pack_to_8bytes( i0, e0, e0 );  // only use first 4\n    *(int*)(output-4) = stbir__simdi_to_int( i0 );\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  #else\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  while( output <= end_output )\n  {\n    float f;\n    f = encode[stbir__encode_order0] + 0.5f; STBIR_CLAMP(f, 0, 255); output[0-4] = (unsigned char)f;\n    f = encode[stbir__encode_order1] + 0.5f; STBIR_CLAMP(f, 0, 255); output[1-4] = (unsigned char)f;\n    f = encode[stbir__encode_order2] + 0.5f; STBIR_CLAMP(f, 0, 255); output[2-4] = (unsigned char)f;\n    f = encode[stbir__encode_order3] + 0.5f; STBIR_CLAMP(f, 0, 255); output[3-4] = (unsigned char)f;\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    float f;\n    STBIR_NO_UNROLL(encode);\n    f = encode[stbir__encode_order0] + 0.5f; STBIR_CLAMP(f, 0, 255); output[0] = (unsigned char)f;\n    #if stbir__coder_min_num >= 2\n    f = encode[stbir__encode_order1] + 0.5f; STBIR_CLAMP(f, 0, 255); output[1] = (unsigned char)f;\n    #endif\n    #if stbir__coder_min_num >= 3\n    f = encode[stbir__encode_order2] + 0.5f; STBIR_CLAMP(f, 0, 255); output[2] = (unsigned char)f;\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n}\n\nstatic float * STBIR__CODER_NAME(stbir__decode_uint8_srgb)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned char const * input = (unsigned char const *)inputp;\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  while( decode <= decode_end )\n  {\n    decode[0-4] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order0 ] ];\n    decode[1-4] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order1 ] ];\n    decode[2-4] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order2 ] ];\n    decode[3-4] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order3 ] ];\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order0 ] ];\n    #if stbir__coder_min_num >= 2\n    decode[1] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order1 ] ];\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = stbir__srgb_uchar_to_linear_float[ input[ stbir__decode_order2 ] ];\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n  return decode_end;\n}\n\n#define stbir__min_max_shift20( i, f ) \\\n    stbir__simdf_max( f, f, stbir_simdf_casti(STBIR__CONSTI( STBIR_almost_zero )) ); \\\n    stbir__simdf_min( f, f, stbir_simdf_casti(STBIR__CONSTI( STBIR_almost_one  )) ); \\\n    stbir__simdi_32shr( i, stbir_simdi_castf( f ), 20 );\n\n#define stbir__scale_and_convert( i, f ) \\\n    stbir__simdf_madd( f, STBIR__CONSTF( STBIR_simd_point5 ), STBIR__CONSTF( STBIR_max_uint8_as_float ), f ); \\\n    stbir__simdf_max( f, f, stbir__simdf_zeroP() ); \\\n    stbir__simdf_min( f, f, STBIR__CONSTF( STBIR_max_uint8_as_float ) ); \\\n    stbir__simdf_convert_float_to_i32( i, f );\n\n#define stbir__linear_to_srgb_finish( i, f ) \\\n{ \\\n    stbir__simdi temp;  \\\n    stbir__simdi_32shr( temp, stbir_simdi_castf( f ), 12 ) ; \\\n    stbir__simdi_and( temp, temp, STBIR__CONSTI(STBIR_mantissa_mask) ); \\\n    stbir__simdi_or( temp, temp, STBIR__CONSTI(STBIR_topscale) ); \\\n    stbir__simdi_16madd( i, i, temp ); \\\n    stbir__simdi_32shr( i, i, 16 ); \\\n}\n\n#define stbir__simdi_table_lookup2( v0,v1, table ) \\\n{ \\\n  stbir__simdi_u32 temp0,temp1; \\\n  temp0.m128i_i128 = v0; \\\n  temp1.m128i_i128 = v1; \\\n  temp0.m128i_u32[0] = table[temp0.m128i_i32[0]]; temp0.m128i_u32[1] = table[temp0.m128i_i32[1]]; temp0.m128i_u32[2] = table[temp0.m128i_i32[2]]; temp0.m128i_u32[3] = table[temp0.m128i_i32[3]]; \\\n  temp1.m128i_u32[0] = table[temp1.m128i_i32[0]]; temp1.m128i_u32[1] = table[temp1.m128i_i32[1]]; temp1.m128i_u32[2] = table[temp1.m128i_i32[2]]; temp1.m128i_u32[3] = table[temp1.m128i_i32[3]]; \\\n  v0 = temp0.m128i_i128; \\\n  v1 = temp1.m128i_i128; \\\n}\n\n#define stbir__simdi_table_lookup3( v0,v1,v2, table ) \\\n{ \\\n  stbir__simdi_u32 temp0,temp1,temp2; \\\n  temp0.m128i_i128 = v0; \\\n  temp1.m128i_i128 = v1; \\\n  temp2.m128i_i128 = v2; \\\n  temp0.m128i_u32[0] = table[temp0.m128i_i32[0]]; temp0.m128i_u32[1] = table[temp0.m128i_i32[1]]; temp0.m128i_u32[2] = table[temp0.m128i_i32[2]]; temp0.m128i_u32[3] = table[temp0.m128i_i32[3]]; \\\n  temp1.m128i_u32[0] = table[temp1.m128i_i32[0]]; temp1.m128i_u32[1] = table[temp1.m128i_i32[1]]; temp1.m128i_u32[2] = table[temp1.m128i_i32[2]]; temp1.m128i_u32[3] = table[temp1.m128i_i32[3]]; \\\n  temp2.m128i_u32[0] = table[temp2.m128i_i32[0]]; temp2.m128i_u32[1] = table[temp2.m128i_i32[1]]; temp2.m128i_u32[2] = table[temp2.m128i_i32[2]]; temp2.m128i_u32[3] = table[temp2.m128i_i32[3]]; \\\n  v0 = temp0.m128i_i128; \\\n  v1 = temp1.m128i_i128; \\\n  v2 = temp2.m128i_i128; \\\n}\n\n#define stbir__simdi_table_lookup4( v0,v1,v2,v3, table ) \\\n{ \\\n  stbir__simdi_u32 temp0,temp1,temp2,temp3; \\\n  temp0.m128i_i128 = v0; \\\n  temp1.m128i_i128 = v1; \\\n  temp2.m128i_i128 = v2; \\\n  temp3.m128i_i128 = v3; \\\n  temp0.m128i_u32[0] = table[temp0.m128i_i32[0]]; temp0.m128i_u32[1] = table[temp0.m128i_i32[1]]; temp0.m128i_u32[2] = table[temp0.m128i_i32[2]]; temp0.m128i_u32[3] = table[temp0.m128i_i32[3]]; \\\n  temp1.m128i_u32[0] = table[temp1.m128i_i32[0]]; temp1.m128i_u32[1] = table[temp1.m128i_i32[1]]; temp1.m128i_u32[2] = table[temp1.m128i_i32[2]]; temp1.m128i_u32[3] = table[temp1.m128i_i32[3]]; \\\n  temp2.m128i_u32[0] = table[temp2.m128i_i32[0]]; temp2.m128i_u32[1] = table[temp2.m128i_i32[1]]; temp2.m128i_u32[2] = table[temp2.m128i_i32[2]]; temp2.m128i_u32[3] = table[temp2.m128i_i32[3]]; \\\n  temp3.m128i_u32[0] = table[temp3.m128i_i32[0]]; temp3.m128i_u32[1] = table[temp3.m128i_i32[1]]; temp3.m128i_u32[2] = table[temp3.m128i_i32[2]]; temp3.m128i_u32[3] = table[temp3.m128i_i32[3]]; \\\n  v0 = temp0.m128i_i128; \\\n  v1 = temp1.m128i_i128; \\\n  v2 = temp2.m128i_i128; \\\n  v3 = temp3.m128i_i128; \\\n}\n\nstatic void STBIR__CODER_NAME( stbir__encode_uint8_srgb )( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned char STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned char*) outputp;\n  unsigned char * end_output = ( (unsigned char*) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n\n  if ( width_times_channels >= 16 )\n  {\n    float const * end_encode_m16 = encode + width_times_channels - 16;\n    end_output -= 16;\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      stbir__simdf f0, f1, f2, f3;\n      stbir__simdi i0, i1, i2, i3;\n      STBIR_SIMD_NO_UNROLL(encode);\n\n      stbir__simdf_load4_transposed( f0, f1, f2, f3, encode );\n\n      stbir__min_max_shift20( i0, f0 );\n      stbir__min_max_shift20( i1, f1 );\n      stbir__min_max_shift20( i2, f2 );\n      stbir__min_max_shift20( i3, f3 );\n\n      stbir__simdi_table_lookup4( i0, i1, i2, i3, ( fp32_to_srgb8_tab4 - (127-13)*8 ) );\n\n      stbir__linear_to_srgb_finish( i0, f0 );\n      stbir__linear_to_srgb_finish( i1, f1 );\n      stbir__linear_to_srgb_finish( i2, f2 );\n      stbir__linear_to_srgb_finish( i3, f3 );\n\n      stbir__interleave_pack_and_store_16_u8( output,  STBIR_strs_join1(i, ,stbir__encode_order0), STBIR_strs_join1(i, ,stbir__encode_order1), STBIR_strs_join1(i, ,stbir__encode_order2), STBIR_strs_join1(i, ,stbir__encode_order3) );\n\n      encode += 16;\n      output += 16;\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + 16 ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m16;\n    }\n    return;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while ( output <= end_output )\n  {\n    STBIR_SIMD_NO_UNROLL(encode);\n\n    output[0-4] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order0] );\n    output[1-4] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order1] );\n    output[2-4] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order2] );\n    output[3-4] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order3] );\n\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    STBIR_NO_UNROLL(encode);\n    output[0] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order0] );\n    #if stbir__coder_min_num >= 2\n    output[1] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order1] );\n    #endif\n    #if stbir__coder_min_num >= 3\n    output[2] = stbir__linear_to_srgb_uchar( encode[stbir__encode_order2] );\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n}\n\n#if ( stbir__coder_min_num == 4 ) || ( ( stbir__coder_min_num == 1 ) && ( !defined(stbir__decode_swizzle) ) )\n\nstatic float * STBIR__CODER_NAME(stbir__decode_uint8_srgb4_linearalpha)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned char const * input = (unsigned char const *)inputp;\n\n  do {\n    decode[0] = stbir__srgb_uchar_to_linear_float[ input[stbir__decode_order0] ];\n    decode[1] = stbir__srgb_uchar_to_linear_float[ input[stbir__decode_order1] ];\n    decode[2] = stbir__srgb_uchar_to_linear_float[ input[stbir__decode_order2] ];\n    decode[3] = ( (float) input[stbir__decode_order3] ) * stbir__max_uint8_as_float_inverted;\n    input += 4;\n    decode += 4;\n  } while( decode < decode_end );\n  return decode_end;\n}\n\n\nstatic void STBIR__CODER_NAME( stbir__encode_uint8_srgb4_linearalpha )( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned char STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned char*) outputp;\n  unsigned char * end_output = ( (unsigned char*) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n\n  if ( width_times_channels >= 16 )\n  {\n    float const * end_encode_m16 = encode + width_times_channels - 16;\n    end_output -= 16;\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      stbir__simdf f0, f1, f2, f3;\n      stbir__simdi i0, i1, i2, i3;\n\n      STBIR_SIMD_NO_UNROLL(encode);\n      stbir__simdf_load4_transposed( f0, f1, f2, f3, encode );\n\n      stbir__min_max_shift20( i0, f0 );\n      stbir__min_max_shift20( i1, f1 );\n      stbir__min_max_shift20( i2, f2 );\n      stbir__scale_and_convert( i3, f3 );\n\n      stbir__simdi_table_lookup3( i0, i1, i2, ( fp32_to_srgb8_tab4 - (127-13)*8 ) );\n\n      stbir__linear_to_srgb_finish( i0, f0 );\n      stbir__linear_to_srgb_finish( i1, f1 );\n      stbir__linear_to_srgb_finish( i2, f2 );\n\n      stbir__interleave_pack_and_store_16_u8( output,  STBIR_strs_join1(i, ,stbir__encode_order0), STBIR_strs_join1(i, ,stbir__encode_order1), STBIR_strs_join1(i, ,stbir__encode_order2), STBIR_strs_join1(i, ,stbir__encode_order3) );\n\n      output += 16;\n      encode += 16;\n\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + 16 ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m16;\n    }\n    return;\n  }\n  #endif\n\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float f;\n    STBIR_SIMD_NO_UNROLL(encode);\n\n    output[stbir__decode_order0] = stbir__linear_to_srgb_uchar( encode[0] );\n    output[stbir__decode_order1] = stbir__linear_to_srgb_uchar( encode[1] );\n    output[stbir__decode_order2] = stbir__linear_to_srgb_uchar( encode[2] );\n\n    f = encode[3] * stbir__max_uint8_as_float + 0.5f;\n    STBIR_CLAMP(f, 0, 255);\n    output[stbir__decode_order3] = (unsigned char) f;\n\n    output += 4;\n    encode += 4;\n  } while( output < end_output );\n}\n\n#endif\n\n#if ( stbir__coder_min_num == 2 ) || ( ( stbir__coder_min_num == 1 ) && ( !defined(stbir__decode_swizzle) ) )\n\nstatic float * STBIR__CODER_NAME(stbir__decode_uint8_srgb2_linearalpha)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned char const * input = (unsigned char const *)inputp;\n\n  decode += 4;\n  while( decode <= decode_end )\n  {\n    decode[0-4] = stbir__srgb_uchar_to_linear_float[ input[stbir__decode_order0] ];\n    decode[1-4] = ( (float) input[stbir__decode_order1] ) * stbir__max_uint8_as_float_inverted;\n    decode[2-4] = stbir__srgb_uchar_to_linear_float[ input[stbir__decode_order0+2] ];\n    decode[3-4] = ( (float) input[stbir__decode_order1+2] ) * stbir__max_uint8_as_float_inverted;\n    input += 4;\n    decode += 4;\n  }\n  decode -= 4;\n  if( decode < decode_end )\n  {\n    decode[0] = stbir__srgb_uchar_to_linear_float[ input[stbir__decode_order0] ];\n    decode[1] = ( (float) input[stbir__decode_order1] ) * stbir__max_uint8_as_float_inverted;\n  }\n  return decode_end;\n}\n\nstatic void STBIR__CODER_NAME( stbir__encode_uint8_srgb2_linearalpha )( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned char STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned char*) outputp;\n  unsigned char * end_output = ( (unsigned char*) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n\n  if ( width_times_channels >= 16 )\n  {\n    float const * end_encode_m16 = encode + width_times_channels - 16;\n    end_output -= 16;\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      stbir__simdf f0, f1, f2, f3;\n      stbir__simdi i0, i1, i2, i3;\n\n      STBIR_SIMD_NO_UNROLL(encode);\n      stbir__simdf_load4_transposed( f0, f1, f2, f3, encode );\n\n      stbir__min_max_shift20( i0, f0 );\n      stbir__scale_and_convert( i1, f1 );\n      stbir__min_max_shift20( i2, f2 );\n      stbir__scale_and_convert( i3, f3 );\n\n      stbir__simdi_table_lookup2( i0, i2, ( fp32_to_srgb8_tab4 - (127-13)*8 ) );\n\n      stbir__linear_to_srgb_finish( i0, f0 );\n      stbir__linear_to_srgb_finish( i2, f2 );\n\n      stbir__interleave_pack_and_store_16_u8( output,  STBIR_strs_join1(i, ,stbir__encode_order0), STBIR_strs_join1(i, ,stbir__encode_order1), STBIR_strs_join1(i, ,stbir__encode_order2), STBIR_strs_join1(i, ,stbir__encode_order3) );\n\n      output += 16;\n      encode += 16;\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + 16 ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m16;\n    }\n    return;\n  }\n  #endif\n\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float f;\n    STBIR_SIMD_NO_UNROLL(encode);\n\n    output[stbir__decode_order0] = stbir__linear_to_srgb_uchar( encode[0] );\n\n    f = encode[1] * stbir__max_uint8_as_float + 0.5f;\n    STBIR_CLAMP(f, 0, 255);\n    output[stbir__decode_order1] = (unsigned char) f;\n\n    output += 2;\n    encode += 2;\n  } while( output < end_output );\n}\n\n#endif\n\nstatic float * STBIR__CODER_NAME(stbir__decode_uint16_linear_scaled)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned short const * input = (unsigned short const *)inputp;\n\n  #ifdef STBIR_SIMD\n  unsigned short const * end_input_m8 = input + width_times_channels - 8;\n  if ( width_times_channels >= 8 )\n  {\n    decode_end -= 8;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      #ifdef STBIR_SIMD8\n      stbir__simdi i; stbir__simdi8 o;\n      stbir__simdf8 of;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi8_expand_u16_to_u32( o, i );\n      stbir__simdi8_convert_i32_to_float( of, o );\n      stbir__simdf8_mult( of, of, STBIR_max_uint16_as_float_inverted8);\n      stbir__decode_simdf8_flip( of );\n      stbir__simdf8_store( decode + 0, of );\n      #else\n      stbir__simdi i, o0, o1;\n      stbir__simdf of0, of1;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi_expand_u16_to_u32( o0,o1,i );\n      stbir__simdi_convert_i32_to_float( of0, o0 );\n      stbir__simdi_convert_i32_to_float( of1, o1 );\n      stbir__simdf_mult( of0, of0, STBIR__CONSTF(STBIR_max_uint16_as_float_inverted) );\n      stbir__simdf_mult( of1, of1, STBIR__CONSTF(STBIR_max_uint16_as_float_inverted));\n      stbir__decode_simdf4_flip( of0 );\n      stbir__decode_simdf4_flip( of1 );\n      stbir__simdf_store( decode + 0,  of0 );\n      stbir__simdf_store( decode + 4,  of1 );\n      #endif\n      decode += 8;\n      input += 8;\n      if ( decode <= decode_end )\n        continue;\n      if ( decode == ( decode_end + 8 ) )\n        break;\n      decode = decode_end; // backup and do last couple\n      input = end_input_m8;\n    }\n    return decode_end + 8;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode <= decode_end )\n  {\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0-4] = ((float)(input[stbir__decode_order0])) * stbir__max_uint16_as_float_inverted;\n    decode[1-4] = ((float)(input[stbir__decode_order1])) * stbir__max_uint16_as_float_inverted;\n    decode[2-4] = ((float)(input[stbir__decode_order2])) * stbir__max_uint16_as_float_inverted;\n    decode[3-4] = ((float)(input[stbir__decode_order3])) * stbir__max_uint16_as_float_inverted;\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = ((float)(input[stbir__decode_order0])) * stbir__max_uint16_as_float_inverted;\n    #if stbir__coder_min_num >= 2\n    decode[1] = ((float)(input[stbir__decode_order1])) * stbir__max_uint16_as_float_inverted;\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = ((float)(input[stbir__decode_order2])) * stbir__max_uint16_as_float_inverted;\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n  return decode_end;\n}\n\n\nstatic void STBIR__CODER_NAME(stbir__encode_uint16_linear_scaled)( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned short STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned short*) outputp;\n  unsigned short * end_output = ( (unsigned short*) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  {\n    if ( width_times_channels >= stbir__simdfX_float_count*2 )\n    {\n      float const * end_encode_m8 = encode + width_times_channels - stbir__simdfX_float_count*2;\n      end_output -= stbir__simdfX_float_count*2;\n      STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n      for(;;)\n      {\n        stbir__simdfX e0, e1;\n        stbir__simdiX i;\n        STBIR_SIMD_NO_UNROLL(encode);\n        stbir__simdfX_madd_mem( e0, STBIR_simd_point5X, STBIR_max_uint16_as_floatX, encode );\n        stbir__simdfX_madd_mem( e1, STBIR_simd_point5X, STBIR_max_uint16_as_floatX, encode+stbir__simdfX_float_count );\n        stbir__encode_simdfX_unflip( e0 );\n        stbir__encode_simdfX_unflip( e1 );\n        stbir__simdfX_pack_to_words( i, e0, e1 );\n        stbir__simdiX_store( output, i );\n        encode += stbir__simdfX_float_count*2;\n        output += stbir__simdfX_float_count*2;\n        if ( output <= end_output )\n          continue;\n        if ( output == ( end_output + stbir__simdfX_float_count*2 ) )\n          break;\n        output = end_output;     // backup and do last couple\n        encode = end_encode_m8;\n      }\n      return;\n    }\n  }\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    stbir__simdf e;\n    stbir__simdi i;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_load( e, encode );\n    stbir__simdf_madd( e, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint16_as_float), e );\n    stbir__encode_simdf4_unflip( e );\n    stbir__simdf_pack_to_8words( i, e, e );  // only use first 4\n    stbir__simdi_store2( output-4, i );\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    stbir__simdf e;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_madd1_mem( e, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint16_as_float), encode+stbir__encode_order0 ); output[0] = stbir__simdf_convert_float_to_short( e );\n    #if stbir__coder_min_num >= 2\n    stbir__simdf_madd1_mem( e, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint16_as_float), encode+stbir__encode_order1 ); output[1] = stbir__simdf_convert_float_to_short( e );\n    #endif\n    #if stbir__coder_min_num >= 3\n    stbir__simdf_madd1_mem( e, STBIR__CONSTF(STBIR_simd_point5), STBIR__CONSTF(STBIR_max_uint16_as_float), encode+stbir__encode_order2 ); output[2] = stbir__simdf_convert_float_to_short( e );\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n\n  #else\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    float f;\n    STBIR_SIMD_NO_UNROLL(encode);\n    f = encode[stbir__encode_order0] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[0-4] = (unsigned short)f;\n    f = encode[stbir__encode_order1] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[1-4] = (unsigned short)f;\n    f = encode[stbir__encode_order2] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[2-4] = (unsigned short)f;\n    f = encode[stbir__encode_order3] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[3-4] = (unsigned short)f;\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    float f;\n    STBIR_NO_UNROLL(encode);\n    f = encode[stbir__encode_order0] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[0] = (unsigned short)f;\n    #if stbir__coder_min_num >= 2\n    f = encode[stbir__encode_order1] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[1] = (unsigned short)f;\n    #endif\n    #if stbir__coder_min_num >= 3\n    f = encode[stbir__encode_order2] * stbir__max_uint16_as_float + 0.5f; STBIR_CLAMP(f, 0, 65535); output[2] = (unsigned short)f;\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n  #endif\n}\n\nstatic float * STBIR__CODER_NAME(stbir__decode_uint16_linear)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  unsigned short const * input = (unsigned short const *)inputp;\n\n  #ifdef STBIR_SIMD\n  unsigned short const * end_input_m8 = input + width_times_channels - 8;\n  if ( width_times_channels >= 8 )\n  {\n    decode_end -= 8;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      #ifdef STBIR_SIMD8\n      stbir__simdi i; stbir__simdi8 o;\n      stbir__simdf8 of;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi8_expand_u16_to_u32( o, i );\n      stbir__simdi8_convert_i32_to_float( of, o );\n      stbir__decode_simdf8_flip( of );\n      stbir__simdf8_store( decode + 0, of );\n      #else\n      stbir__simdi i, o0, o1;\n      stbir__simdf of0, of1;\n      STBIR_NO_UNROLL(decode);\n      stbir__simdi_load( i, input );\n      stbir__simdi_expand_u16_to_u32( o0, o1, i );\n      stbir__simdi_convert_i32_to_float( of0, o0 );\n      stbir__simdi_convert_i32_to_float( of1, o1 );\n      stbir__decode_simdf4_flip( of0 );\n      stbir__decode_simdf4_flip( of1 );\n      stbir__simdf_store( decode + 0,  of0 );\n      stbir__simdf_store( decode + 4,  of1 );\n      #endif\n      decode += 8;\n      input += 8;\n      if ( decode <= decode_end )\n        continue;\n      if ( decode == ( decode_end + 8 ) )\n        break;\n      decode = decode_end; // backup and do last couple\n      input = end_input_m8;\n    }\n    return decode_end + 8;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode <= decode_end )\n  {\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0-4] = ((float)(input[stbir__decode_order0]));\n    decode[1-4] = ((float)(input[stbir__decode_order1]));\n    decode[2-4] = ((float)(input[stbir__decode_order2]));\n    decode[3-4] = ((float)(input[stbir__decode_order3]));\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = ((float)(input[stbir__decode_order0]));\n    #if stbir__coder_min_num >= 2\n    decode[1] = ((float)(input[stbir__decode_order1]));\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = ((float)(input[stbir__decode_order2]));\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n  return decode_end;\n}\n\nstatic void STBIR__CODER_NAME(stbir__encode_uint16_linear)( void * outputp, int width_times_channels, float const * encode )\n{\n  unsigned short STBIR_SIMD_STREAMOUT_PTR( * ) output = (unsigned short*) outputp;\n  unsigned short * end_output = ( (unsigned short*) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  {\n    if ( width_times_channels >= stbir__simdfX_float_count*2 )\n    {\n      float const * end_encode_m8 = encode + width_times_channels - stbir__simdfX_float_count*2;\n      end_output -= stbir__simdfX_float_count*2;\n      STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n      for(;;)\n      {\n        stbir__simdfX e0, e1;\n        stbir__simdiX i;\n        STBIR_SIMD_NO_UNROLL(encode);\n        stbir__simdfX_add_mem( e0, STBIR_simd_point5X, encode );\n        stbir__simdfX_add_mem( e1, STBIR_simd_point5X, encode+stbir__simdfX_float_count );\n        stbir__encode_simdfX_unflip( e0 );\n        stbir__encode_simdfX_unflip( e1 );\n        stbir__simdfX_pack_to_words( i, e0, e1 );\n        stbir__simdiX_store( output, i );\n        encode += stbir__simdfX_float_count*2;\n        output += stbir__simdfX_float_count*2;\n        if ( output <= end_output )\n          continue;\n        if ( output == ( end_output + stbir__simdfX_float_count*2 ) )\n          break;\n        output = end_output; // backup and do last couple\n        encode = end_encode_m8;\n      }\n      return;\n    }\n  }\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    stbir__simdf e;\n    stbir__simdi i;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_load( e, encode );\n    stbir__simdf_add( e, STBIR__CONSTF(STBIR_simd_point5), e );\n    stbir__encode_simdf4_unflip( e );\n    stbir__simdf_pack_to_8words( i, e, e );  // only use first 4\n    stbir__simdi_store2( output-4, i );\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  #else\n\n  // try to do blocks of 4 when you can\n  #if  stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    float f;\n    STBIR_SIMD_NO_UNROLL(encode);\n    f = encode[stbir__encode_order0] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[0-4] = (unsigned short)f;\n    f = encode[stbir__encode_order1] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[1-4] = (unsigned short)f;\n    f = encode[stbir__encode_order2] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[2-4] = (unsigned short)f;\n    f = encode[stbir__encode_order3] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[3-4] = (unsigned short)f;\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    float f;\n    STBIR_NO_UNROLL(encode);\n    f = encode[stbir__encode_order0] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[0] = (unsigned short)f;\n    #if stbir__coder_min_num >= 2\n    f = encode[stbir__encode_order1] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[1] = (unsigned short)f;\n    #endif\n    #if stbir__coder_min_num >= 3\n    f = encode[stbir__encode_order2] + 0.5f; STBIR_CLAMP(f, 0, 65535); output[2] = (unsigned short)f;\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n}\n\nstatic float * STBIR__CODER_NAME(stbir__decode_half_float_linear)( float * decodep, int width_times_channels, void const * inputp )\n{\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  stbir__FP16 const * input = (stbir__FP16 const *)inputp;\n\n  #ifdef STBIR_SIMD\n  if ( width_times_channels >= 8 )\n  {\n    stbir__FP16 const * end_input_m8 = input + width_times_channels - 8;\n    decode_end -= 8;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      STBIR_NO_UNROLL(decode);\n\n      stbir__half_to_float_SIMD( decode, input );\n      #ifdef stbir__decode_swizzle\n      #ifdef STBIR_SIMD8\n      {\n        stbir__simdf8 of;\n        stbir__simdf8_load( of, decode );\n        stbir__decode_simdf8_flip( of );\n        stbir__simdf8_store( decode, of );\n      }\n      #else\n      {\n        stbir__simdf of0,of1;\n        stbir__simdf_load( of0, decode );\n        stbir__simdf_load( of1, decode+4 );\n        stbir__decode_simdf4_flip( of0 );\n        stbir__decode_simdf4_flip( of1 );\n        stbir__simdf_store( decode, of0 );\n        stbir__simdf_store( decode+4, of1 );\n      }\n      #endif\n      #endif\n      decode += 8;\n      input += 8;\n      if ( decode <= decode_end )\n        continue;\n      if ( decode == ( decode_end + 8 ) )\n        break;\n      decode = decode_end; // backup and do last couple\n      input = end_input_m8;\n    }\n    return decode_end + 8;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode <= decode_end )\n  {\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0-4] = stbir__half_to_float(input[stbir__decode_order0]);\n    decode[1-4] = stbir__half_to_float(input[stbir__decode_order1]);\n    decode[2-4] = stbir__half_to_float(input[stbir__decode_order2]);\n    decode[3-4] = stbir__half_to_float(input[stbir__decode_order3]);\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = stbir__half_to_float(input[stbir__decode_order0]);\n    #if stbir__coder_min_num >= 2\n    decode[1] = stbir__half_to_float(input[stbir__decode_order1]);\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = stbir__half_to_float(input[stbir__decode_order2]);\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n  return decode_end;\n}\n\nstatic void STBIR__CODER_NAME( stbir__encode_half_float_linear )( void * outputp, int width_times_channels, float const * encode )\n{\n  stbir__FP16 STBIR_SIMD_STREAMOUT_PTR( * ) output = (stbir__FP16*) outputp;\n  stbir__FP16 * end_output = ( (stbir__FP16*) output ) + width_times_channels;\n\n  #ifdef STBIR_SIMD\n  if ( width_times_channels >= 8 )\n  {\n    float const * end_encode_m8 = encode + width_times_channels - 8;\n    end_output -= 8;\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      STBIR_SIMD_NO_UNROLL(encode);\n      #ifdef stbir__decode_swizzle\n      #ifdef STBIR_SIMD8\n      {\n        stbir__simdf8 of;\n        stbir__simdf8_load( of, encode );\n        stbir__encode_simdf8_unflip( of );\n        stbir__float_to_half_SIMD( output, (float*)&of );\n      }\n      #else\n      {\n        stbir__simdf of[2];\n        stbir__simdf_load( of[0], encode );\n        stbir__simdf_load( of[1], encode+4 );\n        stbir__encode_simdf4_unflip( of[0] );\n        stbir__encode_simdf4_unflip( of[1] );\n        stbir__float_to_half_SIMD( output, (float*)of );\n      }\n      #endif\n      #else\n      stbir__float_to_half_SIMD( output, encode );\n      #endif\n      encode += 8;\n      output += 8;\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + 8 ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m8;\n    }\n    return;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    STBIR_SIMD_NO_UNROLL(output);\n    output[0-4] = stbir__float_to_half(encode[stbir__encode_order0]);\n    output[1-4] = stbir__float_to_half(encode[stbir__encode_order1]);\n    output[2-4] = stbir__float_to_half(encode[stbir__encode_order2]);\n    output[3-4] = stbir__float_to_half(encode[stbir__encode_order3]);\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    STBIR_NO_UNROLL(output);\n    output[0] = stbir__float_to_half(encode[stbir__encode_order0]);\n    #if stbir__coder_min_num >= 2\n    output[1] = stbir__float_to_half(encode[stbir__encode_order1]);\n    #endif\n    #if stbir__coder_min_num >= 3\n    output[2] = stbir__float_to_half(encode[stbir__encode_order2]);\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n}\n\nstatic float * STBIR__CODER_NAME(stbir__decode_float_linear)( float * decodep, int width_times_channels, void const * inputp )\n{\n  #ifdef stbir__decode_swizzle\n  float STBIR_STREAMOUT_PTR( * ) decode = decodep;\n  float * decode_end = (float*) decode + width_times_channels;\n  float const * input = (float const *)inputp;\n\n  #ifdef STBIR_SIMD\n  if ( width_times_channels >= 16 )\n  {\n    float const * end_input_m16 = input + width_times_channels - 16;\n    decode_end -= 16;\n    STBIR_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      STBIR_NO_UNROLL(decode);\n      #ifdef stbir__decode_swizzle\n      #ifdef STBIR_SIMD8\n      {\n        stbir__simdf8 of0,of1;\n        stbir__simdf8_load( of0, input );\n        stbir__simdf8_load( of1, input+8 );\n        stbir__decode_simdf8_flip( of0 );\n        stbir__decode_simdf8_flip( of1 );\n        stbir__simdf8_store( decode, of0 );\n        stbir__simdf8_store( decode+8, of1 );\n      }\n      #else\n      {\n        stbir__simdf of0,of1,of2,of3;\n        stbir__simdf_load( of0, input );\n        stbir__simdf_load( of1, input+4 );\n        stbir__simdf_load( of2, input+8 );\n        stbir__simdf_load( of3, input+12 );\n        stbir__decode_simdf4_flip( of0 );\n        stbir__decode_simdf4_flip( of1 );\n        stbir__decode_simdf4_flip( of2 );\n        stbir__decode_simdf4_flip( of3 );\n        stbir__simdf_store( decode, of0 );\n        stbir__simdf_store( decode+4, of1 );\n        stbir__simdf_store( decode+8, of2 );\n        stbir__simdf_store( decode+12, of3 );\n      }\n      #endif\n      #endif\n      decode += 16;\n      input += 16;\n      if ( decode <= decode_end )\n        continue;\n      if ( decode == ( decode_end + 16 ) )\n        break;\n      decode = decode_end; // backup and do last couple\n      input = end_input_m16;\n    }\n    return decode_end + 16;\n  }\n  #endif\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  decode += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( decode <= decode_end )\n  {\n    STBIR_SIMD_NO_UNROLL(decode);\n    decode[0-4] = input[stbir__decode_order0];\n    decode[1-4] = input[stbir__decode_order1];\n    decode[2-4] = input[stbir__decode_order2];\n    decode[3-4] = input[stbir__decode_order3];\n    decode += 4;\n    input += 4;\n  }\n  decode -= 4;\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( decode < decode_end )\n  {\n    STBIR_NO_UNROLL(decode);\n    decode[0] = input[stbir__decode_order0];\n    #if stbir__coder_min_num >= 2\n    decode[1] = input[stbir__decode_order1];\n    #endif\n    #if stbir__coder_min_num >= 3\n    decode[2] = input[stbir__decode_order2];\n    #endif\n    decode += stbir__coder_min_num;\n    input += stbir__coder_min_num;\n  }\n  #endif\n  return decode_end;\n\n  #else\n\n  if ( (void*)decodep != inputp )\n    STBIR_MEMCPY( decodep, inputp, width_times_channels * sizeof( float ) );\n\n  return decodep + width_times_channels;\n\n  #endif\n}\n\nstatic void STBIR__CODER_NAME( stbir__encode_float_linear )( void * outputp, int width_times_channels, float const * encode )\n{\n  #if !defined( STBIR_FLOAT_HIGH_CLAMP ) && !defined(STBIR_FLOAT_LOW_CLAMP) && !defined(stbir__decode_swizzle)\n\n  if ( (void*)outputp != (void*) encode )\n    STBIR_MEMCPY( outputp, encode, width_times_channels * sizeof( float ) );\n\n  #else\n\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = (float*) outputp;\n  float * end_output = ( (float*) output ) + width_times_channels;\n\n  #ifdef STBIR_FLOAT_HIGH_CLAMP\n  #define stbir_scalar_hi_clamp( v ) if ( v > STBIR_FLOAT_HIGH_CLAMP ) v = STBIR_FLOAT_HIGH_CLAMP;\n  #else\n  #define stbir_scalar_hi_clamp( v )\n  #endif\n  #ifdef STBIR_FLOAT_LOW_CLAMP\n  #define stbir_scalar_lo_clamp( v ) if ( v < STBIR_FLOAT_LOW_CLAMP ) v = STBIR_FLOAT_LOW_CLAMP;\n  #else\n  #define stbir_scalar_lo_clamp( v )\n  #endif\n\n  #ifdef STBIR_SIMD\n\n  #ifdef STBIR_FLOAT_HIGH_CLAMP\n  const stbir__simdfX high_clamp = stbir__simdf_frepX(STBIR_FLOAT_HIGH_CLAMP);\n  #endif\n  #ifdef STBIR_FLOAT_LOW_CLAMP\n  const stbir__simdfX low_clamp = stbir__simdf_frepX(STBIR_FLOAT_LOW_CLAMP);\n  #endif\n\n  if ( width_times_channels >= ( stbir__simdfX_float_count * 2 ) )\n  {\n    float const * end_encode_m8 = encode + width_times_channels - ( stbir__simdfX_float_count * 2 );\n    end_output -= ( stbir__simdfX_float_count * 2 );\n    STBIR_SIMD_NO_UNROLL_LOOP_START_INF_FOR\n    for(;;)\n    {\n      stbir__simdfX e0, e1;\n      STBIR_SIMD_NO_UNROLL(encode);\n      stbir__simdfX_load( e0, encode );\n      stbir__simdfX_load( e1, encode+stbir__simdfX_float_count );\n#ifdef STBIR_FLOAT_HIGH_CLAMP\n      stbir__simdfX_min( e0, e0, high_clamp );\n      stbir__simdfX_min( e1, e1, high_clamp );\n#endif\n#ifdef STBIR_FLOAT_LOW_CLAMP\n      stbir__simdfX_max( e0, e0, low_clamp );\n      stbir__simdfX_max( e1, e1, low_clamp );\n#endif\n      stbir__encode_simdfX_unflip( e0 );\n      stbir__encode_simdfX_unflip( e1 );\n      stbir__simdfX_store( output, e0 );\n      stbir__simdfX_store( output+stbir__simdfX_float_count, e1 );\n      encode += stbir__simdfX_float_count * 2;\n      output += stbir__simdfX_float_count * 2;\n      if ( output <= end_output )\n        continue;\n      if ( output == ( end_output + ( stbir__simdfX_float_count * 2 ) ) )\n        break;\n      output = end_output; // backup and do last couple\n      encode = end_encode_m8;\n    }\n    return;\n  }\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    stbir__simdf e0;\n    STBIR_NO_UNROLL(encode);\n    stbir__simdf_load( e0, encode );\n#ifdef STBIR_FLOAT_HIGH_CLAMP\n    stbir__simdf_min( e0, e0, high_clamp );\n#endif\n#ifdef STBIR_FLOAT_LOW_CLAMP\n    stbir__simdf_max( e0, e0, low_clamp );\n#endif\n    stbir__encode_simdf4_unflip( e0 );\n    stbir__simdf_store( output-4, e0 );\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n  #endif\n\n  #else\n\n  // try to do blocks of 4 when you can\n  #if stbir__coder_min_num != 3 // doesn't divide cleanly by four\n  output += 4;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  while( output <= end_output )\n  {\n    float e;\n    STBIR_SIMD_NO_UNROLL(encode);\n    e = encode[ stbir__encode_order0 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[0-4] = e;\n    e = encode[ stbir__encode_order1 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[1-4] = e;\n    e = encode[ stbir__encode_order2 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[2-4] = e;\n    e = encode[ stbir__encode_order3 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[3-4] = e;\n    output += 4;\n    encode += 4;\n  }\n  output -= 4;\n\n  #endif\n\n  #endif\n\n  // do the remnants\n  #if stbir__coder_min_num < 4\n  STBIR_NO_UNROLL_LOOP_START\n  while( output < end_output )\n  {\n    float e;\n    STBIR_NO_UNROLL(encode);\n    e = encode[ stbir__encode_order0 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[0] = e;\n    #if stbir__coder_min_num >= 2\n    e = encode[ stbir__encode_order1 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[1] = e;\n    #endif\n    #if stbir__coder_min_num >= 3\n    e = encode[ stbir__encode_order2 ]; stbir_scalar_hi_clamp( e ); stbir_scalar_lo_clamp( e ); output[2] = e;\n    #endif\n    output += stbir__coder_min_num;\n    encode += stbir__coder_min_num;\n  }\n  #endif\n\n  #endif\n}\n\n#undef stbir__decode_suffix\n#undef stbir__decode_simdf8_flip\n#undef stbir__decode_simdf4_flip\n#undef stbir__decode_order0\n#undef stbir__decode_order1\n#undef stbir__decode_order2\n#undef stbir__decode_order3\n#undef stbir__encode_order0\n#undef stbir__encode_order1\n#undef stbir__encode_order2\n#undef stbir__encode_order3\n#undef stbir__encode_simdf8_unflip\n#undef stbir__encode_simdf4_unflip\n#undef stbir__encode_simdfX_unflip\n#undef STBIR__CODER_NAME\n#undef stbir__coder_min_num\n#undef stbir__decode_swizzle\n#undef stbir_scalar_hi_clamp\n#undef stbir_scalar_lo_clamp\n#undef STB_IMAGE_RESIZE_DO_CODERS\n\n#elif defined( STB_IMAGE_RESIZE_DO_VERTICALS)\n\n#ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#define STBIR_chans( start, end ) STBIR_strs_join14(start,STBIR__vertical_channels,end,_cont)\n#else\n#define STBIR_chans( start, end ) STBIR_strs_join1(start,STBIR__vertical_channels,end)\n#endif\n\n#if STBIR__vertical_channels >= 1\n#define stbIF0( code ) code\n#else\n#define stbIF0( code )\n#endif\n#if STBIR__vertical_channels >= 2\n#define stbIF1( code ) code\n#else\n#define stbIF1( code )\n#endif\n#if STBIR__vertical_channels >= 3\n#define stbIF2( code ) code\n#else\n#define stbIF2( code )\n#endif\n#if STBIR__vertical_channels >= 4\n#define stbIF3( code ) code\n#else\n#define stbIF3( code )\n#endif\n#if STBIR__vertical_channels >= 5\n#define stbIF4( code ) code\n#else\n#define stbIF4( code )\n#endif\n#if STBIR__vertical_channels >= 6\n#define stbIF5( code ) code\n#else\n#define stbIF5( code )\n#endif\n#if STBIR__vertical_channels >= 7\n#define stbIF6( code ) code\n#else\n#define stbIF6( code )\n#endif\n#if STBIR__vertical_channels >= 8\n#define stbIF7( code ) code\n#else\n#define stbIF7( code )\n#endif\n\nstatic void STBIR_chans( stbir__vertical_scatter_with_,_coeffs)( float ** outputs, float const * vertical_coefficients, float const * input, float const * input_end )\n{\n  stbIF0( float STBIR_SIMD_STREAMOUT_PTR( * ) output0 = outputs[0]; float c0s = vertical_coefficients[0]; )\n  stbIF1( float STBIR_SIMD_STREAMOUT_PTR( * ) output1 = outputs[1]; float c1s = vertical_coefficients[1]; )\n  stbIF2( float STBIR_SIMD_STREAMOUT_PTR( * ) output2 = outputs[2]; float c2s = vertical_coefficients[2]; )\n  stbIF3( float STBIR_SIMD_STREAMOUT_PTR( * ) output3 = outputs[3]; float c3s = vertical_coefficients[3]; )\n  stbIF4( float STBIR_SIMD_STREAMOUT_PTR( * ) output4 = outputs[4]; float c4s = vertical_coefficients[4]; )\n  stbIF5( float STBIR_SIMD_STREAMOUT_PTR( * ) output5 = outputs[5]; float c5s = vertical_coefficients[5]; )\n  stbIF6( float STBIR_SIMD_STREAMOUT_PTR( * ) output6 = outputs[6]; float c6s = vertical_coefficients[6]; )\n  stbIF7( float STBIR_SIMD_STREAMOUT_PTR( * ) output7 = outputs[7]; float c7s = vertical_coefficients[7]; )\n\n  #ifdef STBIR_SIMD\n  {\n    stbIF0(stbir__simdfX c0 = stbir__simdf_frepX( c0s ); )\n    stbIF1(stbir__simdfX c1 = stbir__simdf_frepX( c1s ); )\n    stbIF2(stbir__simdfX c2 = stbir__simdf_frepX( c2s ); )\n    stbIF3(stbir__simdfX c3 = stbir__simdf_frepX( c3s ); )\n    stbIF4(stbir__simdfX c4 = stbir__simdf_frepX( c4s ); )\n    stbIF5(stbir__simdfX c5 = stbir__simdf_frepX( c5s ); )\n    stbIF6(stbir__simdfX c6 = stbir__simdf_frepX( c6s ); )\n    stbIF7(stbir__simdfX c7 = stbir__simdf_frepX( c7s ); )\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    while ( ( (char*)input_end - (char*) input ) >= (16*stbir__simdfX_float_count) )\n    {\n      stbir__simdfX o0, o1, o2, o3, r0, r1, r2, r3;\n      STBIR_SIMD_NO_UNROLL(output0);\n\n      stbir__simdfX_load( r0, input );               stbir__simdfX_load( r1, input+stbir__simdfX_float_count );     stbir__simdfX_load( r2, input+(2*stbir__simdfX_float_count) );      stbir__simdfX_load( r3, input+(3*stbir__simdfX_float_count) );\n\n      #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n      stbIF0( stbir__simdfX_load( o0, output0 );     stbir__simdfX_load( o1, output0+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output0+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output0+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c0 );  stbir__simdfX_madd( o1, o1, r1, c0 );  stbir__simdfX_madd( o2, o2, r2, c0 );   stbir__simdfX_madd( o3, o3, r3, c0 );\n              stbir__simdfX_store( output0, o0 );    stbir__simdfX_store( output0+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output0+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output0+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF1( stbir__simdfX_load( o0, output1 );     stbir__simdfX_load( o1, output1+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output1+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output1+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c1 );  stbir__simdfX_madd( o1, o1, r1, c1 );  stbir__simdfX_madd( o2, o2, r2, c1 );   stbir__simdfX_madd( o3, o3, r3, c1 );\n              stbir__simdfX_store( output1, o0 );    stbir__simdfX_store( output1+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output1+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output1+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF2( stbir__simdfX_load( o0, output2 );     stbir__simdfX_load( o1, output2+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output2+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output2+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c2 );  stbir__simdfX_madd( o1, o1, r1, c2 );  stbir__simdfX_madd( o2, o2, r2, c2 );   stbir__simdfX_madd( o3, o3, r3, c2 );\n              stbir__simdfX_store( output2, o0 );    stbir__simdfX_store( output2+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output2+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output2+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF3( stbir__simdfX_load( o0, output3 );     stbir__simdfX_load( o1, output3+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output3+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output3+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c3 );  stbir__simdfX_madd( o1, o1, r1, c3 );  stbir__simdfX_madd( o2, o2, r2, c3 );   stbir__simdfX_madd( o3, o3, r3, c3 );\n              stbir__simdfX_store( output3, o0 );    stbir__simdfX_store( output3+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output3+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output3+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF4( stbir__simdfX_load( o0, output4 );     stbir__simdfX_load( o1, output4+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output4+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output4+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c4 );  stbir__simdfX_madd( o1, o1, r1, c4 );  stbir__simdfX_madd( o2, o2, r2, c4 );   stbir__simdfX_madd( o3, o3, r3, c4 );\n              stbir__simdfX_store( output4, o0 );    stbir__simdfX_store( output4+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output4+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output4+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF5( stbir__simdfX_load( o0, output5 );     stbir__simdfX_load( o1, output5+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output5+(2*stbir__simdfX_float_count));    stbir__simdfX_load( o3, output5+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c5 );  stbir__simdfX_madd( o1, o1, r1, c5 );  stbir__simdfX_madd( o2, o2, r2, c5 );   stbir__simdfX_madd( o3, o3, r3, c5 );\n              stbir__simdfX_store( output5, o0 );    stbir__simdfX_store( output5+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output5+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output5+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF6( stbir__simdfX_load( o0, output6 );     stbir__simdfX_load( o1, output6+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output6+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output6+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c6 );  stbir__simdfX_madd( o1, o1, r1, c6 );  stbir__simdfX_madd( o2, o2, r2, c6 );   stbir__simdfX_madd( o3, o3, r3, c6 );\n              stbir__simdfX_store( output6, o0 );    stbir__simdfX_store( output6+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output6+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output6+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF7( stbir__simdfX_load( o0, output7 );     stbir__simdfX_load( o1, output7+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output7+(2*stbir__simdfX_float_count) );    stbir__simdfX_load( o3, output7+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c7 );  stbir__simdfX_madd( o1, o1, r1, c7 );  stbir__simdfX_madd( o2, o2, r2, c7 );   stbir__simdfX_madd( o3, o3, r3, c7 );\n              stbir__simdfX_store( output7, o0 );    stbir__simdfX_store( output7+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output7+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output7+(3*stbir__simdfX_float_count), o3 ); )\n      #else\n      stbIF0( stbir__simdfX_mult( o0, r0, c0 );      stbir__simdfX_mult( o1, r1, c0 );      stbir__simdfX_mult( o2, r2, c0 );       stbir__simdfX_mult( o3, r3, c0 );\n              stbir__simdfX_store( output0, o0 );    stbir__simdfX_store( output0+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output0+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output0+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF1( stbir__simdfX_mult( o0, r0, c1 );      stbir__simdfX_mult( o1, r1, c1 );      stbir__simdfX_mult( o2, r2, c1 );       stbir__simdfX_mult( o3, r3, c1 );\n              stbir__simdfX_store( output1, o0 );    stbir__simdfX_store( output1+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output1+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output1+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF2( stbir__simdfX_mult( o0, r0, c2 );      stbir__simdfX_mult( o1, r1, c2 );      stbir__simdfX_mult( o2, r2, c2 );       stbir__simdfX_mult( o3, r3, c2 );\n              stbir__simdfX_store( output2, o0 );    stbir__simdfX_store( output2+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output2+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output2+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF3( stbir__simdfX_mult( o0, r0, c3 );      stbir__simdfX_mult( o1, r1, c3 );      stbir__simdfX_mult( o2, r2, c3 );       stbir__simdfX_mult( o3, r3, c3 );\n              stbir__simdfX_store( output3, o0 );    stbir__simdfX_store( output3+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output3+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output3+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF4( stbir__simdfX_mult( o0, r0, c4 );      stbir__simdfX_mult( o1, r1, c4 );      stbir__simdfX_mult( o2, r2, c4 );       stbir__simdfX_mult( o3, r3, c4 );\n              stbir__simdfX_store( output4, o0 );    stbir__simdfX_store( output4+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output4+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output4+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF5( stbir__simdfX_mult( o0, r0, c5 );      stbir__simdfX_mult( o1, r1, c5 );      stbir__simdfX_mult( o2, r2, c5 );       stbir__simdfX_mult( o3, r3, c5 );\n              stbir__simdfX_store( output5, o0 );    stbir__simdfX_store( output5+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output5+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output5+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF6( stbir__simdfX_mult( o0, r0, c6 );      stbir__simdfX_mult( o1, r1, c6 );      stbir__simdfX_mult( o2, r2, c6 );       stbir__simdfX_mult( o3, r3, c6 );\n              stbir__simdfX_store( output6, o0 );    stbir__simdfX_store( output6+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output6+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output6+(3*stbir__simdfX_float_count), o3 ); )\n      stbIF7( stbir__simdfX_mult( o0, r0, c7 );      stbir__simdfX_mult( o1, r1, c7 );      stbir__simdfX_mult( o2, r2, c7 );       stbir__simdfX_mult( o3, r3, c7 );\n              stbir__simdfX_store( output7, o0 );    stbir__simdfX_store( output7+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output7+(2*stbir__simdfX_float_count), o2 );   stbir__simdfX_store( output7+(3*stbir__simdfX_float_count), o3 ); )\n      #endif\n\n      input += (4*stbir__simdfX_float_count);\n      stbIF0( output0 += (4*stbir__simdfX_float_count); ) stbIF1( output1 += (4*stbir__simdfX_float_count); ) stbIF2( output2 += (4*stbir__simdfX_float_count); ) stbIF3( output3 += (4*stbir__simdfX_float_count); ) stbIF4( output4 += (4*stbir__simdfX_float_count); ) stbIF5( output5 += (4*stbir__simdfX_float_count); ) stbIF6( output6 += (4*stbir__simdfX_float_count); ) stbIF7( output7 += (4*stbir__simdfX_float_count); )\n    }\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    while ( ( (char*)input_end - (char*) input ) >= 16 )\n    {\n      stbir__simdf o0, r0;\n      STBIR_SIMD_NO_UNROLL(output0);\n\n      stbir__simdf_load( r0, input );\n\n      #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n      stbIF0( stbir__simdf_load( o0, output0 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c0 ) );  stbir__simdf_store( output0, o0 ); )\n      stbIF1( stbir__simdf_load( o0, output1 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c1 ) );  stbir__simdf_store( output1, o0 ); )\n      stbIF2( stbir__simdf_load( o0, output2 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c2 ) );  stbir__simdf_store( output2, o0 ); )\n      stbIF3( stbir__simdf_load( o0, output3 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c3 ) );  stbir__simdf_store( output3, o0 ); )\n      stbIF4( stbir__simdf_load( o0, output4 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c4 ) );  stbir__simdf_store( output4, o0 ); )\n      stbIF5( stbir__simdf_load( o0, output5 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c5 ) );  stbir__simdf_store( output5, o0 ); )\n      stbIF6( stbir__simdf_load( o0, output6 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c6 ) );  stbir__simdf_store( output6, o0 ); )\n      stbIF7( stbir__simdf_load( o0, output7 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c7 ) );  stbir__simdf_store( output7, o0 ); )\n      #else\n      stbIF0( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c0 ) );   stbir__simdf_store( output0, o0 ); )\n      stbIF1( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c1 ) );   stbir__simdf_store( output1, o0 ); )\n      stbIF2( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c2 ) );   stbir__simdf_store( output2, o0 ); )\n      stbIF3( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c3 ) );   stbir__simdf_store( output3, o0 ); )\n      stbIF4( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c4 ) );   stbir__simdf_store( output4, o0 ); )\n      stbIF5( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c5 ) );   stbir__simdf_store( output5, o0 ); )\n      stbIF6( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c6 ) );   stbir__simdf_store( output6, o0 ); )\n      stbIF7( stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c7 ) );   stbir__simdf_store( output7, o0 ); )\n      #endif\n\n      input += 4;\n      stbIF0( output0 += 4; ) stbIF1( output1 += 4; ) stbIF2( output2 += 4; ) stbIF3( output3 += 4; ) stbIF4( output4 += 4; ) stbIF5( output5 += 4; ) stbIF6( output6 += 4; ) stbIF7( output7 += 4; )\n    }\n  }\n  #else\n  STBIR_NO_UNROLL_LOOP_START\n  while ( ( (char*)input_end - (char*) input ) >= 16 )\n  {\n    float r0, r1, r2, r3;\n    STBIR_NO_UNROLL(input);\n\n    r0 = input[0], r1 = input[1], r2 = input[2], r3 = input[3];\n\n    #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n    stbIF0( output0[0] += ( r0 * c0s ); output0[1] += ( r1 * c0s ); output0[2] += ( r2 * c0s ); output0[3] += ( r3 * c0s ); )\n    stbIF1( output1[0] += ( r0 * c1s ); output1[1] += ( r1 * c1s ); output1[2] += ( r2 * c1s ); output1[3] += ( r3 * c1s ); )\n    stbIF2( output2[0] += ( r0 * c2s ); output2[1] += ( r1 * c2s ); output2[2] += ( r2 * c2s ); output2[3] += ( r3 * c2s ); )\n    stbIF3( output3[0] += ( r0 * c3s ); output3[1] += ( r1 * c3s ); output3[2] += ( r2 * c3s ); output3[3] += ( r3 * c3s ); )\n    stbIF4( output4[0] += ( r0 * c4s ); output4[1] += ( r1 * c4s ); output4[2] += ( r2 * c4s ); output4[3] += ( r3 * c4s ); )\n    stbIF5( output5[0] += ( r0 * c5s ); output5[1] += ( r1 * c5s ); output5[2] += ( r2 * c5s ); output5[3] += ( r3 * c5s ); )\n    stbIF6( output6[0] += ( r0 * c6s ); output6[1] += ( r1 * c6s ); output6[2] += ( r2 * c6s ); output6[3] += ( r3 * c6s ); )\n    stbIF7( output7[0] += ( r0 * c7s ); output7[1] += ( r1 * c7s ); output7[2] += ( r2 * c7s ); output7[3] += ( r3 * c7s ); )\n    #else\n    stbIF0( output0[0]  = ( r0 * c0s ); output0[1]  = ( r1 * c0s ); output0[2]  = ( r2 * c0s ); output0[3]  = ( r3 * c0s ); )\n    stbIF1( output1[0]  = ( r0 * c1s ); output1[1]  = ( r1 * c1s ); output1[2]  = ( r2 * c1s ); output1[3]  = ( r3 * c1s ); )\n    stbIF2( output2[0]  = ( r0 * c2s ); output2[1]  = ( r1 * c2s ); output2[2]  = ( r2 * c2s ); output2[3]  = ( r3 * c2s ); )\n    stbIF3( output3[0]  = ( r0 * c3s ); output3[1]  = ( r1 * c3s ); output3[2]  = ( r2 * c3s ); output3[3]  = ( r3 * c3s ); )\n    stbIF4( output4[0]  = ( r0 * c4s ); output4[1]  = ( r1 * c4s ); output4[2]  = ( r2 * c4s ); output4[3]  = ( r3 * c4s ); )\n    stbIF5( output5[0]  = ( r0 * c5s ); output5[1]  = ( r1 * c5s ); output5[2]  = ( r2 * c5s ); output5[3]  = ( r3 * c5s ); )\n    stbIF6( output6[0]  = ( r0 * c6s ); output6[1]  = ( r1 * c6s ); output6[2]  = ( r2 * c6s ); output6[3]  = ( r3 * c6s ); )\n    stbIF7( output7[0]  = ( r0 * c7s ); output7[1]  = ( r1 * c7s ); output7[2]  = ( r2 * c7s ); output7[3]  = ( r3 * c7s ); )\n    #endif\n\n    input += 4;\n    stbIF0( output0 += 4; ) stbIF1( output1 += 4; ) stbIF2( output2 += 4; ) stbIF3( output3 += 4; ) stbIF4( output4 += 4; ) stbIF5( output5 += 4; ) stbIF6( output6 += 4; ) stbIF7( output7 += 4; )\n  }\n  #endif\n  STBIR_NO_UNROLL_LOOP_START\n  while ( input < input_end )\n  {\n    float r = input[0];\n    STBIR_NO_UNROLL(output0);\n\n    #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n    stbIF0( output0[0] += ( r * c0s ); )\n    stbIF1( output1[0] += ( r * c1s ); )\n    stbIF2( output2[0] += ( r * c2s ); )\n    stbIF3( output3[0] += ( r * c3s ); )\n    stbIF4( output4[0] += ( r * c4s ); )\n    stbIF5( output5[0] += ( r * c5s ); )\n    stbIF6( output6[0] += ( r * c6s ); )\n    stbIF7( output7[0] += ( r * c7s ); )\n    #else\n    stbIF0( output0[0]  = ( r * c0s ); )\n    stbIF1( output1[0]  = ( r * c1s ); )\n    stbIF2( output2[0]  = ( r * c2s ); )\n    stbIF3( output3[0]  = ( r * c3s ); )\n    stbIF4( output4[0]  = ( r * c4s ); )\n    stbIF5( output5[0]  = ( r * c5s ); )\n    stbIF6( output6[0]  = ( r * c6s ); )\n    stbIF7( output7[0]  = ( r * c7s ); )\n    #endif\n\n    ++input;\n    stbIF0( ++output0; ) stbIF1( ++output1; ) stbIF2( ++output2; ) stbIF3( ++output3; ) stbIF4( ++output4; ) stbIF5( ++output5; ) stbIF6( ++output6; ) stbIF7( ++output7; )\n  }\n}\n\nstatic void STBIR_chans( stbir__vertical_gather_with_,_coeffs)( float * outputp, float const * vertical_coefficients, float const ** inputs, float const * input0_end )\n{\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = outputp;\n\n  stbIF0( float const * input0 = inputs[0]; float c0s = vertical_coefficients[0]; )\n  stbIF1( float const * input1 = inputs[1]; float c1s = vertical_coefficients[1]; )\n  stbIF2( float const * input2 = inputs[2]; float c2s = vertical_coefficients[2]; )\n  stbIF3( float const * input3 = inputs[3]; float c3s = vertical_coefficients[3]; )\n  stbIF4( float const * input4 = inputs[4]; float c4s = vertical_coefficients[4]; )\n  stbIF5( float const * input5 = inputs[5]; float c5s = vertical_coefficients[5]; )\n  stbIF6( float const * input6 = inputs[6]; float c6s = vertical_coefficients[6]; )\n  stbIF7( float const * input7 = inputs[7]; float c7s = vertical_coefficients[7]; )\n\n#if ( STBIR__vertical_channels == 1 ) && !defined(STB_IMAGE_RESIZE_VERTICAL_CONTINUE)\n  // check single channel one weight\n  if ( ( c0s >= (1.0f-0.000001f) ) && ( c0s <= (1.0f+0.000001f) ) )\n  {\n    STBIR_MEMCPY( output, input0, (char*)input0_end - (char*)input0 );\n    return;\n  }\n#endif\n\n  #ifdef STBIR_SIMD\n  {\n    stbIF0(stbir__simdfX c0 = stbir__simdf_frepX( c0s ); )\n    stbIF1(stbir__simdfX c1 = stbir__simdf_frepX( c1s ); )\n    stbIF2(stbir__simdfX c2 = stbir__simdf_frepX( c2s ); )\n    stbIF3(stbir__simdfX c3 = stbir__simdf_frepX( c3s ); )\n    stbIF4(stbir__simdfX c4 = stbir__simdf_frepX( c4s ); )\n    stbIF5(stbir__simdfX c5 = stbir__simdf_frepX( c5s ); )\n    stbIF6(stbir__simdfX c6 = stbir__simdf_frepX( c6s ); )\n    stbIF7(stbir__simdfX c7 = stbir__simdf_frepX( c7s ); )\n\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    while ( ( (char*)input0_end - (char*) input0 ) >= (16*stbir__simdfX_float_count) )\n    {\n      stbir__simdfX o0, o1, o2, o3, r0, r1, r2, r3;\n      STBIR_SIMD_NO_UNROLL(output);\n\n      // prefetch four loop iterations ahead (doesn't affect much for small resizes, but helps with big ones)\n      stbIF0( stbir__prefetch( input0 + (16*stbir__simdfX_float_count) ); )\n      stbIF1( stbir__prefetch( input1 + (16*stbir__simdfX_float_count) ); )\n      stbIF2( stbir__prefetch( input2 + (16*stbir__simdfX_float_count) ); )\n      stbIF3( stbir__prefetch( input3 + (16*stbir__simdfX_float_count) ); )\n      stbIF4( stbir__prefetch( input4 + (16*stbir__simdfX_float_count) ); )\n      stbIF5( stbir__prefetch( input5 + (16*stbir__simdfX_float_count) ); )\n      stbIF6( stbir__prefetch( input6 + (16*stbir__simdfX_float_count) ); )\n      stbIF7( stbir__prefetch( input7 + (16*stbir__simdfX_float_count) ); )\n\n      #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n      stbIF0( stbir__simdfX_load( o0, output );      stbir__simdfX_load( o1, output+stbir__simdfX_float_count );   stbir__simdfX_load( o2, output+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( o3, output+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_load( r0, input0 );      stbir__simdfX_load( r1, input0+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input0+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input0+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c0 );  stbir__simdfX_madd( o1, o1, r1, c0 );                         stbir__simdfX_madd( o2, o2, r2, c0 );                             stbir__simdfX_madd( o3, o3, r3, c0 ); )\n      #else\n      stbIF0( stbir__simdfX_load( r0, input0 );      stbir__simdfX_load( r1, input0+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input0+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input0+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_mult( o0, r0, c0 );      stbir__simdfX_mult( o1, r1, c0 );                             stbir__simdfX_mult( o2, r2, c0 );                                 stbir__simdfX_mult( o3, r3, c0 );  )\n      #endif\n\n      stbIF1( stbir__simdfX_load( r0, input1 );      stbir__simdfX_load( r1, input1+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input1+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input1+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c1 );  stbir__simdfX_madd( o1, o1, r1, c1 );                         stbir__simdfX_madd( o2, o2, r2, c1 );                             stbir__simdfX_madd( o3, o3, r3, c1 ); )\n      stbIF2( stbir__simdfX_load( r0, input2 );      stbir__simdfX_load( r1, input2+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input2+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input2+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c2 );  stbir__simdfX_madd( o1, o1, r1, c2 );                         stbir__simdfX_madd( o2, o2, r2, c2 );                             stbir__simdfX_madd( o3, o3, r3, c2 ); )\n      stbIF3( stbir__simdfX_load( r0, input3 );      stbir__simdfX_load( r1, input3+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input3+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input3+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c3 );  stbir__simdfX_madd( o1, o1, r1, c3 );                         stbir__simdfX_madd( o2, o2, r2, c3 );                             stbir__simdfX_madd( o3, o3, r3, c3 ); )\n      stbIF4( stbir__simdfX_load( r0, input4 );      stbir__simdfX_load( r1, input4+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input4+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input4+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c4 );  stbir__simdfX_madd( o1, o1, r1, c4 );                         stbir__simdfX_madd( o2, o2, r2, c4 );                             stbir__simdfX_madd( o3, o3, r3, c4 ); )\n      stbIF5( stbir__simdfX_load( r0, input5 );      stbir__simdfX_load( r1, input5+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input5+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input5+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c5 );  stbir__simdfX_madd( o1, o1, r1, c5 );                         stbir__simdfX_madd( o2, o2, r2, c5 );                             stbir__simdfX_madd( o3, o3, r3, c5 ); )\n      stbIF6( stbir__simdfX_load( r0, input6 );      stbir__simdfX_load( r1, input6+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input6+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input6+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c6 );  stbir__simdfX_madd( o1, o1, r1, c6 );                         stbir__simdfX_madd( o2, o2, r2, c6 );                             stbir__simdfX_madd( o3, o3, r3, c6 ); )\n      stbIF7( stbir__simdfX_load( r0, input7 );      stbir__simdfX_load( r1, input7+stbir__simdfX_float_count );   stbir__simdfX_load( r2, input7+(2*stbir__simdfX_float_count) );   stbir__simdfX_load( r3, input7+(3*stbir__simdfX_float_count) );\n              stbir__simdfX_madd( o0, o0, r0, c7 );  stbir__simdfX_madd( o1, o1, r1, c7 );                         stbir__simdfX_madd( o2, o2, r2, c7 );                             stbir__simdfX_madd( o3, o3, r3, c7 ); )\n\n      stbir__simdfX_store( output, o0 );             stbir__simdfX_store( output+stbir__simdfX_float_count, o1 );  stbir__simdfX_store( output+(2*stbir__simdfX_float_count), o2 );  stbir__simdfX_store( output+(3*stbir__simdfX_float_count), o3 );\n      output += (4*stbir__simdfX_float_count);\n      stbIF0( input0 += (4*stbir__simdfX_float_count); ) stbIF1( input1 += (4*stbir__simdfX_float_count); ) stbIF2( input2 += (4*stbir__simdfX_float_count); ) stbIF3( input3 += (4*stbir__simdfX_float_count); ) stbIF4( input4 += (4*stbir__simdfX_float_count); ) stbIF5( input5 += (4*stbir__simdfX_float_count); ) stbIF6( input6 += (4*stbir__simdfX_float_count); ) stbIF7( input7 += (4*stbir__simdfX_float_count); )\n    }\n\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    while ( ( (char*)input0_end - (char*) input0 ) >= 16 )\n    {\n      stbir__simdf o0, r0;\n      STBIR_SIMD_NO_UNROLL(output);\n\n      #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n      stbIF0( stbir__simdf_load( o0, output );   stbir__simdf_load( r0, input0 ); stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c0 ) ); )\n      #else\n      stbIF0( stbir__simdf_load( r0, input0 );  stbir__simdf_mult( o0, r0, stbir__if_simdf8_cast_to_simdf4( c0 ) ); )\n      #endif\n      stbIF1( stbir__simdf_load( r0, input1 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c1 ) ); )\n      stbIF2( stbir__simdf_load( r0, input2 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c2 ) ); )\n      stbIF3( stbir__simdf_load( r0, input3 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c3 ) ); )\n      stbIF4( stbir__simdf_load( r0, input4 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c4 ) ); )\n      stbIF5( stbir__simdf_load( r0, input5 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c5 ) ); )\n      stbIF6( stbir__simdf_load( r0, input6 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c6 ) ); )\n      stbIF7( stbir__simdf_load( r0, input7 );  stbir__simdf_madd( o0, o0, r0, stbir__if_simdf8_cast_to_simdf4( c7 ) ); )\n\n      stbir__simdf_store( output, o0 );\n      output += 4;\n      stbIF0( input0 += 4; ) stbIF1( input1 += 4; ) stbIF2( input2 += 4; ) stbIF3( input3 += 4; ) stbIF4( input4 += 4; ) stbIF5( input5 += 4; ) stbIF6( input6 += 4; ) stbIF7( input7 += 4; )\n    }\n  }\n  #else\n  STBIR_NO_UNROLL_LOOP_START\n  while ( ( (char*)input0_end - (char*) input0 ) >= 16 )\n  {\n    float o0, o1, o2, o3;\n    STBIR_NO_UNROLL(output);\n    #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n    stbIF0( o0 = output[0] + input0[0] * c0s; o1 = output[1] + input0[1] * c0s; o2 = output[2] + input0[2] * c0s; o3 = output[3] + input0[3] * c0s; )\n    #else\n    stbIF0( o0  = input0[0] * c0s; o1  = input0[1] * c0s; o2  = input0[2] * c0s; o3  = input0[3] * c0s; )\n    #endif\n    stbIF1( o0 += input1[0] * c1s; o1 += input1[1] * c1s; o2 += input1[2] * c1s; o3 += input1[3] * c1s; )\n    stbIF2( o0 += input2[0] * c2s; o1 += input2[1] * c2s; o2 += input2[2] * c2s; o3 += input2[3] * c2s; )\n    stbIF3( o0 += input3[0] * c3s; o1 += input3[1] * c3s; o2 += input3[2] * c3s; o3 += input3[3] * c3s; )\n    stbIF4( o0 += input4[0] * c4s; o1 += input4[1] * c4s; o2 += input4[2] * c4s; o3 += input4[3] * c4s; )\n    stbIF5( o0 += input5[0] * c5s; o1 += input5[1] * c5s; o2 += input5[2] * c5s; o3 += input5[3] * c5s; )\n    stbIF6( o0 += input6[0] * c6s; o1 += input6[1] * c6s; o2 += input6[2] * c6s; o3 += input6[3] * c6s; )\n    stbIF7( o0 += input7[0] * c7s; o1 += input7[1] * c7s; o2 += input7[2] * c7s; o3 += input7[3] * c7s; )\n    output[0] = o0; output[1] = o1; output[2] = o2; output[3] = o3;\n    output += 4;\n    stbIF0( input0 += 4; ) stbIF1( input1 += 4; ) stbIF2( input2 += 4; ) stbIF3( input3 += 4; ) stbIF4( input4 += 4; ) stbIF5( input5 += 4; ) stbIF6( input6 += 4; ) stbIF7( input7 += 4; )\n  }\n  #endif\n  STBIR_NO_UNROLL_LOOP_START\n  while ( input0 < input0_end )\n  {\n    float o0;\n    STBIR_NO_UNROLL(output);\n    #ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n    stbIF0( o0 = output[0] + input0[0] * c0s; )\n    #else\n    stbIF0( o0  = input0[0] * c0s; )\n    #endif\n    stbIF1( o0 += input1[0] * c1s; )\n    stbIF2( o0 += input2[0] * c2s; )\n    stbIF3( o0 += input3[0] * c3s; )\n    stbIF4( o0 += input4[0] * c4s; )\n    stbIF5( o0 += input5[0] * c5s; )\n    stbIF6( o0 += input6[0] * c6s; )\n    stbIF7( o0 += input7[0] * c7s; )\n    output[0] = o0;\n    ++output;\n    stbIF0( ++input0; ) stbIF1( ++input1; ) stbIF2( ++input2; ) stbIF3( ++input3; ) stbIF4( ++input4; ) stbIF5( ++input5; ) stbIF6( ++input6; ) stbIF7( ++input7; )\n  }\n}\n\n#undef stbIF0\n#undef stbIF1\n#undef stbIF2\n#undef stbIF3\n#undef stbIF4\n#undef stbIF5\n#undef stbIF6\n#undef stbIF7\n#undef STB_IMAGE_RESIZE_DO_VERTICALS\n#undef STBIR__vertical_channels\n#undef STB_IMAGE_RESIZE_DO_HORIZONTALS\n#undef STBIR_strs_join24\n#undef STBIR_strs_join14\n#undef STBIR_chans\n#ifdef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#undef STB_IMAGE_RESIZE_VERTICAL_CONTINUE\n#endif\n\n#else // !STB_IMAGE_RESIZE_DO_VERTICALS\n\n#define STBIR_chans( start, end ) STBIR_strs_join1(start,STBIR__horizontal_channels,end)\n\n#ifndef stbir__2_coeff_only\n#define stbir__2_coeff_only()             \\\n    stbir__1_coeff_only();                \\\n    stbir__1_coeff_remnant(1);\n#endif\n\n#ifndef stbir__2_coeff_remnant\n#define stbir__2_coeff_remnant( ofs )     \\\n    stbir__1_coeff_remnant(ofs);          \\\n    stbir__1_coeff_remnant((ofs)+1);\n#endif\n\n#ifndef stbir__3_coeff_only\n#define stbir__3_coeff_only()             \\\n    stbir__2_coeff_only();                \\\n    stbir__1_coeff_remnant(2);\n#endif\n\n#ifndef stbir__3_coeff_remnant\n#define stbir__3_coeff_remnant( ofs )     \\\n    stbir__2_coeff_remnant(ofs);          \\\n    stbir__1_coeff_remnant((ofs)+2);\n#endif\n\n#ifndef stbir__3_coeff_setup\n#define stbir__3_coeff_setup()\n#endif\n\n#ifndef stbir__4_coeff_start\n#define stbir__4_coeff_start()            \\\n    stbir__2_coeff_only();                \\\n    stbir__2_coeff_remnant(2);\n#endif\n\n#ifndef stbir__4_coeff_continue_from_4\n#define stbir__4_coeff_continue_from_4( ofs )     \\\n    stbir__2_coeff_remnant(ofs);                  \\\n    stbir__2_coeff_remnant((ofs)+2);\n#endif\n\n#ifndef stbir__store_output_tiny\n#define stbir__store_output_tiny stbir__store_output\n#endif\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_1_coeff)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__1_coeff_only();\n    stbir__store_output_tiny();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_2_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__2_coeff_only();\n    stbir__store_output_tiny();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_3_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__3_coeff_only();\n    stbir__store_output_tiny();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_4_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_5_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__1_coeff_remnant(4);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_6_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__2_coeff_remnant(4);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_7_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  stbir__3_coeff_setup();\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n\n    stbir__4_coeff_start();\n    stbir__3_coeff_remnant(4);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_8_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__4_coeff_continue_from_4(4);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_9_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__4_coeff_continue_from_4(4);\n    stbir__1_coeff_remnant(8);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_10_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__4_coeff_continue_from_4(4);\n    stbir__2_coeff_remnant(8);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_11_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  stbir__3_coeff_setup();\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__4_coeff_continue_from_4(4);\n    stbir__3_coeff_remnant(8);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_12_coeffs)( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    float const * hc = horizontal_coefficients;\n    stbir__4_coeff_start();\n    stbir__4_coeff_continue_from_4(4);\n    stbir__4_coeff_continue_from_4(8);\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_n_coeffs_mod0 )( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    int n = ( ( horizontal_contributors->n1 - horizontal_contributors->n0 + 1 ) - 4 + 3 ) >> 2;\n    float const * hc = horizontal_coefficients;\n\n    stbir__4_coeff_start();\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    do {\n      hc += 4;\n      decode += STBIR__horizontal_channels * 4;\n      stbir__4_coeff_continue_from_4( 0 );\n      --n;\n    } while ( n > 0 );\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_n_coeffs_mod1 )( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    int n = ( ( horizontal_contributors->n1 - horizontal_contributors->n0 + 1 ) - 5 + 3 ) >> 2;\n    float const * hc = horizontal_coefficients;\n\n    stbir__4_coeff_start();\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    do {\n      hc += 4;\n      decode += STBIR__horizontal_channels * 4;\n      stbir__4_coeff_continue_from_4( 0 );\n      --n;\n    } while ( n > 0 );\n    stbir__1_coeff_remnant( 4 );\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_n_coeffs_mod2 )( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    int n = ( ( horizontal_contributors->n1 - horizontal_contributors->n0 + 1 ) - 6 + 3 ) >> 2;\n    float const * hc = horizontal_coefficients;\n\n    stbir__4_coeff_start();\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    do {\n      hc += 4;\n      decode += STBIR__horizontal_channels * 4;\n      stbir__4_coeff_continue_from_4( 0 );\n      --n;\n    } while ( n > 0 );\n    stbir__2_coeff_remnant( 4 );\n\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic void STBIR_chans( stbir__horizontal_gather_,_channels_with_n_coeffs_mod3 )( float * output_buffer, unsigned int output_sub_size, float const * decode_buffer, stbir__contributors const * horizontal_contributors, float const * horizontal_coefficients, int coefficient_width )\n{\n  float const * output_end = output_buffer + output_sub_size * STBIR__horizontal_channels;\n  float STBIR_SIMD_STREAMOUT_PTR( * ) output = output_buffer;\n  stbir__3_coeff_setup();\n  STBIR_SIMD_NO_UNROLL_LOOP_START\n  do {\n    float const * decode = decode_buffer + horizontal_contributors->n0 * STBIR__horizontal_channels;\n    int n = ( ( horizontal_contributors->n1 - horizontal_contributors->n0 + 1 ) - 7 + 3 ) >> 2;\n    float const * hc = horizontal_coefficients;\n\n    stbir__4_coeff_start();\n    STBIR_SIMD_NO_UNROLL_LOOP_START\n    do {\n      hc += 4;\n      decode += STBIR__horizontal_channels * 4;\n      stbir__4_coeff_continue_from_4( 0 );\n      --n;\n    } while ( n > 0 );\n    stbir__3_coeff_remnant( 4 );\n\n    stbir__store_output();\n  } while ( output < output_end );\n}\n\nstatic stbir__horizontal_gather_channels_func * STBIR_chans(stbir__horizontal_gather_,_channels_with_n_coeffs_funcs)[4]=\n{\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_n_coeffs_mod0),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_n_coeffs_mod1),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_n_coeffs_mod2),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_n_coeffs_mod3),\n};\n\nstatic stbir__horizontal_gather_channels_func * STBIR_chans(stbir__horizontal_gather_,_channels_funcs)[12]=\n{\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_1_coeff),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_2_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_3_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_4_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_5_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_6_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_7_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_8_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_9_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_10_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_11_coeffs),\n  STBIR_chans(stbir__horizontal_gather_,_channels_with_12_coeffs),\n};\n\n#undef STBIR__horizontal_channels\n#undef STB_IMAGE_RESIZE_DO_HORIZONTALS\n#undef stbir__1_coeff_only\n#undef stbir__1_coeff_remnant\n#undef stbir__2_coeff_only\n#undef stbir__2_coeff_remnant\n#undef stbir__3_coeff_only\n#undef stbir__3_coeff_remnant\n#undef stbir__3_coeff_setup\n#undef stbir__4_coeff_start\n#undef stbir__4_coeff_continue_from_4\n#undef stbir__store_output\n#undef stbir__store_output_tiny\n#undef STBIR_chans\n\n#endif  // HORIZONALS\n\n#undef STBIR_strs_join2\n#undef STBIR_strs_join1\n\n#endif // STB_IMAGE_RESIZE_DO_HORIZONTALS/VERTICALS/CODERS\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_image_resize_test/dotimings.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef _MSC_VER\n\n#define stop() __debugbreak()\n#include <windows.h>\n#define int64 __int64\n#pragma warning(disable:4127)\n\n#define get_milliseconds GetTickCount\n\n#else\n\n#define stop() __builtin_trap()\n#define int64 long long\n\ntypedef unsigned int U32;\ntypedef unsigned long long U64;\n\n#include <time.h>\nstatic int get_milliseconds()\n{\n  struct timespec ts;\n  clock_gettime( CLOCK_MONOTONIC, &ts );\n  return (U32) ( ( ((U64)(U32)ts.tv_sec) * 1000LL ) + (U64)(((U32)ts.tv_nsec+500000)/1000000) );\n}\n\n#endif\n\n#if defined(TIME_SIMD)\n  // default for most platforms\n#elif defined(TIME_SCALAR)\n  #define STBIR_NO_SIMD\n#else\n  #error You must define TIME_SIMD or TIME_SCALAR when compiling this file.\n#endif\n\n#define STBIR_PROFILE\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#define STBIR__V_FIRST_INFO_BUFFER v_info\n#include \"stb_image_resize2.h\"  // new one!\n\n#if defined(TIME_SIMD)  && !defined(STBIR_SIMD)\n#error Timing SIMD, but scalar was ON!\n#endif\n\n#if defined(TIME_SCALAR)  && defined(STBIR_SIMD)\n#error Timing scalar, but SIMD was ON!\n#endif\n\n#define HEADER 32\n\n\nstatic int file_write( const char *filename, void * buffer, size_t size ) \n{\n  FILE * f = fopen( filename, \"wb\" );\n  if ( f == 0 ) return 0;\n  if ( fwrite( buffer, 1, size, f) != size ) return 0;\n  fclose(f);\n  return 1;\n}\n\nint64 nresize( void * o, int ox, int oy, int op, void * i, int ix, int iy, int ip, int buf, int type, int edg, int flt )\n{\n  STBIR_RESIZE resize;\n  int t;\n  int64 b;\n\n  stbir_resize_init( &resize, i, ix, iy, ip, o, ox, oy, op, buf, type );\n  stbir_set_edgemodes( &resize, edg, edg );\n  stbir_set_filters( &resize, flt, flt );\n  \n  stbir_build_samplers_with_splits( &resize, 1 );\n\n  b = 0x7fffffffffffffffULL;\n  for( t = 0 ; t < 16 ; t++ )\n  {\n    STBIR_PROFILE_INFO profile;\n    int64 v;\n    if(!stbir_resize_extended( &resize ) )\n      stop();\n    stbir_resize_extended_profile_info( &profile, &resize );\n    v = profile.clocks[1]+profile.clocks[2];\n    if ( v < b )\n    {\n      b = v;\n      t = 0;\n    }\n  }\n\n  stbir_free_samplers( &resize );\n\n  return b;\n}\n\n\n#define INSIZES 5\n#define TYPESCOUNT 5\n#define NUM 64\n\nstatic const int sizes[INSIZES]={63,126,252,520,772};\nstatic const int types[TYPESCOUNT]={STBIR_1CHANNEL,STBIR_2CHANNEL,STBIR_RGB,STBIR_4CHANNEL,STBIR_RGBA};\nstatic const int effective[TYPESCOUNT]={1,2,3,4,7};\n\nint main( int argc, char ** argv )\n{\n  unsigned char * input;\n  unsigned char * output;\n  int dimensionx, dimensiony;\n  int scalex, scaley;\n  int totalms;\n  int timing_count;\n  int ir;\n  int * file;\n  int * ts;\n  int64 totalcycles;\n\n  if ( argc != 6 )\n  {\n    printf(\"command: dotimings x_samps y_samps x_scale y_scale outfilename\\n\");\n    exit(1);\n  }\n\n  input = malloc( 4*1200*1200 );\n  memset( input, 0x80, 4*1200*1200 );\n  output = malloc( 4*10000*10000ULL );\n  \n  dimensionx = atoi( argv[1] );\n  dimensiony = atoi( argv[2] );\n  scalex = atoi( argv[3] );\n  scaley = atoi( argv[4] );\n\n  timing_count = dimensionx * dimensiony * INSIZES * TYPESCOUNT;\n\n  file = malloc( sizeof(int) * ( 2 * timing_count + HEADER ) );\n  ts = file + HEADER;\n\n  totalms = get_milliseconds();  \n  totalcycles = STBIR_PROFILE_FUNC();\n  for( ir = 0 ; ir < INSIZES ; ir++ )\n  {\n    int ix, iy, ty;\n    ix = iy = sizes[ir];\n\n    for( ty = 0 ; ty < TYPESCOUNT ; ty++ )\n    {\n      int h, hh;\n\n      h = 1;\n      for( hh = 0 ; hh < dimensiony; hh++ )\n      {\n        int ww, w = 1;\n        for( ww = 0 ; ww < dimensionx; ww++ )\n        {\n          int64 VF, HF;\n          int good;\n        \n          v_info.control_v_first = 2; // vertical first\n          VF = nresize( output, w, h, (w*4*1)&~3, input, ix, iy, ix*4*1, types[ty], STBIR_TYPE_UINT8, STBIR_EDGE_CLAMP, STBIR_FILTER_MITCHELL );\n          v_info.control_v_first = 1; // horizonal first\n          HF = nresize( output, w, h, (w*4*1)&~3, input, ix, iy, ix*4*1, types[ty], STBIR_TYPE_UINT8, STBIR_EDGE_CLAMP, STBIR_FILTER_MITCHELL );\n\n          good = ( ((HF<=VF) && (!v_info.v_first)) || ((VF<=HF) && (v_info.v_first)));\n\n//          printf(\"\\r%d,%d, %d,%d, %d, %I64d,%I64d, // Good: %c(%c-%d)  CompEst: %.1f %.1f\\n\", ix, iy, w, h, ty, VF, HF, good?'y':'n', v_info.v_first?'v':'h', v_info.v_resize_classification, v_info.v_cost,v_info.h_cost );\n          ts[0] = (int)VF;\n          ts[1] = (int)HF;\n\n          ts += 2;\n\n          w += scalex;\n        }\n        printf(\".\");\n        h += scaley;  \n      }\n    }\n  }\n  totalms = get_milliseconds() - totalms;  \n  totalcycles = STBIR_PROFILE_FUNC() - totalcycles;\n\n  printf(\"\\n\");\n\n  file[0] = 'VFT1';\n\n  #if defined(_x86_64) || defined( __x86_64__ ) || defined( _M_X64 ) || defined(__x86_64) || defined(__SSE2__) || defined( _M_IX86_FP ) || defined(__i386) || defined( __i386__ ) || defined( _M_IX86 ) || defined( _X86_ )\n  file[1] = 1;  // x64\n  #elif defined( _M_AMD64 ) || defined( __aarch64__ ) || defined( __arm64__ ) || defined(__ARM_NEON__) || defined(__ARM_NEON) || defined(__arm__) || defined( _M_ARM )\n  file[1] = 2;  // arm\n  #else\n  file[1] = 99;  // who knows???\n  #endif\n  \n  #ifdef STBIR_SIMD8\n    file[2] = 2;  // simd-8\n  #elif defined( STBIR_SIMD )\n    file[2] = 1;  // simd-4\n  #else\n    file[2] = 0;  // nosimd\n  #endif\n  \n  file[3] = dimensionx; // dimx\n  file[4] = dimensiony; // dimy\n  file[5] = TYPESCOUNT;  // channel types\n  file[ 6] = types[0]; file[7] = types[1]; file[8] = types[2]; file[9] = types[3]; file[10] = types[4];  // buffer_type \n  file[11] = effective[0]; file[12] = effective[1]; file[13] = effective[2]; file[14] = effective[3]; file[15] = effective[4];  // effective channels \n  file[16] = INSIZES;  // resizes\n  file[17] = sizes[0]; file[18] = sizes[0]; // input sizes (w x h)\n  file[19] = sizes[1]; file[20] = sizes[1];\n  file[21] = sizes[2]; file[22] = sizes[2];\n  file[23] = sizes[3]; file[24] = sizes[3];\n  file[25] = sizes[4]; file[26] = sizes[4];\n  file[27] = scalex;   file[28] = scaley;  // scale the dimx and dimy amount ( for(i=0;i<dimx) outputx = 1 + i*scalex; )\n  file[29] = totalms;\n  ((int64*)(file+30))[0] = totalcycles;\n\n  if ( !file_write( argv[5], file, sizeof(int) * ( 2 * timing_count + HEADER ) ) )\n    printf( \"Error writing file: %s\\n\", argv[5] );\n  else\n    printf( \"Successfully wrote timing file: %s\\n\", argv[5] );\n\n  return 0;\n}\n"
  },
  {
    "path": "stb_image_resize_test/old_image_resize.h",
    "content": "/* stb_image_resize - v0.96 - public domain image resizing\n   by Jorge L Rodriguez (@VinoBS) - 2014\n   http://github.com/nothings/stb\n\n   Written with emphasis on usability, portability, and efficiency. (No\n   SIMD or threads, so it be easily outperformed by libs that use those.)\n   Only scaling and translation is supported, no rotations or shears.\n   Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation.\n\n   COMPILING & LINKING\n      In one C/C++ file that #includes this file, do this:\n         #define STB_IMAGE_RESIZE_IMPLEMENTATION\n      before the #include. That will create the implementation in that file.\n\n   QUICKSTART\n      stbir_resize_uint8(      input_pixels , in_w , in_h , 0,\n                               output_pixels, out_w, out_h, 0, num_channels)\n      stbir_resize_float(...)\n      stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0,\n                               output_pixels, out_w, out_h, 0,\n                               num_channels , alpha_chan  , 0)\n      stbir_resize_uint8_srgb_edgemode(\n                               input_pixels , in_w , in_h , 0, \n                               output_pixels, out_w, out_h, 0, \n                               num_channels , alpha_chan  , 0, STBIR_EDGE_CLAMP)\n                                                            // WRAP/REFLECT/ZERO\n\n   FULL API\n      See the \"header file\" section of the source for API documentation.\n\n   ADDITIONAL DOCUMENTATION\n\n      SRGB & FLOATING POINT REPRESENTATION\n         The sRGB functions presume IEEE floating point. If you do not have\n         IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use\n         a slower implementation.\n\n      MEMORY ALLOCATION\n         The resize functions here perform a single memory allocation using\n         malloc. To control the memory allocation, before the #include that\n         triggers the implementation, do:\n\n            #define STBIR_MALLOC(size,context) ...\n            #define STBIR_FREE(ptr,context)   ...\n\n         Each resize function makes exactly one call to malloc/free, so to use\n         temp memory, store the temp memory in the context and return that.\n\n      ASSERT\n         Define STBIR_ASSERT(boolval) to override assert() and not use assert.h\n\n      OPTIMIZATION\n         Define STBIR_SATURATE_INT to compute clamp values in-range using\n         integer operations instead of float operations. This may be faster\n         on some platforms.\n\n      DEFAULT FILTERS\n         For functions which don't provide explicit control over what filters\n         to use, you can change the compile-time defaults with\n\n            #define STBIR_DEFAULT_FILTER_UPSAMPLE     STBIR_FILTER_something\n            #define STBIR_DEFAULT_FILTER_DOWNSAMPLE   STBIR_FILTER_something\n\n         See stbir_filter in the header-file section for the list of filters.\n\n      NEW FILTERS\n         A number of 1D filter kernels are used. For a list of\n         supported filters see the stbir_filter enum. To add a new filter,\n         write a filter function and add it to stbir__filter_info_table.\n\n      PROGRESS\n         For interactive use with slow resize operations, you can install\n         a progress-report callback:\n\n            #define STBIR_PROGRESS_REPORT(val)   some_func(val)\n\n         The parameter val is a float which goes from 0 to 1 as progress is made.\n\n         For example:\n\n            static void my_progress_report(float progress);\n            #define STBIR_PROGRESS_REPORT(val) my_progress_report(val)\n\n            #define STB_IMAGE_RESIZE_IMPLEMENTATION\n            #include \"stb_image_resize.h\"\n\n            static void my_progress_report(float progress)\n            {\n               printf(\"Progress: %f%%\\n\", progress*100);\n            }\n\n      MAX CHANNELS\n         If your image has more than 64 channels, define STBIR_MAX_CHANNELS\n         to the max you'll have.\n\n      ALPHA CHANNEL\n         Most of the resizing functions provide the ability to control how\n         the alpha channel of an image is processed. The important things\n         to know about this:\n\n         1. The best mathematically-behaved version of alpha to use is\n         called \"premultiplied alpha\", in which the other color channels\n         have had the alpha value multiplied in. If you use premultiplied\n         alpha, linear filtering (such as image resampling done by this\n         library, or performed in texture units on GPUs) does the \"right\n         thing\". While premultiplied alpha is standard in the movie CGI\n         industry, it is still uncommon in the videogame/real-time world.\n\n         If you linearly filter non-premultiplied alpha, strange effects\n         occur. (For example, the 50/50 average of 99% transparent bright green\n         and 1% transparent black produces 50% transparent dark green when\n         non-premultiplied, whereas premultiplied it produces 50%\n         transparent near-black. The former introduces green energy\n         that doesn't exist in the source image.)\n\n         2. Artists should not edit premultiplied-alpha images; artists\n         want non-premultiplied alpha images. Thus, art tools generally output\n         non-premultiplied alpha images.\n\n         3. You will get best results in most cases by converting images\n         to premultiplied alpha before processing them mathematically.\n\n         4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the\n         resizer does not do anything special for the alpha channel;\n         it is resampled identically to other channels. This produces\n         the correct results for premultiplied-alpha images, but produces\n         less-than-ideal results for non-premultiplied-alpha images.\n\n         5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED,\n         then the resizer weights the contribution of input pixels\n         based on their alpha values, or, equivalently, it multiplies\n         the alpha value into the color channels, resamples, then divides\n         by the resultant alpha value. Input pixels which have alpha=0 do\n         not contribute at all to output pixels unless _all_ of the input\n         pixels affecting that output pixel have alpha=0, in which case\n         the result for that pixel is the same as it would be without\n         STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for\n         input images in integer formats. For input images in float format,\n         input pixels with alpha=0 have no effect, and output pixels\n         which have alpha=0 will be 0 in all channels. (For float images,\n         you can manually achieve the same result by adding a tiny epsilon\n         value to the alpha channel of every image, and then subtracting\n         or clamping it at the end.)\n\n         6. You can suppress the behavior described in #5 and make\n         all-0-alpha pixels have 0 in all channels by #defining\n         STBIR_NO_ALPHA_EPSILON.\n\n         7. You can separately control whether the alpha channel is\n         interpreted as linear or affected by the colorspace. By default\n         it is linear; you almost never want to apply the colorspace.\n         (For example, graphics hardware does not apply sRGB conversion\n         to the alpha channel.)\n\n   CONTRIBUTORS\n      Jorge L Rodriguez: Implementation\n      Sean Barrett: API design, optimizations\n      Aras Pranckevicius: bugfix\n      Nathan Reed: warning fixes\n\n   REVISIONS\n      0.96 (2019-03-04) fixed warnings\n      0.95 (2017-07-23) fixed warnings\n      0.94 (2017-03-18) fixed warnings\n      0.93 (2017-03-03) fixed bug with certain combinations of heights\n      0.92 (2017-01-02) fix integer overflow on large (>2GB) images\n      0.91 (2016-04-02) fix warnings; fix handling of subpixel regions\n      0.90 (2014-09-17) first released version\n\n   LICENSE\n     See end of file for license information.\n\n   TODO\n      Don't decode all of the image data when only processing a partial tile\n      Don't use full-width decode buffers when only processing a partial tile\n      When processing wide images, break processing into tiles so data fits in L1 cache\n      Installable filters?\n      Resize that respects alpha test coverage\n         (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage:\n         https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp )\n*/\n\n#ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H\n#define STBIR_INCLUDE_STB_IMAGE_RESIZE_H\n\n#ifdef _MSC_VER\ntypedef unsigned char  stbir_uint8;\ntypedef unsigned short stbir_uint16;\ntypedef unsigned int   stbir_uint32;\ntypedef unsigned __int64   stbir_uint64;\n#else\n#include <stdint.h>\ntypedef uint8_t  stbir_uint8;\ntypedef uint16_t stbir_uint16;\ntypedef uint32_t stbir_uint32;\ntypedef uint64_t stbir_uint64;\n#endif\n\n#ifndef STBIRDEF\n#ifdef STB_IMAGE_RESIZE_STATIC\n#define STBIRDEF static\n#else\n#ifdef __cplusplus\n#define STBIRDEF extern \"C\"\n#else\n#define STBIRDEF extern\n#endif\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Easy-to-use API:\n//\n//     * \"input pixels\" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4)\n//     * input_w is input image width (x-axis), input_h is input image height (y-axis)\n//     * stride is the offset between successive rows of image data in memory, in bytes. you can\n//       specify 0 to mean packed continuously in memory\n//     * alpha channel is treated identically to other channels.\n//     * colorspace is linear or sRGB as specified by function name\n//     * returned result is 1 for success or 0 in case of an error.\n//       #define STBIR_ASSERT() to trigger an assert on parameter validation errors.\n//     * Memory required grows approximately linearly with input and output size, but with\n//       discontinuities at input_w == output_w and input_h == output_h.\n//     * These functions use a \"default\" resampling filter defined at compile time. To change the filter,\n//       you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE\n//       and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API.\n\nSTBIRDEF int stbir_resize_uint8(     const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels);\n\nSTBIRDEF int stbir_resize_float(     const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels);\n\n\n// The following functions interpret image data as gamma-corrected sRGB. \n// Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel,\n// or otherwise provide the index of the alpha channel. Flags value\n// of 0 will probably do the right thing if you're not sure what\n// the flags mean.\n\n#define STBIR_ALPHA_CHANNEL_NONE       -1\n\n// Set this flag if your texture has premultiplied alpha. Otherwise, stbir will\n// use alpha-weighted resampling (effectively premultiplying, resampling,\n// then unpremultiplying).\n#define STBIR_FLAG_ALPHA_PREMULTIPLIED    (1 << 0)\n// The specified alpha channel should be handled as gamma-corrected value even\n// when doing sRGB operations.\n#define STBIR_FLAG_ALPHA_USES_COLORSPACE  (1 << 1)\n\n#define STBIR_FLAG_ALPHA_OUT_PREMULTIPLIED (1 << 2)\n\nSTBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels, int alpha_channel, int flags);\n\n\ntypedef enum\n{\n    STBIR_EDGE_CLAMP   = 1,\n    STBIR_EDGE_REFLECT = 2,\n    STBIR_EDGE_WRAP    = 3,\n    STBIR_EDGE_ZERO    = 4,\n} stbir_edge;\n\n// This function adds the ability to specify how requests to sample off the edge of the image are handled.\nSTBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                                    unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                              int num_channels, int alpha_channel, int flags,\n                                              stbir_edge edge_wrap_mode);\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Medium-complexity API\n//\n// This extends the easy-to-use API as follows:\n//\n//     * Alpha-channel can be processed separately\n//       * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE\n//         * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT)\n//         * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)\n//     * Filter can be selected explicitly\n//     * uint16 image type\n//     * sRGB colorspace available for all types\n//     * context parameter for passing to STBIR_MALLOC\n\ntypedef enum\n{\n    STBIR_FILTER_DEFAULT      = 0,  // use same filter type that easy-to-use API chooses\n    STBIR_FILTER_BOX          = 1,  // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios\n    STBIR_FILTER_TRIANGLE     = 2,  // On upsampling, produces same results as bilinear texture filtering\n    STBIR_FILTER_CUBICBSPLINE = 3,  // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque\n    STBIR_FILTER_CATMULLROM   = 4,  // An interpolating cubic spline\n    STBIR_FILTER_MITCHELL     = 5,  // Mitchell-Netrevalli filter with B=1/3, C=1/3\n} stbir_filter;\n\ntypedef enum\n{\n    STBIR_COLORSPACE_LINEAR,\n    STBIR_COLORSPACE_SRGB,\n\n    STBIR_MAX_COLORSPACES,\n} stbir_colorspace;\n\n// The following functions are all identical except for the type of the image data\n\nSTBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                               unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, \n                                         void *alloc_context);\n\nSTBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels  , int input_w , int input_h , int input_stride_in_bytes,\n                                               stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, \n                                         void *alloc_context);\n\nSTBIRDEF int stbir_resize_float_generic( const float *input_pixels         , int input_w , int input_h , int input_stride_in_bytes,\n                                               float *output_pixels        , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, \n                                         void *alloc_context);\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Full-complexity API\n//\n// This extends the medium API as follows:\n//\n//       * uint32 image type\n//     * not typesafe\n//     * separate filter types for each axis\n//     * separate edge modes for each axis\n//     * can specify scale explicitly for subpixel correctness\n//     * can specify image source tile using texture coordinates\n\ntypedef enum\n{\n    STBIR_TYPE_UINT8 ,\n    STBIR_TYPE_UINT16,\n    STBIR_TYPE_FLOAT ,\n    STBIR_TYPE_UINT32,\n\n    STBIR_MAX_TYPES\n} stbir_datatype;\n\nSTBIRDEF int stbir_resize(         const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, \n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context);\n\nSTBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, \n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float x_scale, float y_scale,\n                                   float x_offset, float y_offset);\n\nSTBIRDEF int stbir_resize_region(  const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, \n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float s0, float t0, float s1, float t1);\n// (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use.\n\n//\n//\n////   end header file   /////////////////////////////////////////////////////\n#endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H\n\n\n\n\n\n#ifdef STB_IMAGE_RESIZE_IMPLEMENTATION\n\n#ifndef STBIR_ASSERT\n#include <assert.h>\n#define STBIR_ASSERT(x) assert(x)\n#endif\n\n// For memset\n#include <string.h>\n\n#include <math.h>\n\n#ifndef STBIR_MALLOC\n#include <stdlib.h>\n// use comma operator to evaluate c, to avoid \"unused parameter\" warnings\n#define STBIR_MALLOC(size,c) ((void)(c), malloc(size))\n#define STBIR_FREE(ptr,c)    ((void)(c), free(ptr))\n#endif\n\n#ifndef _MSC_VER\n#ifdef __cplusplus\n#define stbir__inline inline\n#else\n#define stbir__inline\n#endif\n#else\n#define stbir__inline __forceinline\n#endif\n\n#ifdef STBIR_PROFILE\n\nunion\n{\n  struct { stbir_uint64 total, setup, filters, looping, vertical, horizontal, decode, encode, alpha, unalpha; } named;\n  stbir_uint64 array[10];\n} oldprofile;\nstbir_uint64 * current_zone_excluded_ptr;\n\n#if defined(_x86_64) || defined( __x86_64__ ) || defined( _M_X64 ) || defined(__x86_64) || defined(__SSE2__) || defined(STBIR_SSE) || defined( _M_IX86_FP ) || defined(__i386) || defined( __i386__ ) || defined( _M_IX86 ) || defined( _X86_ )\n\n#ifdef _MSC_VER\n\n  STBIRDEF stbir_uint64 __rdtsc();\n  #define STBIR_PROFILE_FUNC() __rdtsc()\n\n#else // non msvc\n\n  static stbir__inline stbir_uint64 STBIR_PROFILE_FUNC() \n  {\n    stbir_uint32 lo, hi;\n    asm volatile (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi) );\n    return ( ( (stbir_uint64) hi ) << 32 ) | ( (stbir_uint64) lo );\n  }\n\n#endif  // msvc\n\n#elif defined( _M_AMD64 ) || defined( __aarch64__ ) || defined( __arm64__ ) || defined(__ARM_NEON__) || defined(__ARM_NEON)\n\n#ifdef _MSC_VER\n\n  #error Not sure what the intrinsic for cntvct_el0 is on MSVC\n\n#else // no msvc\n\n  static stbir__inline stbir_uint64 STBIR_PROFILE_FUNC()\n  {\n    stbir_uint64 tsc;\n    asm volatile(\"mrs %0, cntvct_el0\" : \"=r\" (tsc));\n    return tsc;\n  }\n\n#endif\n\n#elif // x64, arm\n\n#error Unknown platform for profiling.\n\n#endif  //x64 and   \n\n#define STBIR_PROFILE_START() { stbir_uint64 thiszonetime = STBIR_PROFILE_FUNC(); stbir_uint64 * save_parent_excluded_ptr = current_zone_excluded_ptr; stbir_uint64 current_zone_excluded = 0; current_zone_excluded_ptr = &current_zone_excluded; \n#define STBIR_PROFILE_END( wh ) thiszonetime = STBIR_PROFILE_FUNC() - thiszonetime; oldprofile.named.wh += thiszonetime - current_zone_excluded; *save_parent_excluded_ptr += thiszonetime; current_zone_excluded_ptr = save_parent_excluded_ptr; }\n#define STBIR_PROFILE_FIRST_START() { int i; current_zone_excluded_ptr = &oldprofile.named.total; for(i=0;i<STBIR__ARRAY_SIZE(oldprofile.array);i++) oldprofile.array[i]=0; } STBIR_PROFILE_START();\n\n#else\n\n#define STBIR_PROFILE_START()\n#define STBIR_PROFILE_END( wh )\n#define STBIR_PROFILE_FIRST_START()\n\n#endif\n\n// should produce compiler error if size is wrong\ntypedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1];\n\n#ifdef _MSC_VER\n#define STBIR__NOTUSED(v)  (void)(v)\n#else\n#define STBIR__NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0]))\n\n#ifndef STBIR_DEFAULT_FILTER_UPSAMPLE\n#define STBIR_DEFAULT_FILTER_UPSAMPLE    STBIR_FILTER_CATMULLROM\n#endif\n\n#ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE\n#define STBIR_DEFAULT_FILTER_DOWNSAMPLE  STBIR_FILTER_MITCHELL\n#endif\n\n#ifndef STBIR_PROGRESS_REPORT\n#define STBIR_PROGRESS_REPORT(float_0_to_1)\n#endif\n\n#ifndef STBIR_MAX_CHANNELS\n#define STBIR_MAX_CHANNELS 64\n#endif\n\n#if STBIR_MAX_CHANNELS > 65536\n#error \"Too many channels; STBIR_MAX_CHANNELS must be no more than 65536.\"\n// because we store the indices in 16-bit variables\n#endif\n\n// This value is added to alpha just before premultiplication to avoid\n// zeroing out color values. It is equivalent to 2^-80. If you don't want\n// that behavior (it may interfere if you have floating point images with\n// very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to\n// disable it.\n#ifndef STBIR_ALPHA_EPSILON\n#define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20))\n#endif\n\n\n\n#ifdef _MSC_VER\n#define STBIR__UNUSED_PARAM(v)  (void)(v)\n#else\n#define STBIR__UNUSED_PARAM(v)  (void)sizeof(v)\n#endif\n\n// must match stbir_datatype\nstatic unsigned char stbir__type_size[] = {\n    1, // STBIR_TYPE_UINT8\n    2, // STBIR_TYPE_UINT16\n    4, // STBIR_TYPE_UINT32\n    4, // STBIR_TYPE_FLOAT\n};\n\n// Kernel function centered at 0\ntypedef float (stbir__kernel_fn)(float x, float scale);\ntypedef float (stbir__support_fn)(float scale);\n\ntypedef struct\n{\n    stbir__kernel_fn* kernel;\n    stbir__support_fn* support;\n} stbir__filter_info;\n\n// When upsampling, the contributors are which source pixels contribute.\n// When downsampling, the contributors are which destination pixels are contributed to.\ntypedef struct\n{\n    int n0; // First contributing pixel\n    int n1; // Last contributing pixel\n} stbir__contributors;\n\ntypedef struct\n{\n    const void* input_data;\n    int input_w;\n    int input_h;\n    int input_stride_bytes;\n\n    void* output_data;\n    int output_w;\n    int output_h;\n    int output_stride_bytes;\n\n    float s0, t0, s1, t1;\n\n    float horizontal_shift; // Units: output pixels\n    float vertical_shift;   // Units: output pixels\n    float horizontal_scale;\n    float vertical_scale;\n\n    int channels;\n    int alpha_channel;\n    stbir_uint32 flags;\n    stbir_datatype type;\n    stbir_filter horizontal_filter;\n    stbir_filter vertical_filter;\n    stbir_edge edge_horizontal;\n    stbir_edge edge_vertical;\n    stbir_colorspace colorspace;\n\n    stbir__contributors* horizontal_contributors;\n    float* horizontal_coefficients;\n\n    stbir__contributors* vertical_contributors;\n    float* vertical_coefficients;\n\n    int decode_buffer_pixels;\n    float* decode_buffer;\n\n    float* horizontal_buffer;\n\n    // cache these because ceil/floor are inexplicably showing up in profile\n    int horizontal_coefficient_width;\n    int vertical_coefficient_width;\n    int horizontal_filter_pixel_width;\n    int vertical_filter_pixel_width;\n    int horizontal_filter_pixel_margin;\n    int vertical_filter_pixel_margin;\n    int horizontal_num_contributors;\n    int vertical_num_contributors;\n\n    int ring_buffer_length_bytes;   // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter)\n    int ring_buffer_num_entries;    // Total number of entries in the ring buffer.\n    int ring_buffer_first_scanline;\n    int ring_buffer_last_scanline;\n    int ring_buffer_begin_index;    // first_scanline is at this index in the ring buffer\n    float* ring_buffer;\n\n    float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds.\n\n    int horizontal_contributors_size;\n    int horizontal_coefficients_size;\n    int vertical_contributors_size;\n    int vertical_coefficients_size;\n    int decode_buffer_size;\n    int horizontal_buffer_size;\n    int ring_buffer_size;\n    int encode_buffer_size;\n} ostbir__info;\n\n\nstatic const float stbir__max_uint8_as_float  = 255.0f;\nstatic const float stbir__max_uint16_as_float = 65535.0f;\nstatic const double stbir__max_uint32_as_float = 4294967295.0;\n\n\nstatic stbir__inline int stbir__min(int a, int b)\n{\n    return a < b ? a : b;\n}\n\nstatic stbir__inline float stbir__saturate(float x)\n{\n    if (x < 0)\n        return 0;\n\n    if (x > 1)\n        return 1;\n\n    return x;\n}\n\n#ifdef STBIR_SATURATE_INT\nstatic stbir__inline stbir_uint8 stbir__saturate8(int x)\n{\n    if ((unsigned int) x <= 255)\n        return (stbir_uint8) x;\n\n    if (x < 0)\n        return 0;\n\n    return 255;\n}\n\nstatic stbir__inline stbir_uint16 stbir__saturate16(int x)\n{\n    if ((unsigned int) x <= 65535)\n        return (stbir_uint16) x;\n\n    if (x < 0)\n        return 0;\n\n    return 65535;\n}\n#endif\n\nstatic float stbir__srgb_uchar_to_linear_float[256] = {\n    0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f,\n    0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f,\n    0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f,\n    0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f,\n    0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f,\n    0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f,\n    0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f,\n    0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f,\n    0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f,\n    0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f,\n    0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f,\n    0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f,\n    0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f,\n    0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f,\n    0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f,\n    0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f,\n    0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f,\n    0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f,\n    0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f,\n    0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f,\n    0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f,\n    0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f,\n    0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f,\n    0.982251f, 0.991102f, 1.0f\n};\n\nstatic float stbir__srgb_to_linear(float f)\n{\n    if (f <= 0.04045f)\n        return f / 12.92f;\n    else\n        return (float)pow((f + 0.055f) / 1.055f, 2.4f);\n}\n\nstatic float stbir__linear_to_srgb(float f)\n{\n    if (f <= 0.0031308f)\n        return f * 12.92f;\n    else\n        return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f;\n}\n\n#ifndef STBIR_NON_IEEE_FLOAT\n// From https://gist.github.com/rygorous/2203834\n\ntypedef union\n{\n    stbir_uint32 u;\n    float f;\n} stbir__FP32;\n\nstatic const stbir_uint32 fp32_to_srgb8_tab4[104] = {\n    0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d,\n    0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a,\n    0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033,\n    0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067,\n    0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5,\n    0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2,\n    0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143,\n    0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af,\n    0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240,\n    0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300,\n    0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401,\n    0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559,\n    0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723,\n};\n \nstatic stbir_uint8 stbir__linear_to_srgb_uchar(float in)\n{\n    static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps\n    static const stbir__FP32 minval = { (127-13) << 23 };\n    stbir_uint32 tab,bias,scale,t;\n    stbir__FP32 f;\n \n    // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively.\n    // The tests are carefully written so that NaNs map to 0, same as in the reference\n    // implementation.\n    if (!(in > minval.f)) // written this way to catch NaNs\n        in = minval.f;\n    if (in > almostone.f)\n        in = almostone.f;\n \n    // Do the table lookup and unpack bias, scale\n    f.f = in;\n    tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20];\n    bias = (tab >> 16) << 9;\n    scale = tab & 0xffff;\n \n    // Grab next-highest mantissa bits and perform linear interpolation\n    t = (f.u >> 12) & 0xff;\n    return (unsigned char) ((bias + scale*t) >> 16);\n}\n\n#else\n// sRGB transition values, scaled by 1<<28\nstatic int stbir__srgb_offset_to_linear_scaled[256] =\n{\n            0,     40738,    122216,    203693,    285170,    366648,    448125,    529603,\n       611080,    692557,    774035,    855852,    942009,   1033024,   1128971,   1229926,\n      1335959,   1447142,   1563542,   1685229,   1812268,   1944725,   2082664,   2226148,\n      2375238,   2529996,   2690481,   2856753,   3028870,   3206888,   3390865,   3580856,\n      3776916,   3979100,   4187460,   4402049,   4622919,   4850123,   5083710,   5323731,\n      5570236,   5823273,   6082892,   6349140,   6622065,   6901714,   7188133,   7481369,\n      7781466,   8088471,   8402427,   8723380,   9051372,   9386448,   9728650,  10078021,\n     10434603,  10798439,  11169569,  11548036,  11933879,  12327139,  12727857,  13136073,\n     13551826,  13975156,  14406100,  14844697,  15290987,  15745007,  16206795,  16676389,\n     17153826,  17639142,  18132374,  18633560,  19142734,  19659934,  20185196,  20718552,\n     21260042,  21809696,  22367554,  22933648,  23508010,  24090680,  24681686,  25281066,\n     25888850,  26505076,  27129772,  27762974,  28404716,  29055026,  29713942,  30381490,\n     31057708,  31742624,  32436272,  33138682,  33849884,  34569912,  35298800,  36036568,\n     36783260,  37538896,  38303512,  39077136,  39859796,  40651528,  41452360,  42262316,\n     43081432,  43909732,  44747252,  45594016,  46450052,  47315392,  48190064,  49074096,\n     49967516,  50870356,  51782636,  52704392,  53635648,  54576432,  55526772,  56486700,\n     57456236,  58435408,  59424248,  60422780,  61431036,  62449032,  63476804,  64514376,\n     65561776,  66619028,  67686160,  68763192,  69850160,  70947088,  72053992,  73170912,\n     74297864,  75434880,  76581976,  77739184,  78906536,  80084040,  81271736,  82469648,\n     83677792,  84896192,  86124888,  87363888,  88613232,  89872928,  91143016,  92423512,\n     93714432,  95015816,  96327688,  97650056,  98982952, 100326408, 101680440, 103045072,\n    104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544,\n    115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832,\n    127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528,\n    140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968,\n    154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184,\n    168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992,\n    183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968,\n    199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480,\n    215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656,\n    232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464,\n    250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664,\n};\n\nstatic stbir_uint8 stbir__linear_to_srgb_uchar(float f)\n{\n    int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp\n    int v = 0;\n    int i;\n\n    // Refine the guess with a short binary search.\n    i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +  64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +  32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +  16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n    i = v +   1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;\n\n    return (stbir_uint8) v;\n}\n#endif\n\nstatic float stbir__filter_trapezoid(float x, float scale)\n{\n    float halfscale = scale / 2;\n    float t = 0.5f + halfscale;\n    STBIR_ASSERT(scale <= 1);\n\n    x = (float)fabs(x);\n\n    if (x >= t)\n        return 0;\n    else\n    {\n        float r = 0.5f - halfscale;\n        if (x <= r)\n            return 1;\n        else\n            return (t - x) / scale;\n    }\n}\n\nstatic float stbir__support_trapezoid(float scale)\n{\n    STBIR_ASSERT(scale <= 1);\n    return 0.5f + scale / 2;\n}\n\nstatic float stbir__filter_triangle(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x <= 1.0f)\n        return 1 - x;\n    else\n        return 0;\n}\n\nstatic float stbir__filter_cubic(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x < 1.0f)\n        return (4 + x*x*(3*x - 6))/6;\n    else if (x < 2.0f)\n        return (8 + x*(-12 + x*(6 - x)))/6;\n\n    return (0.0f);\n}\n\nstatic float stbir__filter_catmullrom(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x < 1.0f)\n        return 1 - x*x*(2.5f - 1.5f*x);\n    else if (x < 2.0f)\n        return 2 - x*(4 + x*(0.5f*x - 2.5f));\n\n    return (0.0f);\n}\n\nstatic float stbir__filter_mitchell(float x, float s)\n{\n    STBIR__UNUSED_PARAM(s);\n\n    x = (float)fabs(x);\n\n    if (x < 1.0f)\n        return (16 + x*x*(21 * x - 36))/18;\n    else if (x < 2.0f)\n        return (32 + x*(-60 + x*(36 - 7*x)))/18;\n\n    return (0.0f);\n}\n\nstatic float stbir__support_zero(float s)\n{\n    STBIR__UNUSED_PARAM(s);\n    return 0;\n}\n\nstatic float stbir__support_one(float s)\n{\n    STBIR__UNUSED_PARAM(s);\n    return 1;\n}\n\nstatic float stbir__support_two(float s)\n{\n    STBIR__UNUSED_PARAM(s);\n    return 2;\n}\n\nstatic stbir__filter_info stbir__filter_info_table[] = {\n        { NULL,                     stbir__support_zero },\n        { stbir__filter_trapezoid,  stbir__support_trapezoid },\n        { stbir__filter_triangle,   stbir__support_one },\n        { stbir__filter_cubic,      stbir__support_two },\n        { stbir__filter_catmullrom, stbir__support_two },\n        { stbir__filter_mitchell,   stbir__support_two },\n};\n\nstbir__inline static int stbir__use_upsampling(float ratio)\n{\n    return ratio > 1;\n}\n\nstbir__inline static int stbir__use_width_upsampling(ostbir__info* stbir_info)\n{\n    return stbir__use_upsampling(stbir_info->horizontal_scale);\n}\n\nstbir__inline static int stbir__use_height_upsampling(ostbir__info* stbir_info)\n{\n    return stbir__use_upsampling(stbir_info->vertical_scale);\n}\n\n// This is the maximum number of input samples that can affect an output sample\n// with the given filter\nstatic int stbir__get_filter_pixel_width(stbir_filter filter, float scale)\n{\n    STBIR_ASSERT(filter != 0);\n    STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));\n\n    if (stbir__use_upsampling(scale))\n        return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2);\n    else\n        return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale);\n}\n\n// This is how much to expand buffers to account for filters seeking outside\n// the image boundaries.\nstatic int stbir__get_filter_pixel_margin(stbir_filter filter, float scale)\n{\n    return stbir__get_filter_pixel_width(filter, scale) / 2;\n}\n\nstatic int stbir__get_coefficient_width(stbir_filter filter, float scale)\n{\n    if (stbir__use_upsampling(scale))\n        return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2);\n    else\n        return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2);\n}\n\nstatic int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size)\n{\n    if (stbir__use_upsampling(scale))\n        return output_size;\n    else\n        return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2);\n}\n\nstatic int stbir__get_total_horizontal_coefficients(ostbir__info* info)\n{\n    return info->horizontal_num_contributors\n         * stbir__get_coefficient_width      (info->horizontal_filter, info->horizontal_scale);\n}\n\nstatic int stbir__get_total_vertical_coefficients(ostbir__info* info)\n{\n    return info->vertical_num_contributors\n         * stbir__get_coefficient_width      (info->vertical_filter, info->vertical_scale);\n}\n\nstatic stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n)\n{\n    return &contributors[n];\n}\n\n// For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample,\n// if you change it here change it there too.\nstatic float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c)\n{\n    int width = stbir__get_coefficient_width(filter, scale);\n    return &coefficients[width*n + c];\n}\n\nstatic int stbir__edge_wrap_slow(stbir_edge edge, int n, int max)\n{\n    switch (edge)\n    {\n    case STBIR_EDGE_ZERO:\n        return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later\n\n    case STBIR_EDGE_CLAMP:\n        if (n < 0)\n            return 0;\n\n        if (n >= max)\n            return max - 1;\n\n        return n; // NOTREACHED\n\n    case STBIR_EDGE_REFLECT:\n    {\n        if (n < 0)\n        {\n            if (n > -max)\n                return -n;\n            else\n                return max - 1;\n        }\n\n        if (n >= max)\n        {\n            int max2 = max * 2;\n            if (n >= max2)\n                return 0;\n            else\n                return max2 - n - 1;\n        }\n\n        return n; // NOTREACHED\n    }\n\n    case STBIR_EDGE_WRAP:\n        if (n >= 0)\n            return (n % max);\n        else\n        {\n            int m = (-n) % max;\n\n            if (m != 0)\n                m = max - m;\n\n            return (m);\n        }\n        // NOTREACHED\n\n    default:\n        STBIR_ASSERT(!\"Unimplemented edge type\");\n        return 0;\n    }\n}\n\nstbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max)\n{\n    // avoid per-pixel switch\n    if (n >= 0 && n < max)\n        return n;\n    return stbir__edge_wrap_slow(edge, n, max);\n}\n\n// What input pixels contribute to this output pixel?\nstatic void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out)\n{\n    float out_pixel_center = (float)n + 0.5f;\n    float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius;\n    float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius;\n\n    float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio;\n    float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio;\n\n    *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio;\n    *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5));\n    *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5));\n}\n\n// What output pixels does this input pixel contribute to?\nstatic void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in)\n{\n    float in_pixel_center = (float)n + 0.5f;\n    float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius;\n    float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius;\n\n    float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift;\n    float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift;\n\n    *out_center_of_in = in_pixel_center * scale_ratio - out_shift;\n    *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5));\n    *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5));\n}\n\nstatic void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group)\n{\n    int i;\n    float total_filter = 0;\n    float filter_scale;\n\n    STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.\n\n    contributor->n0 = in_first_pixel;\n    contributor->n1 = in_last_pixel;\n\n    STBIR_ASSERT(contributor->n1 >= contributor->n0);\n\n    for (i = 0; i <= in_last_pixel - in_first_pixel; i++)\n    {\n        float in_pixel_center = (float)(i + in_first_pixel) + 0.5f;\n        coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale);\n\n        // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.)\n        if (i == 0 && !coefficient_group[i])\n        {\n            contributor->n0 = ++in_first_pixel;\n            i--;\n            continue;\n        }\n\n        total_filter += coefficient_group[i];\n    }\n\n    STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0);\n\n    STBIR_ASSERT(total_filter > 0.9);\n    STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off.\n\n    // Make sure the sum of all coefficients is 1.\n    filter_scale = 1 / total_filter;\n\n    for (i = 0; i <= in_last_pixel - in_first_pixel; i++)\n        coefficient_group[i] *= filter_scale;\n\n    for (i = in_last_pixel - in_first_pixel; i >= 0; i--)\n    {\n        if (coefficient_group[i])\n            break;\n\n        // This line has no weight. We can skip it.\n        contributor->n1 = contributor->n0 + i - 1;\n    }\n}\n\nstatic void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group)\n{\n    int i;\n\n     STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.\n\n    contributor->n0 = out_first_pixel;\n    contributor->n1 = out_last_pixel;\n\n    STBIR_ASSERT(contributor->n1 >= contributor->n0);\n\n    for (i = 0; i <= out_last_pixel - out_first_pixel; i++)\n    {\n        float out_pixel_center = (float)(i + out_first_pixel) + 0.5f;\n        float x = out_pixel_center - out_center_of_in;\n        coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio;\n    }\n\n    STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0);\n\n    for (i = out_last_pixel - out_first_pixel; i >= 0; i--)\n    {\n        if (coefficient_group[i])\n            break;\n\n        // This line has no weight. We can skip it.\n        contributor->n1 = contributor->n0 + i - 1;\n    }\n}\n\nstatic void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size)\n{\n    int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);\n    int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio);\n    int i, j;\n    int skip;\n\n    for (i = 0; i < output_size; i++)\n    {\n        float scale;\n        float total = 0;\n\n        for (j = 0; j < num_contributors; j++)\n        {\n            if (i >= contributors[j].n0 && i <= contributors[j].n1)\n            {\n                float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0);\n                total += coefficient;\n            }\n            else if (i < contributors[j].n0)\n                break;\n        }\n\n        //STBIR_ASSERT(total > 0.9f);\n        //STBIR_ASSERT(total < 1.5f);\n\n        scale = 1 / total;\n\n        for (j = 0; j < num_contributors; j++)\n        {\n            if (i >= contributors[j].n0 && i <= contributors[j].n1)\n                *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale;\n            else if (i < contributors[j].n0)\n                break;\n        }\n    }\n\n    // Optimize: Skip zero coefficients and contributions outside of image bounds.\n    // Do this after normalizing because normalization depends on the n0/n1 values.\n    for (j = 0; j < num_contributors; j++)\n    {\n        int range, max, width;\n\n        skip = 0;\n        while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0)\n            skip++;\n\n        contributors[j].n0 += skip;\n\n        while (contributors[j].n0 < 0)\n        {\n            contributors[j].n0++;\n            skip++;\n        }\n\n        range = contributors[j].n1 - contributors[j].n0 + 1;\n        max = stbir__min(num_coefficients, range);\n\n        width = stbir__get_coefficient_width(filter, scale_ratio);\n        for (i = 0; i < max; i++)\n        {\n            if (i + skip >= width)\n                break;\n\n            *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip);\n        }\n\n        continue;\n    }\n\n    // Using min to avoid writing into invalid pixels.\n    for (i = 0; i < num_contributors; i++)\n        contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1);\n}\n\n// Each scan line uses the same kernel values so we should calculate the kernel\n// values once and then we can use them for every scan line.\nstatic void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size)\n{\n    int n;\n    int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);\n\n    if (stbir__use_upsampling(scale_ratio))\n    {\n        float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio;\n\n        // Looping through out pixels\n        for (n = 0; n < total_contributors; n++)\n        {\n            float in_center_of_out; // Center of the current out pixel in the in pixel space\n            int in_first_pixel, in_last_pixel;\n\n            stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out);\n\n            stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));\n        }\n    }\n    else\n    {\n        float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio;\n\n        // Looping through in pixels\n        for (n = 0; n < total_contributors; n++)\n        {\n            float out_center_of_in; // Center of the current out pixel in the in pixel space\n            int out_first_pixel, out_last_pixel;\n            int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio);\n\n            stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in);\n\n            stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));\n        }\n\n        stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size);\n    }\n}\n\nstatic float* stbir__get_decode_buffer(ostbir__info* stbir_info)\n{\n    // The 0 index of the decode buffer starts after the margin. This makes\n    // it okay to use negative indexes on the decode buffer.\n    return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels];\n}\n\n#define STBIR__DECODE(type, colorspace) ((type) * (STBIR_MAX_COLORSPACES) + (colorspace))\n\nstatic void stbir__decode_scanline(ostbir__info* stbir_info, int n)\n{\n    int c;\n    int channels = stbir_info->channels;\n    int alpha_channel = stbir_info->alpha_channel;\n    int type = stbir_info->type;\n    int colorspace = stbir_info->colorspace;\n    int input_w = stbir_info->input_w;\n    size_t input_stride_bytes = stbir_info->input_stride_bytes;\n    float* decode_buffer = stbir__get_decode_buffer(stbir_info);\n    stbir_edge edge_horizontal = stbir_info->edge_horizontal;\n    stbir_edge edge_vertical = stbir_info->edge_vertical;\n    size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes;\n    const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset;\n    int max_x = input_w + stbir_info->horizontal_filter_pixel_margin;\n    int decode = STBIR__DECODE(type, colorspace);\n\n    int x = -stbir_info->horizontal_filter_pixel_margin;\n\n    // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input,\n    // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO\n    if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h))\n    {\n        for (; x < max_x; x++)\n            for (c = 0; c < channels; c++)\n                decode_buffer[x*channels + c] = 0;\n        return;\n    }\n\n    STBIR_PROFILE_START( );\n    switch (decode)\n    {\n    case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]];\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float);\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float;\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float);\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float));\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float);\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c];\n        }\n        break;\n\n    case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):\n        for (; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n            int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;\n            for (c = 0; c < channels; c++)\n                decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]);\n\n            if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel];\n        }\n\n        break;\n\n    default:\n        STBIR_ASSERT(!\"Unknown type/colorspace/channels combination.\");\n        break;\n    }\n    STBIR_PROFILE_END( decode );\n\n    if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED))\n    {\n        STBIR_PROFILE_START();\n\n        for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++)\n        {\n            int decode_pixel_index = x * channels;\n\n            // If the alpha value is 0 it will clobber the color values. Make sure it's not.\n            float alpha = decode_buffer[decode_pixel_index + alpha_channel];\n#ifndef STBIR_NO_ALPHA_EPSILON\n            if (stbir_info->type != STBIR_TYPE_FLOAT) {\n                alpha += STBIR_ALPHA_EPSILON;\n                decode_buffer[decode_pixel_index + alpha_channel] = alpha;\n            }\n#endif\n            for (c = 0; c < channels; c++)\n            {\n                if (c == alpha_channel)\n                    continue;\n\n                decode_buffer[decode_pixel_index + c] *= alpha;\n            }\n        }\n        STBIR_PROFILE_END( alpha );\n    }\n\n    if (edge_horizontal == STBIR_EDGE_ZERO)\n    {\n        for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++)\n        {\n            for (c = 0; c < channels; c++)\n                decode_buffer[x*channels + c] = 0;\n        }\n        for (x = input_w; x < max_x; x++)\n        {\n            for (c = 0; c < channels; c++)\n                decode_buffer[x*channels + c] = 0;\n        }\n    }\n}\n\nstatic float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length)\n{\n    return &ring_buffer[index * ring_buffer_length];\n}\n\nstatic float* stbir__add_empty_ring_buffer_entry(ostbir__info* stbir_info, int n)\n{\n    int ring_buffer_index;\n    float* ring_buffer;\n\n    stbir_info->ring_buffer_last_scanline = n;\n\n    if (stbir_info->ring_buffer_begin_index < 0)\n    {\n        ring_buffer_index = stbir_info->ring_buffer_begin_index = 0;\n        stbir_info->ring_buffer_first_scanline = n;\n    }\n    else\n    {\n        ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries;\n        STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index);\n    }\n\n    ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float));\n    \n    memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes);\n\n    return ring_buffer;\n}\n\n\nstatic void stbir__resample_horizontal_upsample(ostbir__info* stbir_info, float* output_buffer)\n{\n    int x, k;\n    int output_w = stbir_info->output_w;\n    int channels = stbir_info->channels;\n    float* decode_buffer = stbir__get_decode_buffer(stbir_info);\n    stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;\n    float* horizontal_coefficients = stbir_info->horizontal_coefficients;\n    int coefficient_width = stbir_info->horizontal_coefficient_width;\n\n    STBIR_PROFILE_START( );\n    for (x = 0; x < output_w; x++)\n    {\n        int n0 = horizontal_contributors[x].n0;\n        int n1 = horizontal_contributors[x].n1;\n\n        int out_pixel_index = x * channels;\n        int coefficient_group = coefficient_width * x;\n        int coefficient_counter = 0;\n\n        STBIR_ASSERT(n1 >= n0);\n        STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin);\n        STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin);\n        STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);\n        STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);\n\n        switch (channels) {\n            case 1:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 1;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                }\n                break;\n            case 2:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 2;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                }\n                break;\n            case 3:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 3;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                }\n                break;\n            case 4:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * 4;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                    output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;\n                }\n                break;\n            default:\n                for (k = n0; k <= n1; k++)\n                {\n                    int in_pixel_index = k * channels;\n                    float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];\n                    int c;\n                    STBIR_ASSERT(coefficient != 0);\n                    for (c = 0; c < channels; c++)\n                        output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;\n                }\n                break;\n        }\n    }\n    STBIR_PROFILE_END( horizontal );\n}\n\nstatic void stbir__resample_horizontal_downsample(ostbir__info* stbir_info, float* output_buffer)\n{\n    int x, k;\n    int input_w = stbir_info->input_w;\n    int channels = stbir_info->channels;\n    float* decode_buffer = stbir__get_decode_buffer(stbir_info);\n    stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;\n    float* horizontal_coefficients = stbir_info->horizontal_coefficients;\n    int coefficient_width = stbir_info->horizontal_coefficient_width;\n    int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin;\n    int max_x = input_w + filter_pixel_margin * 2;\n\n    STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info));\n\n    STBIR_PROFILE_START( );\n    switch (channels) {\n        case 1:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 1;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 1;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                }\n            }\n            break;\n\n        case 2:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 2;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 2;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                }\n            }\n            break;\n\n        case 3:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 3;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 3;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    //STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                }\n            }\n            break;\n\n        case 4:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * 4;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int out_pixel_index = k * 4;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    STBIR_ASSERT(coefficient != 0);\n                    output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;\n                    output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;\n                    output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;\n                    output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;\n                }\n            }\n            break;\n\n        default:\n            for (x = 0; x < max_x; x++)\n            {\n                int n0 = horizontal_contributors[x].n0;\n                int n1 = horizontal_contributors[x].n1;\n\n                int in_x = x - filter_pixel_margin;\n                int in_pixel_index = in_x * channels;\n                int max_n = n1;\n                int coefficient_group = coefficient_width * x;\n\n                for (k = n0; k <= max_n; k++)\n                {\n                    int c;\n                    int out_pixel_index = k * channels;\n                    float coefficient = horizontal_coefficients[coefficient_group + k - n0];\n                    STBIR_ASSERT(coefficient != 0);\n                    for (c = 0; c < channels; c++)\n                        output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;\n                }\n            }\n            break;\n    }\n    STBIR_PROFILE_END( horizontal );\n}\n\nstatic void stbir__decode_and_resample_upsample(ostbir__info* stbir_info, int n)\n{\n    // Decode the nth scanline from the source image into the decode buffer.\n    stbir__decode_scanline(stbir_info, n);\n\n    // Now resample it into the ring buffer.\n    if (stbir__use_width_upsampling(stbir_info))\n        stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));\n    else\n        stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));\n\n    // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling.\n}\n\nstatic void stbir__decode_and_resample_downsample(ostbir__info* stbir_info, int n)\n{\n    // Decode the nth scanline from the source image into the decode buffer.\n    stbir__decode_scanline(stbir_info, n);\n\n    memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float));\n\n    // Now resample it into the horizontal buffer.\n    if (stbir__use_width_upsampling(stbir_info))\n        stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer);\n    else\n        stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer);\n\n    // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers.\n}\n\n// Get the specified scan line from the ring buffer.\nstatic float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length)\n{\n    int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries;\n    return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length);\n}\n\n\nstatic void stbir__encode_scanline(ostbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode)\n{\n    int x;\n    int n;\n    int num_nonalpha;\n    stbir_uint16 nonalpha[STBIR_MAX_CHANNELS];\n\n   if ((!(stbir_info->flags&STBIR_FLAG_ALPHA_OUT_PREMULTIPLIED))&&(alpha_channel!=-1))\n   {\n        STBIR_PROFILE_START( );\n\n        for (x=0; x < num_pixels; ++x)\n        {\n            int pixel_index = x*channels;\n\n            float alpha = encode_buffer[pixel_index + alpha_channel];\n            float reciprocal_alpha = alpha ? 1.0f / alpha : 0;\n\n            // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb\n            for (n = 0; n < channels; n++)\n                if (n != alpha_channel)\n                    encode_buffer[pixel_index + n] *= reciprocal_alpha;\n\n            // We added in a small epsilon to prevent the color channel from being deleted with zero alpha.\n            // Because we only add it for integer types, it will automatically be discarded on integer\n            // conversion, so we don't need to subtract it back out (which would be problematic for\n            // numeric precision reasons).\n        }\n      STBIR_PROFILE_END( unalpha );\n    }\n\n    // build a table of all channels that need colorspace correction, so\n    // we don't perform colorspace correction on channels that don't need it.\n    for (x = 0, num_nonalpha = 0; x < channels; ++x)\n    {\n        if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))\n        {\n            nonalpha[num_nonalpha++] = (stbir_uint16)x;\n        }\n    }\n\n    #define STBIR__ROUND_INT(f)    ((int)          ((f)+0.5))\n    #define STBIR__ROUND_UINT(f)   ((stbir_uint32) ((f)+0.5))\n\n    #ifdef STBIR__SATURATE_INT\n    #define STBIR__ENCODE_LINEAR8(f)   stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float ))\n    #define STBIR__ENCODE_LINEAR16(f)  stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float))\n    #else\n    #define STBIR__ENCODE_LINEAR8(f)   (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float )\n    #define STBIR__ENCODE_LINEAR16(f)  (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float)\n    #endif\n\n    STBIR_PROFILE_START( );\n\n    switch (decode)\n    {\n        case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]);\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]);\n                }\n\n                if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]);\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]);\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float);\n                }\n\n                if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]);\n            }\n\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float);\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float);\n                }\n\n                if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                    ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float);\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < channels; n++)\n                {\n                    int index = pixel_index + n;\n                    ((float*)output_buffer)[index] = encode_buffer[index];\n                }\n            }\n            break;\n\n        case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):\n            for (x=0; x < num_pixels; ++x)\n            {\n                int pixel_index = x*channels;\n\n                for (n = 0; n < num_nonalpha; n++)\n                {\n                    int index = pixel_index + nonalpha[n];\n                    float p = encode_buffer[index];\n                    if ( p <= 0 ) p = 0; if ( p >= 1.0 ) p = 1.0;\n                    ((float*)output_buffer)[index] = stbir__linear_to_srgb(p);\n                }\n\n                if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))\n                {\n                    float p = encode_buffer[pixel_index + alpha_channel];\n                    if ( p <= 0 ) p = 0; if ( p >= 1.0 ) p = 1.0;\n                    ((float*)output_buffer)[pixel_index + alpha_channel] = p;\n                }\n            }\n            break;\n\n        default:\n            STBIR_ASSERT(!\"Unknown type/colorspace/channels combination.\");\n            break;\n    }\n    STBIR_PROFILE_END( encode );\n}\n\nstatic void stbir__resample_vertical_upsample(ostbir__info* stbir_info, int n)\n{\n    int x, k;\n    int output_w = stbir_info->output_w;\n    stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;\n    float* vertical_coefficients = stbir_info->vertical_coefficients;\n    int channels = stbir_info->channels;\n    int alpha_channel = stbir_info->alpha_channel;\n    int type = stbir_info->type;\n    int colorspace = stbir_info->colorspace;\n    int ring_buffer_entries = stbir_info->ring_buffer_num_entries;\n    void* output_data = stbir_info->output_data;\n    float* encode_buffer = stbir_info->encode_buffer;\n    int decode = STBIR__DECODE(type, colorspace);\n    int coefficient_width = stbir_info->vertical_coefficient_width;\n    int coefficient_counter;\n    int contributor = n;\n\n    float* ring_buffer = stbir_info->ring_buffer;\n    int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;\n    int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;\n    int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);\n\n    int n0,n1, output_row_start;\n    int coefficient_group = coefficient_width * contributor;\n\n    n0 = vertical_contributors[contributor].n0;\n    n1 = vertical_contributors[contributor].n1;\n\n    output_row_start = n * stbir_info->output_stride_bytes;\n\n    STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));\n\n    STBIR_PROFILE_START( );\n\n    memset(encode_buffer, 0, output_w * sizeof(float) * channels);\n\n    // I tried reblocking this for better cache usage of encode_buffer\n    // (using x_outer, k, x_inner), but it lost speed. -- stb\n\n    coefficient_counter = 0;\n    switch (channels) {\n        case 1:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 1;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                }\n            }\n            break;\n        case 2:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 2;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                    encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;\n                }\n            }\n            break;\n        case 3:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 3;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                    encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;\n                    encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;\n                }\n            }\n            break;\n        case 4:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * 4;\n                    encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;\n                    encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;\n                    encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;\n                    encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient;\n                }\n            }\n            break;\n        default:\n            for (k = n0; k <= n1; k++)\n            {\n                int coefficient_index = coefficient_counter++;\n                float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n                float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n                for (x = 0; x < output_w; ++x)\n                {\n                    int in_pixel_index = x * channels;\n                    int c;\n                    for (c = 0; c < channels; c++)\n                        encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient;\n                }\n            }\n            break;\n    }\n    STBIR_PROFILE_END( vertical );\n    stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode);\n}\n\nstatic void stbir__resample_vertical_downsample(ostbir__info* stbir_info, int n)\n{\n    int x, k;\n    int output_w = stbir_info->output_w;\n    stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;\n    float* vertical_coefficients = stbir_info->vertical_coefficients;\n    int channels = stbir_info->channels;\n    int ring_buffer_entries = stbir_info->ring_buffer_num_entries;\n    float* horizontal_buffer = stbir_info->horizontal_buffer;\n    int coefficient_width = stbir_info->vertical_coefficient_width;\n    int contributor = n + stbir_info->vertical_filter_pixel_margin;\n\n    float* ring_buffer = stbir_info->ring_buffer;\n    int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;\n    int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;\n    int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);\n    int n0,n1;\n\n    n0 = vertical_contributors[contributor].n0;\n    n1 = vertical_contributors[contributor].n1;\n\n    STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));\n\n    STBIR_PROFILE_START( );\n    for (k = n0; k <= n1; k++)\n    {\n        int coefficient_index = k - n0;\n        int coefficient_group = coefficient_width * contributor;\n        float coefficient = vertical_coefficients[coefficient_group + coefficient_index];\n\n        float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);\n\n        switch (channels) {\n            case 1:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 1;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                }\n                break;\n            case 2:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 2;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;\n                }\n                break;\n            case 3:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 3;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;\n                }\n                break;\n            case 4:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * 4;\n                    ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;\n                    ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient;\n                }\n                break;\n            default:\n                for (x = 0; x < output_w; x++)\n                {\n                    int in_pixel_index = x * channels;\n\n                    int c;\n                    for (c = 0; c < channels; c++)\n                        ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient;\n                }\n                break;\n        }\n    }\n    STBIR_PROFILE_END( vertical );\n}\n\nstatic void stbir__buffer_loop_upsample(ostbir__info* stbir_info)\n{\n    int y;\n    float scale_ratio = stbir_info->vertical_scale;\n    float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio;\n\n    STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));\n\n    for (y = 0; y < stbir_info->output_h; y++)\n    {\n        float in_center_of_out = 0; // Center of the current out scanline in the in scanline space\n        int in_first_scanline = 0, in_last_scanline = 0;\n\n        stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out);\n\n        STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);\n\n        if (stbir_info->ring_buffer_begin_index >= 0)\n        {\n            // Get rid of whatever we don't need anymore.\n            while (in_first_scanline > stbir_info->ring_buffer_first_scanline)\n            {\n                if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)\n                {\n                    // We just popped the last scanline off the ring buffer.\n                    // Reset it to the empty state.\n                    stbir_info->ring_buffer_begin_index = -1;\n                    stbir_info->ring_buffer_first_scanline = 0;\n                    stbir_info->ring_buffer_last_scanline = 0;\n                    break;\n                }\n                else\n                {\n                    stbir_info->ring_buffer_first_scanline++;\n                    stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;\n                }\n            }\n        }\n\n        // Load in new ones.\n        if (stbir_info->ring_buffer_begin_index < 0)\n            stbir__decode_and_resample_upsample(stbir_info, in_first_scanline);\n\n        while (in_last_scanline > stbir_info->ring_buffer_last_scanline)\n            stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1);\n\n        // Now all buffers should be ready to write a row of vertical sampling.\n        stbir__resample_vertical_upsample(stbir_info, y);\n\n        STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h);\n    }\n}\n\nstatic void stbir__empty_ring_buffer(ostbir__info* stbir_info, int first_necessary_scanline)\n{\n    int output_stride_bytes = stbir_info->output_stride_bytes;\n    int channels = stbir_info->channels;\n    int alpha_channel = stbir_info->alpha_channel;\n    int type = stbir_info->type;\n    int colorspace = stbir_info->colorspace;\n    int output_w = stbir_info->output_w;\n    void* output_data = stbir_info->output_data;\n    int decode = STBIR__DECODE(type, colorspace);\n\n    float* ring_buffer = stbir_info->ring_buffer;\n    int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);\n\n    if (stbir_info->ring_buffer_begin_index >= 0)\n    {\n        // Get rid of whatever we don't need anymore.\n        while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline)\n        {\n            if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h)\n            {\n                int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes;\n                float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length);\n                stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode);\n                STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h);\n            }\n\n            if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)\n            {\n                // We just popped the last scanline off the ring buffer.\n                // Reset it to the empty state.\n                stbir_info->ring_buffer_begin_index = -1;\n                stbir_info->ring_buffer_first_scanline = 0;\n                stbir_info->ring_buffer_last_scanline = 0;\n                break;\n            }\n            else\n            {\n                stbir_info->ring_buffer_first_scanline++;\n                stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;\n            }\n        }\n    }\n}\n\nstatic void stbir__buffer_loop_downsample(ostbir__info* stbir_info)\n{\n    int y;\n    float scale_ratio = stbir_info->vertical_scale;\n    int output_h = stbir_info->output_h;\n    float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio;\n    int pixel_margin = stbir_info->vertical_filter_pixel_margin;\n    int max_y = stbir_info->input_h + pixel_margin;\n\n    STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));\n\n    for (y = -pixel_margin; y < max_y; y++)\n    {\n        float out_center_of_in; // Center of the current out scanline in the in scanline space\n        int out_first_scanline, out_last_scanline;\n\n        stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in);\n\n        STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);\n\n        if (out_last_scanline < 0 || out_first_scanline >= output_h)\n            continue;\n\n        stbir__empty_ring_buffer(stbir_info, out_first_scanline);\n\n        stbir__decode_and_resample_downsample(stbir_info, y);\n\n        // Load in new ones.\n        if (stbir_info->ring_buffer_begin_index < 0)\n            stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline);\n\n        while (out_last_scanline > stbir_info->ring_buffer_last_scanline)\n            stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1);\n\n        // Now the horizontal buffer is ready to write to all ring buffer rows.\n        stbir__resample_vertical_downsample(stbir_info, y);\n    }\n\n    stbir__empty_ring_buffer(stbir_info, stbir_info->output_h);\n}\n\nstatic void stbir__setup(ostbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels)\n{\n    info->input_w = input_w;\n    info->input_h = input_h;\n    info->output_w = output_w;\n    info->output_h = output_h;\n    info->channels = channels;\n}\n\nstatic void stbir__calculate_transform(ostbir__info *info, float s0, float t0, float s1, float t1, float *transform)\n{\n    info->s0 = s0;\n    info->t0 = t0;\n    info->s1 = s1;\n    info->t1 = t1;\n\n    if (transform)\n    {\n        info->horizontal_scale = transform[0];\n        info->vertical_scale   = transform[1];\n        info->horizontal_shift = transform[2];\n        info->vertical_shift   = transform[3];\n    }\n    else\n    {\n        info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0);\n        info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0);\n\n        info->horizontal_shift = s0 * info->output_w / (s1 - s0);\n        info->vertical_shift = t0 * info->output_h / (t1 - t0);\n    }\n}\n\nstatic void stbir__choose_filter(ostbir__info *info, stbir_filter h_filter, stbir_filter v_filter)\n{\n    if (h_filter == 0)\n        h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;\n    if (v_filter == 0)\n        v_filter = stbir__use_upsampling(info->vertical_scale)   ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;\n    info->horizontal_filter = h_filter;\n    info->vertical_filter = v_filter;\n}\n\nstatic stbir_uint32 stbir__calculate_memory(ostbir__info *info)\n{\n    int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);\n    int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale);\n\n    info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w);\n    info->vertical_num_contributors   = stbir__get_contributors(info->vertical_scale  , info->vertical_filter  , info->input_h, info->output_h);\n\n    // One extra entry because floating point precision problems sometimes cause an extra to be necessary.\n    info->ring_buffer_num_entries = filter_height + 1;\n\n    info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors);\n    info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float);\n    info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors);\n    info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float);\n    info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float);\n    info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float);\n    info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float);\n    info->encode_buffer_size = info->output_w * info->channels * sizeof(float);\n\n    STBIR_ASSERT(info->horizontal_filter != 0);\n    STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late\n    STBIR_ASSERT(info->vertical_filter != 0);\n    STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late\n\n    if (stbir__use_height_upsampling(info))\n        // The horizontal buffer is for when we're downsampling the height and we\n        // can't output the result of sampling the decode buffer directly into the\n        // ring buffers.\n        info->horizontal_buffer_size = 0;\n    else\n        // The encode buffer is to retain precision in the height upsampling method\n        // and isn't used when height downsampling.\n        info->encode_buffer_size = 0;\n\n    return info->horizontal_contributors_size + info->horizontal_coefficients_size\n        + info->vertical_contributors_size + info->vertical_coefficients_size\n        + info->decode_buffer_size + info->horizontal_buffer_size\n        + info->ring_buffer_size + info->encode_buffer_size;\n}\n\nstatic int stbir__resize_allocated(ostbir__info *info,\n    const void* input_data, int input_stride_in_bytes,\n    void* output_data, int output_stride_in_bytes,\n    int alpha_channel, stbir_uint32 flags, stbir_datatype type,\n    stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace,\n    void* tempmem, size_t tempmem_size_in_bytes)\n{\n    size_t memory_required = stbir__calculate_memory(info);\n\n    int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type];\n    int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type];\n\n#ifdef STBIR_DEBUG_OVERWRITE_TEST\n#define OVERWRITE_ARRAY_SIZE 8\n    unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE];\n    unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE];\n    unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE];\n    unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE];\n\n    size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type];\n    memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);\n    memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE);\n    memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);\n    memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE);\n#endif\n\n    STBIR_ASSERT(info->channels >= 0);\n    STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS);\n\n    if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS)\n        return 0;\n\n    STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));\n    STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));\n\n    if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))\n        return 0;\n    if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))\n        return 0;\n\n    if (alpha_channel < 0)\n        flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED;\n\n    if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) {\n        STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels);\n    }\n\n    if (alpha_channel >= info->channels)\n        return 0;\n\n    STBIR_ASSERT(tempmem);\n\n    if (!tempmem)\n        return 0;\n\n    STBIR_ASSERT(tempmem_size_in_bytes >= memory_required);\n\n    if (tempmem_size_in_bytes < memory_required)\n        return 0;\n\n    memset(tempmem, 0, tempmem_size_in_bytes);\n\n    info->input_data = input_data;\n    info->input_stride_bytes = width_stride_input;\n\n    info->output_data = output_data;\n    info->output_stride_bytes = width_stride_output;\n\n    info->alpha_channel = alpha_channel;\n    info->flags = flags;\n    info->type = type;\n    info->edge_horizontal = edge_horizontal;\n    info->edge_vertical = edge_vertical;\n    info->colorspace = colorspace;\n\n    STBIR_PROFILE_START();\n\n    info->horizontal_coefficient_width   = stbir__get_coefficient_width  (info->horizontal_filter, info->horizontal_scale);\n    info->vertical_coefficient_width     = stbir__get_coefficient_width  (info->vertical_filter  , info->vertical_scale  );\n    info->horizontal_filter_pixel_width  = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale);\n    info->vertical_filter_pixel_width    = stbir__get_filter_pixel_width (info->vertical_filter  , info->vertical_scale  );\n    info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);\n    info->vertical_filter_pixel_margin   = stbir__get_filter_pixel_margin(info->vertical_filter  , info->vertical_scale  );\n\n    info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float);\n    info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2;\n\n#define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size)\n\n    info->horizontal_contributors = (stbir__contributors *) tempmem;\n    info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float);\n    info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors);\n    info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float);\n    info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float);\n\n    if (stbir__use_height_upsampling(info))\n    {\n        info->horizontal_buffer = NULL;\n        info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);\n        info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float);\n\n        STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);\n    }\n    else\n    {\n        info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);\n        info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float);\n        info->encode_buffer = NULL;\n\n        STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);\n    }\n\n#undef STBIR__NEXT_MEMPTR\n\n    // This signals that the ring buffer is empty\n    info->ring_buffer_begin_index = -1;\n\n    stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w);\n    stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h);\n    STBIR_PROFILE_END( filters );\n\n    STBIR_PROGRESS_REPORT(0);\n\n    STBIR_PROFILE_START();\n    if (stbir__use_height_upsampling(info))\n    {\n        stbir__buffer_loop_upsample(info);\n    }\n    else\n    {\n        stbir__buffer_loop_downsample(info);\n    }\n    STBIR_PROFILE_END( looping );\n\n\n    STBIR_PROGRESS_REPORT(1);\n\n#ifdef STBIR_DEBUG_OVERWRITE_TEST\n    STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);\n    STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0);\n    STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);\n    STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0);\n#endif\n\n    return 1;\n}\n\n\nstatic int stbir__resize_arbitrary(\n    void *alloc_context,\n    const void* input_data, int input_w, int input_h, int input_stride_in_bytes,\n    void* output_data, int output_w, int output_h, int output_stride_in_bytes,\n    float s0, float t0, float s1, float t1, float *transform,\n    int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type,\n    stbir_filter h_filter, stbir_filter v_filter,\n    stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace)\n{\n    ostbir__info info;\n    int result;\n    size_t memory_required;\n    void* extra_memory;\n    \n    STBIR_PROFILE_FIRST_START();\n\n    stbir__setup(&info, input_w, input_h, output_w, output_h, channels);\n    stbir__calculate_transform(&info, s0,t0,s1,t1,transform);\n    stbir__choose_filter(&info, h_filter, v_filter);\n    memory_required = stbir__calculate_memory(&info);\n    extra_memory = STBIR_MALLOC(memory_required, alloc_context);\n\n    if (!extra_memory)\n    {\n        return 0;\n    }\n\n    result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes,\n                                            output_data, output_stride_in_bytes, \n                                            alpha_channel, flags, type,\n                                            edge_horizontal, edge_vertical,\n                                            colorspace, extra_memory, memory_required);\n\n    STBIR_PROFILE_END( setup);\n\n    STBIR_FREE(extra_memory, alloc_context);\n\n    return result;\n}\n\nSTBIRDEF int stbir_resize_uint8(     const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);\n}\n\nSTBIRDEF int stbir_resize_float(     const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);\n}\n\nSTBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                           unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                     int num_channels, int alpha_channel, int flags)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB);\n}\n\nSTBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                                    unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                              int num_channels, int alpha_channel, int flags,\n                                              stbir_edge edge_wrap_mode)\n{\n    return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,\n        edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB);\n}\n\nSTBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                               unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, \n                                         void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter,\n        edge_wrap_mode, edge_wrap_mode, space);\n}\n\nSTBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels  , int input_w , int input_h , int input_stride_in_bytes,\n                                               stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, \n                                         void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter,\n        edge_wrap_mode, edge_wrap_mode, space);\n}\n\n\nSTBIRDEF int stbir_resize_float_generic( const float *input_pixels         , int input_w , int input_h , int input_stride_in_bytes,\n                                               float *output_pixels        , int output_w, int output_h, int output_stride_in_bytes,\n                                         int num_channels, int alpha_channel, int flags,\n                                         stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, \n                                         void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter,\n        edge_wrap_mode, edge_wrap_mode, space);\n}\n\n\nSTBIRDEF int stbir_resize(         const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, \n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,\n        edge_mode_horizontal, edge_mode_vertical, space);\n}\n\n\nSTBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, \n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float x_scale, float y_scale,\n                                   float x_offset, float y_offset)\n{\n    float transform[4];\n    transform[0] = x_scale;\n    transform[1] = y_scale;\n    transform[2] = x_offset;\n    transform[3] = y_offset;\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,\n        edge_mode_horizontal, edge_mode_vertical, space);\n}\n\nSTBIRDEF int stbir_resize_region(  const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,\n                                         void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,\n                                   stbir_datatype datatype,\n                                   int num_channels, int alpha_channel, int flags,\n                                   stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, \n                                   stbir_filter filter_horizontal,  stbir_filter filter_vertical,\n                                   stbir_colorspace space, void *alloc_context,\n                                   float s0, float t0, float s1, float t1)\n{\n    return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,\n        output_pixels, output_w, output_h, output_stride_in_bytes,\n        s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,\n        edge_mode_horizontal, edge_mode_vertical, space);\n}\n\n#endif // STB_IMAGE_RESIZE_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of \nthis software and associated documentation files (the \"Software\"), to deal in \nthe Software without restriction, including without limitation the rights to \nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies \nof the Software, and to permit persons to whom the Software is furnished to do \nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all \ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this \nsoftware, either in source code form or as a compiled binary, for any purpose, \ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this \nsoftware dedicate any and all copyright interest in the software to the public \ndomain. We make this dedication for the benefit of the public at large and to \nthe detriment of our heirs and successors. We intend this dedication to be an \novert act of relinquishment in perpetuity of all present and future rights to \nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN \nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION \nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_image_resize_test/oldir.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef _MSC_VER\n#define stop() __debugbreak()\n#else\n#define stop() __builtin_trap()\n#endif\n\n//#define HEAVYTM\n#include \"tm.h\"\n\n#define STBIR_SATURATE_INT\n#define STB_IMAGE_RESIZE_STATIC\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#include \"old_image_resize.h\"  \n\n\nstatic int types[4] =    { STBIR_TYPE_UINT8, STBIR_TYPE_UINT8, STBIR_TYPE_UINT16, STBIR_TYPE_FLOAT };\nstatic int edges[4] =    { STBIR_EDGE_CLAMP, STBIR_EDGE_REFLECT, STBIR_EDGE_ZERO, STBIR_EDGE_WRAP };\nstatic int flts[5] =     { STBIR_FILTER_BOX, STBIR_FILTER_TRIANGLE, STBIR_FILTER_CUBICBSPLINE, STBIR_FILTER_CATMULLROM, STBIR_FILTER_MITCHELL };\nstatic int channels[20] = { 1, 2, 3, 4,      4,4,  2,2,  4,4, 2,2,  4,4, 2,2,  4,4, 2,2 }; \nstatic int alphapos[20] = { -1, -1, -1, -1,  3,0,  1,0,   3,0,  1,0,   3,0,  1,0,   3,0,  1,0 }; \n\n\nvoid oresize( void * o, int ox, int oy, int op, void * i, int ix, int iy, int ip, int buf, int type, int edg, int flt )\n{\n  int t = types[type];\n  int ic = channels[buf];\n  int alpha = alphapos[buf];\n  int e = edges[edg];\n  int f = flts[flt];\n  int space = ( type == 1 ) ? STBIR_COLORSPACE_SRGB : 0;\n  int flags = ( buf >= 16 ) ? STBIR_FLAG_ALPHA_PREMULTIPLIED : ( ( buf >= 12 ) ? STBIR_FLAG_ALPHA_OUT_PREMULTIPLIED : ( ( buf >= 8 ) ? (STBIR_FLAG_ALPHA_PREMULTIPLIED|STBIR_FLAG_ALPHA_OUT_PREMULTIPLIED) : 0 ) );\n  stbir_uint64 start;\n\n  ENTER( \"Resize (old)\" );\n  start = tmGetAccumulationStart( tm_mask );\n\n  if(!stbir_resize( i, ix, iy, ip, o, ox, oy, op, t, ic, alpha, flags, e, e, f, f, space, 0 ) )\n    stop();\n\n  #ifdef STBIR_PROFILE\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.setup, \"Setup (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.filters, \"Filters (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.looping, \"Looping (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.vertical, \"Vertical (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.horizontal, \"Horizontal (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.decode, \"Scanline input (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.encode, \"Scanline output (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.alpha, \"Alpha weighting (old)\" );\n  tmEmitAccumulationZone( 0, 0, (tm_uint64 *)&start, 0, oldprofile.named.unalpha, \"Alpha unweighting (old)\" );\n  #endif\n\n  LEAVE();\n}\n"
  },
  {
    "path": "stb_image_resize_test/stbirtest.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n//#define HEAVYTM\n#include \"tm.h\"\n\n#ifdef RADUSETM3\ntm_api * g_tm_api;\n//#define PROFILE_MODE\n#endif\n\n#include <math.h>\n\n#ifdef _MSC_VER\n#define stop() __debugbreak()\n#include <windows.h>\n#define int64 __int64\n#define uint64 unsigned __int64\n#else\n#define stop() __builtin_trap()\n#define int64 long long\n#define uint64 unsigned long long\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(disable:4127)\n#endif\n\n//#define NOCOMP\n\n\n//#define PROFILE_NEW_ONLY\n//#define PROFILE_MODE\n\n\n#if defined(_x86_64) || defined( __x86_64__ ) || defined( _M_X64 ) || defined(__x86_64) || defined(__SSE2__) || defined(STBIR_SSE) || defined( _M_IX86_FP ) || defined(__i386) || defined( __i386__ ) || defined( _M_IX86 ) || defined( _X86_ )\n\n#ifdef _MSC_VER\n\n  uint64 __rdtsc();\n  #define __cycles() __rdtsc()\n\n#else // non msvc\n\n  static inline uint64 __cycles() \n  {\n    unsigned int lo, hi;\n    asm volatile (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi) );\n    return ( ( (uint64) hi ) << 32 ) | ( (uint64) lo );\n  }\n\n#endif  // msvc\n\n#elif defined( _M_ARM64 ) || defined( __aarch64__ ) || defined( __arm64__ ) || defined(__ARM_NEON__) \n\n#ifdef _MSC_VER\n\n  #define __cycles() _ReadStatusReg(ARM64_CNTVCT)\n\n#else\n\n  static inline uint64 __cycles()\n  {\n    uint64 tsc;\n    asm volatile(\"mrs %0, cntvct_el0\" : \"=r\" (tsc));\n    return tsc;\n  }\n\n#endif\n\n#else // x64, arm\n\n#error Unknown platform for timing.\n\n#endif  //x64 and   \n\n\n#ifdef PROFILE_MODE\n\n#define STBIR_ASSERT(cond)\n\n#endif\n\n#ifdef _DEBUG\n#undef STBIR_ASSERT\n#define STBIR_ASSERT(cond) { if (!(cond)) stop(); }\n#endif\n\n\n#define SHRINKBYW 2\n#define ZOOMBYW 2\n#define SHRINKBYH 2\n#define ZOOMBYH 2\n\n\nint mem_count = 0;\n\n#ifdef TEST_WITH_VALLOC\n\n#define STBIR__SEPARATE_ALLOCATIONS\n\n#if TEST_WITH_LIMIT_AT_FRONT\n\n  void * wmalloc(SIZE_T size)\n  {\n     static unsigned int pagesize=0;\n     void* p;\n     SIZE_T s;\n\n     // get the page size, if we haven't yet\n     if (pagesize==0)\n     {\n       SYSTEM_INFO si;\n       GetSystemInfo(&si);\n       pagesize=si.dwPageSize;\n     }\n\n     // we need room for the size, 8 bytes to hide the original pointer and a\n     //   validation dword, and enough data to completely fill one page\n     s=(size+(pagesize-1))&~(pagesize-1);\n\n     // allocate the size plus a page (for the guard)\n     p=VirtualAlloc(0,(SIZE_T)s,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);\n     \n     return p;\n   }\n\n  void wfree(void * ptr)\n  {\n    if (ptr)\n    {\n      if ( ((ptrdiff_t)ptr) & 4095 ) stop();\n      if ( VirtualFree(ptr,0,MEM_RELEASE) == 0 ) stop();\n    }\n  }\n\n#else\n\n  void * wmalloc(SIZE_T size)\n  {\n     static unsigned int pagesize=0;\n     void* p;\n     SIZE_T s;\n\n     // get the page size, if we haven't yet\n     if (pagesize==0)\n     {\n       SYSTEM_INFO si;\n       GetSystemInfo(&si);\n       pagesize=si.dwPageSize;\n     }\n\n     // we need room for the size, 8 bytes to hide the original pointer and a\n     //   validation dword, and enough data to completely fill one page\n     s=(size+16+(pagesize-1))&~(pagesize-1);\n\n     // allocate the size plus a page (for the guard)\n     p=VirtualAlloc(0,(SIZE_T)(s+pagesize+pagesize),MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);\n\n     if (p)\n     {\n       DWORD oldprot;\n       void* orig=p;\n\n       // protect the first page\n       VirtualProtect(((char*)p),pagesize,PAGE_NOACCESS,&oldprot);\n\n       // protect the final page\n       VirtualProtect(((char*)p)+s+pagesize,pagesize,PAGE_NOACCESS,&oldprot);\n\n       // now move the returned pointer so that it bumps right up against the\n       //   the next (protected) page (this may result in unaligned return\n       //   addresses - pre-align the sizes if you always want aligned ptrs)\n//#define ERROR_ON_FRONT\n#ifdef ERROR_ON_FRONT\n       p=((char*)p)+pagesize+16;\n#else\n       p=((char*)p)+(s-size)+pagesize;\n#endif\n\n       // hide the validation value and the original pointer (which we'll\n       //   need used for freeing) right behind the returned pointer\n       ((unsigned int*)p)[-1]=0x98765432;\n       ((void**)p)[-2]=orig;\n       ++mem_count;\n//printf(\"aloc: %p bytes: %d\\n\",p,(int)size);\n       return(p);\n     }\n\n     return 0;\n  }\n\n  void wfree(void * ptr)\n  {\n    if (ptr)\n    {\n      int err=0;\n\n      // is this one of our allocations?\n      if (((((unsigned int*)ptr)[-1])!=0x98765432) || ((((void**)ptr)[-2])==0))\n      {\n        err=1;\n      }\n\n      if (err)\n      {\n        __debugbreak();\n      }\n      else\n      {\n\n        // back up to find the original pointer\n        void* p=((void**)ptr)[-2];\n\n        // clear the validation value and the original pointer\n        ((unsigned int*)ptr)[-1]=0;\n        ((void**)ptr)[-2]=0;\n\n//printf(\"free: %p\\n\",ptr);\n\n        --mem_count;\n\n        // now free the pages\n        if (p)\n          VirtualFree(p,0,MEM_RELEASE);\n\n      }\n    }\n  }\n\n#endif\n\n#define STBIR_MALLOC(size,user_data) ((void)(user_data), wmalloc(size))\n#define STBIR_FREE(ptr,user_data)    ((void)(user_data), wfree(ptr))\n\n#endif\n\n#define STBIR_PROFILE\n//#define STBIR_NO_SIMD\n//#define STBIR_AVX\n//#define STBIR_AVX2\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#include \"stb_image_resize2.h\"  // new one!\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\nint tsizes[5] =   { 1, 1, 2, 4, 2 };\nint ttypes[5] =   { STBIR_TYPE_UINT8, STBIR_TYPE_UINT8_SRGB, STBIR_TYPE_UINT16, STBIR_TYPE_FLOAT, STBIR_TYPE_HALF_FLOAT };\n\nint cedges[4] =   { STBIR_EDGE_CLAMP, STBIR_EDGE_REFLECT, STBIR_EDGE_ZERO, STBIR_EDGE_WRAP };\nint flts[5] =     { STBIR_FILTER_BOX, STBIR_FILTER_TRIANGLE, STBIR_FILTER_CUBICBSPLINE, STBIR_FILTER_CATMULLROM, STBIR_FILTER_MITCHELL };\nint buffers[20] = { STBIR_1CHANNEL, STBIR_2CHANNEL, STBIR_RGB, STBIR_4CHANNEL, \n                    STBIR_BGRA, STBIR_ARGB, STBIR_RA, STBIR_AR,\n                    STBIR_RGBA_PM, STBIR_ARGB_PM, STBIR_RA_PM, STBIR_AR_PM,\n                    STBIR_RGBA, STBIR_ARGB, STBIR_RA, STBIR_AR,\n                    STBIR_RGBA_PM, STBIR_ARGB_PM, STBIR_RA_PM, STBIR_AR_PM,\n                  };\nint obuffers[20] = { STBIR_1CHANNEL, STBIR_2CHANNEL, STBIR_RGB, STBIR_4CHANNEL, \n                     STBIR_BGRA, STBIR_ARGB, STBIR_RA, STBIR_AR,\n                     STBIR_RGBA_PM, STBIR_ARGB_PM, STBIR_RA_PM, STBIR_AR_PM,\n                     STBIR_RGBA_PM, STBIR_ARGB_PM, STBIR_RA_PM, STBIR_AR_PM,\n                     STBIR_RGBA, STBIR_ARGB, STBIR_RA, STBIR_AR,\n                   };\n\nint bchannels[20] = { 1, 2, 3, 4,  4,4, 2,2,  4,4, 2,2,  4,4, 2,2,  4,4, 2,2  }; \nint alphapos[20] = { -1, -1, -1, -1,  3,0,  1,0,   3,0,  1,0,   3,0,  1,0,3,0,  1,0 }; \n\n\nchar const * buffstrs[20] = { \"1ch\", \"2ch\", \"3ch\", \"4ch\",  \"RGBA\", \"ARGB\", \"RA\", \"AR\",  \"RGBA_both_pre\", \"ARGB_both_pre\", \"RA_both_pre\", \"AR_both_pre\",  \"RGBA_out_pre\", \"ARGB_out_pre\", \"RA_out_pre\", \"AR_out_pre\",  \"RGBA_in_pre\", \"ARGB_in_pre\", \"RA_in_pre\", \"AR_in_pre\" };\nchar const * typestrs[5] =  { \"Bytes\", \"BytesSRGB\", \"Shorts\", \"Floats\", \"Half Floats\"};\nchar const * edgestrs[4] =  { \"Clamp\", \"Reflect\", \"Zero\", \"Wrap\" };\nchar const * fltstrs[5] =   { \"Box\", \"Triangle\", \"Cubic\", \"Catmullrom\", \"Mitchell\" };\n\n#ifdef STBIR_PROFILE\n  static void do_acc_zones( STBIR_PROFILE_INFO * profile )\n  {\n    stbir_uint32 j;\n    stbir_uint64 start = tmGetAccumulationStart( tm_mask ); start=start;\n\n    for( j = 0 ; j < profile->count ; j++ )\n    {\n      if ( profile->clocks[j] )\n        tmEmitAccumulationZone( 0, 0, (tm_uint64*)&start, 0, profile->clocks[j], profile->descriptions[j] );\n    }\n  }\n#else\n  #define do_acc_zones(...)\n#endif\n\nint64 vert;\n\n//#define WINTHREADTEST\n#ifdef WINTHREADTEST\n\nstatic STBIR_RESIZE * thread_resize;\nstatic LONG which;\nstatic int threads_started = 0;\nstatic HANDLE threads[32];\nstatic HANDLE starts,stops;\n  \nstatic DWORD resize_shim( LPVOID p )\n{\n  for(;;)\n  {\n    LONG wh;\n\n    WaitForSingleObject( starts, INFINITE );\n\n    wh = InterlockedAdd( &which, 1 ) - 1;\n\n    ENTER( \"Split %d\", wh );\n    stbir_resize_split( thread_resize, wh, 1 );\n  #ifdef STBIR_PROFILE\n    { STBIR_PROFILE_INFO profile; stbir_resize_split_profile_info( &profile, thread_resize, wh, 1 ); do_acc_zones( &profile ); vert = profile.clocks[1]; }\n  #endif\n    LEAVE();\n\n    ReleaseSemaphore( stops, 1, 0 );\n  }\n}\n\n#endif\n\nvoid nresize( void * o, int ox, int oy, int op, void * i, int ix, int iy, int ip, int buf, int type, int edg, int flt )\n{\n  STBIR_RESIZE resize;\n \n  stbir_resize_init( &resize, i, ix, iy, ip, o, ox, oy, op, buffers[buf], ttypes[type] );\n  stbir_set_pixel_layouts( &resize, buffers[buf], obuffers[buf] );\n  stbir_set_edgemodes( &resize, cedges[edg], cedges[edg] );\n  stbir_set_filters( &resize, flts[flt], /*STBIR_FILTER_POINT_SAMPLE */ flts[flt] );\n  //stbir_set_input_subrect( &resize, 0.55f,0.333f,0.75f,0.50f);\n  //stbir_set_output_pixel_subrect( &resize, 00, 00, ox/2,oy/2);\n  //stbir_set_pixel_subrect(&resize, 1430,1361,30,30);\n  \n  ENTER( \"Resize\" );\n \n  #ifndef WINTHREADTEST\n\n  ENTER( \"Filters\" );\n  stbir_build_samplers_with_splits( &resize, 1 );\n  #ifdef STBIR_PROFILE\n    { STBIR_PROFILE_INFO profile; stbir_resize_build_profile_info( &profile, &resize ); do_acc_zones( &profile ); }\n  #endif\n  LEAVE();\n \n  ENTER( \"Resize\" );\n  if(!stbir_resize_extended( &resize ) )\n    stop();\n  #ifdef STBIR_PROFILE\n    { STBIR_PROFILE_INFO profile; stbir_resize_extended_profile_info( &profile, &resize ); do_acc_zones( &profile ); vert = profile.clocks[1]; }\n  #endif\n  LEAVE();\n\n  #else\n  {\n    int c, cnt;\n \n    ENTER( \"Filters\" );\n    cnt =  stbir_build_samplers_with_splits( &resize, 4 );\n    #ifdef STBIR_PROFILE\n      { STBIR_PROFILE_INFO profile; stbir_resize_build_profile_info( &profile, &resize ); do_acc_zones( &profile ); }\n    #endif\n    LEAVE();\n    \n    ENTER( \"Thread start\" );\n    if ( threads_started == 0 )\n    {\n      starts = CreateSemaphore( 0, 0, 32, 0 );\n      stops = CreateSemaphore( 0, 0, 32, 0 );\n    }\n    for( c = threads_started ; c < cnt ; c++ )\n      threads[ c ] = CreateThread( 0, 2048*1024, resize_shim, 0, 0, 0 );\n    \n    threads_started = cnt;\n    thread_resize = &resize;\n    which = 0;\n    LEAVE();\n\n    // starts the threads\n    ReleaseSemaphore( starts, cnt, 0 );\n\n    ENTER( \"Wait\" );\n    for( c = 0 ; c < cnt; c++ )\n      WaitForSingleObject( stops, INFINITE );\n    LEAVE();\n  }\n  #endif\n\n  ENTER( \"Free\" );\n  stbir_free_samplers( &resize );\n  LEAVE();\n  LEAVE();\n}\n\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\nextern void oresize( void * o, int ox, int oy, int op, void * i, int ix, int iy, int ip, int buf, int type, int edg, int flt );\n\n\n\n#define TYPESTART 0\n#define TYPEEND   4\n\n#define LAYOUTSTART  0\n#define LAYOUTEND   19\n\n#define SIZEWSTART 0\n#define SIZEWEND   2\n\n#define SIZEHSTART 0\n#define SIZEHEND   2\n\n#define EDGESTART 0\n#define EDGEEND   3\n\n#define FILTERSTART 0\n#define FILTEREND   4\n\n#define HEIGHTSTART 0\n#define HEIGHTEND   2\n\n#define WIDTHSTART 0\n#define WIDTHEND   2\n\n\n\n\nstatic void * convert8to16( unsigned char * i, int w, int h, int c )\n{\n  unsigned short * ret;\n  int p;\n\n  ret = malloc( w*h*c*sizeof(short) );\n  for(p = 0 ; p < (w*h*c) ; p++ )\n  {\n    ret[p]=(short)((((int)i[p])<<8)+i[p]);\n  }\n\n  return ret;\n}\n\nstatic void * convert8tof( unsigned char * i, int w, int h, int c )\n{\n  float * ret;\n  int p;\n\n  ret = malloc( w*h*c*sizeof(float) );\n  for(p = 0 ; p < (w*h*c) ; p++ )\n  {\n    ret[p]=((float)i[p])*(1.0f/255.0f);\n  }\n\n  return ret;\n}\n\nstatic void * convert8tohf( unsigned char * i, int w, int h, int c )\n{\n  stbir__FP16 * ret;\n  int p;\n\n  ret = malloc( w*h*c*sizeof(stbir__FP16) );\n  for(p = 0 ; p < (w*h*c) ; p++ )\n  {\n    ret[p]=stbir__float_to_half(((float)i[p])*(1.0f/255.0f));\n  }\n\n  return ret;\n}\n\nstatic void * convert8tohff( unsigned char * i, int w, int h, int c )\n{\n  float * ret;\n  int p;\n\n  ret = malloc( w*h*c*sizeof(float) );\n  for(p = 0 ; p < (w*h*c) ; p++ )\n  {\n    ret[p]=stbir__half_to_float(stbir__float_to_half(((float)i[p])*(1.0f/255.0f)));\n  }\n\n  return ret;\n}\n\nstatic int isprime( int v )\n{\n  int i;\n\n  if ( v <= 3 )\n    return ( v > 1 );\n  if ( ( v & 1 ) == 0 )\n    return 0;\n  if ( ( v % 3 ) == 0 )\n    return 0;\n  i = 5;\n  while ( (i*i) <= v )\n  {\n    if ( ( v % i ) == 0 )\n      return 0;\n    if ( ( v % ( i + 2 ) ) == 0 )\n      return 0;\n    i += 6;\n  }\n\n  return 1;\n}\n\nstatic int getprime( int v )\n{\n  int i;\n  i = 0;\n  for(;;)\n  {\n    if ( i >= v )\n      return v;  // can't find any, just return orig\n    if (isprime(v - i))\n      return v - i;\n    if (isprime(v + i))\n      return v + i;\n    ++i;\n  }\n}\n\n\nint main( int argc, char ** argv )\n{\n  int ix, iy, ic;\n  unsigned char * input[6];\n  char * ir1;\n  char * ir2;\n  int szhs[3];\n  int szws[3];\n  int aw, ah, ac;\n  unsigned char * correctalpha;\n  int layouts, types, heights, widths, edges, filters;\n\n  if ( argc != 2 )\n  {\n    printf(\"command: stbirtest [imagefile]\\n\");\n    exit(1);\n  }\n\n  SetupTM( \"127.0.0.1\" );\n\n  correctalpha = stbi_load( \"correctalpha.png\", &aw, &ah, &ac, 0 );\n\n  input[0] = stbi_load( argv[1], &ix, &iy, &ic, 0 );\n  input[1] = input[0];\n  input[2] = convert8to16( input[0], ix, iy, ic );\n  input[3] = convert8tof( input[0], ix, iy, ic );\n  input[4] = convert8tohf( input[0], ix, iy, ic );\n  input[5] = convert8tohff( input[0], ix, iy, ic );\n\n  printf(\"Input %dx%d (%d channels)\\n\",ix,iy,ic);\n\n  ir1 = malloc( 4 * 4 * 3000 * 3000ULL );\n  ir2 = malloc( 4 * 4 * 3000 * 3000ULL );\n\n  szhs[0] = getprime( iy/SHRINKBYH );\n  szhs[1] = iy;\n  szhs[2] = getprime( iy*ZOOMBYH );\n\n  szws[0] = getprime( ix/SHRINKBYW );\n  szws[1] = ix;\n  szws[2] = getprime( ix*ZOOMBYW );\n\n  #if 1\n  for( types = TYPESTART ; types <= TYPEEND ; types++ )\n  #else\n  for( types = 1 ; types <= 1 ; types++ )\n  #endif\n  {\n    ENTER( \"Test type: %s\",typestrs[types]);\n    #if 1\n    for( layouts = LAYOUTSTART ; layouts <= LAYOUTEND ; layouts++ )\n    #else\n    for( layouts = 16; layouts <= 16 ; layouts++ )\n    #endif\n    {\n      ENTER( \"Test layout: %s\",buffstrs[layouts]);\n      \n      #if 0\n      for( heights = HEIGHTSTART ; heights <= HEIGHTEND ; heights++ )\n      {\n        int w, h = szhs[heights];\n      #else\n      for( heights = 0 ; heights <= 11 ; heights++ )\n      {\n        static int szhsz[12]={32, 200, 350, 400, 450, 509, 532, 624, 700, 824, 1023, 2053 };\n        int w, h = szhsz[heights];\n      #endif\n\n        ENTER( \"Test height: %d %s %d\",iy,(h<iy)?\"Down\":((h>iy)?\"Up\":\"Same\"),h);\n  \n        #if 0\n        for( widths = WIDTHSTART ; widths <= WIDTHEND ; widths++ )\n        {\n          w = szws[widths];\n        #else\n        for( widths = 0 ; widths <= 12 ; widths++ )\n        {\n          static int szwsz[13]={2, 32, 200, 350, 400, 450, 509, 532, 624, 700, 824, 1023, 2053 };\n          w = szwsz[widths];\n        #endif\n\n          ENTER( \"Test width: %d %s %d\",ix, (w<ix)?\"Down\":((w>ix)?\"Up\":\"Same\"), w);\n\n          #if 0\n          for( edges = EDGESTART ; edges <= EDGEEND ; edges++ )\n          #else\n          for( edges = 0 ; edges <= 0 ; edges++ )\n          #endif\n          {\n            ENTER( \"Test edge: %s\",edgestrs[edges]);\n            #if 0\n            for( filters = FILTERSTART ; filters <= FILTEREND ; filters++ )\n            #else\n            for( filters = 3 ; filters <= 3 ; filters++ )\n            #endif\n            {\n              int op, opw, np,npw, c, a;\n              #ifdef COMPARE_SAME                        \n              int oldtypes = types;\n              #else\n              int oldtypes = (types==4)?3:types;\n              #endif\n            \n              ENTER( \"Test filter: %s\",fltstrs[filters]);\n              {\n                c = bchannels[layouts];\n                a = alphapos[layouts];\n\n                op = w*tsizes[oldtypes]*c + 60;\n                opw = w*tsizes[oldtypes]*c;\n\n                np = w*tsizes[types]*c + 60;\n                npw = w*tsizes[types]*c;\n\n                printf( \"%s:layout: %s  w: %d h: %d edge: %s filt: %s\\n\", typestrs[types],buffstrs[layouts], w, h, edgestrs[edges], fltstrs[filters] );\n\n\n                // clear pixel area to different, right edge to zero\n                #ifndef NOCLEAR\n                ENTER( \"Test clear padding\" );\n                {\n                  int d;\n                  for( d = 0 ; d < h ; d++ )\n                  {\n                    int oofs = d * op;\n                    int nofs = d * np;\n                    memset( ir1 + oofs, 192, opw );\n                    memset( ir1 + oofs+opw, 79, op-opw );\n                    memset( ir2 + nofs, 255, npw );\n                    memset( ir2 + nofs+npw, 79, np-npw );\n                  }\n                }\n                LEAVE();\n\n                #endif\n\n                #ifdef COMPARE_SAME                        \n                #define TIMINGS 1\n                #else \n                #define TIMINGS 1\n                #endif\n                ENTER( \"Test both\" );\n                {\n                  #ifndef PROFILE_NEW_ONLY\n                    {\n                      int ttt, max = 0x7fffffff;\n                      ENTER( \"Test old\" );\n                      for( ttt = 0 ; ttt < TIMINGS ; ttt++ )\n                      {\n                        int64 m = __cycles();\n\n                        oresize( ir1, w, h, op, \n                        #ifdef COMPARE_SAME                        \n                        input[types], \n                        #else\n                        input[(types==4)?5:types], \n                        #endif\n                        ix, iy, ix*ic*tsizes[oldtypes], layouts, oldtypes, edges, filters );\n\n                        m = __cycles() - m;\n                        if ( ( (int)m ) < max )\n                        max = (int) m;\n                      }\n                      LEAVE();\n                      printf(\"old: %d\\n\", max );\n                    }\n                  #endif\n     \n                  {\n                    int ttt, max = 0x7fffffff, maxv = 0x7fffffff;\n                    ENTER( \"Test new\" );\n                    for( ttt = 0 ; ttt < TIMINGS ; ttt++ )\n                    {\n                      int64 m = __cycles();\n\n                      nresize( ir2, w, h, np, input[types], ix, iy, ix*ic*tsizes[types], layouts, types, edges, filters );\n        \n                      m = __cycles() - m;\n                      if ( ( (int)m ) < max )\n                        max = (int) m;\n                      if ( ( (int)vert ) < maxv )\n                        maxv = (int) vert;\n                    }\n                    LEAVE(); // test new\n                    printf(\"new: %d (v: %d)\\n\", max, maxv );\n                  }\n                }\n                LEAVE();  // test both\n\n                if ( mem_count!= 0 )\n                  stop();\n\n              #ifndef NOCOMP\n                ENTER( \"Test compare\" );\n                {\n                  int x,y,ch;\n                  int nums = 0;\n                  for( y = 0 ; y < h ; y++ )\n                  {\n                    for( x = 0 ; x < w ; x++ )\n                    {\n                      switch(types)\n                      {\n                        case 0:\n                        case 1: //SRGB \n                        {\n                          unsigned char * p1 = (unsigned char *)&ir1[y*op+x*c];\n                          unsigned char * p2 = (unsigned char *)&ir2[y*np+x*c];\n                          for( ch = 0 ; ch < c ; ch++ )\n                          {\n                            float pp1,pp2,d;\n                            float av = (a==-1)?1.0f:((float)p1[a]/255.0f);\n\n                            pp1 = p1[ch];\n                            pp2 = p2[ch];\n\n                            // compare in premult space\n                            #ifndef COMPARE_SAME                        \n                            if ( ( ( layouts >=4 ) && ( layouts <= 7 ) ) || ( ( layouts >=16 ) && ( layouts <= 19 ) ) )\n                            {\n                              pp1 *= av;\n                              pp2 *= av;\n                            }\n                            #endif\n\n                            d = pp1 - pp2;\n                            if ( d < 0 ) d = -d;\n\n                            #ifdef COMPARE_SAME                        \n                            if ( d > 0 ) \n                            #else \n                            if ( d > 1 )\n                            #endif\n                            {\n                              printf(\"Error at %d x %d (chan %d) (d: %g a: %g) [%d %d %d %d] [%d %d %d %d]\\n\",x,y,ch, d,av, p1[0],p1[1],p1[2],p1[3], p2[0],p2[1],p2[2],p2[3]);\n                              ++nums;\n                              if ( nums > 16 ) goto ex;\n                              //if (d) exit(1);\n                              //goto ex;\n                            }\n                          }  \n                        }\n                        break;\n\n                        case 2:\n                        {\n                          unsigned short * p1 = (unsigned short *)&ir1[y*op+x*c*sizeof(short)];\n                          unsigned short * p2 = (unsigned short *)&ir2[y*np+x*c*sizeof(short)];\n                          for( ch = 0 ; ch < c ; ch++ )\n                          {\n                            float thres,pp1,pp2,d;\n                            float av = (a==-1)?1.0f:((float)p1[a]/65535.0f);\n\n                            pp1 = p1[ch];\n                            pp2 = p2[ch];\n\n                            // compare in premult space\n                            #ifndef COMPARE_SAME                        \n                            if ( ( ( layouts >=4 ) && ( layouts <= 7 ) ) || ( ( layouts >= 16 ) && ( layouts <= 19 ) ) )\n                            {\n                              pp1 *= av;\n                              pp2 *= av;\n                            }\n                            #endif\n\n                            d = pp1 - pp2;\n                            if ( d < 0 ) d = -d;\n\n                            thres=((float)p1[ch]*0.007f)+2.0f;\n                            if (thres<4) thres = 4;\n  \n                            #ifdef COMPARE_SAME                        \n                            if ( d > 0 ) \n                            #else \n                            if ( d > thres)\n                            #endif\n                            {\n                              printf(\"Error at %d x %d (chan %d) %d %d [df: %g th: %g al: %g] (%d %d %d %d) (%d %d %d %d)\\n\",x,y,ch, p1[ch],p2[ch],d,thres,av,p1[0],p1[1],p1[2],p1[3],p2[0],p2[1],p2[2],p2[3]);\n                              ++nums;\n                              if ( nums > 16 ) goto ex;\n                              //if (d) exit(1);\n                              //goto ex;\n                            }\n                          }\n                        }\n                        break;\n\n                        case 3:\n                        {\n                          float * p1 = (float *)&ir1[y*op+x*c*sizeof(float)];\n                          float * p2 = (float *)&ir2[y*np+x*c*sizeof(float)];\n                          for( ch = 0 ; ch < c ; ch++ )\n                          {\n                            float pp1 = p1[ch], pp2 = p2[ch];\n                            float av = (a==-1)?1.0f:p1[a];\n                            float thres, d;\n\n                            // clamp\n                            if (pp1<=0.0f) pp1 = 0;\n                            if (pp2<=0.0f) pp2 = 0;\n                            if (av<=0.0f) av = 0;\n                            if (pp1>1.0f) pp1 = 1.0f;\n                            if (pp2>1.0f) pp2 = 1.0f;\n                            if (av>1.0f) av = 1.0f;\n\n                            // compare in premult space\n                            #ifndef COMPARE_SAME                        \n                            if ( ( ( layouts >=4 ) && ( layouts <= 7 ) ) || ( ( layouts >= 16 ) && ( layouts <= 19 ) ) )\n                            {\n                              pp1 *= av;\n                              pp2 *= av;\n                            }\n                            #endif\n\n                            d = pp1 - pp2;\n                            if ( d < 0 ) d = -d;\n\n                            thres=(p1[ch]*0.002f)+0.0002f;\n                            if ( thres < 0 ) thres = -thres;\n\n                            #ifdef COMPARE_SAME                        \n                            if ( d != 0.0f ) \n                            #else \n                            if ( d > thres )\n                            #endif\n                            {\n                              printf(\"Error at %d x %d (chan %d) %g %g [df: %g th: %g al: %g] (%g %g %g %g) (%g %g %g %g)\\n\",x,y,ch, p1[ch],p2[ch],d,thres,av,p1[0],p1[1],p1[2],p1[3],p2[0],p2[1],p2[2],p2[3]);\n                              ++nums;\n                              if ( nums > 16 ) goto ex;\n                              //if (d) exit(1);\n                              //goto ex;\n                            }\n                          }\n                        }\n                        break;\n\n                        case 4:\n                        {\n                          #ifdef COMPARE_SAME                        \n                          stbir__FP16 * p1 = (stbir__FP16 *)&ir1[y*op+x*c*sizeof(stbir__FP16)];\n                          #else\n                          float * p1 = (float *)&ir1[y*op+x*c*sizeof(float)];\n                          #endif\n                          stbir__FP16 * p2 = (stbir__FP16 *)&ir2[y*np+x*c*sizeof(stbir__FP16)];\n                          for( ch = 0 ; ch < c ; ch++ )\n                          {\n                            #ifdef COMPARE_SAME                        \n                            float pp1  = stbir__half_to_float(p1[ch]);\n                            float av = (a==-1)?1.0f:stbir__half_to_float(p1[a]);\n                            #else\n                            float pp1 = stbir__half_to_float(stbir__float_to_half(p1[ch]));\n                            float av = (a==-1)?1.0f:stbir__half_to_float(stbir__float_to_half(p1[a]));\n                            #endif\n                            float pp2 = stbir__half_to_float(p2[ch]);\n                            float d, thres;\n\n                            // clamp\n                            if (pp1<=0.0f) pp1 = 0;\n                            if (pp2<=0.0f) pp2 = 0;\n                            if (av<=0.0f) av = 0;\n                            if (pp1>1.0f) pp1 = 1.0f;\n                            if (pp2>1.0f) pp2 = 1.0f;\n                            if (av>1.0f) av = 1.0f;\n\n                            thres=(pp1*0.002f)+0.0002f;\n\n                            // compare in premult space\n                            #ifndef COMPARE_SAME                        \n                            if ( ( ( layouts >=4 ) && ( layouts <= 7 ) ) || ( ( layouts >= 16 ) && ( layouts <= 19 ) ) )\n                            {\n                              pp1 *= av;\n                              pp2 *= av;\n                            }\n                            #endif\n\n                            d = pp1 - pp2;\n                            if ( d < 0 ) d = -d;\n\n\n                            #ifdef COMPARE_SAME                        \n                            if ( d != 0.0f ) \n                            #else \n                            if ( d > thres )\n                            #endif\n                            {\n                              printf(\"Error at %d x %d (chan %d) %g %g [df: %g th: %g al: %g] (%g %g %g %g) (%g %g %g %g)\\n\",x,y,ch, \n                              #ifdef COMPARE_SAME                        \n                              stbir__half_to_float(p1[ch]), \n                              #else\n                              p1[ch],\n                              #endif\n                              stbir__half_to_float(p2[ch]), \n                              d,thres,av,\n                              #ifdef COMPARE_SAME                        \n                              stbir__half_to_float(p1[0]),stbir__half_to_float(p1[1]),stbir__half_to_float(p1[2]),stbir__half_to_float(p1[3]),\n                              #else\n                              p1[0],p1[1],p1[2],p1[3],\n                              #endif\n                              stbir__half_to_float(p2[0]),stbir__half_to_float(p2[1]),stbir__half_to_float(p2[2]),stbir__half_to_float(p2[3]) );\n                              ++nums;\n                              if ( nums > 16 ) goto ex;\n                              //if (d) exit(1);\n                              //goto ex;\n                            }\n                          }\n                        }\n                        break;\n                      }\n                    }\n\n                    for( x = (w*c)*tsizes[oldtypes]; x < op; x++ )\n                    {\n                      if ( ir1[y*op+x] != 79 )\n                      {\n                        printf(\"Margin error at %d x %d %d (should be 79) OLD!\\n\",x,y,(unsigned char)ir1[y*op+x]);\n                        goto ex;\n                      }\n                    }\n\n                    for( x = (w*c)*tsizes[types]; x < np; x++ )\n                    {\n                      if ( ir2[y*np+x] != 79 )\n                      {\n                        printf(\"Margin error at %d x %d %d (should be 79) NEW\\n\",x,y,(unsigned char)ir2[y*np+x]);\n                        goto ex;\n                      }\n                    }\n                  }\n                \n                  ex:\n                  ENTER( \"OUTPUT IMAGES\" );\n                  printf(\"  tot pix: %d, errs: %d\\n\", w*h*c,nums );\n\n                  if (nums)\n                  {\n                    stbi_write_png(\"old.png\", w, h, c, ir1, op);\n                    stbi_write_png(\"new.png\", w, h, c, ir2, np);\n                    exit(1);\n                  }\n\n                  LEAVE(); // output images\n                }\n                LEAVE(); //test compare\n              #endif\n\n\n\n              }\n              LEAVE(); // test filter\n            }\n            LEAVE(); // test edge\n          }\n          LEAVE(); // test width\n        }\n        LEAVE(); // test height\n      }\n      LEAVE(); // test type\n    }\n    LEAVE();  // test layout\n  }\n\n  CloseTM();\n  return 0;\n}\n"
  },
  {
    "path": "stb_image_resize_test/vf_train.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define stop() __debugbreak()\n#include <windows.h>\n#define int64 __int64\n\n#pragma warning(disable:4127)\n\n#define STBIR__WEIGHT_TABLES  \n#define STBIR_PROFILE\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#include \"stb_image_resize2.h\"  \n\nstatic int * file_read( char const * filename )\n{\n  size_t s;\n  int * m;\n  FILE * f = fopen( filename, \"rb\" );\n  if ( f == 0 ) return 0;\n  \n  fseek( f, 0, SEEK_END);\n  s = ftell( f );\n  fseek( f, 0, SEEK_SET);\n  m = malloc( s + 4 );\n  m[0] = (int)s;\n  fread( m+1, 1, s, f);\n  fclose(f);\n\n  return( m );\n}\n\ntypedef struct fileinfo\n{\n  int * timings;\n  int timing_count;\n  int dimensionx, dimensiony;\n  int numtypes;\n  int * types;\n  int * effective;\n  int cpu;\n  int simd;\n  int numinputrects;\n  int * inputrects;\n  int outputscalex, outputscaley;\n  int milliseconds;\n  int64 cycles;\n  double scale_time;\n  int bitmapx, bitmapy;\n  char const * filename;\n} fileinfo;\n\nint numfileinfo;\nfileinfo fi[256];\nunsigned char * bitmap;\nint bitmapw, bitmaph, bitmapp;\n\nstatic int use_timing_file( char const * filename, int index )\n{\n  int * base = file_read( filename );\n  int * file = base;\n\n  if ( base == 0 ) return 0;\n\n  ++file; // skip file image size;\n  if ( *file++ != 'VFT1' ) return 0;\n  fi[index].cpu = *file++;\n  fi[index].simd = *file++;\n  fi[index].dimensionx = *file++;\n  fi[index].dimensiony = *file++;\n  fi[index].numtypes = *file++;\n  fi[index].types = file; file += fi[index].numtypes;\n  fi[index].effective = file; file += fi[index].numtypes;\n  fi[index].numinputrects = *file++;\n  fi[index].inputrects = file; file += fi[index].numinputrects * 2;\n  fi[index].outputscalex = *file++;\n  fi[index].outputscaley = *file++;\n  fi[index].milliseconds = *file++;\n  fi[index].cycles = ((int64*)file)[0]; file += 2;\n  fi[index].filename = filename;\n\n  fi[index].timings = file;\n  fi[index].timing_count = (int) ( ( base[0] - ( ((char*)file - (char*)base - sizeof(int) ) ) ) / (sizeof(int)*2) );\n\n  fi[index].scale_time = (double)fi[index].milliseconds / (double)fi[index].cycles;\n\n  return 1;\n}\n\nstatic int vert_first( float weights_table[STBIR_RESIZE_CLASSIFICATIONS][4], int ox, int oy, int ix, int iy, int filter, STBIR__V_FIRST_INFO * v_info )\n{\n  float h_scale=(float)ox/(float)(ix);\n  float v_scale=(float)oy/(float)(iy);\n  stbir__support_callback * support = stbir__builtin_supports[filter];\n  int vertical_filter_width = stbir__get_filter_pixel_width(support,v_scale,0);\n  int vertical_gather = ( v_scale >= ( 1.0f - stbir__small_float ) ) || ( vertical_filter_width <= STBIR_FORCE_GATHER_FILTER_SCANLINES_AMOUNT );\n\n  return stbir__should_do_vertical_first( weights_table, stbir__get_filter_pixel_width(support,h_scale,0), h_scale, ox, vertical_filter_width, v_scale, oy, vertical_gather, v_info );\n} \n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\nstatic void alloc_bitmap()\n{\n  int findex;\n  int x = 0, y = 0;\n  int w = 0, h = 0;\n\n  for( findex = 0 ; findex < numfileinfo ; findex++ )\n  {\n    int nx, ny;\n    int thisw, thish;\n\n    thisw = ( fi[findex].dimensionx * fi[findex].numtypes ) + ( fi[findex].numtypes - 1 );\n    thish = ( fi[findex].dimensiony * fi[findex].numinputrects ) + ( fi[findex].numinputrects - 1 );\n\n    for(;;)\n    {\n      nx = x + ((x)?4:0) + thisw;\n      ny = y + ((y)?4:0) + thish;\n      if ( ( nx <= 3600 ) || ( x == 0 ) )\n      { \n        fi[findex].bitmapx = x + ((x)?4:0);\n        fi[findex].bitmapy = y + ((y)?4:0);\n        x = nx;\n        if ( x > w ) w = x;\n        if ( ny > h ) h = ny;\n        break;\n      }\n      else\n      {\n        x = 0;\n        y = h;\n      }\n    }\n  }\n\n  w = (w+3) & ~3;\n  bitmapw = w;\n  bitmaph = h;\n  bitmapp = w * 3; // RGB\n  bitmap = malloc( bitmapp * bitmaph );\n\n  memset( bitmap, 0, bitmapp * bitmaph );\n}\n\nstatic void build_bitmap( float weights[STBIR_RESIZE_CLASSIFICATIONS][4], int do_channel_count_index, int findex )\n{\n  static int colors[STBIR_RESIZE_CLASSIFICATIONS];\n  STBIR__V_FIRST_INFO v_info = {0};\n\n  int * ts;\n  int ir;\n  unsigned char * bitm = bitmap + ( fi[findex].bitmapx*3 ) + ( fi[findex].bitmapy*bitmapp) ;\n\n  for( ir = 0; ir < STBIR_RESIZE_CLASSIFICATIONS ; ir++ ) colors[ ir ] = 127*ir/STBIR_RESIZE_CLASSIFICATIONS+128;\n\n  ts = fi[findex].timings;\n\n  for( ir = 0 ; ir < fi[findex].numinputrects ; ir++ )\n  {\n    int ix, iy, chanind;\n    ix = fi[findex].inputrects[ir*2];\n    iy = fi[findex].inputrects[ir*2+1];\n\n    for( chanind = 0 ; chanind < fi[findex].numtypes ; chanind++ )\n    {\n      int ofs, h, hh;\n\n      // just do the type that we're on\n      if ( chanind != do_channel_count_index )\n      {\n        ts += 2 * fi[findex].dimensionx * fi[findex].dimensiony;\n        continue;\n      }\n\n      // bitmap offset\n      ofs=chanind*(fi[findex].dimensionx+1)*3+ir*(fi[findex].dimensiony+1)*bitmapp;\n\n      h = 1;\n      for( hh = 0 ; hh < fi[findex].dimensiony; hh++ )\n      {\n        int ww, w = 1;\n        for( ww = 0 ; ww < fi[findex].dimensionx; ww++ )\n        {\n          int good, v_first, VF, HF;\n\n          VF = ts[0];\n          HF = ts[1];\n\n          v_first = vert_first( weights, w, h, ix, iy, STBIR_FILTER_MITCHELL, &v_info );\n\n          good = ( ((HF<=VF) && (!v_first)) || ((VF<=HF) && (v_first)));\n\n          if ( good )\n          {\n            bitm[ofs+2] = 0;\n            bitm[ofs+1] = (unsigned char)colors[v_info.v_resize_classification];\n          }\n          else\n          {\n            double r;\n\n            if ( HF < VF )\n              r = (double)(VF-HF)/(double)HF;\n            else\n              r = (double)(HF-VF)/(double)VF;\n            \n            if ( r > 0.4f) r = 0.4;\n            r *= 1.0f/0.4f;   \n\n            bitm[ofs+2] = (char)(255.0f*r);\n            bitm[ofs+1] = (char)(((float)colors[v_info.v_resize_classification])*(1.0f-r));\n          }\n          bitm[ofs] = 0;\n\n          ofs += 3;\n          ts += 2;\n          w += fi[findex].outputscalex;\n        }\n        ofs += bitmapp - fi[findex].dimensionx*3;\n        h += fi[findex].outputscaley;\n      }\n    }\n  }\n}\n\nstatic void build_comp_bitmap( float weights[STBIR_RESIZE_CLASSIFICATIONS][4], int do_channel_count_index )\n{\n  int * ts0;\n  int * ts1;\n  int ir;\n  unsigned char * bitm = bitmap + ( fi[0].bitmapx*3 ) + ( fi[0].bitmapy*bitmapp) ;\n\n  ts0 = fi[0].timings;\n  ts1 = fi[1].timings;\n\n  for( ir = 0 ; ir < fi[0].numinputrects ; ir++ )\n  {\n    int ix, iy, chanind;\n    ix = fi[0].inputrects[ir*2];\n    iy = fi[0].inputrects[ir*2+1];\n\n    for( chanind = 0 ; chanind < fi[0].numtypes ; chanind++ )\n    {\n      int ofs, h, hh;\n\n      // just do the type that we're on\n      if ( chanind != do_channel_count_index )\n      {\n        ts0 += 2 * fi[0].dimensionx * fi[0].dimensiony;\n        ts1 += 2 * fi[0].dimensionx * fi[0].dimensiony;\n        continue;\n      }\n\n      // bitmap offset\n      ofs=chanind*(fi[0].dimensionx+1)*3+ir*(fi[0].dimensiony+1)*bitmapp;\n\n      h = 1;\n      for( hh = 0 ; hh < fi[0].dimensiony; hh++ )\n      {\n        int ww, w = 1;\n        for( ww = 0 ; ww < fi[0].dimensionx; ww++ )\n        {\n          int v_first, time0, time1;\n\n          v_first = vert_first( weights, w, h, ix, iy, STBIR_FILTER_MITCHELL, 0 );\n\n          time0 = ( v_first ) ? ts0[0] : ts0[1];\n          time1 = ( v_first ) ? ts1[0] : ts1[1];\n\n          if ( time0 < time1 )\n          {\n            double r = (double)(time1-time0)/(double)time0;\n            if ( r > 0.4f) r = 0.4;\n            r *= 1.0f/0.4f;   \n            bitm[ofs+2] = 0;\n            bitm[ofs+1] = (char)(255.0f*r);\n            bitm[ofs] = (char)(64.0f*(1.0f-r));\n          }\n          else\n          {\n            double r = (double)(time0-time1)/(double)time1;\n            if ( r > 0.4f) r = 0.4;\n            r *= 1.0f/0.4f;   \n            bitm[ofs+2] = (char)(255.0f*r);\n            bitm[ofs+1] = 0;\n            bitm[ofs] = (char)(64.0f*(1.0f-r));\n          }\n          ofs += 3;\n          ts0 += 2;\n          ts1 += 2;\n          w += fi[0].outputscalex;\n        }\n        ofs += bitmapp - fi[0].dimensionx*3;\n        h += fi[0].outputscaley;\n      }\n    }\n  }\n}\n\nstatic void write_bitmap()\n{\n  stbi_write_png( \"results.png\", bitmapp / 3, bitmaph, 3|STB_IMAGE_BGR, bitmap, bitmapp );\n}\n\n\nstatic void calc_errors( float weights_table[STBIR_RESIZE_CLASSIFICATIONS][4], int * curtot, double * curerr, int do_channel_count_index )\n{\n  int th, findex;\n  STBIR__V_FIRST_INFO v_info = {0};\n\n  for(th=0;th<STBIR_RESIZE_CLASSIFICATIONS;th++)\n  {\n    curerr[th]=0;\n    curtot[th]=0;\n  }\n\n  for( findex = 0 ; findex < numfileinfo ; findex++ )\n  {\n    int * ts;\n    int ir;\n    ts = fi[findex].timings;\n\n    for( ir = 0 ; ir < fi[findex].numinputrects ; ir++ )\n    {\n      int ix, iy, chanind;\n      ix = fi[findex].inputrects[ir*2];\n      iy = fi[findex].inputrects[ir*2+1];\n\n      for( chanind = 0 ; chanind < fi[findex].numtypes ; chanind++ )\n      {\n        int h, hh;\n\n        // just do the type that we're on\n        if ( chanind != do_channel_count_index )\n        {\n          ts += 2 * fi[findex].dimensionx * fi[findex].dimensiony;\n          continue;\n        }\n\n        h = 1;\n        for( hh = 0 ; hh < fi[findex].dimensiony; hh++ )\n        {\n          int ww, w = 1;\n          for( ww = 0 ; ww < fi[findex].dimensionx; ww++ )\n          {\n            int good, v_first, VF, HF;\n\n            VF = ts[0];\n            HF = ts[1];\n\n            v_first = vert_first( weights_table, w, h, ix, iy, STBIR_FILTER_MITCHELL, &v_info );\n\n            good = ( ((HF<=VF) && (!v_first)) || ((VF<=HF) && (v_first)));\n\n            if ( !good )\n            {\n              double diff;\n              if ( VF < HF )\n                diff = ((double)HF-(double)VF) * fi[findex].scale_time;\n              else\n                diff = ((double)VF-(double)HF) * fi[findex].scale_time;\n\n              curtot[v_info.v_resize_classification] += 1;\n              curerr[v_info.v_resize_classification] += diff;\n            }\n\n            ts += 2;\n            w += fi[findex].outputscalex;\n          }\n          h += fi[findex].outputscaley;\n        }\n      }\n    }\n  }\n}\n\n#define TRIESPERWEIGHT 32\n#define MAXRANGE ((TRIESPERWEIGHT+1) * (TRIESPERWEIGHT+1) * (TRIESPERWEIGHT+1) * (TRIESPERWEIGHT+1) - 1)\n\nstatic void expand_to_floats( float * weights, int range )\n{\n  weights[0] = (float)( range % (TRIESPERWEIGHT+1) ) / (float)TRIESPERWEIGHT;\n  weights[1] = (float)( range/(TRIESPERWEIGHT+1) % (TRIESPERWEIGHT+1) ) / (float)TRIESPERWEIGHT;\n  weights[2] = (float)( range/(TRIESPERWEIGHT+1)/(TRIESPERWEIGHT+1) % (TRIESPERWEIGHT+1) ) / (float)TRIESPERWEIGHT;\n  weights[3] = (float)( range/(TRIESPERWEIGHT+1)/(TRIESPERWEIGHT+1)/(TRIESPERWEIGHT+1) % (TRIESPERWEIGHT+1) ) / (float)TRIESPERWEIGHT;\n}\n\nstatic char const * expand_to_string( int range )\n{\n  static char str[128];\n  int w0,w1,w2,w3;\n  w0 = range % (TRIESPERWEIGHT+1);\n  w1 = range/(TRIESPERWEIGHT+1) % (TRIESPERWEIGHT+1);\n  w2 = range/(TRIESPERWEIGHT+1)/(TRIESPERWEIGHT+1) % (TRIESPERWEIGHT+1);\n  w3 = range/(TRIESPERWEIGHT+1)/(TRIESPERWEIGHT+1)/(TRIESPERWEIGHT+1) % (TRIESPERWEIGHT+1);\n  sprintf( str, \"[ %2d/%d %2d/%d %2d/%d %2d/%d ]\",w0,TRIESPERWEIGHT,w1,TRIESPERWEIGHT,w2,TRIESPERWEIGHT,w3,TRIESPERWEIGHT );\n  return str;\n}\n\nstatic void print_weights( float weights[STBIR_RESIZE_CLASSIFICATIONS][4], int channel_count_index, int * tots, double * errs )\n{\n  int th;\n  printf(\"ChInd: %d  Weights:\\n\",channel_count_index);\n  for(th=0;th<STBIR_RESIZE_CLASSIFICATIONS;th++)\n  {\n    float * w = weights[th];\n    printf(\"  %d: [%1.5f %1.5f %1.5f %1.5f] (%d %.4f)\\n\",th, w[0], w[1], w[2], w[3], tots[th], errs[th] );\n  }\n  printf(\"\\n\");\n}\n\nstatic int windowranges[ 16 ];\nstatic int windowstatus = 0;\nstatic DWORD trainstart = 0;\n\nstatic void opt_channel( float best_output_weights[STBIR_RESIZE_CLASSIFICATIONS][4], int channel_count_index )\n{\n  int newbest = 0;\n  float weights[STBIR_RESIZE_CLASSIFICATIONS][4] = {0};\n  double besterr[STBIR_RESIZE_CLASSIFICATIONS];\n  int besttot[STBIR_RESIZE_CLASSIFICATIONS];\n  int best[STBIR_RESIZE_CLASSIFICATIONS]={0};\n\n  double curerr[STBIR_RESIZE_CLASSIFICATIONS];\n  int curtot[STBIR_RESIZE_CLASSIFICATIONS];\n  int th, range;\n  DWORD lasttick = 0;\n\n  for(th=0;th<STBIR_RESIZE_CLASSIFICATIONS;th++) \n  {\n    besterr[th]=1000000000000.0;\n    besttot[th]=0x7fffffff;\n  }\n\n  newbest = 0;\n\n  // try the whole range  \n  range = MAXRANGE;\n  do\n  {\n    for(th=0;th<STBIR_RESIZE_CLASSIFICATIONS;th++)\n      expand_to_floats( weights[th], range );\n\n    calc_errors( weights, curtot, curerr, channel_count_index );\n\n    for(th=0;th<STBIR_RESIZE_CLASSIFICATIONS;th++)\n    {\n      if ( curerr[th] < besterr[th] )\n      {\n        besterr[th] = curerr[th];\n        besttot[th] = curtot[th];\n        best[th] = range;\n        expand_to_floats( best_output_weights[th], best[th] );\n        newbest = 1;\n      }\n    }\n\n    {\n      DWORD t = GetTickCount();\n      if ( range == 0 )\n        goto do_bitmap;\n\n      if ( newbest )\n      {\n        if ( ( GetTickCount() - lasttick ) > 200 )\n        {\n          int findex;\n        \n         do_bitmap:\n          lasttick = t;\n          newbest = 0;\n\n          for( findex = 0 ; findex < numfileinfo ; findex++ )\n            build_bitmap( best_output_weights, channel_count_index, findex );\n\n          lasttick = GetTickCount();\n        }\n      }\n    }\n   \n    windowranges[ channel_count_index ] = range;\n\n    // advance all the weights and loop\n    --range;\n  } while( ( range >= 0 ) && ( !windowstatus ) );\n\n  // if we hit here, then we tried all weights for this opt, so save them \n}\n\nstatic void print_struct( float weight[5][STBIR_RESIZE_CLASSIFICATIONS][4], char const * name )\n{\n  printf(\"\\n\\nstatic float %s[5][STBIR_RESIZE_CLASSIFICATIONS][4]=\\n{\", name );\n  {\n    int i;\n    for(i=0;i<5;i++) \n    { \n      int th;\n      for(th=0;th<STBIR_RESIZE_CLASSIFICATIONS;th++)\n      {\n        int j;\n        printf(\"\\n  \"); \n        for(j=0;j<4;j++) \n          printf(\"%1.5ff, \", weight[i][th][j] ); \n      }\n      printf(\"\\n\");\n    }\n    printf(\"\\n};\\n\");\n  }\n}\n\nstatic float retrain_weights[5][STBIR_RESIZE_CLASSIFICATIONS][4];\n\nstatic DWORD __stdcall retrain_shim( LPVOID p )\n{\n  int chanind = (int) (size_t)p;\n  opt_channel( retrain_weights[chanind], chanind );\n  return 0;\n}\n\nstatic char const * gettime( int ms )\n{\n  static char time[32];\n  if (ms > 60000)\n    sprintf( time, \"%dm %ds\",ms/60000, (ms/1000)%60 );\n  else  \n    sprintf( time, \"%ds\",ms/1000 );\n  return time;\n}\n\nstatic BITMAPINFOHEADER bmiHeader;\nstatic DWORD extrawindoww, extrawindowh;\nstatic HINSTANCE instance;\nstatic int curzoom = 1;\n\nstatic LRESULT WINAPI WindowProc( HWND   window,\n                                  UINT   message,\n                                  WPARAM wparam,\n                                  LPARAM lparam )\n{\n  switch( message )\n  {\n    case WM_CHAR:\n      if ( wparam != 27 )\n        break;\n      // falls through\n\n    case WM_CLOSE:\n    {\n      int i;\n      int max = 0;\n      \n      for( i = 0 ; i < fi[0].numtypes ; i++ )\n        if( windowranges[i] > max ) max = windowranges[i];\n   \n      if ( ( max == 0 ) || ( MessageBox( window, \"Cancel before training is finished?\", \"Vertical First Training\", MB_OKCANCEL|MB_ICONSTOP ) == IDOK ) )\n      {\n        for( i = 0 ; i < fi[0].numtypes ; i++ )\n          if( windowranges[i] > max ) max = windowranges[i];\n        if ( max )\n          windowstatus = 1;\n        DestroyWindow( window );\n      }\n    }\n    return 0;\n       \n    case WM_PAINT:\n    {\n      PAINTSTRUCT ps;\n      HDC dc;\n\n      dc = BeginPaint( window, &ps );\n      StretchDIBits( dc, \n        0, 0, bitmapw*curzoom, bitmaph*curzoom,\n        0, 0, bitmapw, bitmaph,\n        bitmap, (BITMAPINFO*)&bmiHeader, DIB_RGB_COLORS, SRCCOPY );\n\n      PatBlt( dc, bitmapw*curzoom, 0, 4096, 4096, WHITENESS );\n      PatBlt( dc, 0, bitmaph*curzoom, 4096, 4096, WHITENESS );\n\n      SetTextColor( dc, RGB(0,0,0)  );\n      SetBkColor( dc, RGB(255,255,255) );\n      SetBkMode( dc, OPAQUE );\n\n      {\n        int i, l = 0, max = 0;\n        char buf[1024];\n        RECT rc;\n        POINT p;\n\n        for( i = 0 ; i < fi[0].numtypes ; i++ )\n        {\n          l += sprintf( buf + l, \"channels: %d %s\\n\", fi[0].effective[i], windowranges[i] ? expand_to_string( windowranges[i] ) : \"Done.\" );\n          if ( windowranges[i] > max ) max = windowranges[i];\n        }\n\n        rc.left = 32; rc.top = bitmaph*curzoom+10;\n        rc.right = 512; rc.bottom = rc.top + 512;\n        DrawText( dc, buf, -1, &rc, DT_TOP );\n\n        l = 0;\n        if ( max == 0 )\n        {\n          static DWORD traindone = 0;\n          if ( traindone == 0 ) traindone = GetTickCount();\n          l = sprintf( buf, \"Finished in %s.\", gettime( traindone - trainstart ) );\n        }\n        else if ( max != MAXRANGE )\n          l = sprintf( buf, \"Done in %s...\", gettime( (int) ( ( ( (int64)max * ( (int64)GetTickCount() - (int64)trainstart ) ) ) / (int64) ( MAXRANGE - max ) ) ) );\n\n        GetCursorPos( &p );\n        ScreenToClient( window, &p );\n\n        if ( ( p.x >= 0 ) && ( p.y >= 0 ) && ( p.x < (bitmapw*curzoom) ) && ( p.y < (bitmaph*curzoom) ) )\n        {\n          int findex;\n          int x, y, w, h, sx, sy, ix, iy, ox, oy;\n          int ir, chanind;\n          int * ts;\n          char badstr[64];\n          STBIR__V_FIRST_INFO v_info={0};\n\n          p.x /= curzoom;\n          p.y /= curzoom;\n\n          for( findex = 0 ; findex < numfileinfo ; findex++ )\n          {\n            x = fi[findex].bitmapx;\n            y = fi[findex].bitmapy;\n            w = x + ( fi[findex].dimensionx + 1 ) * fi[findex].numtypes;\n            h = y + ( fi[findex].dimensiony + 1 ) * fi[findex].numinputrects;\n\n            if ( ( p.x >= x ) && ( p.y >= y ) && ( p.x < w ) && ( p.y < h ) )\n              goto found;\n          }\n          goto nope;\n         \n         found:\n            \n          ir = ( p.y - y ) / ( fi[findex].dimensiony + 1 );\n          sy = ( p.y - y ) % ( fi[findex].dimensiony + 1 );\n          if ( sy >= fi[findex].dimensiony ) goto nope;\n\n          chanind = ( p.x - x ) / ( fi[findex].dimensionx + 1 );\n          sx = ( p.x - x ) % ( fi[findex].dimensionx + 1 );\n          if ( sx >= fi[findex].dimensionx ) goto nope;\n\n          ix = fi[findex].inputrects[ir*2];\n          iy = fi[findex].inputrects[ir*2+1];\n\n          ts = fi[findex].timings + ( ( fi[findex].dimensionx * fi[findex].dimensiony * fi[findex].numtypes * ir ) + ( fi[findex].dimensionx * fi[findex].dimensiony * chanind ) + ( fi[findex].dimensionx * sy ) + sx ) * 2;\n\n          ox = 1+fi[findex].outputscalex*sx;\n          oy = 1+fi[findex].outputscaley*sy;\n\n          if ( windowstatus != 2 )\n          {\n            int VF, HF, v_first, good;\n            VF = ts[0];\n            HF = ts[1];\n\n            v_first = vert_first( retrain_weights[chanind], ox, oy, ix, iy, STBIR_FILTER_MITCHELL, &v_info );\n\n            good = ( ((HF<=VF) && (!v_first)) || ((VF<=HF) && (v_first)));\n\n            if ( good )\n              badstr[0] = 0;\n            else\n            {\n              double r;\n\n              if ( HF < VF )\n                r = (double)(VF-HF)/(double)HF;\n              else\n                r = (double)(HF-VF)/(double)VF;\n              sprintf( badstr, \" %.1f%% off\", r*100 );\n            }\n            sprintf( buf + l, \"\\n\\n%s\\nCh: %d Resize: %dx%d to %dx%d\\nV: %d H: %d  Order: %c (%s%s)\\nClass: %d Scale: %.2f %s\", fi[findex].filename,fi[findex].effective[chanind], ix,iy,ox,oy, VF, HF, v_first?'V':'H', good?\"Good\":\"Wrong\", badstr, v_info.v_resize_classification, (double)oy/(double)iy, v_info.is_gather ? \"Gather\" : \"Scatter\" );\n          }\n          else\n          {\n            int v_first, time0, time1;\n            float (* weights)[4] = stbir__compute_weights[chanind];\n            int * ts1;\n            char b0[32], b1[32];\n\n            ts1 = fi[1].timings + ( ts - fi[0].timings );\n\n            v_first = vert_first( weights, ox, oy, ix, iy, STBIR_FILTER_MITCHELL, &v_info );\n\n            time0 = ( v_first ) ? ts[0] : ts[1];\n            time1 = ( v_first ) ? ts1[0] : ts1[1];\n            \n            b0[0] = b1[0] = 0;\n            if ( time0 < time1 )\n              sprintf( b0,\" (%.f%% better)\", ((double)time1-(double)time0)*100.0f/(double)time0);\n            else\n              sprintf( b1,\" (%.f%% better)\", ((double)time0-(double)time1)*100.0f/(double)time1);\n\n            sprintf( buf + l, \"\\n\\n0: %s\\n1: %s\\nCh: %d Resize: %dx%d to %dx%d\\nClass: %d Scale: %.2f %s\\nTime0: %d%s\\nTime1: %d%s\", fi[0].filename, fi[1].filename, fi[0].effective[chanind], ix,iy,ox,oy, v_info.v_resize_classification, (double)oy/(double)iy, v_info.is_gather ? \"Gather\" : \"Scatter\", time0, b0, time1, b1 );\n          }\n        }\n       nope:\n\n        rc.left = 32+320; rc.right = 512+320; \n        SetTextColor( dc, RGB(0,0,128) );\n        DrawText( dc, buf, -1, &rc, DT_TOP );\n\n      }\n      EndPaint( window, &ps );\n      return 0;\n    }\n\n    case WM_TIMER:\n      InvalidateRect( window, 0, 0 );\n      return 0;\n\n    case WM_DESTROY:\n      PostQuitMessage( 0 );\n      return 0;\n  }\n   \n\n  return DefWindowProc( window, message, wparam, lparam );\n}\n\nstatic void SetHighDPI(void)\n{\n  typedef HRESULT WINAPI setdpitype(int v);\n  HMODULE h=LoadLibrary(\"Shcore.dll\");\n  if (h)\n  {\n    setdpitype * sd = (setdpitype*)GetProcAddress(h,\"SetProcessDpiAwareness\");\n    if (sd )\n      sd(1);\n  }\n} \n\nstatic void draw_window()\n{\n  WNDCLASS wc;\n  HWND w;\n  MSG msg;\n  \n  instance = GetModuleHandle(NULL);\n\n  wc.style = 0;\n  wc.lpfnWndProc = WindowProc;\n  wc.cbClsExtra = 0;\n  wc.cbWndExtra = 0;\n  wc.hInstance = instance;\n  wc.hIcon = 0;\n  wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n  wc.hbrBackground = 0;\n  wc.lpszMenuName = 0;\n  wc.lpszClassName = \"WHTrain\";\n\n  if ( !RegisterClass( &wc ) )\n    exit(1);\n\n  SetHighDPI();\n\n  bmiHeader.biSize          =  sizeof(BITMAPINFOHEADER);\n  bmiHeader.biWidth         =  bitmapp/3;\n  bmiHeader.biHeight        =  -bitmaph;\n  bmiHeader.biPlanes        =  1;\n  bmiHeader.biBitCount      =  24;\n  bmiHeader.biCompression   =  BI_RGB;\n\n  w = CreateWindow( \"WHTrain\",\n                    \"Vertical First Training\",\n                    WS_CAPTION | WS_POPUP| WS_CLIPCHILDREN |\n                    WS_SYSMENU | WS_MINIMIZEBOX | WS_SIZEBOX,\n                    CW_USEDEFAULT,CW_USEDEFAULT,\n                    CW_USEDEFAULT,CW_USEDEFAULT,\n                    0, 0, instance, 0 );\n\n  {\n    RECT r, c;\n    GetWindowRect( w, &r );\n    GetClientRect( w, &c );\n    extrawindoww = ( r.right - r.left ) - ( c.right - c.left );\n    extrawindowh = ( r.bottom - r.top ) - ( c.bottom - c.top );\n    SetWindowPos( w, 0, 0, 0, bitmapw * curzoom + extrawindoww, bitmaph * curzoom + extrawindowh + 164, SWP_NOMOVE );\n  }\n\n  ShowWindow( w, SW_SHOWNORMAL );\n  SetTimer( w, 1, 250, 0 );\n\n  {\n    BOOL ret;\n    while( ( ret = GetMessage( &msg, w, 0, 0 ) ) != 0 )\n    { \n      if ( ret == -1 )\n        break;\n      TranslateMessage( &msg ); \n      DispatchMessage( &msg ); \n    }\n  }\n}\n\nstatic void retrain()\n{\n  HANDLE threads[ 16 ];\n  int chanind;\n\n  trainstart = GetTickCount();\n  for( chanind = 0 ; chanind < fi[0].numtypes ; chanind++ )\n    threads[ chanind ] = CreateThread( 0, 2048*1024, retrain_shim, (LPVOID)(size_t)chanind, 0, 0 );\n\n  draw_window();\n\n  for( chanind = 0 ; chanind < fi[0].numtypes ; chanind++ )\n  {\n    WaitForSingleObject( threads[ chanind ], INFINITE );\n    CloseHandle( threads[ chanind ] );\n  }\n\n  write_bitmap();\n\n  print_struct( retrain_weights, \"retained_weights\" );\n  if ( windowstatus ) printf( \"CANCELLED!\\n\" );\n}\n\nstatic void info()\n{\n  int findex;\n\n  // display info about each input file\n  for( findex = 0 ; findex < numfileinfo ; findex++ )\n  {\n    int i, h,m,s;\n    if ( findex ) printf( \"\\n\" );\n    printf( \"Timing file: %s\\n\", fi[findex].filename );\n    printf( \"CPU type: %d  %s\\n\", fi[findex].cpu, fi[findex].simd?(fi[findex].simd==2?\"SIMD8\":\"SIMD4\"):\"Scalar\" );\n    h = fi[findex].milliseconds/3600000;\n    m = (fi[findex].milliseconds-h*3600000)/60000;\n    s = (fi[findex].milliseconds-h*3600000-m*60000)/1000;\n    printf( \"Total time in test: %dh %dm %ds  Cycles/sec: %.f\\n\", h,m,s, 1000.0/fi[findex].scale_time );\n    printf( \"Each tile of samples is %dx%d, and is scaled by %dx%d.\\n\", fi[findex].dimensionx,fi[findex].dimensiony, fi[findex].outputscalex,fi[findex].outputscaley );\n    printf( \"So the x coords are: \" );\n    for( i=0; i < fi[findex].dimensionx ; i++ ) printf( \"%d \",1+i*fi[findex].outputscalex );\n    printf( \"\\n\" );\n    printf( \"And the y coords are: \" );\n    for( i=0; i < fi[findex].dimensiony ; i++ ) printf( \"%d \",1+i*fi[findex].outputscaley );\n    printf( \"\\n\" );\n    printf( \"There are %d channel counts and they are: \", fi[findex].numtypes );\n    for( i=0; i < fi[findex].numtypes ; i++ ) printf( \"%d \",fi[findex].effective[i] );\n    printf( \"\\n\" );\n    printf( \"There are %d input rect sizes and they are: \", fi[findex].numinputrects );\n    for( i=0; i < fi[findex].numtypes ; i++ ) printf( \"%dx%d \",fi[findex].inputrects[i*2],fi[findex].inputrects[i*2+1] );\n    printf( \"\\n\" );\n  }\n}\n\nstatic void current( int do_win, int do_bitmap )\n{\n  int i, findex;\n\n  trainstart = GetTickCount();\n\n  // clear progress\n  memset( windowranges, 0, sizeof( windowranges ) );\n  // copy in appropriate weights\n  memcpy( retrain_weights, stbir__compute_weights, sizeof( retrain_weights ) );\n\n  // build and print current errors and build current bitmap\n  for( i = 0 ; i < fi[0].numtypes ; i++ )\n  {\n    double curerr[STBIR_RESIZE_CLASSIFICATIONS];\n    int curtot[STBIR_RESIZE_CLASSIFICATIONS];\n    float (* weights)[4] = retrain_weights[i];\n \n    calc_errors( weights, curtot, curerr, i );\n    if ( !do_bitmap )\n      print_weights( weights, i, curtot, curerr );\n\n    for( findex = 0 ; findex < numfileinfo ; findex++ )\n      build_bitmap( weights, i, findex );\n  }\n\n  if ( do_win )\n    draw_window();\n\n  if ( do_bitmap )\n    write_bitmap();\n}\n\nstatic void compare()\n{\n  int i;\n\n  trainstart = GetTickCount();\n  windowstatus = 2; // comp mode\n\n  // clear progress\n  memset( windowranges, 0, sizeof( windowranges ) );\n\n  if ( ( fi[0].numtypes != fi[1].numtypes ) || ( fi[0].numinputrects != fi[1].numinputrects ) ||\n       ( fi[0].dimensionx != fi[1].dimensionx ) || ( fi[0].dimensiony != fi[1].dimensiony ) || \n       ( fi[0].outputscalex != fi[1].outputscalex ) || ( fi[0].outputscaley != fi[1].outputscaley ) )\n  {\n   err:\n    printf( \"Timing files don't match.\\n\" );\n    exit(5);\n  }\n\n  for( i=0; i < fi[0].numtypes ; i++ )\n  {\n    if ( fi[0].effective[i]      != fi[1].effective[i] ) goto err;\n    if ( fi[0].inputrects[i*2]   != fi[1].inputrects[i*2] ) goto err;\n    if ( fi[0].inputrects[i*2+1] != fi[1].inputrects[i*2+1] ) goto err;\n  }\n    \n  alloc_bitmap( 1 );\n  \n  for( i = 0 ; i < fi[0].numtypes ; i++ )\n  {\n    float (* weights)[4] = stbir__compute_weights[i];\n    build_comp_bitmap( weights, i );\n  }\n\n  draw_window();\n}\n\nstatic void load_files( char ** args, int count )\n{\n  int i;\n\n  if ( count == 0 )\n  {\n    printf( \"No timing files listed!\" );\n    exit(3);\n  }\n\n  for ( i = 0 ; i < count ; i++ )\n  {\n    if ( !use_timing_file( args[i], i ) )\n    {\n      printf( \"Bad timing file %s\\n\", args[i] );\n      exit(2);\n    }\n  }\n  numfileinfo = count;\n}  \n\nint main( int argc, char ** argv )\n{\n  int check;\n  if ( argc < 3 )\n  {\n   err:\n    printf( \"vf_train retrain [timing_filenames....] - recalcs weights for all the files on the command line.\\n\");\n    printf( \"vf_train info [timing_filenames....] - shows info about each timing file.\\n\");\n    printf( \"vf_train check [timing_filenames...] - show results for the current weights for all files listed.\\n\");\n    printf( \"vf_train compare <timing file1> <timing file2> - compare two timing files (must only be two files and same resolution).\\n\");\n    printf( \"vf_train bitmap [timing_filenames...] - write out results.png, comparing against the current weights for all files listed.\\n\");\n    exit(1);\n  }\n  \n  check = ( strcmp( argv[1], \"check\" ) == 0 );\n  if ( ( check ) || ( strcmp( argv[1], \"bitmap\" ) == 0 ) )\n  {\n    load_files( argv + 2, argc - 2 );\n    alloc_bitmap( numfileinfo );\n    current( check, !check );\n  }\n  else if ( strcmp( argv[1], \"info\" ) == 0 ) \n  {\n    load_files( argv + 2, argc - 2 );\n    info();\n  }\n  else if ( strcmp( argv[1], \"compare\" ) == 0 ) \n  {\n    if ( argc != 4 )\n    {\n      printf( \"You must specify two files to compare.\\n\" );\n      exit(4);\n    }\n\n    load_files( argv + 2, argc - 2 );\n    compare();\n  }\n  else if ( strcmp( argv[1], \"retrain\" ) == 0 ) \n  {\n    load_files( argv + 2, argc - 2 );\n    alloc_bitmap( numfileinfo );\n    retrain();  \n  }\n  else\n  {\n    goto err;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "stb_image_write.h",
    "content": "/* stb_image_write - v1.16 - public domain - http://nothings.org/stb\n   writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015\n                                     no warranty implied; use at your own risk\n\n   Before #including,\n\n       #define STB_IMAGE_WRITE_IMPLEMENTATION\n\n   in the file that you want to have the implementation.\n\n   Will probably not work correctly with strict-aliasing optimizations.\n\nABOUT:\n\n   This header file is a library for writing images to C stdio or a callback.\n\n   The PNG output is not optimal; it is 20-50% larger than the file\n   written by a decent optimizing implementation; though providing a custom\n   zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that.\n   This library is designed for source code compactness and simplicity,\n   not optimal image file size or run-time performance.\n\nBUILDING:\n\n   You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h.\n   You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace\n   malloc,realloc,free.\n   You can #define STBIW_MEMMOVE() to replace memmove()\n   You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function\n   for PNG compression (instead of the builtin one), it must have the following signature:\n   unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality);\n   The returned data will be freed with STBIW_FREE() (free() by default),\n   so it must be heap allocated with STBIW_MALLOC() (malloc() by default),\n\nUNICODE:\n\n   If compiling for Windows and you wish to use Unicode filenames, compile\n   with\n       #define STBIW_WINDOWS_UTF8\n   and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert\n   Windows wchar_t filenames to utf8.\n\nUSAGE:\n\n   There are five functions, one for each image file format:\n\n     int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);\n     int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);\n     int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);\n     int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality);\n     int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);\n\n     void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically\n\n   There are also five equivalent functions that use an arbitrary write function. You are\n   expected to open/close your file-equivalent before and after calling these:\n\n     int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void  *data, int stride_in_bytes);\n     int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void  *data);\n     int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void  *data);\n     int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);\n     int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);\n\n   where the callback is:\n      void stbi_write_func(void *context, void *data, int size);\n\n   You can configure it with these global variables:\n      int stbi_write_tga_with_rle;             // defaults to true; set to 0 to disable RLE\n      int stbi_write_png_compression_level;    // defaults to 8; set to higher for more compression\n      int stbi_write_force_png_filter;         // defaults to -1; set to 0..5 to force a filter mode\n\n\n   You can define STBI_WRITE_NO_STDIO to disable the file variant of these\n   functions, so the library will not use stdio.h at all. However, this will\n   also disable HDR writing, because it requires stdio for formatted output.\n\n   Each function returns 0 on failure and non-0 on success.\n\n   The functions create an image file defined by the parameters. The image\n   is a rectangle of pixels stored from left-to-right, top-to-bottom.\n   Each pixel contains 'comp' channels of data stored interleaved with 8-bits\n   per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is\n   monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall.\n   The *data pointer points to the first byte of the top-left-most pixel.\n   For PNG, \"stride_in_bytes\" is the distance in bytes from the first byte of\n   a row of pixels to the first byte of the next row of pixels.\n\n   PNG creates output files with the same number of components as the input.\n   The BMP format expands Y to RGB in the file format and does not\n   output alpha.\n\n   PNG supports writing rectangles of data even when the bytes storing rows of\n   data are not consecutive in memory (e.g. sub-rectangles of a larger image),\n   by supplying the stride between the beginning of adjacent rows. The other\n   formats do not. (Thus you cannot write a native-format BMP through the BMP\n   writer, both because it is in BGR order and because it may have padding\n   at the end of the line.)\n\n   PNG allows you to set the deflate compression level by setting the global\n   variable 'stbi_write_png_compression_level' (it defaults to 8).\n\n   HDR expects linear float data. Since the format is always 32-bit rgb(e)\n   data, alpha (if provided) is discarded, and for monochrome data it is\n   replicated across all three channels.\n\n   TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed\n   data, set the global variable 'stbi_write_tga_with_rle' to 0.\n\n   JPEG does ignore alpha channels in input data; quality is between 1 and 100.\n   Higher quality looks better but results in a bigger image.\n   JPEG baseline (no JPEG progressive).\n\nCREDITS:\n\n\n   Sean Barrett           -    PNG/BMP/TGA\n   Baldur Karlsson        -    HDR\n   Jean-Sebastien Guay    -    TGA monochrome\n   Tim Kelsey             -    misc enhancements\n   Alan Hickman           -    TGA RLE\n   Emmanuel Julien        -    initial file IO callback implementation\n   Jon Olick              -    original jo_jpeg.cpp code\n   Daniel Gibson          -    integrate JPEG, allow external zlib\n   Aarni Koskela          -    allow choosing PNG filter\n\n   bugfixes:\n      github:Chribba\n      Guillaume Chereau\n      github:jry2\n      github:romigrou\n      Sergio Gonzalez\n      Jonas Karlsson\n      Filip Wasil\n      Thatcher Ulrich\n      github:poppolopoppo\n      Patrick Boettcher\n      github:xeekworx\n      Cap Petschulat\n      Simon Rodriguez\n      Ivan Tikhonov\n      github:ignotion\n      Adam Schackart\n      Andrew Kensler\n\nLICENSE\n\n  See end of file for license information.\n\n*/\n\n#ifndef INCLUDE_STB_IMAGE_WRITE_H\n#define INCLUDE_STB_IMAGE_WRITE_H\n\n#include <stdlib.h>\n\n// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline'\n#ifndef STBIWDEF\n#ifdef STB_IMAGE_WRITE_STATIC\n#define STBIWDEF  static\n#else\n#ifdef __cplusplus\n#define STBIWDEF  extern \"C\"\n#else\n#define STBIWDEF  extern\n#endif\n#endif\n#endif\n\n#ifndef STB_IMAGE_WRITE_STATIC  // C++ forbids static forward declarations\nSTBIWDEF int stbi_write_tga_with_rle;\nSTBIWDEF int stbi_write_png_compression_level;\nSTBIWDEF int stbi_write_force_png_filter;\n#endif\n\n#ifndef STBI_WRITE_NO_STDIO\nSTBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void  *data, int stride_in_bytes);\nSTBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void  *data);\nSTBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void  *data);\nSTBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);\nSTBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void  *data, int quality);\n\n#ifdef STBIW_WINDOWS_UTF8\nSTBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);\n#endif\n#endif\n\ntypedef void stbi_write_func(void *context, void *data, int size);\n\nSTBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void  *data, int stride_in_bytes);\nSTBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void  *data);\nSTBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void  *data);\nSTBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);\nSTBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void  *data, int quality);\n\nSTBIWDEF void stbi_flip_vertically_on_write(int flip_boolean);\n\n#endif//INCLUDE_STB_IMAGE_WRITE_H\n\n#ifdef STB_IMAGE_WRITE_IMPLEMENTATION\n\n#ifdef _WIN32\n   #ifndef _CRT_SECURE_NO_WARNINGS\n   #define _CRT_SECURE_NO_WARNINGS\n   #endif\n   #ifndef _CRT_NONSTDC_NO_DEPRECATE\n   #define _CRT_NONSTDC_NO_DEPRECATE\n   #endif\n#endif\n\n#ifndef STBI_WRITE_NO_STDIO\n#include <stdio.h>\n#endif // STBI_WRITE_NO_STDIO\n\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED))\n// ok\n#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED)\n// ok\n#else\n#error \"Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED).\"\n#endif\n\n#ifndef STBIW_MALLOC\n#define STBIW_MALLOC(sz)        malloc(sz)\n#define STBIW_REALLOC(p,newsz)  realloc(p,newsz)\n#define STBIW_FREE(p)           free(p)\n#endif\n\n#ifndef STBIW_REALLOC_SIZED\n#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz)\n#endif\n\n\n#ifndef STBIW_MEMMOVE\n#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz)\n#endif\n\n\n#ifndef STBIW_ASSERT\n#include <assert.h>\n#define STBIW_ASSERT(x) assert(x)\n#endif\n\n#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff)\n\n#ifdef STB_IMAGE_WRITE_STATIC\nstatic int stbi_write_png_compression_level = 8;\nstatic int stbi_write_tga_with_rle = 1;\nstatic int stbi_write_force_png_filter = -1;\n#else\nint stbi_write_png_compression_level = 8;\nint stbi_write_tga_with_rle = 1;\nint stbi_write_force_png_filter = -1;\n#endif\n\nstatic int stbi__flip_vertically_on_write = 0;\n\nSTBIWDEF void stbi_flip_vertically_on_write(int flag)\n{\n   stbi__flip_vertically_on_write = flag;\n}\n\ntypedef struct\n{\n   stbi_write_func *func;\n   void *context;\n   unsigned char buffer[64];\n   int buf_used;\n} stbi__write_context;\n\n// initialize a callback-based context\nstatic void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context)\n{\n   s->func    = c;\n   s->context = context;\n}\n\n#ifndef STBI_WRITE_NO_STDIO\n\nstatic void stbi__stdio_write(void *context, void *data, int size)\n{\n   fwrite(data,1,size,(FILE*) context);\n}\n\n#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8)\n#ifdef __cplusplus\n#define STBIW_EXTERN extern \"C\"\n#else\n#define STBIW_EXTERN extern\n#endif\nSTBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);\nSTBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);\n\nSTBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)\n{\n   return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);\n}\n#endif\n\nstatic FILE *stbiw__fopen(char const *filename, char const *mode)\n{\n   FILE *f;\n#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8)\n   wchar_t wMode[64];\n   wchar_t wFilename[1024];\n   if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))\n      return 0;\n\n   if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))\n      return 0;\n\n#if defined(_MSC_VER) && _MSC_VER >= 1400\n   if (0 != _wfopen_s(&f, wFilename, wMode))\n      f = 0;\n#else\n   f = _wfopen(wFilename, wMode);\n#endif\n\n#elif defined(_MSC_VER) && _MSC_VER >= 1400\n   if (0 != fopen_s(&f, filename, mode))\n      f=0;\n#else\n   f = fopen(filename, mode);\n#endif\n   return f;\n}\n\nstatic int stbi__start_write_file(stbi__write_context *s, const char *filename)\n{\n   FILE *f = stbiw__fopen(filename, \"wb\");\n   stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f);\n   return f != NULL;\n}\n\nstatic void stbi__end_write_file(stbi__write_context *s)\n{\n   fclose((FILE *)s->context);\n}\n\n#endif // !STBI_WRITE_NO_STDIO\n\ntypedef unsigned int stbiw_uint32;\ntypedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];\n\nstatic void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v)\n{\n   while (*fmt) {\n      switch (*fmt++) {\n         case ' ': break;\n         case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int));\n                     s->func(s->context,&x,1);\n                     break; }\n         case '2': { int x = va_arg(v,int);\n                     unsigned char b[2];\n                     b[0] = STBIW_UCHAR(x);\n                     b[1] = STBIW_UCHAR(x>>8);\n                     s->func(s->context,b,2);\n                     break; }\n         case '4': { stbiw_uint32 x = va_arg(v,int);\n                     unsigned char b[4];\n                     b[0]=STBIW_UCHAR(x);\n                     b[1]=STBIW_UCHAR(x>>8);\n                     b[2]=STBIW_UCHAR(x>>16);\n                     b[3]=STBIW_UCHAR(x>>24);\n                     s->func(s->context,b,4);\n                     break; }\n         default:\n            STBIW_ASSERT(0);\n            return;\n      }\n   }\n}\n\nstatic void stbiw__writef(stbi__write_context *s, const char *fmt, ...)\n{\n   va_list v;\n   va_start(v, fmt);\n   stbiw__writefv(s, fmt, v);\n   va_end(v);\n}\n\nstatic void stbiw__write_flush(stbi__write_context *s)\n{\n   if (s->buf_used) {\n      s->func(s->context, &s->buffer, s->buf_used);\n      s->buf_used = 0;\n   }\n}\n\nstatic void stbiw__putc(stbi__write_context *s, unsigned char c)\n{\n   s->func(s->context, &c, 1);\n}\n\nstatic void stbiw__write1(stbi__write_context *s, unsigned char a)\n{\n   if ((size_t)s->buf_used + 1 > sizeof(s->buffer))\n      stbiw__write_flush(s);\n   s->buffer[s->buf_used++] = a;\n}\n\nstatic void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c)\n{\n   int n;\n   if ((size_t)s->buf_used + 3 > sizeof(s->buffer))\n      stbiw__write_flush(s);\n   n = s->buf_used;\n   s->buf_used = n+3;\n   s->buffer[n+0] = a;\n   s->buffer[n+1] = b;\n   s->buffer[n+2] = c;\n}\n\nstatic void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d)\n{\n   unsigned char bg[3] = { 255, 0, 255}, px[3];\n   int k;\n\n   if (write_alpha < 0)\n      stbiw__write1(s, d[comp - 1]);\n\n   switch (comp) {\n      case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case\n      case 1:\n         if (expand_mono)\n            stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp\n         else\n            stbiw__write1(s, d[0]);  // monochrome TGA\n         break;\n      case 4:\n         if (!write_alpha) {\n            // composite against pink background\n            for (k = 0; k < 3; ++k)\n               px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255;\n            stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]);\n            break;\n         }\n         /* FALLTHROUGH */\n      case 3:\n         stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]);\n         break;\n   }\n   if (write_alpha > 0)\n      stbiw__write1(s, d[comp - 1]);\n}\n\nstatic void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono)\n{\n   stbiw_uint32 zero = 0;\n   int i,j, j_end;\n\n   if (y <= 0)\n      return;\n\n   if (stbi__flip_vertically_on_write)\n      vdir *= -1;\n\n   if (vdir < 0) {\n      j_end = -1; j = y-1;\n   } else {\n      j_end =  y; j = 0;\n   }\n\n   for (; j != j_end; j += vdir) {\n      for (i=0; i < x; ++i) {\n         unsigned char *d = (unsigned char *) data + (j*x+i)*comp;\n         stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d);\n      }\n      stbiw__write_flush(s);\n      s->func(s->context, &zero, scanline_pad);\n   }\n}\n\nstatic int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...)\n{\n   if (y < 0 || x < 0) {\n      return 0;\n   } else {\n      va_list v;\n      va_start(v, fmt);\n      stbiw__writefv(s, fmt, v);\n      va_end(v);\n      stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono);\n      return 1;\n   }\n}\n\nstatic int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data)\n{\n   if (comp != 4) {\n      // write RGB bitmap\n      int pad = (-x*3) & 3;\n      return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad,\n              \"11 4 22 4\" \"4 44 22 444444\",\n              'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40,  // file header\n               40, x,y, 1,24, 0,0,0,0,0,0);             // bitmap header\n   } else {\n      // RGBA bitmaps need a v4 header\n      // use BI_BITFIELDS mode with 32bpp and alpha mask\n      // (straight BI_RGB with alpha mask doesn't work in most readers)\n      return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0,\n         \"11 4 22 4\" \"4 44 22 444444 4444 4 444 444 444 444\",\n         'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header\n         108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header\n   }\n}\n\nSTBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data)\n{\n   stbi__write_context s = { 0 };\n   stbi__start_write_callbacks(&s, func, context);\n   return stbi_write_bmp_core(&s, x, y, comp, data);\n}\n\n#ifndef STBI_WRITE_NO_STDIO\nSTBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)\n{\n   stbi__write_context s = { 0 };\n   if (stbi__start_write_file(&s,filename)) {\n      int r = stbi_write_bmp_core(&s, x, y, comp, data);\n      stbi__end_write_file(&s);\n      return r;\n   } else\n      return 0;\n}\n#endif //!STBI_WRITE_NO_STDIO\n\nstatic int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data)\n{\n   int has_alpha = (comp == 2 || comp == 4);\n   int colorbytes = has_alpha ? comp-1 : comp;\n   int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3\n\n   if (y < 0 || x < 0)\n      return 0;\n\n   if (!stbi_write_tga_with_rle) {\n      return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0,\n         \"111 221 2222 11\", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8);\n   } else {\n      int i,j,k;\n      int jend, jdir;\n\n      stbiw__writef(s, \"111 221 2222 11\", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8);\n\n      if (stbi__flip_vertically_on_write) {\n         j = 0;\n         jend = y;\n         jdir = 1;\n      } else {\n         j = y-1;\n         jend = -1;\n         jdir = -1;\n      }\n      for (; j != jend; j += jdir) {\n         unsigned char *row = (unsigned char *) data + j * x * comp;\n         int len;\n\n         for (i = 0; i < x; i += len) {\n            unsigned char *begin = row + i * comp;\n            int diff = 1;\n            len = 1;\n\n            if (i < x - 1) {\n               ++len;\n               diff = memcmp(begin, row + (i + 1) * comp, comp);\n               if (diff) {\n                  const unsigned char *prev = begin;\n                  for (k = i + 2; k < x && len < 128; ++k) {\n                     if (memcmp(prev, row + k * comp, comp)) {\n                        prev += comp;\n                        ++len;\n                     } else {\n                        --len;\n                        break;\n                     }\n                  }\n               } else {\n                  for (k = i + 2; k < x && len < 128; ++k) {\n                     if (!memcmp(begin, row + k * comp, comp)) {\n                        ++len;\n                     } else {\n                        break;\n                     }\n                  }\n               }\n            }\n\n            if (diff) {\n               unsigned char header = STBIW_UCHAR(len - 1);\n               stbiw__write1(s, header);\n               for (k = 0; k < len; ++k) {\n                  stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp);\n               }\n            } else {\n               unsigned char header = STBIW_UCHAR(len - 129);\n               stbiw__write1(s, header);\n               stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin);\n            }\n         }\n      }\n      stbiw__write_flush(s);\n   }\n   return 1;\n}\n\nSTBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data)\n{\n   stbi__write_context s = { 0 };\n   stbi__start_write_callbacks(&s, func, context);\n   return stbi_write_tga_core(&s, x, y, comp, (void *) data);\n}\n\n#ifndef STBI_WRITE_NO_STDIO\nSTBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)\n{\n   stbi__write_context s = { 0 };\n   if (stbi__start_write_file(&s,filename)) {\n      int r = stbi_write_tga_core(&s, x, y, comp, (void *) data);\n      stbi__end_write_file(&s);\n      return r;\n   } else\n      return 0;\n}\n#endif\n\n// *************************************************************************************************\n// Radiance RGBE HDR writer\n// by Baldur Karlsson\n\n#define stbiw__max(a, b)  ((a) > (b) ? (a) : (b))\n\n#ifndef STBI_WRITE_NO_STDIO\n\nstatic void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear)\n{\n   int exponent;\n   float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2]));\n\n   if (maxcomp < 1e-32f) {\n      rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;\n   } else {\n      float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp;\n\n      rgbe[0] = (unsigned char)(linear[0] * normalize);\n      rgbe[1] = (unsigned char)(linear[1] * normalize);\n      rgbe[2] = (unsigned char)(linear[2] * normalize);\n      rgbe[3] = (unsigned char)(exponent + 128);\n   }\n}\n\nstatic void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte)\n{\n   unsigned char lengthbyte = STBIW_UCHAR(length+128);\n   STBIW_ASSERT(length+128 <= 255);\n   s->func(s->context, &lengthbyte, 1);\n   s->func(s->context, &databyte, 1);\n}\n\nstatic void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data)\n{\n   unsigned char lengthbyte = STBIW_UCHAR(length);\n   STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code\n   s->func(s->context, &lengthbyte, 1);\n   s->func(s->context, data, length);\n}\n\nstatic void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline)\n{\n   unsigned char scanlineheader[4] = { 2, 2, 0, 0 };\n   unsigned char rgbe[4];\n   float linear[3];\n   int x;\n\n   scanlineheader[2] = (width&0xff00)>>8;\n   scanlineheader[3] = (width&0x00ff);\n\n   /* skip RLE for images too small or large */\n   if (width < 8 || width >= 32768) {\n      for (x=0; x < width; x++) {\n         switch (ncomp) {\n            case 4: /* fallthrough */\n            case 3: linear[2] = scanline[x*ncomp + 2];\n                    linear[1] = scanline[x*ncomp + 1];\n                    linear[0] = scanline[x*ncomp + 0];\n                    break;\n            default:\n                    linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0];\n                    break;\n         }\n         stbiw__linear_to_rgbe(rgbe, linear);\n         s->func(s->context, rgbe, 4);\n      }\n   } else {\n      int c,r;\n      /* encode into scratch buffer */\n      for (x=0; x < width; x++) {\n         switch(ncomp) {\n            case 4: /* fallthrough */\n            case 3: linear[2] = scanline[x*ncomp + 2];\n                    linear[1] = scanline[x*ncomp + 1];\n                    linear[0] = scanline[x*ncomp + 0];\n                    break;\n            default:\n                    linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0];\n                    break;\n         }\n         stbiw__linear_to_rgbe(rgbe, linear);\n         scratch[x + width*0] = rgbe[0];\n         scratch[x + width*1] = rgbe[1];\n         scratch[x + width*2] = rgbe[2];\n         scratch[x + width*3] = rgbe[3];\n      }\n\n      s->func(s->context, scanlineheader, 4);\n\n      /* RLE each component separately */\n      for (c=0; c < 4; c++) {\n         unsigned char *comp = &scratch[width*c];\n\n         x = 0;\n         while (x < width) {\n            // find first run\n            r = x;\n            while (r+2 < width) {\n               if (comp[r] == comp[r+1] && comp[r] == comp[r+2])\n                  break;\n               ++r;\n            }\n            if (r+2 >= width)\n               r = width;\n            // dump up to first run\n            while (x < r) {\n               int len = r-x;\n               if (len > 128) len = 128;\n               stbiw__write_dump_data(s, len, &comp[x]);\n               x += len;\n            }\n            // if there's a run, output it\n            if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd\n               // find next byte after run\n               while (r < width && comp[r] == comp[x])\n                  ++r;\n               // output run up to r\n               while (x < r) {\n                  int len = r-x;\n                  if (len > 127) len = 127;\n                  stbiw__write_run_data(s, len, comp[x]);\n                  x += len;\n               }\n            }\n         }\n      }\n   }\n}\n\nstatic int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data)\n{\n   if (y <= 0 || x <= 0 || data == NULL)\n      return 0;\n   else {\n      // Each component is stored separately. Allocate scratch space for full output scanline.\n      unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4);\n      int i, len;\n      char buffer[128];\n      char header[] = \"#?RADIANCE\\n# Written by stb_image_write.h\\nFORMAT=32-bit_rle_rgbe\\n\";\n      s->func(s->context, header, sizeof(header)-1);\n\n#ifdef __STDC_LIB_EXT1__\n      len = sprintf_s(buffer, sizeof(buffer), \"EXPOSURE=          1.0000000000000\\n\\n-Y %d +X %d\\n\", y, x);\n#else\n      len = sprintf(buffer, \"EXPOSURE=          1.0000000000000\\n\\n-Y %d +X %d\\n\", y, x);\n#endif\n      s->func(s->context, buffer, len);\n\n      for(i=0; i < y; i++)\n         stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i));\n      STBIW_FREE(scratch);\n      return 1;\n   }\n}\n\nSTBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data)\n{\n   stbi__write_context s = { 0 };\n   stbi__start_write_callbacks(&s, func, context);\n   return stbi_write_hdr_core(&s, x, y, comp, (float *) data);\n}\n\nSTBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data)\n{\n   stbi__write_context s = { 0 };\n   if (stbi__start_write_file(&s,filename)) {\n      int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data);\n      stbi__end_write_file(&s);\n      return r;\n   } else\n      return 0;\n}\n#endif // STBI_WRITE_NO_STDIO\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// PNG writer\n//\n\n#ifndef STBIW_ZLIB_COMPRESS\n// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size()\n#define stbiw__sbraw(a) ((int *) (void *) (a) - 2)\n#define stbiw__sbm(a)   stbiw__sbraw(a)[0]\n#define stbiw__sbn(a)   stbiw__sbraw(a)[1]\n\n#define stbiw__sbneedgrow(a,n)  ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a))\n#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0)\n#define stbiw__sbgrow(a,n)  stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a)))\n\n#define stbiw__sbpush(a, v)      (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v))\n#define stbiw__sbcount(a)        ((a) ? stbiw__sbn(a) : 0)\n#define stbiw__sbfree(a)         ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0)\n\nstatic void *stbiw__sbgrowf(void **arr, int increment, int itemsize)\n{\n   int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1;\n   void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2);\n   STBIW_ASSERT(p);\n   if (p) {\n      if (!*arr) ((int *) p)[1] = 0;\n      *arr = (void *) ((int *) p + 2);\n      stbiw__sbm(*arr) = m;\n   }\n   return *arr;\n}\n\nstatic unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)\n{\n   while (*bitcount >= 8) {\n      stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer));\n      *bitbuffer >>= 8;\n      *bitcount -= 8;\n   }\n   return data;\n}\n\nstatic int stbiw__zlib_bitrev(int code, int codebits)\n{\n   int res=0;\n   while (codebits--) {\n      res = (res << 1) | (code & 1);\n      code >>= 1;\n   }\n   return res;\n}\n\nstatic unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit)\n{\n   int i;\n   for (i=0; i < limit && i < 258; ++i)\n      if (a[i] != b[i]) break;\n   return i;\n}\n\nstatic unsigned int stbiw__zhash(unsigned char *data)\n{\n   stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);\n   hash ^= hash << 3;\n   hash += hash >> 5;\n   hash ^= hash << 4;\n   hash += hash >> 17;\n   hash ^= hash << 25;\n   hash += hash >> 6;\n   return hash;\n}\n\n#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount))\n#define stbiw__zlib_add(code,codebits) \\\n      (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush())\n#define stbiw__zlib_huffa(b,c)  stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c)\n// default huffman tables\n#define stbiw__zlib_huff1(n)  stbiw__zlib_huffa(0x30 + (n), 8)\n#define stbiw__zlib_huff2(n)  stbiw__zlib_huffa(0x190 + (n)-144, 9)\n#define stbiw__zlib_huff3(n)  stbiw__zlib_huffa(0 + (n)-256,7)\n#define stbiw__zlib_huff4(n)  stbiw__zlib_huffa(0xc0 + (n)-280,8)\n#define stbiw__zlib_huff(n)  ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n))\n#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n))\n\n#define stbiw__ZHASH   16384\n\n#endif // STBIW_ZLIB_COMPRESS\n\nSTBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)\n{\n#ifdef STBIW_ZLIB_COMPRESS\n   // user provided a zlib compress implementation, use that\n   return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality);\n#else // use builtin\n   static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };\n   static unsigned char  lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,  4,  5,  5,  5,  5,  0 };\n   static unsigned short distc[]   = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };\n   static unsigned char  disteb[]  = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };\n   unsigned int bitbuf=0;\n   int i,j, bitcount=0;\n   unsigned char *out = NULL;\n   unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**));\n   if (hash_table == NULL)\n      return NULL;\n   if (quality < 5) quality = 5;\n\n   stbiw__sbpush(out, 0x78);   // DEFLATE 32K window\n   stbiw__sbpush(out, 0x5e);   // FLEVEL = 1\n   stbiw__zlib_add(1,1);  // BFINAL = 1\n   stbiw__zlib_add(1,2);  // BTYPE = 1 -- fixed huffman\n\n   for (i=0; i < stbiw__ZHASH; ++i)\n      hash_table[i] = NULL;\n\n   i=0;\n   while (i < data_len-3) {\n      // hash next 3 bytes of data to be compressed\n      int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3;\n      unsigned char *bestloc = 0;\n      unsigned char **hlist = hash_table[h];\n      int n = stbiw__sbcount(hlist);\n      for (j=0; j < n; ++j) {\n         if (hlist[j]-data > i-32768) { // if entry lies within window\n            int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i);\n            if (d >= best) { best=d; bestloc=hlist[j]; }\n         }\n      }\n      // when hash table entry is too long, delete half the entries\n      if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) {\n         STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);\n         stbiw__sbn(hash_table[h]) = quality;\n      }\n      stbiw__sbpush(hash_table[h],data+i);\n\n      if (bestloc) {\n         // \"lazy matching\" - check match at *next* byte, and if it's better, do cur byte as literal\n         h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1);\n         hlist = hash_table[h];\n         n = stbiw__sbcount(hlist);\n         for (j=0; j < n; ++j) {\n            if (hlist[j]-data > i-32767) {\n               int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1);\n               if (e > best) { // if next match is better, bail on current match\n                  bestloc = NULL;\n                  break;\n               }\n            }\n         }\n      }\n\n      if (bestloc) {\n         int d = (int) (data+i - bestloc); // distance back\n         STBIW_ASSERT(d <= 32767 && best <= 258);\n         for (j=0; best > lengthc[j+1]-1; ++j);\n         stbiw__zlib_huff(j+257);\n         if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]);\n         for (j=0; d > distc[j+1]-1; ++j);\n         stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5);\n         if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]);\n         i += best;\n      } else {\n         stbiw__zlib_huffb(data[i]);\n         ++i;\n      }\n   }\n   // write out final bytes\n   for (;i < data_len; ++i)\n      stbiw__zlib_huffb(data[i]);\n   stbiw__zlib_huff(256); // end of block\n   // pad with 0 bits to byte boundary\n   while (bitcount)\n      stbiw__zlib_add(0,1);\n\n   for (i=0; i < stbiw__ZHASH; ++i)\n      (void) stbiw__sbfree(hash_table[i]);\n   STBIW_FREE(hash_table);\n\n   // store uncompressed instead if compression was worse\n   if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) {\n      stbiw__sbn(out) = 2;  // truncate to DEFLATE 32K window and FLEVEL = 1\n      for (j = 0; j < data_len;) {\n         int blocklen = data_len - j;\n         if (blocklen > 32767) blocklen = 32767;\n         stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression\n         stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN\n         stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8));\n         stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN\n         stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8));\n         memcpy(out+stbiw__sbn(out), data+j, blocklen);\n         stbiw__sbn(out) += blocklen;\n         j += blocklen;\n      }\n   }\n\n   {\n      // compute adler32 on input\n      unsigned int s1=1, s2=0;\n      int blocklen = (int) (data_len % 5552);\n      j=0;\n      while (j < data_len) {\n         for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; }\n         s1 %= 65521; s2 %= 65521;\n         j += blocklen;\n         blocklen = 5552;\n      }\n      stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8));\n      stbiw__sbpush(out, STBIW_UCHAR(s2));\n      stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8));\n      stbiw__sbpush(out, STBIW_UCHAR(s1));\n   }\n   *out_len = stbiw__sbn(out);\n   // make returned pointer freeable\n   STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len);\n   return (unsigned char *) stbiw__sbraw(out);\n#endif // STBIW_ZLIB_COMPRESS\n}\n\nstatic unsigned int stbiw__crc32(unsigned char *buffer, int len)\n{\n#ifdef STBIW_CRC32\n    return STBIW_CRC32(buffer, len);\n#else\n   static unsigned int crc_table[256] =\n   {\n      0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,\n      0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,\n      0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,\n      0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,\n      0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,\n      0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,\n      0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,\n      0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,\n      0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,\n      0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,\n      0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,\n      0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,\n      0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,\n      0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,\n      0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,\n      0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,\n      0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,\n      0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,\n      0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,\n      0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,\n      0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,\n      0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,\n      0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,\n      0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,\n      0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,\n      0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,\n      0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,\n      0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,\n      0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,\n      0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,\n      0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,\n      0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D\n   };\n\n   unsigned int crc = ~0u;\n   int i;\n   for (i=0; i < len; ++i)\n      crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];\n   return ~crc;\n#endif\n}\n\n#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4)\n#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));\n#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3])\n\nstatic void stbiw__wpcrc(unsigned char **data, int len)\n{\n   unsigned int crc = stbiw__crc32(*data - len - 4, len+4);\n   stbiw__wp32(*data, crc);\n}\n\nstatic unsigned char stbiw__paeth(int a, int b, int c)\n{\n   int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);\n   if (pa <= pb && pa <= pc) return STBIW_UCHAR(a);\n   if (pb <= pc) return STBIW_UCHAR(b);\n   return STBIW_UCHAR(c);\n}\n\n// @OPTIMIZE: provide an option that always forces left-predict or paeth predict\nstatic void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer)\n{\n   static int mapping[] = { 0,1,2,3,4 };\n   static int firstmap[] = { 0,1,0,5,6 };\n   int *mymap = (y != 0) ? mapping : firstmap;\n   int i;\n   int type = mymap[filter_type];\n   unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y);\n   int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes;\n\n   if (type==0) {\n      memcpy(line_buffer, z, width*n);\n      return;\n   }\n\n   // first loop isn't optimized since it's just one pixel\n   for (i = 0; i < n; ++i) {\n      switch (type) {\n         case 1: line_buffer[i] = z[i]; break;\n         case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break;\n         case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break;\n         case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break;\n         case 5: line_buffer[i] = z[i]; break;\n         case 6: line_buffer[i] = z[i]; break;\n      }\n   }\n   switch (type) {\n      case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break;\n      case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break;\n      case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break;\n      case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break;\n      case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break;\n      case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break;\n   }\n}\n\nSTBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)\n{\n   int force_filter = stbi_write_force_png_filter;\n   int ctype[5] = { -1, 0, 4, 2, 6 };\n   unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };\n   unsigned char *out,*o, *filt, *zlib;\n   signed char *line_buffer;\n   int j,zlen;\n\n   if (stride_bytes == 0)\n      stride_bytes = x * n;\n\n   if (force_filter >= 5) {\n      force_filter = -1;\n   }\n\n   filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0;\n   line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; }\n   for (j=0; j < y; ++j) {\n      int filter_type;\n      if (force_filter > -1) {\n         filter_type = force_filter;\n         stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer);\n      } else { // Estimate the best filter by running through all of them:\n         int best_filter = 0, best_filter_val = 0x7fffffff, est, i;\n         for (filter_type = 0; filter_type < 5; filter_type++) {\n            stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer);\n\n            // Estimate the entropy of the line using this filter; the less, the better.\n            est = 0;\n            for (i = 0; i < x*n; ++i) {\n               est += abs((signed char) line_buffer[i]);\n            }\n            if (est < best_filter_val) {\n               best_filter_val = est;\n               best_filter = filter_type;\n            }\n         }\n         if (filter_type != best_filter) {  // If the last iteration already got us the best filter, don't redo it\n            stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer);\n            filter_type = best_filter;\n         }\n      }\n      // when we get here, filter_type contains the filter type, and line_buffer contains the data\n      filt[j*(x*n+1)] = (unsigned char) filter_type;\n      STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n);\n   }\n   STBIW_FREE(line_buffer);\n   zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level);\n   STBIW_FREE(filt);\n   if (!zlib) return 0;\n\n   // each tag requires 12 bytes of overhead\n   out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12);\n   if (!out) return 0;\n   *out_len = 8 + 12+13 + 12+zlen + 12;\n\n   o=out;\n   STBIW_MEMMOVE(o,sig,8); o+= 8;\n   stbiw__wp32(o, 13); // header length\n   stbiw__wptag(o, \"IHDR\");\n   stbiw__wp32(o, x);\n   stbiw__wp32(o, y);\n   *o++ = 8;\n   *o++ = STBIW_UCHAR(ctype[n]);\n   *o++ = 0;\n   *o++ = 0;\n   *o++ = 0;\n   stbiw__wpcrc(&o,13);\n\n   stbiw__wp32(o, zlen);\n   stbiw__wptag(o, \"IDAT\");\n   STBIW_MEMMOVE(o, zlib, zlen);\n   o += zlen;\n   STBIW_FREE(zlib);\n   stbiw__wpcrc(&o, zlen);\n\n   stbiw__wp32(o,0);\n   stbiw__wptag(o, \"IEND\");\n   stbiw__wpcrc(&o,0);\n\n   STBIW_ASSERT(o == out + *out_len);\n\n   return out;\n}\n\n#ifndef STBI_WRITE_NO_STDIO\nSTBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)\n{\n   FILE *f;\n   int len;\n   unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);\n   if (png == NULL) return 0;\n\n   f = stbiw__fopen(filename, \"wb\");\n   if (!f) { STBIW_FREE(png); return 0; }\n   fwrite(png, 1, len, f);\n   fclose(f);\n   STBIW_FREE(png);\n   return 1;\n}\n#endif\n\nSTBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes)\n{\n   int len;\n   unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);\n   if (png == NULL) return 0;\n   func(context, png, len);\n   STBIW_FREE(png);\n   return 1;\n}\n\n\n/* ***************************************************************************\n *\n * JPEG writer\n *\n * This is based on Jon Olick's jo_jpeg.cpp:\n * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html\n */\n\nstatic const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,\n      24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 };\n\nstatic void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) {\n   int bitBuf = *bitBufP, bitCnt = *bitCntP;\n   bitCnt += bs[1];\n   bitBuf |= bs[0] << (24 - bitCnt);\n   while(bitCnt >= 8) {\n      unsigned char c = (bitBuf >> 16) & 255;\n      stbiw__putc(s, c);\n      if(c == 255) {\n         stbiw__putc(s, 0);\n      }\n      bitBuf <<= 8;\n      bitCnt -= 8;\n   }\n   *bitBufP = bitBuf;\n   *bitCntP = bitCnt;\n}\n\nstatic void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) {\n   float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p;\n   float z1, z2, z3, z4, z5, z11, z13;\n\n   float tmp0 = d0 + d7;\n   float tmp7 = d0 - d7;\n   float tmp1 = d1 + d6;\n   float tmp6 = d1 - d6;\n   float tmp2 = d2 + d5;\n   float tmp5 = d2 - d5;\n   float tmp3 = d3 + d4;\n   float tmp4 = d3 - d4;\n\n   // Even part\n   float tmp10 = tmp0 + tmp3;   // phase 2\n   float tmp13 = tmp0 - tmp3;\n   float tmp11 = tmp1 + tmp2;\n   float tmp12 = tmp1 - tmp2;\n\n   d0 = tmp10 + tmp11;       // phase 3\n   d4 = tmp10 - tmp11;\n\n   z1 = (tmp12 + tmp13) * 0.707106781f; // c4\n   d2 = tmp13 + z1;       // phase 5\n   d6 = tmp13 - z1;\n\n   // Odd part\n   tmp10 = tmp4 + tmp5;       // phase 2\n   tmp11 = tmp5 + tmp6;\n   tmp12 = tmp6 + tmp7;\n\n   // The rotator is modified from fig 4-8 to avoid extra negations.\n   z5 = (tmp10 - tmp12) * 0.382683433f; // c6\n   z2 = tmp10 * 0.541196100f + z5; // c2-c6\n   z4 = tmp12 * 1.306562965f + z5; // c2+c6\n   z3 = tmp11 * 0.707106781f; // c4\n\n   z11 = tmp7 + z3;      // phase 5\n   z13 = tmp7 - z3;\n\n   *d5p = z13 + z2;         // phase 6\n   *d3p = z13 - z2;\n   *d1p = z11 + z4;\n   *d7p = z11 - z4;\n\n   *d0p = d0;  *d2p = d2;  *d4p = d4;  *d6p = d6;\n}\n\nstatic void stbiw__jpg_calcBits(int val, unsigned short bits[2]) {\n   int tmp1 = val < 0 ? -val : val;\n   val = val < 0 ? val-1 : val;\n   bits[1] = 1;\n   while(tmp1 >>= 1) {\n      ++bits[1];\n   }\n   bits[0] = val & ((1<<bits[1])-1);\n}\n\nstatic int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf, int *bitCnt, float *CDU, int du_stride, float *fdtbl, int DC, const unsigned short HTDC[256][2], const unsigned short HTAC[256][2]) {\n   const unsigned short EOB[2] = { HTAC[0x00][0], HTAC[0x00][1] };\n   const unsigned short M16zeroes[2] = { HTAC[0xF0][0], HTAC[0xF0][1] };\n   int dataOff, i, j, n, diff, end0pos, x, y;\n   int DU[64];\n\n   // DCT rows\n   for(dataOff=0, n=du_stride*8; dataOff<n; dataOff+=du_stride) {\n      stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+1], &CDU[dataOff+2], &CDU[dataOff+3], &CDU[dataOff+4], &CDU[dataOff+5], &CDU[dataOff+6], &CDU[dataOff+7]);\n   }\n   // DCT columns\n   for(dataOff=0; dataOff<8; ++dataOff) {\n      stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+du_stride], &CDU[dataOff+du_stride*2], &CDU[dataOff+du_stride*3], &CDU[dataOff+du_stride*4],\n                     &CDU[dataOff+du_stride*5], &CDU[dataOff+du_stride*6], &CDU[dataOff+du_stride*7]);\n   }\n   // Quantize/descale/zigzag the coefficients\n   for(y = 0, j=0; y < 8; ++y) {\n      for(x = 0; x < 8; ++x,++j) {\n         float v;\n         i = y*du_stride+x;\n         v = CDU[i]*fdtbl[j];\n         // DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f));\n         // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway?\n         DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? v - 0.5f : v + 0.5f);\n      }\n   }\n\n   // Encode DC\n   diff = DU[0] - DC;\n   if (diff == 0) {\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]);\n   } else {\n      unsigned short bits[2];\n      stbiw__jpg_calcBits(diff, bits);\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]);\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);\n   }\n   // Encode ACs\n   end0pos = 63;\n   for(; (end0pos>0)&&(DU[end0pos]==0); --end0pos) {\n   }\n   // end0pos = first element in reverse order !=0\n   if(end0pos == 0) {\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);\n      return DU[0];\n   }\n   for(i = 1; i <= end0pos; ++i) {\n      int startpos = i;\n      int nrzeroes;\n      unsigned short bits[2];\n      for (; DU[i]==0 && i<=end0pos; ++i) {\n      }\n      nrzeroes = i-startpos;\n      if ( nrzeroes >= 16 ) {\n         int lng = nrzeroes>>4;\n         int nrmarker;\n         for (nrmarker=1; nrmarker <= lng; ++nrmarker)\n            stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes);\n         nrzeroes &= 15;\n      }\n      stbiw__jpg_calcBits(DU[i], bits);\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]);\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);\n   }\n   if(end0pos != 63) {\n      stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);\n   }\n   return DU[0];\n}\n\nstatic int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) {\n   // Constants that don't pollute global namespace\n   static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0};\n   static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11};\n   static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d};\n   static const unsigned char std_ac_luminance_values[] = {\n      0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,\n      0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,\n      0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,\n      0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,\n      0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,\n      0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,\n      0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa\n   };\n   static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0};\n   static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11};\n   static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77};\n   static const unsigned char std_ac_chrominance_values[] = {\n      0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,\n      0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,\n      0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,\n      0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,\n      0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,\n      0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,\n      0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa\n   };\n   // Huffman tables\n   static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}};\n   static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}};\n   static const unsigned short YAC_HT[256][2] = {\n      {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0}\n   };\n   static const unsigned short UVAC_HT[256][2] = {\n      {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0},\n      {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0}\n   };\n   static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,\n                             37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99};\n   static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,\n                              99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99};\n   static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f,\n                                 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f };\n\n   int row, col, i, k, subsample;\n   float fdtbl_Y[64], fdtbl_UV[64];\n   unsigned char YTable[64], UVTable[64];\n\n   if(!data || !width || !height || comp > 4 || comp < 1) {\n      return 0;\n   }\n\n   quality = quality ? quality : 90;\n   subsample = quality <= 90 ? 1 : 0;\n   quality = quality < 1 ? 1 : quality > 100 ? 100 : quality;\n   quality = quality < 50 ? 5000 / quality : 200 - quality * 2;\n\n   for(i = 0; i < 64; ++i) {\n      int uvti, yti = (YQT[i]*quality+50)/100;\n      YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti);\n      uvti = (UVQT[i]*quality+50)/100;\n      UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti);\n   }\n\n   for(row = 0, k = 0; row < 8; ++row) {\n      for(col = 0; col < 8; ++col, ++k) {\n         fdtbl_Y[k]  = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);\n         fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);\n      }\n   }\n\n   // Write Headers\n   {\n      static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 };\n      static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 };\n      const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width),\n                                      3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 };\n      s->func(s->context, (void*)head0, sizeof(head0));\n      s->func(s->context, (void*)YTable, sizeof(YTable));\n      stbiw__putc(s, 1);\n      s->func(s->context, UVTable, sizeof(UVTable));\n      s->func(s->context, (void*)head1, sizeof(head1));\n      s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1);\n      s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values));\n      stbiw__putc(s, 0x10); // HTYACinfo\n      s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1);\n      s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values));\n      stbiw__putc(s, 1); // HTUDCinfo\n      s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1);\n      s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values));\n      stbiw__putc(s, 0x11); // HTUACinfo\n      s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1);\n      s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values));\n      s->func(s->context, (void*)head2, sizeof(head2));\n   }\n\n   // Encode 8x8 macroblocks\n   {\n      static const unsigned short fillBits[] = {0x7F, 7};\n      int DCY=0, DCU=0, DCV=0;\n      int bitBuf=0, bitCnt=0;\n      // comp == 2 is grey+alpha (alpha is ignored)\n      int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0;\n      const unsigned char *dataR = (const unsigned char *)data;\n      const unsigned char *dataG = dataR + ofsG;\n      const unsigned char *dataB = dataR + ofsB;\n      int x, y, pos;\n      if(subsample) {\n         for(y = 0; y < height; y += 16) {\n            for(x = 0; x < width; x += 16) {\n               float Y[256], U[256], V[256];\n               for(row = y, pos = 0; row < y+16; ++row) {\n                  // row >= height => use last input row\n                  int clamped_row = (row < height) ? row : height - 1;\n                  int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp;\n                  for(col = x; col < x+16; ++col, ++pos) {\n                     // if col >= width => use pixel from last input column\n                     int p = base_p + ((col < width) ? col : (width-1))*comp;\n                     float r = dataR[p], g = dataG[p], b = dataB[p];\n                     Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128;\n                     U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b;\n                     V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b;\n                  }\n               }\n               DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0,   16, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n               DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8,   16, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n               DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n               DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n\n               // subsample U,V\n               {\n                  float subU[64], subV[64];\n                  int yy, xx;\n                  for(yy = 0, pos = 0; yy < 8; ++yy) {\n                     for(xx = 0; xx < 8; ++xx, ++pos) {\n                        int j = yy*32+xx*2;\n                        subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f;\n                        subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f;\n                     }\n                  }\n                  DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);\n                  DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);\n               }\n            }\n         }\n      } else {\n         for(y = 0; y < height; y += 8) {\n            for(x = 0; x < width; x += 8) {\n               float Y[64], U[64], V[64];\n               for(row = y, pos = 0; row < y+8; ++row) {\n                  // row >= height => use last input row\n                  int clamped_row = (row < height) ? row : height - 1;\n                  int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp;\n                  for(col = x; col < x+8; ++col, ++pos) {\n                     // if col >= width => use pixel from last input column\n                     int p = base_p + ((col < width) ? col : (width-1))*comp;\n                     float r = dataR[p], g = dataG[p], b = dataB[p];\n                     Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128;\n                     U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b;\n                     V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b;\n                  }\n               }\n\n               DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y,  DCY, YDC_HT, YAC_HT);\n               DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);\n               DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);\n            }\n         }\n      }\n\n      // Do the bit alignment of the EOI marker\n      stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits);\n   }\n\n   // EOI\n   stbiw__putc(s, 0xFF);\n   stbiw__putc(s, 0xD9);\n\n   return 1;\n}\n\nSTBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality)\n{\n   stbi__write_context s = { 0 };\n   stbi__start_write_callbacks(&s, func, context);\n   return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality);\n}\n\n\n#ifndef STBI_WRITE_NO_STDIO\nSTBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality)\n{\n   stbi__write_context s = { 0 };\n   if (stbi__start_write_file(&s,filename)) {\n      int r = stbi_write_jpg_core(&s, x, y, comp, data, quality);\n      stbi__end_write_file(&s);\n      return r;\n   } else\n      return 0;\n}\n#endif\n\n#endif // STB_IMAGE_WRITE_IMPLEMENTATION\n\n/* Revision history\n      1.16  (2021-07-11)\n             make Deflate code emit uncompressed blocks when it would otherwise expand\n             support writing BMPs with alpha channel\n      1.15  (2020-07-13) unknown\n      1.14  (2020-02-02) updated JPEG writer to downsample chroma channels\n      1.13\n      1.12\n      1.11  (2019-08-11)\n\n      1.10  (2019-02-07)\n             support utf8 filenames in Windows; fix warnings and platform ifdefs\n      1.09  (2018-02-11)\n             fix typo in zlib quality API, improve STB_I_W_STATIC in C++\n      1.08  (2018-01-29)\n             add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter\n      1.07  (2017-07-24)\n             doc fix\n      1.06 (2017-07-23)\n             writing JPEG (using Jon Olick's code)\n      1.05   ???\n      1.04 (2017-03-03)\n             monochrome BMP expansion\n      1.03   ???\n      1.02 (2016-04-02)\n             avoid allocating large structures on the stack\n      1.01 (2016-01-16)\n             STBIW_REALLOC_SIZED: support allocators with no realloc support\n             avoid race-condition in crc initialization\n             minor compile issues\n      1.00 (2015-09-14)\n             installable file IO function\n      0.99 (2015-09-13)\n             warning fixes; TGA rle support\n      0.98 (2015-04-08)\n             added STBIW_MALLOC, STBIW_ASSERT etc\n      0.97 (2015-01-18)\n             fixed HDR asserts, rewrote HDR rle logic\n      0.96 (2015-01-17)\n             add HDR output\n             fix monochrome BMP\n      0.95 (2014-08-17)\n             add monochrome TGA output\n      0.94 (2014-05-31)\n             rename private functions to avoid conflicts with stb_image.h\n      0.93 (2014-05-27)\n             warning fixes\n      0.92 (2010-08-01)\n             casts to unsigned char to fix warnings\n      0.91 (2010-07-17)\n             first public release\n      0.90   first internal release\n*/\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_include.h",
    "content": "// stb_include.h - v0.02 - parse and process #include directives - public domain\n//\n// To build this, in one source file that includes this file do\n//      #define STB_INCLUDE_IMPLEMENTATION\n//\n// This program parses a string and replaces lines of the form\n//         #include \"foo\"\n// with the contents of a file named \"foo\". It also embeds the\n// appropriate #line directives. Note that all include files must\n// reside in the location specified in the path passed to the API;\n// it does not check multiple directories.\n//\n// If the string contains a line of the form\n//         #inject\n// then it will be replaced with the contents of the string 'inject' passed to the API.\n//\n// Options:\n//\n//      Define STB_INCLUDE_LINE_GLSL to get GLSL-style #line directives\n//      which use numbers instead of filenames.\n//\n//      Define STB_INCLUDE_LINE_NONE to disable output of #line directives.\n//\n// Standard libraries:\n//\n//      stdio.h     FILE, fopen, fclose, fseek, ftell\n//      stdlib.h    malloc, realloc, free\n//      string.h    strcpy, strncmp, memcpy\n//\n// Credits:\n//\n// Written by Sean Barrett.\n//\n// Fixes:\n//  Michal Klos\n\n#ifndef STB_INCLUDE_STB_INCLUDE_H\n#define STB_INCLUDE_STB_INCLUDE_H\n\n// Do include-processing on the string 'str'. To free the return value, pass it to free()\nchar *stb_include_string(char *str, char *inject, char *path_to_includes, char *filename_for_line_directive, char error[256]);\n\n// Concatenate the strings 'strs' and do include-processing on the result. To free the return value, pass it to free()\nchar *stb_include_strings(char **strs, int count, char *inject, char *path_to_includes, char *filename_for_line_directive, char error[256]);\n\n// Load the file 'filename' and do include-processing on the string therein. note that\n// 'filename' is opened directly; 'path_to_includes' is not used. To free the return value, pass it to free()\nchar *stb_include_file(char *filename, char *inject, char *path_to_includes, char error[256]);\n\n#endif\n\n\n#ifdef STB_INCLUDE_IMPLEMENTATION\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic char *stb_include_load_file(char *filename, size_t *plen)\n{\n   char *text;\n   size_t len;\n   FILE *f = fopen(filename, \"rb\");\n   if (f == 0) return 0;\n   fseek(f, 0, SEEK_END);\n   len = (size_t) ftell(f);\n   if (plen) *plen = len;\n   text = (char *) malloc(len+1);\n   if (text == 0) return 0;\n   fseek(f, 0, SEEK_SET);\n   fread(text, 1, len, f);\n   fclose(f);\n   text[len] = 0;\n   return text;\n}\n\ntypedef struct\n{\n   int offset;\n   int end;\n   char *filename;\n   int next_line_after;\n} include_info;\n\nstatic include_info *stb_include_append_include(include_info *array, int len, int offset, int end, char *filename, int next_line)\n{\n   include_info *z = (include_info *) realloc(array, sizeof(*z) * (len+1));\n   z[len].offset   = offset;\n   z[len].end      = end;\n   z[len].filename = filename;\n   z[len].next_line_after = next_line;\n   return z;\n}\n\nstatic void stb_include_free_includes(include_info *array, int len)\n{\n   int i;\n   for (i=0; i < len; ++i)\n      free(array[i].filename);\n   free(array);\n}\n\nstatic int stb_include_isspace(int ch)\n{\n   return (ch == ' ' || ch == '\\t' || ch == '\\r' || ch == '\\n');\n}\n\n// find location of all #include and #inject\nstatic int stb_include_find_includes(char *text, include_info **plist)\n{\n   int line_count = 1;\n   int inc_count = 0;\n   char *s = text, *start;\n   include_info *list = NULL;\n   while (*s) {\n      // parse is always at start of line when we reach here\n      start = s;\n      while (*s == ' ' || *s == '\\t')\n         ++s;\n      if (*s == '#') {\n         ++s;\n         while (*s == ' ' || *s == '\\t')\n            ++s;\n         if (0==strncmp(s, \"include\", 7) && stb_include_isspace(s[7])) {\n            s += 7;\n            while (*s == ' ' || *s == '\\t')\n               ++s;\n            if (*s == '\"') {\n               char *t = ++s;\n               while (*t != '\"' && *t != '\\n' && *t != '\\r' && *t != 0)\n                  ++t;\n               if (*t == '\"') {\n                  char *filename = (char *) malloc(t-s+1);\n                  memcpy(filename, s, t-s);\n                  filename[t-s] = 0;\n                  s=t;\n                  while (*s != '\\r' && *s != '\\n' && *s != 0)\n                     ++s;\n                  // s points to the newline, so s-start is everything except the newline\n                  list = stb_include_append_include(list, inc_count++, start-text, s-text, filename, line_count+1);\n               }\n            }\n         } else if (0==strncmp(s, \"inject\", 6) && (stb_include_isspace(s[6]) || s[6]==0)) {\n            while (*s != '\\r' && *s != '\\n' && *s != 0)\n               ++s;\n            list = stb_include_append_include(list, inc_count++, start-text, s-text, NULL, line_count+1);\n         }\n      }\n      while (*s != '\\r' && *s != '\\n' && *s != 0)\n         ++s;\n      if (*s == '\\r' || *s == '\\n') {\n         s = s + (s[0] + s[1] == '\\r' + '\\n' ? 2 : 1);\n      }\n      ++line_count;\n   }\n   *plist = list;\n   return inc_count;\n}\n\n// avoid dependency on sprintf()\nstatic void stb_include_itoa(char str[9], int n)\n{\n   int i;\n   for (i=0; i < 8; ++i)\n      str[i] = ' ';\n   str[i] = 0;\n\n   for (i=1; i < 8; ++i) {\n      str[7-i] = '0' + (n % 10);\n      n /= 10;\n      if (n == 0)\n         break;\n   }\n}\n\nstatic char *stb_include_append(char *str, size_t *curlen, char *addstr, size_t addlen)\n{\n   str = (char *) realloc(str, *curlen + addlen);\n   memcpy(str + *curlen, addstr, addlen);\n   *curlen += addlen;\n   return str;\n}\n\nchar *stb_include_string(char *str, char *inject, char *path_to_includes, char *filename, char error[256])\n{\n   char temp[4096];\n   include_info *inc_list;\n   int i, num = stb_include_find_includes(str, &inc_list);\n   size_t source_len = strlen(str);\n   char *text=0;\n   size_t textlen=0, last=0;\n   for (i=0; i < num; ++i) {\n      text = stb_include_append(text, &textlen, str+last, inc_list[i].offset - last);\n      // write out line directive for the include\n      #ifndef STB_INCLUDE_LINE_NONE\n      #ifdef STB_INCLUDE_LINE_GLSL\n      if (textlen != 0)  // GLSL #version must appear first, so don't put a #line at the top\n      #endif\n      {\n         strcpy(temp, \"#line \");\n         stb_include_itoa(temp+6, 1);\n         strcat(temp, \" \");\n         #ifdef STB_INCLUDE_LINE_GLSL\n         stb_include_itoa(temp+15, i+1);\n         #else\n         strcat(temp, \"\\\"\");\n         if (inc_list[i].filename == 0)\n            strcmp(temp, \"INJECT\");\n         else\n            strcat(temp, inc_list[i].filename);\n         strcat(temp, \"\\\"\");\n         #endif\n         strcat(temp, \"\\n\");\n         text = stb_include_append(text, &textlen, temp, strlen(temp));\n      }\n      #endif\n      if (inc_list[i].filename == 0) {\n         if (inject != 0)\n            text = stb_include_append(text, &textlen, inject, strlen(inject));\n      } else {\n         char *inc;\n         strcpy(temp, path_to_includes);\n         strcat(temp, \"/\");\n         strcat(temp, inc_list[i].filename);\n         inc = stb_include_file(temp, inject, path_to_includes, error);\n         if (inc == NULL) {\n            stb_include_free_includes(inc_list, num);\n            return NULL;\n         }\n         text = stb_include_append(text, &textlen, inc, strlen(inc));\n         free(inc);\n      }\n      // write out line directive\n      #ifndef STB_INCLUDE_LINE_NONE\n      strcpy(temp, \"\\n#line \");\n      stb_include_itoa(temp+6, inc_list[i].next_line_after);\n      strcat(temp, \" \");\n      #ifdef STB_INCLUDE_LINE_GLSL\n      stb_include_itoa(temp+15, 0);\n      #else\n      strcat(temp, filename != 0 ? filename : \"source-file\");\n      #endif\n      text = stb_include_append(text, &textlen, temp, strlen(temp));\n      // no newlines, because we kept the #include newlines, which will get appended next\n      #endif\n      last = inc_list[i].end;\n   }\n   text = stb_include_append(text, &textlen, str+last, source_len - last + 1); // append '\\0'\n   stb_include_free_includes(inc_list, num);\n   return text;\n}\n\nchar *stb_include_strings(char **strs, int count, char *inject, char *path_to_includes, char *filename, char error[256])\n{\n   char *text;\n   char *result;\n   int i;\n   size_t length=0;\n   for (i=0; i < count; ++i)\n      length += strlen(strs[i]);\n   text = (char *) malloc(length+1);\n   length = 0;\n   for (i=0; i < count; ++i) {\n      strcpy(text + length, strs[i]);\n      length += strlen(strs[i]);\n   }\n   result = stb_include_string(text, inject, path_to_includes, filename, error);\n   free(text);\n   return result;\n}\n\nchar *stb_include_file(char *filename, char *inject, char *path_to_includes, char error[256])\n{\n   size_t len;\n   char *result;\n   char *text = stb_include_load_file(filename, &len);\n   if (text == NULL) {\n      strcpy(error, \"Error: couldn't load '\");\n      strcat(error, filename);\n      strcat(error, \"'\");\n      return 0;\n   }\n   result = stb_include_string(text, inject, path_to_includes, filename, error);\n   free(text);\n   return result;\n}\n\n#if 0 // @TODO, GL_ARB_shader_language_include-style system that doesn't touch filesystem\nchar *stb_include_preloaded(char *str, char *inject, char *includes[][2], char error[256])\n{\n\n}\n#endif\n\n#endif // STB_INCLUDE_IMPLEMENTATION\n"
  },
  {
    "path": "stb_leakcheck.h",
    "content": "// stb_leakcheck.h - v0.6 - quick & dirty malloc leak-checking - public domain\n// LICENSE\n//\n//   See end of file.\n\n#ifdef STB_LEAKCHECK_IMPLEMENTATION\n#undef STB_LEAKCHECK_IMPLEMENTATION // don't implement more than once\n\n// if we've already included leakcheck before, undefine the macros\n#ifdef malloc\n#undef malloc\n#undef free\n#undef realloc\n#endif\n\n#ifndef STB_LEAKCHECK_OUTPUT_PIPE\n#define STB_LEAKCHECK_OUTPUT_PIPE stdout\n#endif\n\n#include <assert.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <stddef.h>\ntypedef struct malloc_info stb_leakcheck_malloc_info;\n\nstruct malloc_info\n{\n   const char *file;\n   int line;\n   size_t size;\n   stb_leakcheck_malloc_info *next,*prev;\n};\n\nstatic stb_leakcheck_malloc_info *mi_head;\n\nvoid *stb_leakcheck_malloc(size_t sz, const char *file, int line)\n{\n   stb_leakcheck_malloc_info *mi = (stb_leakcheck_malloc_info *) malloc(sz + sizeof(*mi));\n   if (mi == NULL) return mi;\n   mi->file = file;\n   mi->line = line;\n   mi->next = mi_head;\n   if (mi_head)\n      mi->next->prev = mi;\n   mi->prev = NULL;\n   mi->size = (int) sz;\n   mi_head = mi;\n   return mi+1;\n}\n\nvoid stb_leakcheck_free(void *ptr)\n{\n   if (ptr != NULL) {\n      stb_leakcheck_malloc_info *mi = (stb_leakcheck_malloc_info *) ptr - 1;\n      mi->size = ~mi->size;\n      #ifndef STB_LEAKCHECK_SHOWALL\n      if (mi->prev == NULL) {\n         assert(mi_head == mi);\n         mi_head = mi->next;\n      } else\n         mi->prev->next = mi->next;\n      if (mi->next)\n         mi->next->prev = mi->prev;\n      free(mi);\n      #endif\n   }\n}\n\nvoid *stb_leakcheck_realloc(void *ptr, size_t sz, const char *file, int line)\n{\n   if (ptr == NULL) {\n      return stb_leakcheck_malloc(sz, file, line);\n   } else if (sz == 0) {\n      stb_leakcheck_free(ptr);\n      return NULL;\n   } else {\n      stb_leakcheck_malloc_info *mi = (stb_leakcheck_malloc_info *) ptr - 1;\n      if (sz <= mi->size)\n         return ptr;\n      else {\n         #ifdef STB_LEAKCHECK_REALLOC_PRESERVE_MALLOC_FILELINE\n         void *q = stb_leakcheck_malloc(sz, mi->file, mi->line);\n         #else\n         void *q = stb_leakcheck_malloc(sz, file, line);\n         #endif\n         if (q) {\n            memcpy(q, ptr, mi->size);\n            stb_leakcheck_free(ptr);\n         }\n         return q;\n      }\n   }\n}\n\nstatic void stblkck_internal_print(const char *reason, stb_leakcheck_malloc_info *mi)\n{\n#if defined(_MSC_VER) && _MSC_VER < 1900 // 1900=VS 2015\n   // Compilers that use the old MS C runtime library don't have %zd\n   // and the older ones don't even have %lld either... however, the old compilers\n   // without \"long long\" don't support 64-bit targets either, so here's the\n   // compromise:\n   #if _MSC_VER < 1400 // before VS 2005\n      fprintf(STB_LEAKCHECK_OUTPUT_PIPE, \"%s: %s (%4d): %8d bytes at %p\\n\", reason, mi->file, mi->line, (int)mi->size, (void*)(mi+1));\n   #else\n      fprintf(STB_LEAKCHECK_OUTPUT_PIPE, \"%s: %s (%4d): %16lld bytes at %p\\n\", reason, mi->file, mi->line, (long long)mi->size, (void*)(mi+1));\n   #endif\n#else\n   // Assume we have %zd on other targets.\n   #ifdef __MINGW32__\n      __mingw_fprintf(STB_LEAKCHECK_OUTPUT_PIPE, \"%s: %s (%4d): %zd bytes at %p\\n\", reason, mi->file, mi->line, mi->size, (void*)(mi+1));\n   #else\n      fprintf(STB_LEAKCHECK_OUTPUT_PIPE, \"%s: %s (%4d): %zd bytes at %p\\n\", reason, mi->file, mi->line, mi->size, (void*)(mi+1));\n   #endif\n#endif\n}\n\nvoid stb_leakcheck_dumpmem(void)\n{\n   stb_leakcheck_malloc_info *mi = mi_head;\n   while (mi) {\n      if ((ptrdiff_t) mi->size >= 0)\n         stblkck_internal_print(\"LEAKED\", mi);\n      mi = mi->next;\n   }\n   #ifdef STB_LEAKCHECK_SHOWALL\n   mi = mi_head;\n   while (mi) {\n      if ((ptrdiff_t) mi->size < 0)\n         stblkck_internal_print(\"FREED \", mi);\n      mi = mi->next;\n   }\n   #endif\n}\n#endif // STB_LEAKCHECK_IMPLEMENTATION\n\n#if !defined(INCLUDE_STB_LEAKCHECK_H) || !defined(malloc)\n#define INCLUDE_STB_LEAKCHECK_H\n\n#include <stdlib.h> // we want to define the macros *after* stdlib to avoid a slew of errors\n\n#define malloc(sz)    stb_leakcheck_malloc(sz, __FILE__, __LINE__)\n#define free(p)       stb_leakcheck_free(p)\n#define realloc(p,sz) stb_leakcheck_realloc(p,sz, __FILE__, __LINE__)\n\nextern void * stb_leakcheck_malloc(size_t sz, const char *file, int line);\nextern void * stb_leakcheck_realloc(void *ptr, size_t sz, const char *file, int line);\nextern void   stb_leakcheck_free(void *ptr);\nextern void   stb_leakcheck_dumpmem(void);\n\n#endif // INCLUDE_STB_LEAKCHECK_H\n\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_perlin.h",
    "content": "// stb_perlin.h - v0.5 - perlin noise\n// public domain single-file C implementation by Sean Barrett\n//\n// LICENSE\n//\n//   See end of file.\n//\n//\n// to create the implementation,\n//     #define STB_PERLIN_IMPLEMENTATION\n// in *one* C/CPP file that includes this file.\n//\n//\n// Documentation:\n//\n// float  stb_perlin_noise3( float x,\n//                           float y,\n//                           float z,\n//                           int   x_wrap=0,\n//                           int   y_wrap=0,\n//                           int   z_wrap=0)\n//\n// This function computes a random value at the coordinate (x,y,z).\n// Adjacent random values are continuous but the noise fluctuates\n// its randomness with period 1, i.e. takes on wholly unrelated values\n// at integer points. Specifically, this implements Ken Perlin's\n// revised noise function from 2002.\n//\n// The \"wrap\" parameters can be used to create wraparound noise that\n// wraps at powers of two. The numbers MUST be powers of two. Specify\n// 0 to mean \"don't care\". (The noise always wraps every 256 due\n// details of the implementation, even if you ask for larger or no\n// wrapping.)\n//\n// float  stb_perlin_noise3_seed( float x,\n//                                float y,\n//                                float z,\n//                                int   x_wrap=0,\n//                                int   y_wrap=0,\n//                                int   z_wrap=0,\n//                                int   seed)\n//\n// As above, but 'seed' selects from multiple different variations of the\n// noise function. The current implementation only uses the bottom 8 bits\n// of 'seed', but possibly in the future more bits will be used.\n//\n//\n// Fractal Noise:\n//\n// Three common fractal noise functions are included, which produce\n// a wide variety of nice effects depending on the parameters\n// provided. Note that each function will call stb_perlin_noise3\n// 'octaves' times, so this parameter will affect runtime.\n//\n// float stb_perlin_ridge_noise3(float x, float y, float z,\n//                               float lacunarity, float gain, float offset, int octaves)\n//\n// float stb_perlin_fbm_noise3(float x, float y, float z,\n//                             float lacunarity, float gain, int octaves)\n//\n// float stb_perlin_turbulence_noise3(float x, float y, float z,\n//                                    float lacunarity, float gain, int octaves)\n//\n// Typical values to start playing with:\n//     octaves    =   6     -- number of \"octaves\" of noise3() to sum\n//     lacunarity = ~ 2.0   -- spacing between successive octaves (use exactly 2.0 for wrapping output)\n//     gain       =   0.5   -- relative weighting applied to each successive octave\n//     offset     =   1.0?  -- used to invert the ridges, may need to be larger, not sure\n//\n//\n// Contributors:\n//    Jack Mott - additional noise functions\n//    Jordan Peck - seeded noise\n//\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nextern float stb_perlin_noise3(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap);\nextern float stb_perlin_noise3_seed(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, int seed);\nextern float stb_perlin_ridge_noise3(float x, float y, float z, float lacunarity, float gain, float offset, int octaves);\nextern float stb_perlin_fbm_noise3(float x, float y, float z, float lacunarity, float gain, int octaves);\nextern float stb_perlin_turbulence_noise3(float x, float y, float z, float lacunarity, float gain, int octaves);\nextern float stb_perlin_noise3_wrap_nonpow2(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, unsigned char seed);\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef STB_PERLIN_IMPLEMENTATION\n\n#include <math.h> // fabs()\n\n// not same permutation table as Perlin's reference to avoid copyright issues;\n// Perlin's table can be found at http://mrl.nyu.edu/~perlin/noise/\nstatic unsigned char stb__perlin_randtab[512] =\n{\n   23, 125, 161, 52, 103, 117, 70, 37, 247, 101, 203, 169, 124, 126, 44, 123,\n   152, 238, 145, 45, 171, 114, 253, 10, 192, 136, 4, 157, 249, 30, 35, 72,\n   175, 63, 77, 90, 181, 16, 96, 111, 133, 104, 75, 162, 93, 56, 66, 240,\n   8, 50, 84, 229, 49, 210, 173, 239, 141, 1, 87, 18, 2, 198, 143, 57,\n   225, 160, 58, 217, 168, 206, 245, 204, 199, 6, 73, 60, 20, 230, 211, 233,\n   94, 200, 88, 9, 74, 155, 33, 15, 219, 130, 226, 202, 83, 236, 42, 172,\n   165, 218, 55, 222, 46, 107, 98, 154, 109, 67, 196, 178, 127, 158, 13, 243,\n   65, 79, 166, 248, 25, 224, 115, 80, 68, 51, 184, 128, 232, 208, 151, 122,\n   26, 212, 105, 43, 179, 213, 235, 148, 146, 89, 14, 195, 28, 78, 112, 76,\n   250, 47, 24, 251, 140, 108, 186, 190, 228, 170, 183, 139, 39, 188, 244, 246,\n   132, 48, 119, 144, 180, 138, 134, 193, 82, 182, 120, 121, 86, 220, 209, 3,\n   91, 241, 149, 85, 205, 150, 113, 216, 31, 100, 41, 164, 177, 214, 153, 231,\n   38, 71, 185, 174, 97, 201, 29, 95, 7, 92, 54, 254, 191, 118, 34, 221,\n   131, 11, 163, 99, 234, 81, 227, 147, 156, 176, 17, 142, 69, 12, 110, 62,\n   27, 255, 0, 194, 59, 116, 242, 252, 19, 21, 187, 53, 207, 129, 64, 135,\n   61, 40, 167, 237, 102, 223, 106, 159, 197, 189, 215, 137, 36, 32, 22, 5,\n\n   // and a second copy so we don't need an extra mask or static initializer\n   23, 125, 161, 52, 103, 117, 70, 37, 247, 101, 203, 169, 124, 126, 44, 123,\n   152, 238, 145, 45, 171, 114, 253, 10, 192, 136, 4, 157, 249, 30, 35, 72,\n   175, 63, 77, 90, 181, 16, 96, 111, 133, 104, 75, 162, 93, 56, 66, 240,\n   8, 50, 84, 229, 49, 210, 173, 239, 141, 1, 87, 18, 2, 198, 143, 57,\n   225, 160, 58, 217, 168, 206, 245, 204, 199, 6, 73, 60, 20, 230, 211, 233,\n   94, 200, 88, 9, 74, 155, 33, 15, 219, 130, 226, 202, 83, 236, 42, 172,\n   165, 218, 55, 222, 46, 107, 98, 154, 109, 67, 196, 178, 127, 158, 13, 243,\n   65, 79, 166, 248, 25, 224, 115, 80, 68, 51, 184, 128, 232, 208, 151, 122,\n   26, 212, 105, 43, 179, 213, 235, 148, 146, 89, 14, 195, 28, 78, 112, 76,\n   250, 47, 24, 251, 140, 108, 186, 190, 228, 170, 183, 139, 39, 188, 244, 246,\n   132, 48, 119, 144, 180, 138, 134, 193, 82, 182, 120, 121, 86, 220, 209, 3,\n   91, 241, 149, 85, 205, 150, 113, 216, 31, 100, 41, 164, 177, 214, 153, 231,\n   38, 71, 185, 174, 97, 201, 29, 95, 7, 92, 54, 254, 191, 118, 34, 221,\n   131, 11, 163, 99, 234, 81, 227, 147, 156, 176, 17, 142, 69, 12, 110, 62,\n   27, 255, 0, 194, 59, 116, 242, 252, 19, 21, 187, 53, 207, 129, 64, 135,\n   61, 40, 167, 237, 102, 223, 106, 159, 197, 189, 215, 137, 36, 32, 22, 5,\n};\n\n\n// perlin's gradient has 12 cases so some get used 1/16th of the time\n// and some 2/16ths. We reduce bias by changing those fractions\n// to 5/64ths and 6/64ths\n\n// this array is designed to match the previous implementation\n// of gradient hash: indices[stb__perlin_randtab[i]&63]\nstatic unsigned char stb__perlin_randtab_grad_idx[512] =\n{\n    7, 9, 5, 0, 11, 1, 6, 9, 3, 9, 11, 1, 8, 10, 4, 7,\n    8, 6, 1, 5, 3, 10, 9, 10, 0, 8, 4, 1, 5, 2, 7, 8,\n    7, 11, 9, 10, 1, 0, 4, 7, 5, 0, 11, 6, 1, 4, 2, 8,\n    8, 10, 4, 9, 9, 2, 5, 7, 9, 1, 7, 2, 2, 6, 11, 5,\n    5, 4, 6, 9, 0, 1, 1, 0, 7, 6, 9, 8, 4, 10, 3, 1,\n    2, 8, 8, 9, 10, 11, 5, 11, 11, 2, 6, 10, 3, 4, 2, 4,\n    9, 10, 3, 2, 6, 3, 6, 10, 5, 3, 4, 10, 11, 2, 9, 11,\n    1, 11, 10, 4, 9, 4, 11, 0, 4, 11, 4, 0, 0, 0, 7, 6,\n    10, 4, 1, 3, 11, 5, 3, 4, 2, 9, 1, 3, 0, 1, 8, 0,\n    6, 7, 8, 7, 0, 4, 6, 10, 8, 2, 3, 11, 11, 8, 0, 2,\n    4, 8, 3, 0, 0, 10, 6, 1, 2, 2, 4, 5, 6, 0, 1, 3,\n    11, 9, 5, 5, 9, 6, 9, 8, 3, 8, 1, 8, 9, 6, 9, 11,\n    10, 7, 5, 6, 5, 9, 1, 3, 7, 0, 2, 10, 11, 2, 6, 1,\n    3, 11, 7, 7, 2, 1, 7, 3, 0, 8, 1, 1, 5, 0, 6, 10,\n    11, 11, 0, 2, 7, 0, 10, 8, 3, 5, 7, 1, 11, 1, 0, 7,\n    9, 0, 11, 5, 10, 3, 2, 3, 5, 9, 7, 9, 8, 4, 6, 5,\n\n    // and a second copy so we don't need an extra mask or static initializer\n    7, 9, 5, 0, 11, 1, 6, 9, 3, 9, 11, 1, 8, 10, 4, 7,\n    8, 6, 1, 5, 3, 10, 9, 10, 0, 8, 4, 1, 5, 2, 7, 8,\n    7, 11, 9, 10, 1, 0, 4, 7, 5, 0, 11, 6, 1, 4, 2, 8,\n    8, 10, 4, 9, 9, 2, 5, 7, 9, 1, 7, 2, 2, 6, 11, 5,\n    5, 4, 6, 9, 0, 1, 1, 0, 7, 6, 9, 8, 4, 10, 3, 1,\n    2, 8, 8, 9, 10, 11, 5, 11, 11, 2, 6, 10, 3, 4, 2, 4,\n    9, 10, 3, 2, 6, 3, 6, 10, 5, 3, 4, 10, 11, 2, 9, 11,\n    1, 11, 10, 4, 9, 4, 11, 0, 4, 11, 4, 0, 0, 0, 7, 6,\n    10, 4, 1, 3, 11, 5, 3, 4, 2, 9, 1, 3, 0, 1, 8, 0,\n    6, 7, 8, 7, 0, 4, 6, 10, 8, 2, 3, 11, 11, 8, 0, 2,\n    4, 8, 3, 0, 0, 10, 6, 1, 2, 2, 4, 5, 6, 0, 1, 3,\n    11, 9, 5, 5, 9, 6, 9, 8, 3, 8, 1, 8, 9, 6, 9, 11,\n    10, 7, 5, 6, 5, 9, 1, 3, 7, 0, 2, 10, 11, 2, 6, 1,\n    3, 11, 7, 7, 2, 1, 7, 3, 0, 8, 1, 1, 5, 0, 6, 10,\n    11, 11, 0, 2, 7, 0, 10, 8, 3, 5, 7, 1, 11, 1, 0, 7,\n    9, 0, 11, 5, 10, 3, 2, 3, 5, 9, 7, 9, 8, 4, 6, 5,\n};\n\nstatic float stb__perlin_lerp(float a, float b, float t)\n{\n   return a + (b-a) * t;\n}\n\nstatic int stb__perlin_fastfloor(float a)\n{\n    int ai = (int) a;\n    return (a < ai) ? ai-1 : ai;\n}\n\n// different grad function from Perlin's, but easy to modify to match reference\nstatic float stb__perlin_grad(int grad_idx, float x, float y, float z)\n{\n   static float basis[12][4] =\n   {\n      {  1, 1, 0 },\n      { -1, 1, 0 },\n      {  1,-1, 0 },\n      { -1,-1, 0 },\n      {  1, 0, 1 },\n      { -1, 0, 1 },\n      {  1, 0,-1 },\n      { -1, 0,-1 },\n      {  0, 1, 1 },\n      {  0,-1, 1 },\n      {  0, 1,-1 },\n      {  0,-1,-1 },\n   };\n\n   float *grad = basis[grad_idx];\n   return grad[0]*x + grad[1]*y + grad[2]*z;\n}\n\nfloat stb_perlin_noise3_internal(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, unsigned char seed)\n{\n   float u,v,w;\n   float n000,n001,n010,n011,n100,n101,n110,n111;\n   float n00,n01,n10,n11;\n   float n0,n1;\n\n   unsigned int x_mask = (x_wrap-1) & 255;\n   unsigned int y_mask = (y_wrap-1) & 255;\n   unsigned int z_mask = (z_wrap-1) & 255;\n   int px = stb__perlin_fastfloor(x);\n   int py = stb__perlin_fastfloor(y);\n   int pz = stb__perlin_fastfloor(z);\n   int x0 = px & x_mask, x1 = (px+1) & x_mask;\n   int y0 = py & y_mask, y1 = (py+1) & y_mask;\n   int z0 = pz & z_mask, z1 = (pz+1) & z_mask;\n   int r0,r1, r00,r01,r10,r11;\n\n   #define stb__perlin_ease(a)   (((a*6-15)*a + 10) * a * a * a)\n\n   x -= px; u = stb__perlin_ease(x);\n   y -= py; v = stb__perlin_ease(y);\n   z -= pz; w = stb__perlin_ease(z);\n\n   r0 = stb__perlin_randtab[x0+seed];\n   r1 = stb__perlin_randtab[x1+seed];\n\n   r00 = stb__perlin_randtab[r0+y0];\n   r01 = stb__perlin_randtab[r0+y1];\n   r10 = stb__perlin_randtab[r1+y0];\n   r11 = stb__perlin_randtab[r1+y1];\n\n   n000 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r00+z0], x  , y  , z   );\n   n001 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r00+z1], x  , y  , z-1 );\n   n010 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r01+z0], x  , y-1, z   );\n   n011 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r01+z1], x  , y-1, z-1 );\n   n100 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r10+z0], x-1, y  , z   );\n   n101 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r10+z1], x-1, y  , z-1 );\n   n110 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r11+z0], x-1, y-1, z   );\n   n111 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r11+z1], x-1, y-1, z-1 );\n\n   n00 = stb__perlin_lerp(n000,n001,w);\n   n01 = stb__perlin_lerp(n010,n011,w);\n   n10 = stb__perlin_lerp(n100,n101,w);\n   n11 = stb__perlin_lerp(n110,n111,w);\n\n   n0 = stb__perlin_lerp(n00,n01,v);\n   n1 = stb__perlin_lerp(n10,n11,v);\n\n   return stb__perlin_lerp(n0,n1,u);\n}\n\nfloat stb_perlin_noise3(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap)\n{\n    return stb_perlin_noise3_internal(x,y,z,x_wrap,y_wrap,z_wrap,0);\n}\n\nfloat stb_perlin_noise3_seed(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, int seed)\n{\n    return stb_perlin_noise3_internal(x,y,z,x_wrap,y_wrap,z_wrap, (unsigned char) seed);\n}\n\nfloat stb_perlin_ridge_noise3(float x, float y, float z, float lacunarity, float gain, float offset, int octaves)\n{\n   int i;\n   float frequency = 1.0f;\n   float prev = 1.0f;\n   float amplitude = 0.5f;\n   float sum = 0.0f;\n\n   for (i = 0; i < octaves; i++) {\n      float r = stb_perlin_noise3_internal(x*frequency,y*frequency,z*frequency,0,0,0,(unsigned char)i);\n      r = offset - (float) fabs(r);\n      r = r*r;\n      sum += r*amplitude*prev;\n      prev = r;\n      frequency *= lacunarity;\n      amplitude *= gain;\n   }\n   return sum;\n}\n\nfloat stb_perlin_fbm_noise3(float x, float y, float z, float lacunarity, float gain, int octaves)\n{\n   int i;\n   float frequency = 1.0f;\n   float amplitude = 1.0f;\n   float sum = 0.0f;\n\n   for (i = 0; i < octaves; i++) {\n      sum += stb_perlin_noise3_internal(x*frequency,y*frequency,z*frequency,0,0,0,(unsigned char)i)*amplitude;\n      frequency *= lacunarity;\n      amplitude *= gain;\n   }\n   return sum;\n}\n\nfloat stb_perlin_turbulence_noise3(float x, float y, float z, float lacunarity, float gain, int octaves)\n{\n   int i;\n   float frequency = 1.0f;\n   float amplitude = 1.0f;\n   float sum = 0.0f;\n\n   for (i = 0; i < octaves; i++) {\n      float r = stb_perlin_noise3_internal(x*frequency,y*frequency,z*frequency,0,0,0,(unsigned char)i)*amplitude;\n      sum += (float) fabs(r);\n      frequency *= lacunarity;\n      amplitude *= gain;\n   }\n   return sum;\n}\n\nfloat stb_perlin_noise3_wrap_nonpow2(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, unsigned char seed)\n{\n   float u,v,w;\n   float n000,n001,n010,n011,n100,n101,n110,n111;\n   float n00,n01,n10,n11;\n   float n0,n1;\n\n   int px = stb__perlin_fastfloor(x);\n   int py = stb__perlin_fastfloor(y);\n   int pz = stb__perlin_fastfloor(z);\n   int x_wrap2 = (x_wrap ? x_wrap : 256);\n   int y_wrap2 = (y_wrap ? y_wrap : 256);\n   int z_wrap2 = (z_wrap ? z_wrap : 256);\n   int x0 = px % x_wrap2, x1;\n   int y0 = py % y_wrap2, y1;\n   int z0 = pz % z_wrap2, z1;\n   int r0,r1, r00,r01,r10,r11;\n\n   if (x0 < 0) x0 += x_wrap2;\n   if (y0 < 0) y0 += y_wrap2;\n   if (z0 < 0) z0 += z_wrap2;\n   x1 = (x0+1) % x_wrap2;\n   y1 = (y0+1) % y_wrap2;\n   z1 = (z0+1) % z_wrap2;\n\n   #define stb__perlin_ease(a)   (((a*6-15)*a + 10) * a * a * a)\n\n   x -= px; u = stb__perlin_ease(x);\n   y -= py; v = stb__perlin_ease(y);\n   z -= pz; w = stb__perlin_ease(z);\n\n   r0 = stb__perlin_randtab[x0];\n   r0 = stb__perlin_randtab[r0+seed];\n   r1 = stb__perlin_randtab[x1];\n   r1 = stb__perlin_randtab[r1+seed];\n\n   r00 = stb__perlin_randtab[r0+y0];\n   r01 = stb__perlin_randtab[r0+y1];\n   r10 = stb__perlin_randtab[r1+y0];\n   r11 = stb__perlin_randtab[r1+y1];\n\n   n000 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r00+z0], x  , y  , z   );\n   n001 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r00+z1], x  , y  , z-1 );\n   n010 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r01+z0], x  , y-1, z   );\n   n011 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r01+z1], x  , y-1, z-1 );\n   n100 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r10+z0], x-1, y  , z   );\n   n101 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r10+z1], x-1, y  , z-1 );\n   n110 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r11+z0], x-1, y-1, z   );\n   n111 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r11+z1], x-1, y-1, z-1 );\n\n   n00 = stb__perlin_lerp(n000,n001,w);\n   n01 = stb__perlin_lerp(n010,n011,w);\n   n10 = stb__perlin_lerp(n100,n101,w);\n   n11 = stb__perlin_lerp(n110,n111,w);\n\n   n0 = stb__perlin_lerp(n00,n01,v);\n   n1 = stb__perlin_lerp(n10,n11,v);\n\n   return stb__perlin_lerp(n0,n1,u);\n}\n#endif  // STB_PERLIN_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_rect_pack.h",
    "content": "// stb_rect_pack.h - v1.01 - public domain - rectangle packing\n// Sean Barrett 2014\n//\n// Useful for e.g. packing rectangular textures into an atlas.\n// Does not do rotation.\n//\n// Before #including,\n//\n//    #define STB_RECT_PACK_IMPLEMENTATION\n//\n// in the file that you want to have the implementation.\n//\n// Not necessarily the awesomest packing method, but better than\n// the totally naive one in stb_truetype (which is primarily what\n// this is meant to replace).\n//\n// Has only had a few tests run, may have issues.\n//\n// More docs to come.\n//\n// No memory allocations; uses qsort() and assert() from stdlib.\n// Can override those by defining STBRP_SORT and STBRP_ASSERT.\n//\n// This library currently uses the Skyline Bottom-Left algorithm.\n//\n// Please note: better rectangle packers are welcome! Please\n// implement them to the same API, but with a different init\n// function.\n//\n// Credits\n//\n//  Library\n//    Sean Barrett\n//  Minor features\n//    Martins Mozeiko\n//    github:IntellectualKitty\n//\n//  Bugfixes / warning fixes\n//    Jeremy Jaussaud\n//    Fabian Giesen\n//\n// Version history:\n//\n//     1.01  (2021-07-11)  always use large rect mode, expose STBRP__MAXVAL in public section\n//     1.00  (2019-02-25)  avoid small space waste; gracefully fail too-wide rectangles\n//     0.99  (2019-02-07)  warning fixes\n//     0.11  (2017-03-03)  return packing success/fail result\n//     0.10  (2016-10-25)  remove cast-away-const to avoid warnings\n//     0.09  (2016-08-27)  fix compiler warnings\n//     0.08  (2015-09-13)  really fix bug with empty rects (w=0 or h=0)\n//     0.07  (2015-09-13)  fix bug with empty rects (w=0 or h=0)\n//     0.06  (2015-04-15)  added STBRP_SORT to allow replacing qsort\n//     0.05:  added STBRP_ASSERT to allow replacing assert\n//     0.04:  fixed minor bug in STBRP_LARGE_RECTS support\n//     0.01:  initial release\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//       INCLUDE SECTION\n//\n\n#ifndef STB_INCLUDE_STB_RECT_PACK_H\n#define STB_INCLUDE_STB_RECT_PACK_H\n\n#define STB_RECT_PACK_VERSION  1\n\n#ifdef STBRP_STATIC\n#define STBRP_DEF static\n#else\n#define STBRP_DEF extern\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct stbrp_context stbrp_context;\ntypedef struct stbrp_node    stbrp_node;\ntypedef struct stbrp_rect    stbrp_rect;\n\ntypedef int            stbrp_coord;\n\n#define STBRP__MAXVAL  0x7fffffff\n// Mostly for internal use, but this is the maximum supported coordinate value.\n\nSTBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);\n// Assign packed locations to rectangles. The rectangles are of type\n// 'stbrp_rect' defined below, stored in the array 'rects', and there\n// are 'num_rects' many of them.\n//\n// Rectangles which are successfully packed have the 'was_packed' flag\n// set to a non-zero value and 'x' and 'y' store the minimum location\n// on each axis (i.e. bottom-left in cartesian coordinates, top-left\n// if you imagine y increasing downwards). Rectangles which do not fit\n// have the 'was_packed' flag set to 0.\n//\n// You should not try to access the 'rects' array from another thread\n// while this function is running, as the function temporarily reorders\n// the array while it executes.\n//\n// To pack into another rectangle, you need to call stbrp_init_target\n// again. To continue packing into the same rectangle, you can call\n// this function again. Calling this multiple times with multiple rect\n// arrays will probably produce worse packing results than calling it\n// a single time with the full rectangle array, but the option is\n// available.\n//\n// The function returns 1 if all of the rectangles were successfully\n// packed and 0 otherwise.\n\nstruct stbrp_rect\n{\n   // reserved for your use:\n   int            id;\n\n   // input:\n   stbrp_coord    w, h;\n\n   // output:\n   stbrp_coord    x, y;\n   int            was_packed;  // non-zero if valid packing\n\n}; // 16 bytes, nominally\n\n\nSTBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);\n// Initialize a rectangle packer to:\n//    pack a rectangle that is 'width' by 'height' in dimensions\n//    using temporary storage provided by the array 'nodes', which is 'num_nodes' long\n//\n// You must call this function every time you start packing into a new target.\n//\n// There is no \"shutdown\" function. The 'nodes' memory must stay valid for\n// the following stbrp_pack_rects() call (or calls), but can be freed after\n// the call (or calls) finish.\n//\n// Note: to guarantee best results, either:\n//       1. make sure 'num_nodes' >= 'width'\n//   or  2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'\n//\n// If you don't do either of the above things, widths will be quantized to multiples\n// of small integers to guarantee the algorithm doesn't run out of temporary storage.\n//\n// If you do #2, then the non-quantized algorithm will be used, but the algorithm\n// may run out of temporary storage and be unable to pack some rectangles.\n\nSTBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);\n// Optionally call this function after init but before doing any packing to\n// change the handling of the out-of-temp-memory scenario, described above.\n// If you call init again, this will be reset to the default (false).\n\n\nSTBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);\n// Optionally select which packing heuristic the library should use. Different\n// heuristics will produce better/worse results for different data sets.\n// If you call init again, this will be reset to the default.\n\nenum\n{\n   STBRP_HEURISTIC_Skyline_default=0,\n   STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,\n   STBRP_HEURISTIC_Skyline_BF_sortHeight\n};\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// the details of the following structures don't matter to you, but they must\n// be visible so you can handle the memory allocations for them\n\nstruct stbrp_node\n{\n   stbrp_coord  x,y;\n   stbrp_node  *next;\n};\n\nstruct stbrp_context\n{\n   int width;\n   int height;\n   int align;\n   int init_mode;\n   int heuristic;\n   int num_nodes;\n   stbrp_node *active_head;\n   stbrp_node *free_head;\n   stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'\n};\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//     IMPLEMENTATION SECTION\n//\n\n#ifdef STB_RECT_PACK_IMPLEMENTATION\n#ifndef STBRP_SORT\n#include <stdlib.h>\n#define STBRP_SORT qsort\n#endif\n\n#ifndef STBRP_ASSERT\n#include <assert.h>\n#define STBRP_ASSERT assert\n#endif\n\n#ifdef _MSC_VER\n#define STBRP__NOTUSED(v)  (void)(v)\n#define STBRP__CDECL       __cdecl\n#else\n#define STBRP__NOTUSED(v)  (void)sizeof(v)\n#define STBRP__CDECL\n#endif\n\nenum\n{\n   STBRP__INIT_skyline = 1\n};\n\nSTBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)\n{\n   switch (context->init_mode) {\n      case STBRP__INIT_skyline:\n         STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);\n         context->heuristic = heuristic;\n         break;\n      default:\n         STBRP_ASSERT(0);\n   }\n}\n\nSTBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)\n{\n   if (allow_out_of_mem)\n      // if it's ok to run out of memory, then don't bother aligning them;\n      // this gives better packing, but may fail due to OOM (even though\n      // the rectangles easily fit). @TODO a smarter approach would be to only\n      // quantize once we've hit OOM, then we could get rid of this parameter.\n      context->align = 1;\n   else {\n      // if it's not ok to run out of memory, then quantize the widths\n      // so that num_nodes is always enough nodes.\n      //\n      // I.e. num_nodes * align >= width\n      //                  align >= width / num_nodes\n      //                  align = ceil(width/num_nodes)\n\n      context->align = (context->width + context->num_nodes-1) / context->num_nodes;\n   }\n}\n\nSTBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)\n{\n   int i;\n\n   for (i=0; i < num_nodes-1; ++i)\n      nodes[i].next = &nodes[i+1];\n   nodes[i].next = NULL;\n   context->init_mode = STBRP__INIT_skyline;\n   context->heuristic = STBRP_HEURISTIC_Skyline_default;\n   context->free_head = &nodes[0];\n   context->active_head = &context->extra[0];\n   context->width = width;\n   context->height = height;\n   context->num_nodes = num_nodes;\n   stbrp_setup_allow_out_of_mem(context, 0);\n\n   // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)\n   context->extra[0].x = 0;\n   context->extra[0].y = 0;\n   context->extra[0].next = &context->extra[1];\n   context->extra[1].x = (stbrp_coord) width;\n   context->extra[1].y = (1<<30);\n   context->extra[1].next = NULL;\n}\n\n// find minimum y position if it starts at x1\nstatic int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)\n{\n   stbrp_node *node = first;\n   int x1 = x0 + width;\n   int min_y, visited_width, waste_area;\n\n   STBRP__NOTUSED(c);\n\n   STBRP_ASSERT(first->x <= x0);\n\n   #if 0\n   // skip in case we're past the node\n   while (node->next->x <= x0)\n      ++node;\n   #else\n   STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency\n   #endif\n\n   STBRP_ASSERT(node->x <= x0);\n\n   min_y = 0;\n   waste_area = 0;\n   visited_width = 0;\n   while (node->x < x1) {\n      if (node->y > min_y) {\n         // raise min_y higher.\n         // we've accounted for all waste up to min_y,\n         // but we'll now add more waste for everything we've visted\n         waste_area += visited_width * (node->y - min_y);\n         min_y = node->y;\n         // the first time through, visited_width might be reduced\n         if (node->x < x0)\n            visited_width += node->next->x - x0;\n         else\n            visited_width += node->next->x - node->x;\n      } else {\n         // add waste area\n         int under_width = node->next->x - node->x;\n         if (under_width + visited_width > width)\n            under_width = width - visited_width;\n         waste_area += under_width * (min_y - node->y);\n         visited_width += under_width;\n      }\n      node = node->next;\n   }\n\n   *pwaste = waste_area;\n   return min_y;\n}\n\ntypedef struct\n{\n   int x,y;\n   stbrp_node **prev_link;\n} stbrp__findresult;\n\nstatic stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)\n{\n   int best_waste = (1<<30), best_x, best_y = (1 << 30);\n   stbrp__findresult fr;\n   stbrp_node **prev, *node, *tail, **best = NULL;\n\n   // align to multiple of c->align\n   width = (width + c->align - 1);\n   width -= width % c->align;\n   STBRP_ASSERT(width % c->align == 0);\n\n   // if it can't possibly fit, bail immediately\n   if (width > c->width || height > c->height) {\n      fr.prev_link = NULL;\n      fr.x = fr.y = 0;\n      return fr;\n   }\n\n   node = c->active_head;\n   prev = &c->active_head;\n   while (node->x + width <= c->width) {\n      int y,waste;\n      y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);\n      if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL\n         // bottom left\n         if (y < best_y) {\n            best_y = y;\n            best = prev;\n         }\n      } else {\n         // best-fit\n         if (y + height <= c->height) {\n            // can only use it if it first vertically\n            if (y < best_y || (y == best_y && waste < best_waste)) {\n               best_y = y;\n               best_waste = waste;\n               best = prev;\n            }\n         }\n      }\n      prev = &node->next;\n      node = node->next;\n   }\n\n   best_x = (best == NULL) ? 0 : (*best)->x;\n\n   // if doing best-fit (BF), we also have to try aligning right edge to each node position\n   //\n   // e.g, if fitting\n   //\n   //     ____________________\n   //    |____________________|\n   //\n   //            into\n   //\n   //   |                         |\n   //   |             ____________|\n   //   |____________|\n   //\n   // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned\n   //\n   // This makes BF take about 2x the time\n\n   if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {\n      tail = c->active_head;\n      node = c->active_head;\n      prev = &c->active_head;\n      // find first node that's admissible\n      while (tail->x < width)\n         tail = tail->next;\n      while (tail) {\n         int xpos = tail->x - width;\n         int y,waste;\n         STBRP_ASSERT(xpos >= 0);\n         // find the left position that matches this\n         while (node->next->x <= xpos) {\n            prev = &node->next;\n            node = node->next;\n         }\n         STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);\n         y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);\n         if (y + height <= c->height) {\n            if (y <= best_y) {\n               if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {\n                  best_x = xpos;\n                  STBRP_ASSERT(y <= best_y);\n                  best_y = y;\n                  best_waste = waste;\n                  best = prev;\n               }\n            }\n         }\n         tail = tail->next;\n      }\n   }\n\n   fr.prev_link = best;\n   fr.x = best_x;\n   fr.y = best_y;\n   return fr;\n}\n\nstatic stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)\n{\n   // find best position according to heuristic\n   stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);\n   stbrp_node *node, *cur;\n\n   // bail if:\n   //    1. it failed\n   //    2. the best node doesn't fit (we don't always check this)\n   //    3. we're out of memory\n   if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {\n      res.prev_link = NULL;\n      return res;\n   }\n\n   // on success, create new node\n   node = context->free_head;\n   node->x = (stbrp_coord) res.x;\n   node->y = (stbrp_coord) (res.y + height);\n\n   context->free_head = node->next;\n\n   // insert the new node into the right starting point, and\n   // let 'cur' point to the remaining nodes needing to be\n   // stiched back in\n\n   cur = *res.prev_link;\n   if (cur->x < res.x) {\n      // preserve the existing one, so start testing with the next one\n      stbrp_node *next = cur->next;\n      cur->next = node;\n      cur = next;\n   } else {\n      *res.prev_link = node;\n   }\n\n   // from here, traverse cur and free the nodes, until we get to one\n   // that shouldn't be freed\n   while (cur->next && cur->next->x <= res.x + width) {\n      stbrp_node *next = cur->next;\n      // move the current node to the free list\n      cur->next = context->free_head;\n      context->free_head = cur;\n      cur = next;\n   }\n\n   // stitch the list back in\n   node->next = cur;\n\n   if (cur->x < res.x + width)\n      cur->x = (stbrp_coord) (res.x + width);\n\n#ifdef _DEBUG\n   cur = context->active_head;\n   while (cur->x < context->width) {\n      STBRP_ASSERT(cur->x < cur->next->x);\n      cur = cur->next;\n   }\n   STBRP_ASSERT(cur->next == NULL);\n\n   {\n      int count=0;\n      cur = context->active_head;\n      while (cur) {\n         cur = cur->next;\n         ++count;\n      }\n      cur = context->free_head;\n      while (cur) {\n         cur = cur->next;\n         ++count;\n      }\n      STBRP_ASSERT(count == context->num_nodes+2);\n   }\n#endif\n\n   return res;\n}\n\nstatic int STBRP__CDECL rect_height_compare(const void *a, const void *b)\n{\n   const stbrp_rect *p = (const stbrp_rect *) a;\n   const stbrp_rect *q = (const stbrp_rect *) b;\n   if (p->h > q->h)\n      return -1;\n   if (p->h < q->h)\n      return  1;\n   return (p->w > q->w) ? -1 : (p->w < q->w);\n}\n\nstatic int STBRP__CDECL rect_original_order(const void *a, const void *b)\n{\n   const stbrp_rect *p = (const stbrp_rect *) a;\n   const stbrp_rect *q = (const stbrp_rect *) b;\n   return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);\n}\n\nSTBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)\n{\n   int i, all_rects_packed = 1;\n\n   // we use the 'was_packed' field internally to allow sorting/unsorting\n   for (i=0; i < num_rects; ++i) {\n      rects[i].was_packed = i;\n   }\n\n   // sort according to heuristic\n   STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);\n\n   for (i=0; i < num_rects; ++i) {\n      if (rects[i].w == 0 || rects[i].h == 0) {\n         rects[i].x = rects[i].y = 0;  // empty rect needs no space\n      } else {\n         stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);\n         if (fr.prev_link) {\n            rects[i].x = (stbrp_coord) fr.x;\n            rects[i].y = (stbrp_coord) fr.y;\n         } else {\n            rects[i].x = rects[i].y = STBRP__MAXVAL;\n         }\n      }\n   }\n\n   // unsort\n   STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);\n\n   // set was_packed flags and all_rects_packed status\n   for (i=0; i < num_rects; ++i) {\n      rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);\n      if (!rects[i].was_packed)\n         all_rects_packed = 0;\n   }\n\n   // return the all_rects_packed status\n   return all_rects_packed;\n}\n#endif\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_sprintf.h",
    "content": "// stb_sprintf - v1.10 - public domain snprintf() implementation\n// originally by Jeff Roberts / RAD Game Tools, 2015/10/20\n// http://github.com/nothings/stb\n//\n// allowed types:  sc uidBboXx p AaGgEef n\n// lengths      :  hh h ll j z t I64 I32 I\n//\n// Contributors:\n//    Fabian \"ryg\" Giesen (reformatting)\n//    github:aganm (attribute format)\n//\n// Contributors (bugfixes):\n//    github:d26435\n//    github:trex78\n//    github:account-login\n//    Jari Komppa (SI suffixes)\n//    Rohit Nirmal\n//    Marcin Wojdyr\n//    Leonard Ritter\n//    Stefano Zanotti\n//    Adam Allison\n//    Arvid Gerstmann\n//    Markus Kolb\n//\n// LICENSE:\n//\n//   See end of file for license information.\n\n#ifndef STB_SPRINTF_H_INCLUDE\n#define STB_SPRINTF_H_INCLUDE\n\n/*\nSingle file sprintf replacement.\n\nOriginally written by Jeff Roberts at RAD Game Tools - 2015/10/20.\nHereby placed in public domain.\n\nThis is a full sprintf replacement that supports everything that\nthe C runtime sprintfs support, including float/double, 64-bit integers,\nhex floats, field parameters (%*.*d stuff), length reads backs, etc.\n\nWhy would you need this if sprintf already exists?  Well, first off,\nit's *much* faster (see below). It's also much smaller than the CRT\nversions code-space-wise. We've also added some simple improvements\nthat are super handy (commas in thousands, callbacks at buffer full,\nfor example). Finally, the format strings for MSVC and GCC differ\nfor 64-bit integers (among other small things), so this lets you use\nthe same format strings in cross platform code.\n\nIt uses the standard single file trick of being both the header file\nand the source itself. If you just include it normally, you just get\nthe header file function definitions. To get the code, you include\nit from a C or C++ file and define STB_SPRINTF_IMPLEMENTATION first.\n\nIt only uses va_args macros from the C runtime to do it's work. It\ndoes cast doubles to S64s and shifts and divides U64s, which does\ndrag in CRT code on most platforms.\n\nIt compiles to roughly 8K with float support, and 4K without.\nAs a comparison, when using MSVC static libs, calling sprintf drags\nin 16K.\n\nAPI:\n====\nint stbsp_sprintf( char * buf, char const * fmt, ... )\nint stbsp_snprintf( char * buf, int count, char const * fmt, ... )\n  Convert an arg list into a buffer.  stbsp_snprintf always returns\n  a zero-terminated string (unlike regular snprintf).\n\nint stbsp_vsprintf( char * buf, char const * fmt, va_list va )\nint stbsp_vsnprintf( char * buf, int count, char const * fmt, va_list va )\n  Convert a va_list arg list into a buffer.  stbsp_vsnprintf always returns\n  a zero-terminated string (unlike regular snprintf).\n\nint stbsp_vsprintfcb( STBSP_SPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )\n    typedef char * STBSP_SPRINTFCB( char const * buf, void * user, int len );\n  Convert into a buffer, calling back every STB_SPRINTF_MIN chars.\n  Your callback can then copy the chars out, print them or whatever.\n  This function is actually the workhorse for everything else.\n  The buffer you pass in must hold at least STB_SPRINTF_MIN characters.\n    // you return the next buffer to use or 0 to stop converting\n\nvoid stbsp_set_separators( char comma, char period )\n  Set the comma and period characters to use.\n\nFLOATS/DOUBLES:\n===============\nThis code uses a internal float->ascii conversion method that uses\ndoubles with error correction (double-doubles, for ~105 bits of\nprecision).  This conversion is round-trip perfect - that is, an atof\nof the values output here will give you the bit-exact double back.\n\nOne difference is that our insignificant digits will be different than\nwith MSVC or GCC (but they don't match each other either).  We also\ndon't attempt to find the minimum length matching float (pre-MSVC15\ndoesn't either).\n\nIf you don't need float or doubles at all, define STB_SPRINTF_NOFLOAT\nand you'll save 4K of code space.\n\n64-BIT INTS:\n============\nThis library also supports 64-bit integers and you can use MSVC style or\nGCC style indicators (%I64d or %lld).  It supports the C99 specifiers\nfor size_t and ptr_diff_t (%jd %zd) as well.\n\nEXTRAS:\n=======\nLike some GCCs, for integers and floats, you can use a ' (single quote)\nspecifier and commas will be inserted on the thousands: \"%'d\" on 12345\nwould print 12,345.\n\nFor integers and floats, you can use a \"$\" specifier and the number\nwill be converted to float and then divided to get kilo, mega, giga or\ntera and then printed, so \"%$d\" 1000 is \"1.0 k\", \"%$.2d\" 2536000 is\n\"2.53 M\", etc. For byte values, use two $:s, like \"%$$d\" to turn\n2536000 to \"2.42 Mi\". If you prefer JEDEC suffixes to SI ones, use three\n$:s: \"%$$$d\" -> \"2.42 M\". To remove the space between the number and the\nsuffix, add \"_\" specifier: \"%_$d\" -> \"2.53M\".\n\nIn addition to octal and hexadecimal conversions, you can print\nintegers in binary: \"%b\" for 256 would print 100.\n\nPERFORMANCE vs MSVC 2008 32-/64-bit (GCC is even slower than MSVC):\n===================================================================\n\"%d\" across all 32-bit ints (4.8x/4.0x faster than 32-/64-bit MSVC)\n\"%24d\" across all 32-bit ints (4.5x/4.2x faster)\n\"%x\" across all 32-bit ints (4.5x/3.8x faster)\n\"%08x\" across all 32-bit ints (4.3x/3.8x faster)\n\"%f\" across e-10 to e+10 floats (7.3x/6.0x faster)\n\"%e\" across e-10 to e+10 floats (8.1x/6.0x faster)\n\"%g\" across e-10 to e+10 floats (10.0x/7.1x faster)\n\"%f\" for values near e-300 (7.9x/6.5x faster)\n\"%f\" for values near e+300 (10.0x/9.1x faster)\n\"%e\" for values near e-300 (10.1x/7.0x faster)\n\"%e\" for values near e+300 (9.2x/6.0x faster)\n\"%.320f\" for values near e-300 (12.6x/11.2x faster)\n\"%a\" for random values (8.6x/4.3x faster)\n\"%I64d\" for 64-bits with 32-bit values (4.8x/3.4x faster)\n\"%I64d\" for 64-bits > 32-bit values (4.9x/5.5x faster)\n\"%s%s%s\" for 64 char strings (7.1x/7.3x faster)\n\"...512 char string...\" ( 35.0x/32.5x faster!)\n*/\n\n#if defined(__clang__)\n #if defined(__has_feature) && defined(__has_attribute)\n  #if __has_feature(address_sanitizer)\n   #if __has_attribute(__no_sanitize__)\n    #define STBSP__ASAN __attribute__((__no_sanitize__(\"address\")))\n   #elif __has_attribute(__no_sanitize_address__)\n    #define STBSP__ASAN __attribute__((__no_sanitize_address__))\n   #elif __has_attribute(__no_address_safety_analysis__)\n    #define STBSP__ASAN __attribute__((__no_address_safety_analysis__))\n   #endif\n  #endif\n #endif\n#elif defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))\n #if defined(__SANITIZE_ADDRESS__) && __SANITIZE_ADDRESS__\n  #define STBSP__ASAN __attribute__((__no_sanitize_address__))\n #endif\n#endif\n\n#ifndef STBSP__ASAN\n#define STBSP__ASAN\n#endif\n\n#ifdef STB_SPRINTF_STATIC\n#define STBSP__PUBLICDEC static\n#define STBSP__PUBLICDEF static STBSP__ASAN\n#else\n#ifdef __cplusplus\n#define STBSP__PUBLICDEC extern \"C\"\n#define STBSP__PUBLICDEF extern \"C\" STBSP__ASAN\n#else\n#define STBSP__PUBLICDEC extern\n#define STBSP__PUBLICDEF STBSP__ASAN\n#endif\n#endif\n\n#if defined(__has_attribute)\n #if __has_attribute(format)\n   #define STBSP__ATTRIBUTE_FORMAT(fmt,va) __attribute__((format(printf,fmt,va)))\n #endif\n#endif\n\n#ifndef STBSP__ATTRIBUTE_FORMAT\n#define STBSP__ATTRIBUTE_FORMAT(fmt,va)\n#endif\n\n#ifdef _MSC_VER\n#define STBSP__NOTUSED(v)  (void)(v)\n#else\n#define STBSP__NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#include <stdarg.h> // for va_arg(), va_list()\n#include <stddef.h> // size_t, ptrdiff_t\n\n#ifndef STB_SPRINTF_MIN\n#define STB_SPRINTF_MIN 512 // how many characters per callback\n#endif\ntypedef char *STBSP_SPRINTFCB(const char *buf, void *user, int len);\n\n#ifndef STB_SPRINTF_DECORATE\n#define STB_SPRINTF_DECORATE(name) stbsp_##name // define this before including if you want to change the names\n#endif\n\nSTBSP__PUBLICDEC int STB_SPRINTF_DECORATE(vsprintf)(char *buf, char const *fmt, va_list va);\nSTBSP__PUBLICDEC int STB_SPRINTF_DECORATE(vsnprintf)(char *buf, int count, char const *fmt, va_list va);\nSTBSP__PUBLICDEC int STB_SPRINTF_DECORATE(sprintf)(char *buf, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(2,3);\nSTBSP__PUBLICDEC int STB_SPRINTF_DECORATE(snprintf)(char *buf, int count, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(3,4);\n\nSTBSP__PUBLICDEC int STB_SPRINTF_DECORATE(vsprintfcb)(STBSP_SPRINTFCB *callback, void *user, char *buf, char const *fmt, va_list va);\nSTBSP__PUBLICDEC void STB_SPRINTF_DECORATE(set_separators)(char comma, char period);\n\n#endif // STB_SPRINTF_H_INCLUDE\n\n#ifdef STB_SPRINTF_IMPLEMENTATION\n\n#define stbsp__uint32 unsigned int\n#define stbsp__int32 signed int\n\n#ifdef _MSC_VER\n#define stbsp__uint64 unsigned __int64\n#define stbsp__int64 signed __int64\n#else\n#define stbsp__uint64 unsigned long long\n#define stbsp__int64 signed long long\n#endif\n#define stbsp__uint16 unsigned short\n\n#ifndef stbsp__uintptr\n#if defined(__ppc64__) || defined(__powerpc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64) || defined(__s390x__)\n#define stbsp__uintptr stbsp__uint64\n#else\n#define stbsp__uintptr stbsp__uint32\n#endif\n#endif\n\n#ifndef STB_SPRINTF_MSVC_MODE // used for MSVC2013 and earlier (MSVC2015 matches GCC)\n#if defined(_MSC_VER) && (_MSC_VER < 1900)\n#define STB_SPRINTF_MSVC_MODE\n#endif\n#endif\n\n#ifdef STB_SPRINTF_NOUNALIGNED // define this before inclusion to force stbsp_sprintf to always use aligned accesses\n#define STBSP__UNALIGNED(code)\n#else\n#define STBSP__UNALIGNED(code) code\n#endif\n\n#ifndef STB_SPRINTF_NOFLOAT\n// internal float utility functions\nstatic stbsp__int32 stbsp__real_to_str(char const **start, stbsp__uint32 *len, char *out, stbsp__int32 *decimal_pos, double value, stbsp__uint32 frac_digits);\nstatic stbsp__int32 stbsp__real_to_parts(stbsp__int64 *bits, stbsp__int32 *expo, double value);\n#define STBSP__SPECIAL 0x7000\n#endif\n\nstatic char stbsp__period = '.';\nstatic char stbsp__comma = ',';\nstatic struct\n{\n   short temp; // force next field to be 2-byte aligned\n   char pair[201];\n} stbsp__digitpair =\n{\n  0,\n   \"00010203040506070809101112131415161718192021222324\"\n   \"25262728293031323334353637383940414243444546474849\"\n   \"50515253545556575859606162636465666768697071727374\"\n   \"75767778798081828384858687888990919293949596979899\"\n};\n\nSTBSP__PUBLICDEF void STB_SPRINTF_DECORATE(set_separators)(char pcomma, char pperiod)\n{\n   stbsp__period = pperiod;\n   stbsp__comma = pcomma;\n}\n\n#define STBSP__LEFTJUST 1\n#define STBSP__LEADINGPLUS 2\n#define STBSP__LEADINGSPACE 4\n#define STBSP__LEADING_0X 8\n#define STBSP__LEADINGZERO 16\n#define STBSP__INTMAX 32\n#define STBSP__TRIPLET_COMMA 64\n#define STBSP__NEGATIVE 128\n#define STBSP__METRIC_SUFFIX 256\n#define STBSP__HALFWIDTH 512\n#define STBSP__METRIC_NOSPACE 1024\n#define STBSP__METRIC_1024 2048\n#define STBSP__METRIC_JEDEC 4096\n\nstatic void stbsp__lead_sign(stbsp__uint32 fl, char *sign)\n{\n   sign[0] = 0;\n   if (fl & STBSP__NEGATIVE) {\n      sign[0] = 1;\n      sign[1] = '-';\n   } else if (fl & STBSP__LEADINGSPACE) {\n      sign[0] = 1;\n      sign[1] = ' ';\n   } else if (fl & STBSP__LEADINGPLUS) {\n      sign[0] = 1;\n      sign[1] = '+';\n   }\n}\n\nstatic STBSP__ASAN stbsp__uint32 stbsp__strlen_limited(char const *s, stbsp__uint32 limit)\n{\n   char const * sn = s;\n\n   // get up to 4-byte alignment\n   for (;;) {\n      if (((stbsp__uintptr)sn & 3) == 0)\n         break;\n\n      if (!limit || *sn == 0)\n         return (stbsp__uint32)(sn - s);\n\n      ++sn;\n      --limit;\n   }\n\n   // scan over 4 bytes at a time to find terminating 0\n   // this will intentionally scan up to 3 bytes past the end of buffers,\n   // but becase it works 4B aligned, it will never cross page boundaries\n   // (hence the STBSP__ASAN markup; the over-read here is intentional\n   // and harmless)\n   while (limit >= 4) {\n      stbsp__uint32 v = *(stbsp__uint32 *)sn;\n      // bit hack to find if there's a 0 byte in there\n      if ((v - 0x01010101) & (~v) & 0x80808080UL)\n         break;\n\n      sn += 4;\n      limit -= 4;\n   }\n\n   // handle the last few characters to find actual size\n   while (limit && *sn) {\n      ++sn;\n      --limit;\n   }\n\n   return (stbsp__uint32)(sn - s);\n}\n\nSTBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsprintfcb)(STBSP_SPRINTFCB *callback, void *user, char *buf, char const *fmt, va_list va)\n{\n   static char hex[] = \"0123456789abcdefxp\";\n   static char hexu[] = \"0123456789ABCDEFXP\";\n   char *bf;\n   char const *f;\n   int tlen = 0;\n\n   bf = buf;\n   f = fmt;\n   for (;;) {\n      stbsp__int32 fw, pr, tz;\n      stbsp__uint32 fl;\n\n      // macros for the callback buffer stuff\n      #define stbsp__chk_cb_bufL(bytes)                        \\\n         {                                                     \\\n            int len = (int)(bf - buf);                         \\\n            if ((len + (bytes)) >= STB_SPRINTF_MIN) {          \\\n               tlen += len;                                    \\\n               if (0 == (bf = buf = callback(buf, user, len))) \\\n                  goto done;                                   \\\n            }                                                  \\\n         }\n      #define stbsp__chk_cb_buf(bytes)    \\\n         {                                \\\n            if (callback) {               \\\n               stbsp__chk_cb_bufL(bytes); \\\n            }                             \\\n         }\n      #define stbsp__flush_cb()                      \\\n         {                                           \\\n            stbsp__chk_cb_bufL(STB_SPRINTF_MIN - 1); \\\n         } // flush if there is even one byte in the buffer\n      #define stbsp__cb_buf_clamp(cl, v)                \\\n         cl = v;                                        \\\n         if (callback) {                                \\\n            int lg = STB_SPRINTF_MIN - (int)(bf - buf); \\\n            if (cl > lg)                                \\\n               cl = lg;                                 \\\n         }\n\n      // fast copy everything up to the next % (or end of string)\n      for (;;) {\n         while (((stbsp__uintptr)f) & 3) {\n         schk1:\n            if (f[0] == '%')\n               goto scandd;\n         schk2:\n            if (f[0] == 0)\n               goto endfmt;\n            stbsp__chk_cb_buf(1);\n            *bf++ = f[0];\n            ++f;\n         }\n         for (;;) {\n            // Check if the next 4 bytes contain %(0x25) or end of string.\n            // Using the 'hasless' trick:\n            // https://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord\n            stbsp__uint32 v, c;\n            v = *(stbsp__uint32 *)f;\n            c = (~v) & 0x80808080;\n            if (((v ^ 0x25252525) - 0x01010101) & c)\n               goto schk1;\n            if ((v - 0x01010101) & c)\n               goto schk2;\n            if (callback)\n               if ((STB_SPRINTF_MIN - (int)(bf - buf)) < 4)\n                  goto schk1;\n            #ifdef STB_SPRINTF_NOUNALIGNED\n                if(((stbsp__uintptr)bf) & 3) {\n                    bf[0] = f[0];\n                    bf[1] = f[1];\n                    bf[2] = f[2];\n                    bf[3] = f[3];\n                } else\n            #endif\n            {\n                *(stbsp__uint32 *)bf = v;\n            }\n            bf += 4;\n            f += 4;\n         }\n      }\n   scandd:\n\n      ++f;\n\n      // ok, we have a percent, read the modifiers first\n      fw = 0;\n      pr = -1;\n      fl = 0;\n      tz = 0;\n\n      // flags\n      for (;;) {\n         switch (f[0]) {\n         // if we have left justify\n         case '-':\n            fl |= STBSP__LEFTJUST;\n            ++f;\n            continue;\n         // if we have leading plus\n         case '+':\n            fl |= STBSP__LEADINGPLUS;\n            ++f;\n            continue;\n         // if we have leading space\n         case ' ':\n            fl |= STBSP__LEADINGSPACE;\n            ++f;\n            continue;\n         // if we have leading 0x\n         case '#':\n            fl |= STBSP__LEADING_0X;\n            ++f;\n            continue;\n         // if we have thousand commas\n         case '\\'':\n            fl |= STBSP__TRIPLET_COMMA;\n            ++f;\n            continue;\n         // if we have kilo marker (none->kilo->kibi->jedec)\n         case '$':\n            if (fl & STBSP__METRIC_SUFFIX) {\n               if (fl & STBSP__METRIC_1024) {\n                  fl |= STBSP__METRIC_JEDEC;\n               } else {\n                  fl |= STBSP__METRIC_1024;\n               }\n            } else {\n               fl |= STBSP__METRIC_SUFFIX;\n            }\n            ++f;\n            continue;\n         // if we don't want space between metric suffix and number\n         case '_':\n            fl |= STBSP__METRIC_NOSPACE;\n            ++f;\n            continue;\n         // if we have leading zero\n         case '0':\n            fl |= STBSP__LEADINGZERO;\n            ++f;\n            goto flags_done;\n         default: goto flags_done;\n         }\n      }\n   flags_done:\n\n      // get the field width\n      if (f[0] == '*') {\n         fw = va_arg(va, stbsp__uint32);\n         ++f;\n      } else {\n         while ((f[0] >= '0') && (f[0] <= '9')) {\n            fw = fw * 10 + f[0] - '0';\n            f++;\n         }\n      }\n      // get the precision\n      if (f[0] == '.') {\n         ++f;\n         if (f[0] == '*') {\n            pr = va_arg(va, stbsp__uint32);\n            ++f;\n         } else {\n            pr = 0;\n            while ((f[0] >= '0') && (f[0] <= '9')) {\n               pr = pr * 10 + f[0] - '0';\n               f++;\n            }\n         }\n      }\n\n      // handle integer size overrides\n      switch (f[0]) {\n      // are we halfwidth?\n      case 'h':\n         fl |= STBSP__HALFWIDTH;\n         ++f;\n         if (f[0] == 'h')\n            ++f;  // QUARTERWIDTH\n         break;\n      // are we 64-bit (unix style)\n      case 'l':\n         fl |= ((sizeof(long) == 8) ? STBSP__INTMAX : 0);\n         ++f;\n         if (f[0] == 'l') {\n            fl |= STBSP__INTMAX;\n            ++f;\n         }\n         break;\n      // are we 64-bit on intmax? (c99)\n      case 'j':\n         fl |= (sizeof(size_t) == 8) ? STBSP__INTMAX : 0;\n         ++f;\n         break;\n      // are we 64-bit on size_t or ptrdiff_t? (c99)\n      case 'z':\n         fl |= (sizeof(ptrdiff_t) == 8) ? STBSP__INTMAX : 0;\n         ++f;\n         break;\n      case 't':\n         fl |= (sizeof(ptrdiff_t) == 8) ? STBSP__INTMAX : 0;\n         ++f;\n         break;\n      // are we 64-bit (msft style)\n      case 'I':\n         if ((f[1] == '6') && (f[2] == '4')) {\n            fl |= STBSP__INTMAX;\n            f += 3;\n         } else if ((f[1] == '3') && (f[2] == '2')) {\n            f += 3;\n         } else {\n            fl |= ((sizeof(void *) == 8) ? STBSP__INTMAX : 0);\n            ++f;\n         }\n         break;\n      default: break;\n      }\n\n      // handle each replacement\n      switch (f[0]) {\n         #define STBSP__NUMSZ 512 // big enough for e308 (with commas) or e-307\n         char num[STBSP__NUMSZ];\n         char lead[8];\n         char tail[8];\n         char *s;\n         char const *h;\n         stbsp__uint32 l, n, cs;\n         stbsp__uint64 n64;\n#ifndef STB_SPRINTF_NOFLOAT\n         double fv;\n#endif\n         stbsp__int32 dp;\n         char const *sn;\n\n      case 's':\n         // get the string\n         s = va_arg(va, char *);\n         if (s == 0)\n            s = (char *)\"null\";\n         // get the length, limited to desired precision\n         // always limit to ~0u chars since our counts are 32b\n         l = stbsp__strlen_limited(s, (pr >= 0) ? pr : ~0u);\n         lead[0] = 0;\n         tail[0] = 0;\n         pr = 0;\n         dp = 0;\n         cs = 0;\n         // copy the string in\n         goto scopy;\n\n      case 'c': // char\n         // get the character\n         s = num + STBSP__NUMSZ - 1;\n         *s = (char)va_arg(va, int);\n         l = 1;\n         lead[0] = 0;\n         tail[0] = 0;\n         pr = 0;\n         dp = 0;\n         cs = 0;\n         goto scopy;\n\n      case 'n': // weird write-bytes specifier\n      {\n         int *d = va_arg(va, int *);\n         *d = tlen + (int)(bf - buf);\n      } break;\n\n#ifdef STB_SPRINTF_NOFLOAT\n      case 'A':              // float\n      case 'a':              // hex float\n      case 'G':              // float\n      case 'g':              // float\n      case 'E':              // float\n      case 'e':              // float\n      case 'f':              // float\n         va_arg(va, double); // eat it\n         s = (char *)\"No float\";\n         l = 8;\n         lead[0] = 0;\n         tail[0] = 0;\n         pr = 0;\n         cs = 0;\n         STBSP__NOTUSED(dp);\n         goto scopy;\n#else\n      case 'A': // hex float\n      case 'a': // hex float\n         h = (f[0] == 'A') ? hexu : hex;\n         fv = va_arg(va, double);\n         if (pr == -1)\n            pr = 6; // default is 6\n         // read the double into a string\n         if (stbsp__real_to_parts((stbsp__int64 *)&n64, &dp, fv))\n            fl |= STBSP__NEGATIVE;\n\n         s = num + 64;\n\n         stbsp__lead_sign(fl, lead);\n\n         if (dp == -1023)\n            dp = (n64) ? -1022 : 0;\n         else\n            n64 |= (((stbsp__uint64)1) << 52);\n         n64 <<= (64 - 56);\n         if (pr < 15)\n            n64 += ((((stbsp__uint64)8) << 56) >> (pr * 4));\n// add leading chars\n\n#ifdef STB_SPRINTF_MSVC_MODE\n         *s++ = '0';\n         *s++ = 'x';\n#else\n         lead[1 + lead[0]] = '0';\n         lead[2 + lead[0]] = 'x';\n         lead[0] += 2;\n#endif\n         *s++ = h[(n64 >> 60) & 15];\n         n64 <<= 4;\n         if (pr)\n            *s++ = stbsp__period;\n         sn = s;\n\n         // print the bits\n         n = pr;\n         if (n > 13)\n            n = 13;\n         if (pr > (stbsp__int32)n)\n            tz = pr - n;\n         pr = 0;\n         while (n--) {\n            *s++ = h[(n64 >> 60) & 15];\n            n64 <<= 4;\n         }\n\n         // print the expo\n         tail[1] = h[17];\n         if (dp < 0) {\n            tail[2] = '-';\n            dp = -dp;\n         } else\n            tail[2] = '+';\n         n = (dp >= 1000) ? 6 : ((dp >= 100) ? 5 : ((dp >= 10) ? 4 : 3));\n         tail[0] = (char)n;\n         for (;;) {\n            tail[n] = '0' + dp % 10;\n            if (n <= 3)\n               break;\n            --n;\n            dp /= 10;\n         }\n\n         dp = (int)(s - sn);\n         l = (int)(s - (num + 64));\n         s = num + 64;\n         cs = 1 + (3 << 24);\n         goto scopy;\n\n      case 'G': // float\n      case 'g': // float\n         h = (f[0] == 'G') ? hexu : hex;\n         fv = va_arg(va, double);\n         if (pr == -1)\n            pr = 6;\n         else if (pr == 0)\n            pr = 1; // default is 6\n         // read the double into a string\n         if (stbsp__real_to_str(&sn, &l, num, &dp, fv, (pr - 1) | 0x80000000))\n            fl |= STBSP__NEGATIVE;\n\n         // clamp the precision and delete extra zeros after clamp\n         n = pr;\n         if (l > (stbsp__uint32)pr)\n            l = pr;\n         while ((l > 1) && (pr) && (sn[l - 1] == '0')) {\n            --pr;\n            --l;\n         }\n\n         // should we use %e\n         if ((dp <= -4) || (dp > (stbsp__int32)n)) {\n            if (pr > (stbsp__int32)l)\n               pr = l - 1;\n            else if (pr)\n               --pr; // when using %e, there is one digit before the decimal\n            goto doexpfromg;\n         }\n         // this is the insane action to get the pr to match %g semantics for %f\n         if (dp > 0) {\n            pr = (dp < (stbsp__int32)l) ? l - dp : 0;\n         } else {\n            pr = -dp + ((pr > (stbsp__int32)l) ? (stbsp__int32) l : pr);\n         }\n         goto dofloatfromg;\n\n      case 'E': // float\n      case 'e': // float\n         h = (f[0] == 'E') ? hexu : hex;\n         fv = va_arg(va, double);\n         if (pr == -1)\n            pr = 6; // default is 6\n         // read the double into a string\n         if (stbsp__real_to_str(&sn, &l, num, &dp, fv, pr | 0x80000000))\n            fl |= STBSP__NEGATIVE;\n      doexpfromg:\n         tail[0] = 0;\n         stbsp__lead_sign(fl, lead);\n         if (dp == STBSP__SPECIAL) {\n            s = (char *)sn;\n            cs = 0;\n            pr = 0;\n            goto scopy;\n         }\n         s = num + 64;\n         // handle leading chars\n         *s++ = sn[0];\n\n         if (pr)\n            *s++ = stbsp__period;\n\n         // handle after decimal\n         if ((l - 1) > (stbsp__uint32)pr)\n            l = pr + 1;\n         for (n = 1; n < l; n++)\n            *s++ = sn[n];\n         // trailing zeros\n         tz = pr - (l - 1);\n         pr = 0;\n         // dump expo\n         tail[1] = h[0xe];\n         dp -= 1;\n         if (dp < 0) {\n            tail[2] = '-';\n            dp = -dp;\n         } else\n            tail[2] = '+';\n#ifdef STB_SPRINTF_MSVC_MODE\n         n = 5;\n#else\n         n = (dp >= 100) ? 5 : 4;\n#endif\n         tail[0] = (char)n;\n         for (;;) {\n            tail[n] = '0' + dp % 10;\n            if (n <= 3)\n               break;\n            --n;\n            dp /= 10;\n         }\n         cs = 1 + (3 << 24); // how many tens\n         goto flt_lead;\n\n      case 'f': // float\n         fv = va_arg(va, double);\n      doafloat:\n         // do kilos\n         if (fl & STBSP__METRIC_SUFFIX) {\n            double divisor;\n            divisor = 1000.0f;\n            if (fl & STBSP__METRIC_1024)\n               divisor = 1024.0;\n            while (fl < 0x4000000) {\n               if ((fv < divisor) && (fv > -divisor))\n                  break;\n               fv /= divisor;\n               fl += 0x1000000;\n            }\n         }\n         if (pr == -1)\n            pr = 6; // default is 6\n         // read the double into a string\n         if (stbsp__real_to_str(&sn, &l, num, &dp, fv, pr))\n            fl |= STBSP__NEGATIVE;\n      dofloatfromg:\n         tail[0] = 0;\n         stbsp__lead_sign(fl, lead);\n         if (dp == STBSP__SPECIAL) {\n            s = (char *)sn;\n            cs = 0;\n            pr = 0;\n            goto scopy;\n         }\n         s = num + 64;\n\n         // handle the three decimal varieties\n         if (dp <= 0) {\n            stbsp__int32 i;\n            // handle 0.000*000xxxx\n            *s++ = '0';\n            if (pr)\n               *s++ = stbsp__period;\n            n = -dp;\n            if ((stbsp__int32)n > pr)\n               n = pr;\n            i = n;\n            while (i) {\n               if ((((stbsp__uintptr)s) & 3) == 0)\n                  break;\n               *s++ = '0';\n               --i;\n            }\n            while (i >= 4) {\n               *(stbsp__uint32 *)s = 0x30303030;\n               s += 4;\n               i -= 4;\n            }\n            while (i) {\n               *s++ = '0';\n               --i;\n            }\n            if ((stbsp__int32)(l + n) > pr)\n               l = pr - n;\n            i = l;\n            while (i) {\n               *s++ = *sn++;\n               --i;\n            }\n            tz = pr - (n + l);\n            cs = 1 + (3 << 24); // how many tens did we write (for commas below)\n         } else {\n            cs = (fl & STBSP__TRIPLET_COMMA) ? ((600 - (stbsp__uint32)dp) % 3) : 0;\n            if ((stbsp__uint32)dp >= l) {\n               // handle xxxx000*000.0\n               n = 0;\n               for (;;) {\n                  if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) {\n                     cs = 0;\n                     *s++ = stbsp__comma;\n                  } else {\n                     *s++ = sn[n];\n                     ++n;\n                     if (n >= l)\n                        break;\n                  }\n               }\n               if (n < (stbsp__uint32)dp) {\n                  n = dp - n;\n                  if ((fl & STBSP__TRIPLET_COMMA) == 0) {\n                     while (n) {\n                        if ((((stbsp__uintptr)s) & 3) == 0)\n                           break;\n                        *s++ = '0';\n                        --n;\n                     }\n                     while (n >= 4) {\n                        *(stbsp__uint32 *)s = 0x30303030;\n                        s += 4;\n                        n -= 4;\n                     }\n                  }\n                  while (n) {\n                     if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) {\n                        cs = 0;\n                        *s++ = stbsp__comma;\n                     } else {\n                        *s++ = '0';\n                        --n;\n                     }\n                  }\n               }\n               cs = (int)(s - (num + 64)) + (3 << 24); // cs is how many tens\n               if (pr) {\n                  *s++ = stbsp__period;\n                  tz = pr;\n               }\n            } else {\n               // handle xxxxx.xxxx000*000\n               n = 0;\n               for (;;) {\n                  if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) {\n                     cs = 0;\n                     *s++ = stbsp__comma;\n                  } else {\n                     *s++ = sn[n];\n                     ++n;\n                     if (n >= (stbsp__uint32)dp)\n                        break;\n                  }\n               }\n               cs = (int)(s - (num + 64)) + (3 << 24); // cs is how many tens\n               if (pr)\n                  *s++ = stbsp__period;\n               if ((l - dp) > (stbsp__uint32)pr)\n                  l = pr + dp;\n               while (n < l) {\n                  *s++ = sn[n];\n                  ++n;\n               }\n               tz = pr - (l - dp);\n            }\n         }\n         pr = 0;\n\n         // handle k,m,g,t\n         if (fl & STBSP__METRIC_SUFFIX) {\n            char idx;\n            idx = 1;\n            if (fl & STBSP__METRIC_NOSPACE)\n               idx = 0;\n            tail[0] = idx;\n            tail[1] = ' ';\n            {\n               if (fl >> 24) { // SI kilo is 'k', JEDEC and SI kibits are 'K'.\n                  if (fl & STBSP__METRIC_1024)\n                     tail[idx + 1] = \"_KMGT\"[fl >> 24];\n                  else\n                     tail[idx + 1] = \"_kMGT\"[fl >> 24];\n                  idx++;\n                  // If printing kibits and not in jedec, add the 'i'.\n                  if (fl & STBSP__METRIC_1024 && !(fl & STBSP__METRIC_JEDEC)) {\n                     tail[idx + 1] = 'i';\n                     idx++;\n                  }\n                  tail[0] = idx;\n               }\n            }\n         };\n\n      flt_lead:\n         // get the length that we copied\n         l = (stbsp__uint32)(s - (num + 64));\n         s = num + 64;\n         goto scopy;\n#endif\n\n      case 'B': // upper binary\n      case 'b': // lower binary\n         h = (f[0] == 'B') ? hexu : hex;\n         lead[0] = 0;\n         if (fl & STBSP__LEADING_0X) {\n            lead[0] = 2;\n            lead[1] = '0';\n            lead[2] = h[0xb];\n         }\n         l = (8 << 4) | (1 << 8);\n         goto radixnum;\n\n      case 'o': // octal\n         h = hexu;\n         lead[0] = 0;\n         if (fl & STBSP__LEADING_0X) {\n            lead[0] = 1;\n            lead[1] = '0';\n         }\n         l = (3 << 4) | (3 << 8);\n         goto radixnum;\n\n      case 'p': // pointer\n         fl |= (sizeof(void *) == 8) ? STBSP__INTMAX : 0;\n         pr = sizeof(void *) * 2;\n         fl &= ~STBSP__LEADINGZERO; // 'p' only prints the pointer with zeros\n                                    // fall through - to X\n\n      case 'X': // upper hex\n      case 'x': // lower hex\n         h = (f[0] == 'X') ? hexu : hex;\n         l = (4 << 4) | (4 << 8);\n         lead[0] = 0;\n         if (fl & STBSP__LEADING_0X) {\n            lead[0] = 2;\n            lead[1] = '0';\n            lead[2] = h[16];\n         }\n      radixnum:\n         // get the number\n         if (fl & STBSP__INTMAX)\n            n64 = va_arg(va, stbsp__uint64);\n         else\n            n64 = va_arg(va, stbsp__uint32);\n\n         s = num + STBSP__NUMSZ;\n         dp = 0;\n         // clear tail, and clear leading if value is zero\n         tail[0] = 0;\n         if (n64 == 0) {\n            lead[0] = 0;\n            if (pr == 0) {\n               l = 0;\n               cs = 0;\n               goto scopy;\n            }\n         }\n         // convert to string\n         for (;;) {\n            *--s = h[n64 & ((1 << (l >> 8)) - 1)];\n            n64 >>= (l >> 8);\n            if (!((n64) || ((stbsp__int32)((num + STBSP__NUMSZ) - s) < pr)))\n               break;\n            if (fl & STBSP__TRIPLET_COMMA) {\n               ++l;\n               if ((l & 15) == ((l >> 4) & 15)) {\n                  l &= ~15;\n                  *--s = stbsp__comma;\n               }\n            }\n         };\n         // get the tens and the comma pos\n         cs = (stbsp__uint32)((num + STBSP__NUMSZ) - s) + ((((l >> 4) & 15)) << 24);\n         // get the length that we copied\n         l = (stbsp__uint32)((num + STBSP__NUMSZ) - s);\n         // copy it\n         goto scopy;\n\n      case 'u': // unsigned\n      case 'i':\n      case 'd': // integer\n         // get the integer and abs it\n         if (fl & STBSP__INTMAX) {\n            stbsp__int64 i64 = va_arg(va, stbsp__int64);\n            n64 = (stbsp__uint64)i64;\n            if ((f[0] != 'u') && (i64 < 0)) {\n               n64 = (stbsp__uint64)-i64;\n               fl |= STBSP__NEGATIVE;\n            }\n         } else {\n            stbsp__int32 i = va_arg(va, stbsp__int32);\n            n64 = (stbsp__uint32)i;\n            if ((f[0] != 'u') && (i < 0)) {\n               n64 = (stbsp__uint32)-i;\n               fl |= STBSP__NEGATIVE;\n            }\n         }\n\n#ifndef STB_SPRINTF_NOFLOAT\n         if (fl & STBSP__METRIC_SUFFIX) {\n            if (n64 < 1024)\n               pr = 0;\n            else if (pr == -1)\n               pr = 1;\n            fv = (double)(stbsp__int64)n64;\n            goto doafloat;\n         }\n#endif\n\n         // convert to string\n         s = num + STBSP__NUMSZ;\n         l = 0;\n\n         for (;;) {\n            // do in 32-bit chunks (avoid lots of 64-bit divides even with constant denominators)\n            char *o = s - 8;\n            if (n64 >= 100000000) {\n               n = (stbsp__uint32)(n64 % 100000000);\n               n64 /= 100000000;\n            } else {\n               n = (stbsp__uint32)n64;\n               n64 = 0;\n            }\n            if ((fl & STBSP__TRIPLET_COMMA) == 0) {\n               do {\n                  s -= 2;\n                  *(stbsp__uint16 *)s = *(stbsp__uint16 *)&stbsp__digitpair.pair[(n % 100) * 2];\n                  n /= 100;\n               } while (n);\n            }\n            while (n) {\n               if ((fl & STBSP__TRIPLET_COMMA) && (l++ == 3)) {\n                  l = 0;\n                  *--s = stbsp__comma;\n                  --o;\n               } else {\n                  *--s = (char)(n % 10) + '0';\n                  n /= 10;\n               }\n            }\n            if (n64 == 0) {\n               if ((s[0] == '0') && (s != (num + STBSP__NUMSZ)))\n                  ++s;\n               break;\n            }\n            while (s != o)\n               if ((fl & STBSP__TRIPLET_COMMA) && (l++ == 3)) {\n                  l = 0;\n                  *--s = stbsp__comma;\n                  --o;\n               } else {\n                  *--s = '0';\n               }\n         }\n\n         tail[0] = 0;\n         stbsp__lead_sign(fl, lead);\n\n         // get the length that we copied\n         l = (stbsp__uint32)((num + STBSP__NUMSZ) - s);\n         if (l == 0) {\n            *--s = '0';\n            l = 1;\n         }\n         cs = l + (3 << 24);\n         if (pr < 0)\n            pr = 0;\n\n      scopy:\n         // get fw=leading/trailing space, pr=leading zeros\n         if (pr < (stbsp__int32)l)\n            pr = l;\n         n = pr + lead[0] + tail[0] + tz;\n         if (fw < (stbsp__int32)n)\n            fw = n;\n         fw -= n;\n         pr -= l;\n\n         // handle right justify and leading zeros\n         if ((fl & STBSP__LEFTJUST) == 0) {\n            if (fl & STBSP__LEADINGZERO) // if leading zeros, everything is in pr\n            {\n               pr = (fw > pr) ? fw : pr;\n               fw = 0;\n            } else {\n               fl &= ~STBSP__TRIPLET_COMMA; // if no leading zeros, then no commas\n            }\n         }\n\n         // copy the spaces and/or zeros\n         if (fw + pr) {\n            stbsp__int32 i;\n            stbsp__uint32 c;\n\n            // copy leading spaces (or when doing %8.4d stuff)\n            if ((fl & STBSP__LEFTJUST) == 0)\n               while (fw > 0) {\n                  stbsp__cb_buf_clamp(i, fw);\n                  fw -= i;\n                  while (i) {\n                     if ((((stbsp__uintptr)bf) & 3) == 0)\n                        break;\n                     *bf++ = ' ';\n                     --i;\n                  }\n                  while (i >= 4) {\n                     *(stbsp__uint32 *)bf = 0x20202020;\n                     bf += 4;\n                     i -= 4;\n                  }\n                  while (i) {\n                     *bf++ = ' ';\n                     --i;\n                  }\n                  stbsp__chk_cb_buf(1);\n               }\n\n            // copy leader\n            sn = lead + 1;\n            while (lead[0]) {\n               stbsp__cb_buf_clamp(i, lead[0]);\n               lead[0] -= (char)i;\n               while (i) {\n                  *bf++ = *sn++;\n                  --i;\n               }\n               stbsp__chk_cb_buf(1);\n            }\n\n            // copy leading zeros\n            c = cs >> 24;\n            cs &= 0xffffff;\n            cs = (fl & STBSP__TRIPLET_COMMA) ? ((stbsp__uint32)(c - ((pr + cs) % (c + 1)))) : 0;\n            while (pr > 0) {\n               stbsp__cb_buf_clamp(i, pr);\n               pr -= i;\n               if ((fl & STBSP__TRIPLET_COMMA) == 0) {\n                  while (i) {\n                     if ((((stbsp__uintptr)bf) & 3) == 0)\n                        break;\n                     *bf++ = '0';\n                     --i;\n                  }\n                  while (i >= 4) {\n                     *(stbsp__uint32 *)bf = 0x30303030;\n                     bf += 4;\n                     i -= 4;\n                  }\n               }\n               while (i) {\n                  if ((fl & STBSP__TRIPLET_COMMA) && (cs++ == c)) {\n                     cs = 0;\n                     *bf++ = stbsp__comma;\n                  } else\n                     *bf++ = '0';\n                  --i;\n               }\n               stbsp__chk_cb_buf(1);\n            }\n         }\n\n         // copy leader if there is still one\n         sn = lead + 1;\n         while (lead[0]) {\n            stbsp__int32 i;\n            stbsp__cb_buf_clamp(i, lead[0]);\n            lead[0] -= (char)i;\n            while (i) {\n               *bf++ = *sn++;\n               --i;\n            }\n            stbsp__chk_cb_buf(1);\n         }\n\n         // copy the string\n         n = l;\n         while (n) {\n            stbsp__int32 i;\n            stbsp__cb_buf_clamp(i, n);\n            n -= i;\n            STBSP__UNALIGNED(while (i >= 4) {\n               *(stbsp__uint32 volatile *)bf = *(stbsp__uint32 volatile *)s;\n               bf += 4;\n               s += 4;\n               i -= 4;\n            })\n            while (i) {\n               *bf++ = *s++;\n               --i;\n            }\n            stbsp__chk_cb_buf(1);\n         }\n\n         // copy trailing zeros\n         while (tz) {\n            stbsp__int32 i;\n            stbsp__cb_buf_clamp(i, tz);\n            tz -= i;\n            while (i) {\n               if ((((stbsp__uintptr)bf) & 3) == 0)\n                  break;\n               *bf++ = '0';\n               --i;\n            }\n            while (i >= 4) {\n               *(stbsp__uint32 *)bf = 0x30303030;\n               bf += 4;\n               i -= 4;\n            }\n            while (i) {\n               *bf++ = '0';\n               --i;\n            }\n            stbsp__chk_cb_buf(1);\n         }\n\n         // copy tail if there is one\n         sn = tail + 1;\n         while (tail[0]) {\n            stbsp__int32 i;\n            stbsp__cb_buf_clamp(i, tail[0]);\n            tail[0] -= (char)i;\n            while (i) {\n               *bf++ = *sn++;\n               --i;\n            }\n            stbsp__chk_cb_buf(1);\n         }\n\n         // handle the left justify\n         if (fl & STBSP__LEFTJUST)\n            if (fw > 0) {\n               while (fw) {\n                  stbsp__int32 i;\n                  stbsp__cb_buf_clamp(i, fw);\n                  fw -= i;\n                  while (i) {\n                     if ((((stbsp__uintptr)bf) & 3) == 0)\n                        break;\n                     *bf++ = ' ';\n                     --i;\n                  }\n                  while (i >= 4) {\n                     *(stbsp__uint32 *)bf = 0x20202020;\n                     bf += 4;\n                     i -= 4;\n                  }\n                  while (i--)\n                     *bf++ = ' ';\n                  stbsp__chk_cb_buf(1);\n               }\n            }\n         break;\n\n      default: // unknown, just copy code\n         s = num + STBSP__NUMSZ - 1;\n         *s = f[0];\n         l = 1;\n         fw = fl = 0;\n         lead[0] = 0;\n         tail[0] = 0;\n         pr = 0;\n         dp = 0;\n         cs = 0;\n         goto scopy;\n      }\n      ++f;\n   }\nendfmt:\n\n   if (!callback)\n      *bf = 0;\n   else\n      stbsp__flush_cb();\n\ndone:\n   return tlen + (int)(bf - buf);\n}\n\n// cleanup\n#undef STBSP__LEFTJUST\n#undef STBSP__LEADINGPLUS\n#undef STBSP__LEADINGSPACE\n#undef STBSP__LEADING_0X\n#undef STBSP__LEADINGZERO\n#undef STBSP__INTMAX\n#undef STBSP__TRIPLET_COMMA\n#undef STBSP__NEGATIVE\n#undef STBSP__METRIC_SUFFIX\n#undef STBSP__NUMSZ\n#undef stbsp__chk_cb_bufL\n#undef stbsp__chk_cb_buf\n#undef stbsp__flush_cb\n#undef stbsp__cb_buf_clamp\n\n// ============================================================================\n//   wrapper functions\n\nSTBSP__PUBLICDEF int STB_SPRINTF_DECORATE(sprintf)(char *buf, char const *fmt, ...)\n{\n   int result;\n   va_list va;\n   va_start(va, fmt);\n   result = STB_SPRINTF_DECORATE(vsprintfcb)(0, 0, buf, fmt, va);\n   va_end(va);\n   return result;\n}\n\ntypedef struct stbsp__context {\n   char *buf;\n   int count;\n   int length;\n   char tmp[STB_SPRINTF_MIN];\n} stbsp__context;\n\nstatic char *stbsp__clamp_callback(const char *buf, void *user, int len)\n{\n   stbsp__context *c = (stbsp__context *)user;\n   c->length += len;\n\n   if (len > c->count)\n      len = c->count;\n\n   if (len) {\n      if (buf != c->buf) {\n         const char *s, *se;\n         char *d;\n         d = c->buf;\n         s = buf;\n         se = buf + len;\n         do {\n            *d++ = *s++;\n         } while (s < se);\n      }\n      c->buf += len;\n      c->count -= len;\n   }\n\n   if (c->count <= 0)\n      return c->tmp;\n   return (c->count >= STB_SPRINTF_MIN) ? c->buf : c->tmp; // go direct into buffer if you can\n}\n\nstatic char * stbsp__count_clamp_callback( const char * buf, void * user, int len )\n{\n   stbsp__context * c = (stbsp__context*)user;\n   (void) sizeof(buf);\n\n   c->length += len;\n   return c->tmp; // go direct into buffer if you can\n}\n\nSTBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va )\n{\n   stbsp__context c;\n\n   if ( (count == 0) && !buf )\n   {\n      c.length = 0;\n\n      STB_SPRINTF_DECORATE( vsprintfcb )( stbsp__count_clamp_callback, &c, c.tmp, fmt, va );\n   }\n   else\n   {\n      int l;\n\n      c.buf = buf;\n      c.count = count;\n      c.length = 0;\n\n      STB_SPRINTF_DECORATE( vsprintfcb )( stbsp__clamp_callback, &c, stbsp__clamp_callback(0,&c,0), fmt, va );\n\n      // zero-terminate\n      l = (int)( c.buf - buf );\n      if ( l >= count ) // should never be greater, only equal (or less) than count\n         l = count - 1;\n      buf[l] = 0;\n   }\n\n   return c.length;\n}\n\nSTBSP__PUBLICDEF int STB_SPRINTF_DECORATE(snprintf)(char *buf, int count, char const *fmt, ...)\n{\n   int result;\n   va_list va;\n   va_start(va, fmt);\n\n   result = STB_SPRINTF_DECORATE(vsnprintf)(buf, count, fmt, va);\n   va_end(va);\n\n   return result;\n}\n\nSTBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsprintf)(char *buf, char const *fmt, va_list va)\n{\n   return STB_SPRINTF_DECORATE(vsprintfcb)(0, 0, buf, fmt, va);\n}\n\n// =======================================================================\n//   low level float utility functions\n\n#ifndef STB_SPRINTF_NOFLOAT\n\n// copies d to bits w/ strict aliasing (this compiles to nothing on /Ox)\n#define STBSP__COPYFP(dest, src)                   \\\n   {                                               \\\n      int cn;                                      \\\n      for (cn = 0; cn < 8; cn++)                   \\\n         ((char *)&dest)[cn] = ((char *)&src)[cn]; \\\n   }\n\n// get float info\nstatic stbsp__int32 stbsp__real_to_parts(stbsp__int64 *bits, stbsp__int32 *expo, double value)\n{\n   double d;\n   stbsp__int64 b = 0;\n\n   // load value and round at the frac_digits\n   d = value;\n\n   STBSP__COPYFP(b, d);\n\n   *bits = b & ((((stbsp__uint64)1) << 52) - 1);\n   *expo = (stbsp__int32)(((b >> 52) & 2047) - 1023);\n\n   return (stbsp__int32)((stbsp__uint64) b >> 63);\n}\n\nstatic double const stbsp__bot[23] = {\n   1e+000, 1e+001, 1e+002, 1e+003, 1e+004, 1e+005, 1e+006, 1e+007, 1e+008, 1e+009, 1e+010, 1e+011,\n   1e+012, 1e+013, 1e+014, 1e+015, 1e+016, 1e+017, 1e+018, 1e+019, 1e+020, 1e+021, 1e+022\n};\nstatic double const stbsp__negbot[22] = {\n   1e-001, 1e-002, 1e-003, 1e-004, 1e-005, 1e-006, 1e-007, 1e-008, 1e-009, 1e-010, 1e-011,\n   1e-012, 1e-013, 1e-014, 1e-015, 1e-016, 1e-017, 1e-018, 1e-019, 1e-020, 1e-021, 1e-022\n};\nstatic double const stbsp__negboterr[22] = {\n   -5.551115123125783e-018,  -2.0816681711721684e-019, -2.0816681711721686e-020, -4.7921736023859299e-021, -8.1803053914031305e-022, 4.5251888174113741e-023,\n   4.5251888174113739e-024,  -2.0922560830128471e-025, -6.2281591457779853e-026, -3.6432197315497743e-027, 6.0503030718060191e-028,  2.0113352370744385e-029,\n   -3.0373745563400371e-030, 1.1806906454401013e-032,  -7.7705399876661076e-032, 2.0902213275965398e-033,  -7.1542424054621921e-034, -7.1542424054621926e-035,\n   2.4754073164739869e-036,  5.4846728545790429e-037,  9.2462547772103625e-038,  -4.8596774326570872e-039\n};\nstatic double const stbsp__top[13] = {\n   1e+023, 1e+046, 1e+069, 1e+092, 1e+115, 1e+138, 1e+161, 1e+184, 1e+207, 1e+230, 1e+253, 1e+276, 1e+299\n};\nstatic double const stbsp__negtop[13] = {\n   1e-023, 1e-046, 1e-069, 1e-092, 1e-115, 1e-138, 1e-161, 1e-184, 1e-207, 1e-230, 1e-253, 1e-276, 1e-299\n};\nstatic double const stbsp__toperr[13] = {\n   8388608,\n   6.8601809640529717e+028,\n   -7.253143638152921e+052,\n   -4.3377296974619174e+075,\n   -1.5559416129466825e+098,\n   -3.2841562489204913e+121,\n   -3.7745893248228135e+144,\n   -1.7356668416969134e+167,\n   -3.8893577551088374e+190,\n   -9.9566444326005119e+213,\n   6.3641293062232429e+236,\n   -5.2069140800249813e+259,\n   -5.2504760255204387e+282\n};\nstatic double const stbsp__negtoperr[13] = {\n   3.9565301985100693e-040,  -2.299904345391321e-063,  3.6506201437945798e-086,  1.1875228833981544e-109,\n   -5.0644902316928607e-132, -6.7156837247865426e-155, -2.812077463003139e-178,  -5.7778912386589953e-201,\n   7.4997100559334532e-224,  -4.6439668915134491e-247, -6.3691100762962136e-270, -9.436808465446358e-293,\n   8.0970921678014997e-317\n};\n\n#if defined(_MSC_VER) && (_MSC_VER <= 1200)\nstatic stbsp__uint64 const stbsp__powten[20] = {\n   1,\n   10,\n   100,\n   1000,\n   10000,\n   100000,\n   1000000,\n   10000000,\n   100000000,\n   1000000000,\n   10000000000,\n   100000000000,\n   1000000000000,\n   10000000000000,\n   100000000000000,\n   1000000000000000,\n   10000000000000000,\n   100000000000000000,\n   1000000000000000000,\n   10000000000000000000U\n};\n#define stbsp__tento19th ((stbsp__uint64)1000000000000000000)\n#else\nstatic stbsp__uint64 const stbsp__powten[20] = {\n   1,\n   10,\n   100,\n   1000,\n   10000,\n   100000,\n   1000000,\n   10000000,\n   100000000,\n   1000000000,\n   10000000000ULL,\n   100000000000ULL,\n   1000000000000ULL,\n   10000000000000ULL,\n   100000000000000ULL,\n   1000000000000000ULL,\n   10000000000000000ULL,\n   100000000000000000ULL,\n   1000000000000000000ULL,\n   10000000000000000000ULL\n};\n#define stbsp__tento19th (1000000000000000000ULL)\n#endif\n\n#define stbsp__ddmulthi(oh, ol, xh, yh)                            \\\n   {                                                               \\\n      double ahi = 0, alo, bhi = 0, blo;                           \\\n      stbsp__int64 bt;                                             \\\n      oh = xh * yh;                                                \\\n      STBSP__COPYFP(bt, xh);                                       \\\n      bt &= ((~(stbsp__uint64)0) << 27);                           \\\n      STBSP__COPYFP(ahi, bt);                                      \\\n      alo = xh - ahi;                                              \\\n      STBSP__COPYFP(bt, yh);                                       \\\n      bt &= ((~(stbsp__uint64)0) << 27);                           \\\n      STBSP__COPYFP(bhi, bt);                                      \\\n      blo = yh - bhi;                                              \\\n      ol = ((ahi * bhi - oh) + ahi * blo + alo * bhi) + alo * blo; \\\n   }\n\n#define stbsp__ddtoS64(ob, xh, xl)          \\\n   {                                        \\\n      double ahi = 0, alo, vh, t;           \\\n      ob = (stbsp__int64)xh;                \\\n      vh = (double)ob;                      \\\n      ahi = (xh - vh);                      \\\n      t = (ahi - xh);                       \\\n      alo = (xh - (ahi - t)) - (vh + t);    \\\n      ob += (stbsp__int64)(ahi + alo + xl); \\\n   }\n\n#define stbsp__ddrenorm(oh, ol) \\\n   {                            \\\n      double s;                 \\\n      s = oh + ol;              \\\n      ol = ol - (s - oh);       \\\n      oh = s;                   \\\n   }\n\n#define stbsp__ddmultlo(oh, ol, xh, xl, yh, yl) ol = ol + (xh * yl + xl * yh);\n\n#define stbsp__ddmultlos(oh, ol, xh, yl) ol = ol + (xh * yl);\n\nstatic void stbsp__raise_to_power10(double *ohi, double *olo, double d, stbsp__int32 power) // power can be -323 to +350\n{\n   double ph, pl;\n   if ((power >= 0) && (power <= 22)) {\n      stbsp__ddmulthi(ph, pl, d, stbsp__bot[power]);\n   } else {\n      stbsp__int32 e, et, eb;\n      double p2h, p2l;\n\n      e = power;\n      if (power < 0)\n         e = -e;\n      et = (e * 0x2c9) >> 14; /* %23 */\n      if (et > 13)\n         et = 13;\n      eb = e - (et * 23);\n\n      ph = d;\n      pl = 0.0;\n      if (power < 0) {\n         if (eb) {\n            --eb;\n            stbsp__ddmulthi(ph, pl, d, stbsp__negbot[eb]);\n            stbsp__ddmultlos(ph, pl, d, stbsp__negboterr[eb]);\n         }\n         if (et) {\n            stbsp__ddrenorm(ph, pl);\n            --et;\n            stbsp__ddmulthi(p2h, p2l, ph, stbsp__negtop[et]);\n            stbsp__ddmultlo(p2h, p2l, ph, pl, stbsp__negtop[et], stbsp__negtoperr[et]);\n            ph = p2h;\n            pl = p2l;\n         }\n      } else {\n         if (eb) {\n            e = eb;\n            if (eb > 22)\n               eb = 22;\n            e -= eb;\n            stbsp__ddmulthi(ph, pl, d, stbsp__bot[eb]);\n            if (e) {\n               stbsp__ddrenorm(ph, pl);\n               stbsp__ddmulthi(p2h, p2l, ph, stbsp__bot[e]);\n               stbsp__ddmultlos(p2h, p2l, stbsp__bot[e], pl);\n               ph = p2h;\n               pl = p2l;\n            }\n         }\n         if (et) {\n            stbsp__ddrenorm(ph, pl);\n            --et;\n            stbsp__ddmulthi(p2h, p2l, ph, stbsp__top[et]);\n            stbsp__ddmultlo(p2h, p2l, ph, pl, stbsp__top[et], stbsp__toperr[et]);\n            ph = p2h;\n            pl = p2l;\n         }\n      }\n   }\n   stbsp__ddrenorm(ph, pl);\n   *ohi = ph;\n   *olo = pl;\n}\n\n// given a float value, returns the significant bits in bits, and the position of the\n//   decimal point in decimal_pos.  +/-INF and NAN are specified by special values\n//   returned in the decimal_pos parameter.\n// frac_digits is absolute normally, but if you want from first significant digits (got %g and %e), or in 0x80000000\nstatic stbsp__int32 stbsp__real_to_str(char const **start, stbsp__uint32 *len, char *out, stbsp__int32 *decimal_pos, double value, stbsp__uint32 frac_digits)\n{\n   double d;\n   stbsp__int64 bits = 0;\n   stbsp__int32 expo, e, ng, tens;\n\n   d = value;\n   STBSP__COPYFP(bits, d);\n   expo = (stbsp__int32)((bits >> 52) & 2047);\n   ng = (stbsp__int32)((stbsp__uint64) bits >> 63);\n   if (ng)\n      d = -d;\n\n   if (expo == 2047) // is nan or inf?\n   {\n      *start = (bits & ((((stbsp__uint64)1) << 52) - 1)) ? \"NaN\" : \"Inf\";\n      *decimal_pos = STBSP__SPECIAL;\n      *len = 3;\n      return ng;\n   }\n\n   if (expo == 0) // is zero or denormal\n   {\n      if (((stbsp__uint64) bits << 1) == 0) // do zero\n      {\n         *decimal_pos = 1;\n         *start = out;\n         out[0] = '0';\n         *len = 1;\n         return ng;\n      }\n      // find the right expo for denormals\n      {\n         stbsp__int64 v = ((stbsp__uint64)1) << 51;\n         while ((bits & v) == 0) {\n            --expo;\n            v >>= 1;\n         }\n      }\n   }\n\n   // find the decimal exponent as well as the decimal bits of the value\n   {\n      double ph, pl;\n\n      // log10 estimate - very specifically tweaked to hit or undershoot by no more than 1 of log10 of all expos 1..2046\n      tens = expo - 1023;\n      tens = (tens < 0) ? ((tens * 617) / 2048) : (((tens * 1233) / 4096) + 1);\n\n      // move the significant bits into position and stick them into an int\n      stbsp__raise_to_power10(&ph, &pl, d, 18 - tens);\n\n      // get full as much precision from double-double as possible\n      stbsp__ddtoS64(bits, ph, pl);\n\n      // check if we undershot\n      if (((stbsp__uint64)bits) >= stbsp__tento19th)\n         ++tens;\n   }\n\n   // now do the rounding in integer land\n   frac_digits = (frac_digits & 0x80000000) ? ((frac_digits & 0x7ffffff) + 1) : (tens + frac_digits);\n   if ((frac_digits < 24)) {\n      stbsp__uint32 dg = 1;\n      if ((stbsp__uint64)bits >= stbsp__powten[9])\n         dg = 10;\n      while ((stbsp__uint64)bits >= stbsp__powten[dg]) {\n         ++dg;\n         if (dg == 20)\n            goto noround;\n      }\n      if (frac_digits < dg) {\n         stbsp__uint64 r;\n         // add 0.5 at the right position and round\n         e = dg - frac_digits;\n         if ((stbsp__uint32)e >= 24)\n            goto noround;\n         r = stbsp__powten[e];\n         bits = bits + (r / 2);\n         if ((stbsp__uint64)bits >= stbsp__powten[dg])\n            ++tens;\n         bits /= r;\n      }\n   noround:;\n   }\n\n   // kill long trailing runs of zeros\n   if (bits) {\n      stbsp__uint32 n;\n      for (;;) {\n         if (bits <= 0xffffffff)\n            break;\n         if (bits % 1000)\n            goto donez;\n         bits /= 1000;\n      }\n      n = (stbsp__uint32)bits;\n      while ((n % 1000) == 0)\n         n /= 1000;\n      bits = n;\n   donez:;\n   }\n\n   // convert to string\n   out += 64;\n   e = 0;\n   for (;;) {\n      stbsp__uint32 n;\n      char *o = out - 8;\n      // do the conversion in chunks of U32s (avoid most 64-bit divides, worth it, constant denomiators be damned)\n      if (bits >= 100000000) {\n         n = (stbsp__uint32)(bits % 100000000);\n         bits /= 100000000;\n      } else {\n         n = (stbsp__uint32)bits;\n         bits = 0;\n      }\n      while (n) {\n         out -= 2;\n         *(stbsp__uint16 *)out = *(stbsp__uint16 *)&stbsp__digitpair.pair[(n % 100) * 2];\n         n /= 100;\n         e += 2;\n      }\n      if (bits == 0) {\n         if ((e) && (out[0] == '0')) {\n            ++out;\n            --e;\n         }\n         break;\n      }\n      while (out != o) {\n         *--out = '0';\n         ++e;\n      }\n   }\n\n   *decimal_pos = tens;\n   *start = out;\n   *len = e;\n   return ng;\n}\n\n#undef stbsp__ddmulthi\n#undef stbsp__ddrenorm\n#undef stbsp__ddmultlo\n#undef stbsp__ddmultlos\n#undef STBSP__SPECIAL\n#undef STBSP__COPYFP\n\n#endif // STB_SPRINTF_NOFLOAT\n\n// clean up\n#undef stbsp__uint16\n#undef stbsp__uint32\n#undef stbsp__int32\n#undef stbsp__uint64\n#undef stbsp__int64\n#undef STBSP__UNALIGNED\n\n#endif // STB_SPRINTF_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_textedit.h",
    "content": "// stb_textedit.h - v1.14  - public domain - Sean Barrett\n// Development of this library was sponsored by RAD Game Tools\n//\n// This C header file implements the guts of a multi-line text-editing\n// widget; you implement display, word-wrapping, and low-level string\n// insertion/deletion, and stb_textedit will map user inputs into\n// insertions & deletions, plus updates to the cursor position,\n// selection state, and undo state.\n//\n// It is intended for use in games and other systems that need to build\n// their own custom widgets and which do not have heavy text-editing\n// requirements (this library is not recommended for use for editing large\n// texts, as its performance does not scale and it has limited undo).\n//\n// Non-trivial behaviors are modelled after Windows text controls.\n//\n//\n// LICENSE\n//\n// See end of file for license information.\n//\n//\n// DEPENDENCIES\n//\n// Uses the C runtime function 'memmove', which you can override\n// by defining STB_TEXTEDIT_memmove before the implementation.\n// Uses no other functions. Performs no runtime allocations.\n//\n//\n// VERSION HISTORY\n//\n//   1.14 (2021-07-11) page up/down, various fixes\n//   1.13 (2019-02-07) fix bug in undo size management\n//   1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash\n//   1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield\n//   1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual\n//   1.9  (2016-08-27) customizable move-by-word\n//   1.8  (2016-04-02) better keyboard handling when mouse button is down\n//   1.7  (2015-09-13) change y range handling in case baseline is non-0\n//   1.6  (2015-04-15) allow STB_TEXTEDIT_memmove\n//   1.5  (2014-09-10) add support for secondary keys for OS X\n//   1.4  (2014-08-17) fix signed/unsigned warnings\n//   1.3  (2014-06-19) fix mouse clicking to round to nearest char boundary\n//   1.2  (2014-05-27) fix some RAD types that had crept into the new code\n//   1.1  (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )\n//   1.0  (2012-07-26) improve documentation, initial public release\n//   0.3  (2012-02-24) bugfixes, single-line mode; insert mode\n//   0.2  (2011-11-28) fixes to undo/redo\n//   0.1  (2010-07-08) initial version\n//\n// ADDITIONAL CONTRIBUTORS\n//\n//   Ulf Winklemann: move-by-word in 1.1\n//   Fabian Giesen: secondary key inputs in 1.5\n//   Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6\n//   Louis Schnellbach: page up/down in 1.14\n//\n//   Bugfixes:\n//      Scott Graham\n//      Daniel Keller\n//      Omar Cornut\n//      Dan Thompson\n//\n// USAGE\n//\n// This file behaves differently depending on what symbols you define\n// before including it.\n//\n//\n// Header-file mode:\n//\n//   If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,\n//   it will operate in \"header file\" mode. In this mode, it declares a\n//   single public symbol, STB_TexteditState, which encapsulates the current\n//   state of a text widget (except for the string, which you will store\n//   separately).\n//\n//   To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a\n//   primitive type that defines a single character (e.g. char, wchar_t, etc).\n//\n//   To save space or increase undo-ability, you can optionally define the\n//   following things that are used by the undo system:\n//\n//      STB_TEXTEDIT_POSITIONTYPE         small int type encoding a valid cursor position\n//      STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow\n//      STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer\n//\n//   If you don't define these, they are set to permissive types and\n//   moderate sizes. The undo system does no memory allocations, so\n//   it grows STB_TexteditState by the worst-case storage which is (in bytes):\n//\n//        [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATECOUNT\n//      +          sizeof(STB_TEXTEDIT_CHARTYPE)      * STB_TEXTEDIT_UNDOCHARCOUNT\n//\n//\n// Implementation mode:\n//\n//   If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it\n//   will compile the implementation of the text edit widget, depending\n//   on a large number of symbols which must be defined before the include.\n//\n//   The implementation is defined only as static functions. You will then\n//   need to provide your own APIs in the same file which will access the\n//   static functions.\n//\n//   The basic concept is that you provide a \"string\" object which\n//   behaves like an array of characters. stb_textedit uses indices to\n//   refer to positions in the string, implicitly representing positions\n//   in the displayed textedit. This is true for both plain text and\n//   rich text; even with rich text stb_truetype interacts with your\n//   code as if there was an array of all the displayed characters.\n//\n// Symbols that must be the same in header-file and implementation mode:\n//\n//     STB_TEXTEDIT_CHARTYPE             the character type\n//     STB_TEXTEDIT_POSITIONTYPE         small type that is a valid cursor position\n//     STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow\n//     STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer\n//\n// Symbols you must define for implementation mode:\n//\n//    STB_TEXTEDIT_STRING               the type of object representing a string being edited,\n//                                      typically this is a wrapper object with other data you need\n//\n//    STB_TEXTEDIT_STRINGLEN(obj)       the length of the string (ideally O(1))\n//    STB_TEXTEDIT_LAYOUTROW(&r,obj,n)  returns the results of laying out a line of characters\n//                                        starting from character #n (see discussion below)\n//    STB_TEXTEDIT_GETWIDTH(obj,n,i)    returns the pixel delta from the xpos of the i'th character\n//                                        to the xpos of the i+1'th char for a line of characters\n//                                        starting at character #n (i.e. accounts for kerning\n//                                        with previous char)\n//    STB_TEXTEDIT_KEYTOTEXT(k)         maps a keyboard input to an insertable character\n//                                        (return type is int, -1 means not valid to insert)\n//    STB_TEXTEDIT_GETCHAR(obj,i)       returns the i'th character of obj, 0-based\n//    STB_TEXTEDIT_NEWLINE              the character returned by _GETCHAR() we recognize\n//                                        as manually wordwrapping for end-of-line positioning\n//\n//    STB_TEXTEDIT_DELETECHARS(obj,i,n)      delete n characters starting at i\n//    STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n)   insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)\n//\n//    STB_TEXTEDIT_K_SHIFT       a power of two that is or'd in to a keyboard input to represent the shift key\n//\n//    STB_TEXTEDIT_K_LEFT        keyboard input to move cursor left\n//    STB_TEXTEDIT_K_RIGHT       keyboard input to move cursor right\n//    STB_TEXTEDIT_K_UP          keyboard input to move cursor up\n//    STB_TEXTEDIT_K_DOWN        keyboard input to move cursor down\n//    STB_TEXTEDIT_K_PGUP        keyboard input to move cursor up a page\n//    STB_TEXTEDIT_K_PGDOWN      keyboard input to move cursor down a page\n//    STB_TEXTEDIT_K_LINESTART   keyboard input to move cursor to start of line  // e.g. HOME\n//    STB_TEXTEDIT_K_LINEEND     keyboard input to move cursor to end of line    // e.g. END\n//    STB_TEXTEDIT_K_TEXTSTART   keyboard input to move cursor to start of text  // e.g. ctrl-HOME\n//    STB_TEXTEDIT_K_TEXTEND     keyboard input to move cursor to end of text    // e.g. ctrl-END\n//    STB_TEXTEDIT_K_DELETE      keyboard input to delete selection or character under cursor\n//    STB_TEXTEDIT_K_BACKSPACE   keyboard input to delete selection or character left of cursor\n//    STB_TEXTEDIT_K_UNDO        keyboard input to perform undo\n//    STB_TEXTEDIT_K_REDO        keyboard input to perform redo\n//\n// Optional:\n//    STB_TEXTEDIT_K_INSERT              keyboard input to toggle insert mode\n//    STB_TEXTEDIT_IS_SPACE(ch)          true if character is whitespace (e.g. 'isspace'),\n//                                          required for default WORDLEFT/WORDRIGHT handlers\n//    STB_TEXTEDIT_MOVEWORDLEFT(obj,i)   custom handler for WORDLEFT, returns index to move cursor to\n//    STB_TEXTEDIT_MOVEWORDRIGHT(obj,i)  custom handler for WORDRIGHT, returns index to move cursor to\n//    STB_TEXTEDIT_K_WORDLEFT            keyboard input to move cursor left one word // e.g. ctrl-LEFT\n//    STB_TEXTEDIT_K_WORDRIGHT           keyboard input to move cursor right one word // e.g. ctrl-RIGHT\n//    STB_TEXTEDIT_K_LINESTART2          secondary keyboard input to move cursor to start of line\n//    STB_TEXTEDIT_K_LINEEND2            secondary keyboard input to move cursor to end of line\n//    STB_TEXTEDIT_K_TEXTSTART2          secondary keyboard input to move cursor to start of text\n//    STB_TEXTEDIT_K_TEXTEND2            secondary keyboard input to move cursor to end of text\n//\n// Keyboard input must be encoded as a single integer value; e.g. a character code\n// and some bitflags that represent shift states. to simplify the interface, SHIFT must\n// be a bitflag, so we can test the shifted state of cursor movements to allow selection,\n// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.\n//\n// You can encode other things, such as CONTROL or ALT, in additional bits, and\n// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,\n// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN\n// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,\n// and I pass both WM_KEYDOWN and WM_CHAR events to the \"key\" function in the\n// API below. The control keys will only match WM_KEYDOWN events because of the\n// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN\n// bit so it only decodes WM_CHAR events.\n//\n// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed\n// row of characters assuming they start on the i'th character--the width and\n// the height and the number of characters consumed. This allows this library\n// to traverse the entire layout incrementally. You need to compute word-wrapping\n// here.\n//\n// Each textfield keeps its own insert mode state, which is not how normal\n// applications work. To keep an app-wide insert mode, update/copy the\n// \"insert_mode\" field of STB_TexteditState before/after calling API functions.\n//\n// API\n//\n//    void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)\n//\n//    void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\n//    void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\n//    int  stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n//    int  stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)\n//    void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)\n//\n//    Each of these functions potentially updates the string and updates the\n//    state.\n//\n//      initialize_state:\n//          set the textedit state to a known good default state when initially\n//          constructing the textedit.\n//\n//      click:\n//          call this with the mouse x,y on a mouse down; it will update the cursor\n//          and reset the selection start/end to the cursor point. the x,y must\n//          be relative to the text widget, with (0,0) being the top left.\n//\n//      drag:\n//          call this with the mouse x,y on a mouse drag/up; it will update the\n//          cursor and the selection end point\n//\n//      cut:\n//          call this to delete the current selection; returns true if there was\n//          one. you should FIRST copy the current selection to the system paste buffer.\n//          (To copy, just copy the current selection out of the string yourself.)\n//\n//      paste:\n//          call this to paste text at the current cursor point or over the current\n//          selection if there is one.\n//\n//      key:\n//          call this for keyboard inputs sent to the textfield. you can use it\n//          for \"key down\" events or for \"translated\" key events. if you need to\n//          do both (as in Win32), or distinguish Unicode characters from control\n//          inputs, set a high bit to distinguish the two; then you can define the\n//          various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit\n//          set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is\n//          clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to\n//          anything other type you wante before including.\n//\n//\n//   When rendering, you can read the cursor position and selection state from\n//   the STB_TexteditState.\n//\n//\n// Notes:\n//\n// This is designed to be usable in IMGUI, so it allows for the possibility of\n// running in an IMGUI that has NOT cached the multi-line layout. For this\n// reason, it provides an interface that is compatible with computing the\n// layout incrementally--we try to make sure we make as few passes through\n// as possible. (For example, to locate the mouse pointer in the text, we\n// could define functions that return the X and Y positions of characters\n// and binary search Y and then X, but if we're doing dynamic layout this\n// will run the layout algorithm many times, so instead we manually search\n// forward in one pass. Similar logic applies to e.g. up-arrow and\n// down-arrow movement.)\n//\n// If it's run in a widget that *has* cached the layout, then this is less\n// efficient, but it's not horrible on modern computers. But you wouldn't\n// want to edit million-line files with it.\n\n\n////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////\n////\n////   Header-file mode\n////\n////\n\n#ifndef INCLUDE_STB_TEXTEDIT_H\n#define INCLUDE_STB_TEXTEDIT_H\n\n////////////////////////////////////////////////////////////////////////\n//\n//     STB_TexteditState\n//\n// Definition of STB_TexteditState which you should store\n// per-textfield; it includes cursor position, selection state,\n// and undo state.\n//\n\n#ifndef STB_TEXTEDIT_UNDOSTATECOUNT\n#define STB_TEXTEDIT_UNDOSTATECOUNT   99\n#endif\n#ifndef STB_TEXTEDIT_UNDOCHARCOUNT\n#define STB_TEXTEDIT_UNDOCHARCOUNT   999\n#endif\n#ifndef STB_TEXTEDIT_CHARTYPE\n#define STB_TEXTEDIT_CHARTYPE        int\n#endif\n#ifndef STB_TEXTEDIT_POSITIONTYPE\n#define STB_TEXTEDIT_POSITIONTYPE    int\n#endif\n\ntypedef struct\n{\n   // private data\n   STB_TEXTEDIT_POSITIONTYPE  where;\n   STB_TEXTEDIT_POSITIONTYPE  insert_length;\n   STB_TEXTEDIT_POSITIONTYPE  delete_length;\n   int                        char_storage;\n} StbUndoRecord;\n\ntypedef struct\n{\n   // private data\n   StbUndoRecord          undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT];\n   STB_TEXTEDIT_CHARTYPE  undo_char[STB_TEXTEDIT_UNDOCHARCOUNT];\n   short undo_point, redo_point;\n   int undo_char_point, redo_char_point;\n} StbUndoState;\n\ntypedef struct\n{\n   /////////////////////\n   //\n   // public data\n   //\n\n   int cursor;\n   // position of the text cursor within the string\n\n   int select_start;          // selection start point\n   int select_end;\n   // selection start and end point in characters; if equal, no selection.\n   // note that start may be less than or greater than end (e.g. when\n   // dragging the mouse, start is where the initial click was, and you\n   // can drag in either direction)\n\n   unsigned char insert_mode;\n   // each textfield keeps its own insert mode state. to keep an app-wide\n   // insert mode, copy this value in/out of the app state\n\n   int row_count_per_page;\n   // page size in number of row.\n   // this value MUST be set to >0 for pageup or pagedown in multilines documents.\n\n   /////////////////////\n   //\n   // private data\n   //\n   unsigned char cursor_at_end_of_line; // not implemented yet\n   unsigned char initialized;\n   unsigned char has_preferred_x;\n   unsigned char single_line;\n   unsigned char padding1, padding2, padding3;\n   float preferred_x; // this determines where the cursor up/down tries to seek to along x\n   StbUndoState undostate;\n} STB_TexteditState;\n\n\n////////////////////////////////////////////////////////////////////////\n//\n//     StbTexteditRow\n//\n// Result of layout query, used by stb_textedit to determine where\n// the text in each row is.\n\n// result of layout query\ntypedef struct\n{\n   float x0,x1;             // starting x location, end x location (allows for align=right, etc)\n   float baseline_y_delta;  // position of baseline relative to previous row's baseline\n   float ymin,ymax;         // height of row above and below baseline\n   int num_chars;\n} StbTexteditRow;\n#endif //INCLUDE_STB_TEXTEDIT_H\n\n\n////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////\n////\n////   Implementation mode\n////\n////\n\n\n// implementation isn't include-guarded, since it might have indirectly\n// included just the \"header\" portion\n#ifdef STB_TEXTEDIT_IMPLEMENTATION\n\n#ifndef STB_TEXTEDIT_memmove\n#include <string.h>\n#define STB_TEXTEDIT_memmove memmove\n#endif\n\n\n/////////////////////////////////////////////////////////////////////////////\n//\n//      Mouse input handling\n//\n\n// traverse the layout to locate the nearest character to a display position\nstatic int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)\n{\n   StbTexteditRow r;\n   int n = STB_TEXTEDIT_STRINGLEN(str);\n   float base_y = 0, prev_x;\n   int i=0, k;\n\n   r.x0 = r.x1 = 0;\n   r.ymin = r.ymax = 0;\n   r.num_chars = 0;\n\n   // search rows to find one that straddles 'y'\n   while (i < n) {\n      STB_TEXTEDIT_LAYOUTROW(&r, str, i);\n      if (r.num_chars <= 0)\n         return n;\n\n      if (i==0 && y < base_y + r.ymin)\n         return 0;\n\n      if (y < base_y + r.ymax)\n         break;\n\n      i += r.num_chars;\n      base_y += r.baseline_y_delta;\n   }\n\n   // below all text, return 'after' last character\n   if (i >= n)\n      return n;\n\n   // check if it's before the beginning of the line\n   if (x < r.x0)\n      return i;\n\n   // check if it's before the end of the line\n   if (x < r.x1) {\n      // search characters in row for one that straddles 'x'\n      prev_x = r.x0;\n      for (k=0; k < r.num_chars; ++k) {\n         float w = STB_TEXTEDIT_GETWIDTH(str, i, k);\n         if (x < prev_x+w) {\n            if (x < prev_x+w/2)\n               return k+i;\n            else\n               return k+i+1;\n         }\n         prev_x += w;\n      }\n      // shouldn't happen, but if it does, fall through to end-of-line case\n   }\n\n   // if the last character is a newline, return that. otherwise return 'after' the last character\n   if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)\n      return i+r.num_chars-1;\n   else\n      return i+r.num_chars;\n}\n\n// API click: on mouse down, move the cursor to the clicked location, and reset the selection\nstatic void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\n{\n   // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse\n   // goes off the top or bottom of the text\n   if( state->single_line )\n   {\n      StbTexteditRow r;\n      STB_TEXTEDIT_LAYOUTROW(&r, str, 0);\n      y = r.ymin;\n   }\n\n   state->cursor = stb_text_locate_coord(str, x, y);\n   state->select_start = state->cursor;\n   state->select_end = state->cursor;\n   state->has_preferred_x = 0;\n}\n\n// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location\nstatic void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\n{\n   int p = 0;\n\n   // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse\n   // goes off the top or bottom of the text\n   if( state->single_line )\n   {\n      StbTexteditRow r;\n      STB_TEXTEDIT_LAYOUTROW(&r, str, 0);\n      y = r.ymin;\n   }\n\n   if (state->select_start == state->select_end)\n      state->select_start = state->cursor;\n\n   p = stb_text_locate_coord(str, x, y);\n   state->cursor = state->select_end = p;\n}\n\n/////////////////////////////////////////////////////////////////////////////\n//\n//      Keyboard input handling\n//\n\n// forward declarations\nstatic void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);\nstatic void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);\nstatic void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);\nstatic void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);\nstatic void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);\n\ntypedef struct\n{\n   float x,y;    // position of n'th character\n   float height; // height of line\n   int first_char, length; // first char of row, and length\n   int prev_first;  // first char of previous row\n} StbFindState;\n\n// find the x/y location of a character, and remember info about the previous row in\n// case we get a move-up event (for page up, we'll have to rescan)\nstatic void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line)\n{\n   StbTexteditRow r;\n   int prev_start = 0;\n   int z = STB_TEXTEDIT_STRINGLEN(str);\n   int i=0, first;\n\n   if (n == z) {\n      // if it's at the end, then find the last line -- simpler than trying to\n      // explicitly handle this case in the regular code\n      if (single_line) {\n         STB_TEXTEDIT_LAYOUTROW(&r, str, 0);\n         find->y = 0;\n         find->first_char = 0;\n         find->length = z;\n         find->height = r.ymax - r.ymin;\n         find->x = r.x1;\n      } else {\n         find->y = 0;\n         find->x = 0;\n         find->height = 1;\n         while (i < z) {\n            STB_TEXTEDIT_LAYOUTROW(&r, str, i);\n            prev_start = i;\n            i += r.num_chars;\n         }\n         find->first_char = i;\n         find->length = 0;\n         find->prev_first = prev_start;\n      }\n      return;\n   }\n\n   // search rows to find the one that straddles character n\n   find->y = 0;\n\n   for(;;) {\n      STB_TEXTEDIT_LAYOUTROW(&r, str, i);\n      if (n < i + r.num_chars)\n         break;\n      prev_start = i;\n      i += r.num_chars;\n      find->y += r.baseline_y_delta;\n   }\n\n   find->first_char = first = i;\n   find->length = r.num_chars;\n   find->height = r.ymax - r.ymin;\n   find->prev_first = prev_start;\n\n   // now scan to find xpos\n   find->x = r.x0;\n   for (i=0; first+i < n; ++i)\n      find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);\n}\n\n#define STB_TEXT_HAS_SELECTION(s)   ((s)->select_start != (s)->select_end)\n\n// make the selection/cursor state valid if client altered the string\nstatic void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n{\n   int n = STB_TEXTEDIT_STRINGLEN(str);\n   if (STB_TEXT_HAS_SELECTION(state)) {\n      if (state->select_start > n) state->select_start = n;\n      if (state->select_end   > n) state->select_end = n;\n      // if clamping forced them to be equal, move the cursor to match\n      if (state->select_start == state->select_end)\n         state->cursor = state->select_start;\n   }\n   if (state->cursor > n) state->cursor = n;\n}\n\n// delete characters while updating undo\nstatic void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)\n{\n   stb_text_makeundo_delete(str, state, where, len);\n   STB_TEXTEDIT_DELETECHARS(str, where, len);\n   state->has_preferred_x = 0;\n}\n\n// delete the section\nstatic void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n{\n   stb_textedit_clamp(str, state);\n   if (STB_TEXT_HAS_SELECTION(state)) {\n      if (state->select_start < state->select_end) {\n         stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start);\n         state->select_end = state->cursor = state->select_start;\n      } else {\n         stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end);\n         state->select_start = state->cursor = state->select_end;\n      }\n      state->has_preferred_x = 0;\n   }\n}\n\n// canoncialize the selection so start <= end\nstatic void stb_textedit_sortselection(STB_TexteditState *state)\n{\n   if (state->select_end < state->select_start) {\n      int temp = state->select_end;\n      state->select_end = state->select_start;\n      state->select_start = temp;\n   }\n}\n\n// move cursor to first character of selection\nstatic void stb_textedit_move_to_first(STB_TexteditState *state)\n{\n   if (STB_TEXT_HAS_SELECTION(state)) {\n      stb_textedit_sortselection(state);\n      state->cursor = state->select_start;\n      state->select_end = state->select_start;\n      state->has_preferred_x = 0;\n   }\n}\n\n// move cursor to last character of selection\nstatic void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n{\n   if (STB_TEXT_HAS_SELECTION(state)) {\n      stb_textedit_sortselection(state);\n      stb_textedit_clamp(str, state);\n      state->cursor = state->select_end;\n      state->select_start = state->select_end;\n      state->has_preferred_x = 0;\n   }\n}\n\n#ifdef STB_TEXTEDIT_IS_SPACE\nstatic int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx )\n{\n   return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;\n}\n\n#ifndef STB_TEXTEDIT_MOVEWORDLEFT\nstatic int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c )\n{\n   --c; // always move at least one character\n   while( c >= 0 && !is_word_boundary( str, c ) )\n      --c;\n\n   if( c < 0 )\n      c = 0;\n\n   return c;\n}\n#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous\n#endif\n\n#ifndef STB_TEXTEDIT_MOVEWORDRIGHT\nstatic int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c )\n{\n   const int len = STB_TEXTEDIT_STRINGLEN(str);\n   ++c; // always move at least one character\n   while( c < len && !is_word_boundary( str, c ) )\n      ++c;\n\n   if( c > len )\n      c = len;\n\n   return c;\n}\n#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next\n#endif\n\n#endif\n\n// update selection and cursor to match each other\nstatic void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)\n{\n   if (!STB_TEXT_HAS_SELECTION(state))\n      state->select_start = state->select_end = state->cursor;\n   else\n      state->cursor = state->select_end;\n}\n\n// API cut: delete selection\nstatic int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n{\n   if (STB_TEXT_HAS_SELECTION(state)) {\n      stb_textedit_delete_selection(str,state); // implicitly clamps\n      state->has_preferred_x = 0;\n      return 1;\n   }\n   return 0;\n}\n\n// API paste: replace existing selection with passed-in text\nstatic int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)\n{\n   // if there's a selection, the paste should delete it\n   stb_textedit_clamp(str, state);\n   stb_textedit_delete_selection(str,state);\n   // try to insert the characters\n   if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) {\n      stb_text_makeundo_insert(state, state->cursor, len);\n      state->cursor += len;\n      state->has_preferred_x = 0;\n      return 1;\n   }\n   // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details)\n   return 0;\n}\n\n#ifndef STB_TEXTEDIT_KEYTYPE\n#define STB_TEXTEDIT_KEYTYPE int\n#endif\n\n// API key: process a keyboard input\nstatic void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)\n{\nretry:\n   switch (key) {\n      default: {\n         int c = STB_TEXTEDIT_KEYTOTEXT(key);\n         if (c > 0) {\n            STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c;\n\n            // can't add newline in single-line mode\n            if (c == '\\n' && state->single_line)\n               break;\n\n            if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {\n               stb_text_makeundo_replace(str, state, state->cursor, 1, 1);\n               STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);\n               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {\n                  ++state->cursor;\n                  state->has_preferred_x = 0;\n               }\n            } else {\n               stb_textedit_delete_selection(str,state); // implicitly clamps\n               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {\n                  stb_text_makeundo_insert(state, state->cursor, 1);\n                  ++state->cursor;\n                  state->has_preferred_x = 0;\n               }\n            }\n         }\n         break;\n      }\n\n#ifdef STB_TEXTEDIT_K_INSERT\n      case STB_TEXTEDIT_K_INSERT:\n         state->insert_mode = !state->insert_mode;\n         break;\n#endif\n\n      case STB_TEXTEDIT_K_UNDO:\n         stb_text_undo(str, state);\n         state->has_preferred_x = 0;\n         break;\n\n      case STB_TEXTEDIT_K_REDO:\n         stb_text_redo(str, state);\n         state->has_preferred_x = 0;\n         break;\n\n      case STB_TEXTEDIT_K_LEFT:\n         // if currently there's a selection, move cursor to start of selection\n         if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_move_to_first(state);\n         else\n            if (state->cursor > 0)\n               --state->cursor;\n         state->has_preferred_x = 0;\n         break;\n\n      case STB_TEXTEDIT_K_RIGHT:\n         // if currently there's a selection, move cursor to end of selection\n         if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_move_to_last(str, state);\n         else\n            ++state->cursor;\n         stb_textedit_clamp(str, state);\n         state->has_preferred_x = 0;\n         break;\n\n      case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT:\n         stb_textedit_clamp(str, state);\n         stb_textedit_prep_selection_at_cursor(state);\n         // move selection left\n         if (state->select_end > 0)\n            --state->select_end;\n         state->cursor = state->select_end;\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_MOVEWORDLEFT\n      case STB_TEXTEDIT_K_WORDLEFT:\n         if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_move_to_first(state);\n         else {\n            state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);\n            stb_textedit_clamp( str, state );\n         }\n         break;\n\n      case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT:\n         if( !STB_TEXT_HAS_SELECTION( state ) )\n            stb_textedit_prep_selection_at_cursor(state);\n\n         state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);\n         state->select_end = state->cursor;\n\n         stb_textedit_clamp( str, state );\n         break;\n#endif\n\n#ifdef STB_TEXTEDIT_MOVEWORDRIGHT\n      case STB_TEXTEDIT_K_WORDRIGHT:\n         if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_move_to_last(str, state);\n         else {\n            state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);\n            stb_textedit_clamp( str, state );\n         }\n         break;\n\n      case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT:\n         if( !STB_TEXT_HAS_SELECTION( state ) )\n            stb_textedit_prep_selection_at_cursor(state);\n\n         state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);\n         state->select_end = state->cursor;\n\n         stb_textedit_clamp( str, state );\n         break;\n#endif\n\n      case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:\n         stb_textedit_prep_selection_at_cursor(state);\n         // move selection right\n         ++state->select_end;\n         stb_textedit_clamp(str, state);\n         state->cursor = state->select_end;\n         state->has_preferred_x = 0;\n         break;\n\n      case STB_TEXTEDIT_K_DOWN:\n      case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT:\n      case STB_TEXTEDIT_K_PGDOWN:\n      case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: {\n         StbFindState find;\n         StbTexteditRow row;\n         int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;\n         int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN;\n         int row_count = is_page ? state->row_count_per_page : 1;\n\n         if (!is_page && state->single_line) {\n            // on windows, up&down in single-line behave like left&right\n            key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);\n            goto retry;\n         }\n\n         if (sel)\n            stb_textedit_prep_selection_at_cursor(state);\n         else if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_move_to_last(str, state);\n\n         // compute current position of cursor point\n         stb_textedit_clamp(str, state);\n         stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);\n\n         for (j = 0; j < row_count; ++j) {\n            float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;\n            int start = find.first_char + find.length;\n\n            if (find.length == 0)\n               break;\n\n            // now find character position down a row\n            state->cursor = start;\n            STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);\n            x = row.x0;\n            for (i=0; i < row.num_chars; ++i) {\n               float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);\n               #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE\n               if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)\n                  break;\n               #endif\n               x += dx;\n               if (x > goal_x)\n                  break;\n               ++state->cursor;\n            }\n            stb_textedit_clamp(str, state);\n\n            state->has_preferred_x = 1;\n            state->preferred_x = goal_x;\n\n            if (sel)\n               state->select_end = state->cursor;\n\n            // go to next line\n            find.first_char = find.first_char + find.length;\n            find.length = row.num_chars;\n         }\n         break;\n      }\n\n      case STB_TEXTEDIT_K_UP:\n      case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT:\n      case STB_TEXTEDIT_K_PGUP:\n      case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: {\n         StbFindState find;\n         StbTexteditRow row;\n         int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;\n         int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP;\n         int row_count = is_page ? state->row_count_per_page : 1;\n\n         if (!is_page && state->single_line) {\n            // on windows, up&down become left&right\n            key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);\n            goto retry;\n         }\n\n         if (sel)\n            stb_textedit_prep_selection_at_cursor(state);\n         else if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_move_to_first(state);\n\n         // compute current position of cursor point\n         stb_textedit_clamp(str, state);\n         stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);\n\n         for (j = 0; j < row_count; ++j) {\n            float  x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;\n\n            // can only go up if there's a previous row\n            if (find.prev_first == find.first_char)\n               break;\n\n            // now find character position up a row\n            state->cursor = find.prev_first;\n            STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);\n            x = row.x0;\n            for (i=0; i < row.num_chars; ++i) {\n               float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);\n               #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE\n               if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)\n                  break;\n               #endif\n               x += dx;\n               if (x > goal_x)\n                  break;\n               ++state->cursor;\n            }\n            stb_textedit_clamp(str, state);\n\n            state->has_preferred_x = 1;\n            state->preferred_x = goal_x;\n\n            if (sel)\n               state->select_end = state->cursor;\n\n            // go to previous line\n            // (we need to scan previous line the hard way. maybe we could expose this as a new API function?)\n            prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0;\n            while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE)\n               --prev_scan;\n            find.first_char = find.prev_first;\n            find.prev_first = prev_scan;\n         }\n         break;\n      }\n\n      case STB_TEXTEDIT_K_DELETE:\n      case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT:\n         if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_delete_selection(str, state);\n         else {\n            int n = STB_TEXTEDIT_STRINGLEN(str);\n            if (state->cursor < n)\n               stb_textedit_delete(str, state, state->cursor, 1);\n         }\n         state->has_preferred_x = 0;\n         break;\n\n      case STB_TEXTEDIT_K_BACKSPACE:\n      case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT:\n         if (STB_TEXT_HAS_SELECTION(state))\n            stb_textedit_delete_selection(str, state);\n         else {\n            stb_textedit_clamp(str, state);\n            if (state->cursor > 0) {\n               stb_textedit_delete(str, state, state->cursor-1, 1);\n               --state->cursor;\n            }\n         }\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_K_TEXTSTART2\n      case STB_TEXTEDIT_K_TEXTSTART2:\n#endif\n      case STB_TEXTEDIT_K_TEXTSTART:\n         state->cursor = state->select_start = state->select_end = 0;\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_K_TEXTEND2\n      case STB_TEXTEDIT_K_TEXTEND2:\n#endif\n      case STB_TEXTEDIT_K_TEXTEND:\n         state->cursor = STB_TEXTEDIT_STRINGLEN(str);\n         state->select_start = state->select_end = 0;\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_K_TEXTSTART2\n      case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT:\n#endif\n      case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT:\n         stb_textedit_prep_selection_at_cursor(state);\n         state->cursor = state->select_end = 0;\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_K_TEXTEND2\n      case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT:\n#endif\n      case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT:\n         stb_textedit_prep_selection_at_cursor(state);\n         state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str);\n         state->has_preferred_x = 0;\n         break;\n\n\n#ifdef STB_TEXTEDIT_K_LINESTART2\n      case STB_TEXTEDIT_K_LINESTART2:\n#endif\n      case STB_TEXTEDIT_K_LINESTART:\n         stb_textedit_clamp(str, state);\n         stb_textedit_move_to_first(state);\n         if (state->single_line)\n            state->cursor = 0;\n         else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)\n            --state->cursor;\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_K_LINEEND2\n      case STB_TEXTEDIT_K_LINEEND2:\n#endif\n      case STB_TEXTEDIT_K_LINEEND: {\n         int n = STB_TEXTEDIT_STRINGLEN(str);\n         stb_textedit_clamp(str, state);\n         stb_textedit_move_to_first(state);\n         if (state->single_line)\n             state->cursor = n;\n         else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)\n             ++state->cursor;\n         state->has_preferred_x = 0;\n         break;\n      }\n\n#ifdef STB_TEXTEDIT_K_LINESTART2\n      case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT:\n#endif\n      case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:\n         stb_textedit_clamp(str, state);\n         stb_textedit_prep_selection_at_cursor(state);\n         if (state->single_line)\n            state->cursor = 0;\n         else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)\n            --state->cursor;\n         state->select_end = state->cursor;\n         state->has_preferred_x = 0;\n         break;\n\n#ifdef STB_TEXTEDIT_K_LINEEND2\n      case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:\n#endif\n      case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {\n         int n = STB_TEXTEDIT_STRINGLEN(str);\n         stb_textedit_clamp(str, state);\n         stb_textedit_prep_selection_at_cursor(state);\n         if (state->single_line)\n             state->cursor = n;\n         else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)\n            ++state->cursor;\n         state->select_end = state->cursor;\n         state->has_preferred_x = 0;\n         break;\n      }\n   }\n}\n\n/////////////////////////////////////////////////////////////////////////////\n//\n//      Undo processing\n//\n// @OPTIMIZE: the undo/redo buffer should be circular\n\nstatic void stb_textedit_flush_redo(StbUndoState *state)\n{\n   state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;\n   state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;\n}\n\n// discard the oldest entry in the undo list\nstatic void stb_textedit_discard_undo(StbUndoState *state)\n{\n   if (state->undo_point > 0) {\n      // if the 0th undo state has characters, clean those up\n      if (state->undo_rec[0].char_storage >= 0) {\n         int n = state->undo_rec[0].insert_length, i;\n         // delete n characters from all other records\n         state->undo_char_point -= n;\n         STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));\n         for (i=0; i < state->undo_point; ++i)\n            if (state->undo_rec[i].char_storage >= 0)\n               state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it\n      }\n      --state->undo_point;\n      STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));\n   }\n}\n\n// discard the oldest entry in the redo list--it's bad if this\n// ever happens, but because undo & redo have to store the actual\n// characters in different cases, the redo character buffer can\n// fill up even though the undo buffer didn't\nstatic void stb_textedit_discard_redo(StbUndoState *state)\n{\n   int k = STB_TEXTEDIT_UNDOSTATECOUNT-1;\n\n   if (state->redo_point <= k) {\n      // if the k'th undo state has characters, clean those up\n      if (state->undo_rec[k].char_storage >= 0) {\n         int n = state->undo_rec[k].insert_length, i;\n         // move the remaining redo character data to the end of the buffer\n         state->redo_char_point += n;\n         STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));\n         // adjust the position of all the other records to account for above memmove\n         for (i=state->redo_point; i < k; ++i)\n            if (state->undo_rec[i].char_storage >= 0)\n               state->undo_rec[i].char_storage += n;\n      }\n      // now move all the redo records towards the end of the buffer; the first one is at 'redo_point'\n      STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, (size_t) ((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0])));\n      // now move redo_point to point to the new one\n      ++state->redo_point;\n   }\n}\n\nstatic StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars)\n{\n   // any time we create a new undo record, we discard redo\n   stb_textedit_flush_redo(state);\n\n   // if we have no free records, we have to make room, by sliding the\n   // existing records down\n   if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT)\n      stb_textedit_discard_undo(state);\n\n   // if the characters to store won't possibly fit in the buffer, we can't undo\n   if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) {\n      state->undo_point = 0;\n      state->undo_char_point = 0;\n      return NULL;\n   }\n\n   // if we don't have enough free characters in the buffer, we have to make room\n   while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT)\n      stb_textedit_discard_undo(state);\n\n   return &state->undo_rec[state->undo_point++];\n}\n\nstatic STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)\n{\n   StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);\n   if (r == NULL)\n      return NULL;\n\n   r->where = pos;\n   r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len;\n   r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len;\n\n   if (insert_len == 0) {\n      r->char_storage = -1;\n      return NULL;\n   } else {\n      r->char_storage = state->undo_char_point;\n      state->undo_char_point += insert_len;\n      return &state->undo_char[r->char_storage];\n   }\n}\n\nstatic void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n{\n   StbUndoState *s = &state->undostate;\n   StbUndoRecord u, *r;\n   if (s->undo_point == 0)\n      return;\n\n   // we need to do two things: apply the undo record, and create a redo record\n   u = s->undo_rec[s->undo_point-1];\n   r = &s->undo_rec[s->redo_point-1];\n   r->char_storage = -1;\n\n   r->insert_length = u.delete_length;\n   r->delete_length = u.insert_length;\n   r->where = u.where;\n\n   if (u.delete_length) {\n      // if the undo record says to delete characters, then the redo record will\n      // need to re-insert the characters that get deleted, so we need to store\n      // them.\n\n      // there are three cases:\n      //    there's enough room to store the characters\n      //    characters stored for *redoing* don't leave room for redo\n      //    characters stored for *undoing* don't leave room for redo\n      // if the last is true, we have to bail\n\n      if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) {\n         // the undo records take up too much character space; there's no space to store the redo characters\n         r->insert_length = 0;\n      } else {\n         int i;\n\n         // there's definitely room to store the characters eventually\n         while (s->undo_char_point + u.delete_length > s->redo_char_point) {\n            // should never happen:\n            if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)\n               return;\n            // there's currently not enough room, so discard a redo record\n            stb_textedit_discard_redo(s);\n         }\n         r = &s->undo_rec[s->redo_point-1];\n\n         r->char_storage = s->redo_char_point - u.delete_length;\n         s->redo_char_point = s->redo_char_point - u.delete_length;\n\n         // now save the characters\n         for (i=0; i < u.delete_length; ++i)\n            s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i);\n      }\n\n      // now we can carry out the deletion\n      STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length);\n   }\n\n   // check type of recorded action:\n   if (u.insert_length) {\n      // easy case: was a deletion, so we need to insert n characters\n      STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length);\n      s->undo_char_point -= u.insert_length;\n   }\n\n   state->cursor = u.where + u.insert_length;\n\n   s->undo_point--;\n   s->redo_point--;\n}\n\nstatic void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\n{\n   StbUndoState *s = &state->undostate;\n   StbUndoRecord *u, r;\n   if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)\n      return;\n\n   // we need to do two things: apply the redo record, and create an undo record\n   u = &s->undo_rec[s->undo_point];\n   r = s->undo_rec[s->redo_point];\n\n   // we KNOW there must be room for the undo record, because the redo record\n   // was derived from an undo record\n\n   u->delete_length = r.insert_length;\n   u->insert_length = r.delete_length;\n   u->where = r.where;\n   u->char_storage = -1;\n\n   if (r.delete_length) {\n      // the redo record requires us to delete characters, so the undo record\n      // needs to store the characters\n\n      if (s->undo_char_point + u->insert_length > s->redo_char_point) {\n         u->insert_length = 0;\n         u->delete_length = 0;\n      } else {\n         int i;\n         u->char_storage = s->undo_char_point;\n         s->undo_char_point = s->undo_char_point + u->insert_length;\n\n         // now save the characters\n         for (i=0; i < u->insert_length; ++i)\n            s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i);\n      }\n\n      STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length);\n   }\n\n   if (r.insert_length) {\n      // easy case: need to insert n characters\n      STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length);\n      s->redo_char_point += r.insert_length;\n   }\n\n   state->cursor = r.where + r.insert_length;\n\n   s->undo_point++;\n   s->redo_point++;\n}\n\nstatic void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length)\n{\n   stb_text_createundo(&state->undostate, where, 0, length);\n}\n\nstatic void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)\n{\n   int i;\n   STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);\n   if (p) {\n      for (i=0; i < length; ++i)\n         p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);\n   }\n}\n\nstatic void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)\n{\n   int i;\n   STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);\n   if (p) {\n      for (i=0; i < old_length; ++i)\n         p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);\n   }\n}\n\n// reset the state to default\nstatic void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line)\n{\n   state->undostate.undo_point = 0;\n   state->undostate.undo_char_point = 0;\n   state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;\n   state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;\n   state->select_end = state->select_start = 0;\n   state->cursor = 0;\n   state->has_preferred_x = 0;\n   state->preferred_x = 0;\n   state->cursor_at_end_of_line = 0;\n   state->initialized = 1;\n   state->single_line = (unsigned char) is_single_line;\n   state->insert_mode = 0;\n   state->row_count_per_page = 0;\n}\n\n// API initialize\nstatic void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)\n{\n   stb_textedit_clear_state(state, is_single_line);\n}\n\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\n#endif\n\nstatic int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)\n{\n   return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len);\n}\n\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n\n#endif//STB_TEXTEDIT_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_tilemap_editor.h",
    "content": "// stb_tilemap_editor.h - v0.42 - Sean Barrett - http://nothings.org/stb\n// placed in the public domain - not copyrighted - first released 2014-09\n//\n// Embeddable tilemap editor for C/C++\n//\n//\n// TABLE OF CONTENTS\n//    FAQ\n//    How to compile/use the library\n//    Additional configuration macros\n//    API documentation\n//    Info on editing multiple levels\n//    Revision history\n//    Todo\n//    Credits\n//    License\n//\n//\n// FAQ\n//\n//   Q: What counts as a tilemap for this library?\n//\n//   A: An array of rectangles, where each rectangle contains a small\n//      stack of images.\n//\n//   Q: What are the limitations?\n//\n//   A: Maps are limited to 4096x4096 in dimension.\n//      Each map square can only contain a stack of at most 32 images.\n//      A map can only use up to 32768 distinct image tiles.\n//\n//   Q: How do I compile this?\n//\n//   A: You need to #define several symbols before #including it, but only\n//      in one file. This will cause all the function definitions to be\n//      generated in that file. See the \"HOW TO COMPILE\" section.\n//\n//   Q: What advantages does this have over a standalone editor?\n//\n//   A: For one, you can integrate the editor into your game so you can\n//      flip between editing and testing without even switching windows.\n//      For another, you don't need an XML parser to get at the map data.\n//\n//   Q: Can I live-edit my game maps?\n//\n//   A: Not really, the editor keeps its own map representation.\n//\n//   Q: How do I save and load maps?\n//\n//   A: You have to do this yourself. The editor provides serialization\n//      functions (get & set) for reading and writing the map it holds.\n//      You can choose whatever format you want to store the map to on\n//      disk; you just need to provide functions to convert. (For example,\n//      I actually store the editor's map representation to disk basically\n//      as-is; then I have a single function that converts from the editor\n//      map representation to the game representation, which is used both\n//      to go from editor-to-game and from loaded-map-to-game.)\n//\n//   Q: I want to have tiles change appearance based on what's\n//      adjacent, or other tile-display/substitution trickiness.\n//\n//   A: You can do this when you convert from the editor's map\n//      representation to the game representation, but there's\n//      no way to show this live in the editor.\n//\n//   Q: The editor appears to be put map location (0,0) at the top left?\n//      I want to use a different coordinate system in my game (e.g. y\n//      increasing upwards, or origin at the center).\n//\n//   A: You can do this when you convert from the editor's map\n//      representation to the game representation. (Don't forget to\n//      translate link coordinates as well!)\n//\n//   Q: The editor appears to put pixel (0,0) at the top left? I want\n//      to use a different coordinate system in my game.\n//\n//   A: The editor defines an \"editor pixel coordinate system\" with\n//      (0,0) at the top left and requires you to display things in\n//      that coordinate system. You can freely remap those coordinates\n//      to anything you want on screen.\n//\n//   Q: How do I scale the user interface?\n//\n//   A: Since you do all the rendering, you can scale up all the rendering\n//      calls that the library makes to you. If you do, (a) you need\n//      to also scale up the mouse coordinates, and (b) you may want\n//      to scale the map display back down so that you're only scaling\n//      the UI and not everything. See the next question.\n//\n//   Q: How do I scale the map display?\n//\n//   A: Use stbte_set_spacing() to change the size that the map is displayed\n//      at. Note that the \"callbacks\" to draw tiles are used for both drawing\n//      the map and drawing the tile palette, so that callback may need to\n//      draw at two different scales. You should choose the scales to match\n//       You can tell them apart because the\n//      tile palette gets NULL for the property pointer.\n//\n//   Q: How does object editing work?\n//\n//   A: One way to think of this is that in the editor, you're placing\n//      spawners, not objects. Each spawner must be tile-aligned, because\n//      it's only a tile editor. Each tile (stack of layers) gets\n//      an associated set of properties, and it's up to you to\n//      determine what properties should appear for a given tile,\n//      based on e.g. the spawners that are in it.\n//\n//   Q: How are properties themselves handled?\n//\n//   A: All properties, regardless of UI behavior, are internally floats.\n//      Each tile has an array of floats associated with it, which is\n//      passed back to you when drawing the tiles so you can draw\n//      objects appropriately modified by the properties.\n//\n//   Q: What if I want to have two different objects/spawners in\n//      one tile, both of which have their own properties?\n//\n//   A: Make sure STBTE_MAX_PROPERTIES is large enough for the sum of\n//      properties in both objects, and then you have to explicitly\n//      map the property slot #s to the appropriate objects. They'll\n//      still all appear in a single property panel; there's no way\n//      to get multiple panels.\n//\n//   Q: Can I do one-to-many linking?\n//\n//   A: The library only supports one link per tile. However, you\n//      can have multiple tiles all link to a single tile. So, you\n//      can fake one-to-many linking by linking in the reverse\n//      direction.\n//\n//   Q: What if I have two objects in the same tile, and they each\n//      need an independent link? Or I have two kinds of link associated\n//      with a single object?\n//\n//   A: There is no way to do this. (Unless you can reverse one link.)\n//\n//   Q: How does cut & paste interact with object properties & links?\n//\n//   A: Currently the library has no idea which properties or links\n//      are associated with which layers of a tile. So currently, the\n//      library will only copy properties & links if the layer panel\n//      is set to allow all layers to be copied, OR if you set the\n//      \"props\" in the layer panel to \"always\". Similarly, you can\n//      set \"props\" to \"none\" so it will never copy.\n//\n//   Q: What happens if the library gets a memory allocation failure\n//      while I'm editing? Will I lose my work?\n//\n//   A: The library allocates all editor memory when you create\n//      the tilemap. It allocates a maximally-sized map and a\n//      fixed-size undo buffer (and the fixed-size copy buffer\n//      is static), and never allocates memory while it's running.\n//      So it can't fail due to running out of memory.\n//\n//   Q: What happens if the library crashes while I'm editing? Will\n//      I lose my work?\n//\n//   A: Yes. Save often.\n//\n//\n// HOW TO COMPILE\n//\n//   This header file contains both the header file and the\n//   implementation file in one. To create the implementation,\n//   in one source file define a few symbols first and then\n//   include this header:\n//\n//      #define STB_TILEMAP_EDITOR_IMPLEMENTATION\n//      // this triggers the implementation\n//\n//      void STBTE_DRAW_RECT(int x0, int y0, int x1, int y1, unsigned int color);\n//      // this must draw a filled rectangle (exclusive on right/bottom)\n//      // color = (r<<16)|(g<<8)|(b)\n//\n//      void STBTE_DRAW_TILE(int x0, int y0,\n//                    unsigned short id, int highlight, float *data);\n//      // this draws the tile image identified by 'id' in one of several\n//      // highlight modes (see STBTE_drawmode_* in the header section);\n//      // if 'data' is NULL, it's drawing the tile in the palette; if 'data'\n//      // is not NULL, it's drawing a tile on the map, and that is the data\n//      // associated with that map tile\n//\n//      #include \"stb_tilemap_editor.h\"\n//\n//   Optionally you can define the following functions before the include;\n//   note these must be macros (but they can just call a function) so\n//   this library can #ifdef to detect if you've defined them:\n//\n//      #define STBTE_PROP_TYPE(int n, short *tiledata, float *params) ...\n//      // Returns the type of the n'th property of a given tile, which\n//      // controls how it is edited. Legal types are:\n//      //     0                    /* no editable property in this slot */\n//      //     STBTE_PROP_int       /* uses a slider to adjust value     */\n//      //     STBTE_PROP_float     /* uses a weird multi-axis control   */\n//      //     STBTE_PROP_bool      /* uses a checkbox to change value   */\n//      // And you can bitwise-OR in the following flags:\n//      //     STBTE_PROP_disabled\n//      // Note that all of these are stored as floats in the param array.\n//      // The integer slider is limited in precision based on the space\n//      // available on screen, so for wide-ranged integers you may want\n//      // to use floats instead.\n//      //\n//      // Since the tiledata is passed to you, you can choose which property\n//      // is bound to that slot based on that data.\n//      //\n//      // Changing the type of a parameter does not cause the underlying\n//      // value to be clamped to the type min/max except when the tile is\n//      // explicitly selected.\n//\n//      #define STBTE_PROP_NAME(int n, short *tiledata, float *params) ...\n//      // these return a string with the name for slot #n in the float\n//      // property list for the tile.\n//\n//      #define STBTE_PROP_MIN(int n, short *tiledata) ...your code here...\n//      #define STBTE_PROP_MAX(int n, short *tiledata) ...your code here...\n//      // These return the allowable range for the property values for\n//      // the specified slot. It is never called for boolean types.\n//\n//      #define STBTE_PROP_FLOAT_SCALE(int n, short *tiledata, float *params)\n//      // This rescales the float control for a given property; by default\n//      // left mouse drags add integers, right mouse drags adds fractions,\n//      // but you can rescale this per-property.\n//\n//      #define STBTE_FLOAT_CONTROL_GRANULARITY       ... value ...\n//      // This returns the number of pixels of mouse motion necessary\n//      // to advance the object float control. Default is 4\n//\n//      #define STBTE_ALLOW_LINK(short *src, float *src_data,  \\\n//                               short *dest, float *dest_data) ...your code...\n//      // this returns true or false depending on whether you allow a link\n//      // to be drawn from a tile 'src' to a tile 'dest'. if you don't\n//      // define this, linking will not be supported\n//\n//      #define STBTE_LINK_COLOR(short *src, float *src_data,  \\\n//                               short *dest, float *dest_data) ...your code...\n//      // return a color encoded as a 24-bit unsigned integer in the\n//      // form 0xRRGGBB. If you don't define this, default colors will\n//      // be used.\n//\n//\n//      [[ support for those below is not implemented yet ]]\n//\n//      #define STBTE_HITTEST_TILE(x0,y0,id,mx,my)   ...your code here...\n//      // this returns true or false depending on whether the mouse\n//      // pointer at mx,my is over (touching) a tile of type 'id'\n//      // displayed at x0,y0. Normally stb_tilemap_editor just does\n//      // this hittest based on the tile geometry, but if you have\n//      // tiles whose images extend out of the tile, you'll need this.\n//\n// ADDITIONAL CONFIGURATION\n//\n//   The following symbols set static limits which determine how much\n//   memory will be allocated for the editor. You can override them\n//   by making similar definitions, but memory usage will increase.\n//\n//      #define STBTE_MAX_TILEMAP_X      200   // max 4096\n//      #define STBTE_MAX_TILEMAP_Y      200   // max 4096\n//      #define STBTE_MAX_LAYERS         8     // max 32\n//      #define STBTE_MAX_CATEGORIES     100\n//      #define STBTE_UNDO_BUFFER_BYTES  (1 << 24) // 16 MB\n//      #define STBTE_MAX_COPY           90000  // e.g. 300x300\n//      #define STBTE_MAX_PROPERTIES     10     // max properties per tile\n//\n// API\n//\n//   Further documentation appears in the header-file section below.\n//\n// EDITING MULTIPLE LEVELS\n//\n//   You can only have one active editor instance. To switch between multiple\n//   levels, you can either store the levels in your own format and copy them\n//   in and out of the editor format, or you can create multiple stbte_tilemap\n//   objects and switch between them. The latter has the advantage that each\n//   stbte_tilemap keeps its own undo state. (The clipboard is global, so\n//   either approach allows cut&pasting between levels.)\n//\n// REVISION HISTORY\n//   0.42  fix compilation errors\n//   0.41  fix warnings\n//   0.40  fix warning\n//   0.39  fix warning\n//   0.38  fix warning\n//   0.37  fix warning\n//   0.36  minor compiler support\n//   0.35  layername button changes\n//          - layername buttons grow with the layer panel\n//          - fix stbte_create_map being declared as stbte_create\n//          - fix declaration of stbte_create_map\n//   0.30  properties release\n//          - properties panel for editing user-defined \"object\" properties\n//          - can link each tile to one other tile\n//          - keyboard interface\n//          - fix eraser tool bug (worked in complex cases, failed in simple)\n//          - undo/redo tools have visible disabled state\n//          - tiles on higher layers draw on top of adjacent lower-layer tiles\n//   0.20  erasable release\n//          - eraser tool\n//          - fix bug when pasting into protected layer\n//          - better color scheme\n//          - internal-use color picker\n//   0.10  initial release\n//\n// TODO\n//\n//   Separate scroll state for each category\n//   Implement paint bucket\n//   Support STBTE_HITTEST_TILE above\n//  ?Cancel drags by clicking other button? - may be fixed\n//   Finish support for toolbar at side\n//\n// CREDITS\n//\n//\n//   Main editor & features\n//      Sean Barrett\n//   Additional features:\n//      Josh Huelsman\n//   Bugfixes:\n//      Ryan Whitworth\n//      Eugene Opalev\n//      Rob Loach\n//      github:wernsey\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n\n\n///////////////////////////////////////////////////////////////////////\n//\n//   HEADER SECTION\n\n#ifndef STB_TILEMAP_INCLUDE_STB_TILEMAP_EDITOR_H\n#define STB_TILEMAP_INCLUDE_STB_TILEMAP_EDITOR_H\n\n#ifdef _WIN32\n  #ifndef _CRT_SECURE_NO_WARNINGS\n  #define _CRT_SECURE_NO_WARNINGS\n  #endif\n  #include <stdlib.h>\n  #include <stdio.h>\n#endif\n\ntypedef struct stbte_tilemap stbte_tilemap;\n\n// these are the drawmodes used in STBTE_DRAW_TILE\nenum\n{\n   STBTE_drawmode_deemphasize = -1,\n   STBTE_drawmode_normal      =  0,\n   STBTE_drawmode_emphasize   =  1,\n};\n\n// these are the property types\n#define STBTE_PROP_none     0\n#define STBTE_PROP_int      1\n#define STBTE_PROP_float    2\n#define STBTE_PROP_bool     3\n#define STBTE_PROP_disabled 4\n\n////////\n//\n// creation\n//\n\nextern stbte_tilemap *stbte_create_map(int map_x, int map_y, int map_layers, int spacing_x, int spacing_y, int max_tiles);\n// create an editable tilemap\n//   map_x      : dimensions of map horizontally (user can change this in editor), <= STBTE_MAX_TILEMAP_X\n//   map_y      : dimensions of map vertically (user can change this in editor)    <= STBTE_MAX_TILEMAP_Y\n//   map_layers : number of layers to use (fixed), <= STBTE_MAX_LAYERS\n//   spacing_x  : initial horizontal distance between left edges of map tiles in stb_tilemap_editor pixels\n//   spacing_y  : initial vertical distance between top edges of map tiles in stb_tilemap_editor pixels\n//   max_tiles  : maximum number of tiles that can defined\n//\n// If insufficient memory, returns NULL\n\nextern void stbte_define_tile(stbte_tilemap *tm, unsigned short id, unsigned int layermask, const char * category);\n// call this repeatedly for each tile to install the tile definitions into the editable tilemap\n//   tm        : tilemap created by stbte_create_map\n//   id        : unique identifier for each tile, 0 <= id < 32768\n//   layermask : bitmask of which layers tile is allowed on: 1 = layer 0, 255 = layers 0..7\n//               (note that onscreen, the editor numbers the layers from 1 not 0)\n//               layer 0 is the furthest back, layer 1 is just in front of layer 0, etc\n//   category  : which category this tile is grouped in\n\nextern void stbte_set_display(int x0, int y0, int x1, int y1);\n// call this once to set the size; if you resize, call it again\n\n\n/////////\n//\n// every frame\n//\n\nextern void stbte_draw(stbte_tilemap *tm);\n\nextern void stbte_tick(stbte_tilemap *tm, float time_in_seconds_since_last_frame);\n\n////////////\n//\n//  user input\n//\n\n// if you're using SDL, call the next function for SDL_MOUSEMOTION, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL;\n// the transformation lets you scale from SDL mouse coords to stb_tilemap_editor coords\nextern void stbte_mouse_sdl(stbte_tilemap *tm, const void *sdl_event, float xscale, float yscale, int xoffset, int yoffset);\n\n// otherwise, hook these up explicitly:\nextern void stbte_mouse_move(stbte_tilemap *tm, int x, int y, int shifted, int scrollkey);\nextern void stbte_mouse_button(stbte_tilemap *tm, int x, int y, int right, int down, int shifted, int scrollkey);\nextern void stbte_mouse_wheel(stbte_tilemap *tm, int x, int y, int vscroll);\n\n// note: at the moment, mouse wheel events (SDL_MOUSEWHEEL) are ignored.\n\n// for keyboard, define your own mapping from keys to the following actions.\n// this is totally optional, as all features are accessible with the mouse\nenum stbte_action\n{\n   STBTE_tool_select,\n   STBTE_tool_brush,\n   STBTE_tool_erase,\n   STBTE_tool_rectangle,\n   STBTE_tool_eyedropper,\n   STBTE_tool_link,\n   STBTE_act_toggle_grid,\n   STBTE_act_toggle_links,\n   STBTE_act_undo,\n   STBTE_act_redo,\n   STBTE_act_cut,\n   STBTE_act_copy,\n   STBTE_act_paste,\n   STBTE_scroll_left,\n   STBTE_scroll_right,\n   STBTE_scroll_up,\n   STBTE_scroll_down,\n};\nextern void stbte_action(stbte_tilemap *tm, enum stbte_action act);\n\n////////////////\n//\n//  save/load\n//\n//  There is no editor file format. You have to save and load the data yourself\n//  through the following functions. You can also use these functions to get the\n//  data to generate game-formatted levels directly. (But make sure you save\n//  first! You may also want to autosave to a temp file periodically, etc etc.)\n\n#define STBTE_EMPTY    -1\n\nextern void stbte_get_dimensions(stbte_tilemap *tm, int *max_x, int *max_y);\n// get the dimensions of the level, since the user can change them\n\nextern short* stbte_get_tile(stbte_tilemap *tm, int x, int y);\n// returns an array of shorts that is 'map_layers' in length. each short is\n// either one of the tile_id values from define_tile, or STBTE_EMPTY.\n\nextern float *stbte_get_properties(stbte_tilemap *tm, int x, int y);\n// get the property array associated with the tile at x,y. this is an\n// array of floats that is STBTE_MAX_PROPERTIES in length; you have to\n// interpret the slots according to the semantics you've chosen\n\nextern void stbte_get_link(stbte_tilemap *tm, int x, int y, int *destx, int *desty);\n// gets the link associated with the tile at x,y.\n\nextern void stbte_set_dimensions(stbte_tilemap *tm, int max_x, int max_y);\n// set the dimensions of the level, overrides previous stbte_create_map()\n// values or anything the user has changed\n\nextern void stbte_clear_map(stbte_tilemap *tm);\n// clears the map, including the region outside the defined region, so if the\n// user expands the map, they won't see garbage there\n\nextern void stbte_set_tile(stbte_tilemap *tm, int x, int y, int layer, signed short tile);\n// tile is your tile_id from define_tile, or STBTE_EMPTY\n\nextern void stbte_set_property(stbte_tilemap *tm, int x, int y, int n, float val);\n// set the value of the n'th slot of the tile at x,y\n\nextern void stbte_set_link(stbte_tilemap *tm, int x, int y, int destx, int desty);\n// set a link going from x,y to destx,desty. to force no link,\n// use destx=desty=-1\n\n////////\n//\n// optional\n//\n\nextern void stbte_set_background_tile(stbte_tilemap *tm, short id);\n// selects the tile to fill the bottom layer with and used to clear bottom tiles to;\n// should be same ID as\n\nextern void stbte_set_sidewidths(int left, int right);\n// call this once to set the left & right side widths. don't call\n// it again since the user can change it\n\nextern void stbte_set_spacing(stbte_tilemap *tm, int spacing_x, int spacing_y, int palette_spacing_x, int palette_spacing_y);\n// call this to set the spacing of map tiles and the spacing of palette tiles.\n// if you rescale your display, call it again (e.g. you can implement map zooming yourself)\n\nextern void stbte_set_layername(stbte_tilemap *tm, int layer, const char *layername);\n// sets a string name for your layer that shows in the layer selector. note that this\n// makes the layer selector wider. 'layer' is from 0..(map_layers-1)\n\n#endif\n\n#ifdef STB_TILEMAP_EDITOR_IMPLEMENTATION\n\n#ifndef STBTE_ASSERT\n#define STBTE_ASSERT assert\n#include <assert.h>\n#endif\n\n#ifdef _MSC_VER\n#define STBTE__NOTUSED(v)  (void)(v)\n#else\n#define STBTE__NOTUSED(v)  (void)sizeof(v)\n#endif\n\n#ifndef STBTE_MAX_TILEMAP_X\n#define STBTE_MAX_TILEMAP_X      200\n#endif\n\n#ifndef STBTE_MAX_TILEMAP_Y\n#define STBTE_MAX_TILEMAP_Y      200\n#endif\n\n#ifndef STBTE_MAX_LAYERS\n#define STBTE_MAX_LAYERS         8\n#endif\n\n#ifndef STBTE_MAX_CATEGORIES\n#define STBTE_MAX_CATEGORIES     100\n#endif\n\n#ifndef STBTE_MAX_COPY\n#define STBTE_MAX_COPY           65536\n#endif\n\n#ifndef STBTE_UNDO_BUFFER_BYTES\n#define STBTE_UNDO_BUFFER_BYTES  (1 << 24) // 16 MB\n#endif\n\n#ifndef STBTE_PROP_TYPE\n#define STBTE__NO_PROPS\n#define STBTE_PROP_TYPE(n,td,tp)   0\n#endif\n\n#ifndef STBTE_PROP_NAME\n#define STBTE_PROP_NAME(n,td,tp)  \"\"\n#endif\n\n#ifndef STBTE_MAX_PROPERTIES\n#define STBTE_MAX_PROPERTIES           10\n#endif\n\n#ifndef STBTE_PROP_MIN\n#define STBTE_PROP_MIN(n,td,tp)  0\n#endif\n\n#ifndef STBTE_PROP_MAX\n#define STBTE_PROP_MAX(n,td,tp)  100.0\n#endif\n\n#ifndef STBTE_PROP_FLOAT_SCALE\n#define STBTE_PROP_FLOAT_SCALE(n,td,tp)  1   // default scale size\n#endif\n\n#ifndef STBTE_FLOAT_CONTROL_GRANULARITY\n#define STBTE_FLOAT_CONTROL_GRANULARITY 4\n#endif\n\n\n#define STBTE__UNDO_BUFFER_COUNT  (STBTE_UNDO_BUFFER_BYTES>>1)\n\n#if STBTE_MAX_TILEMAP_X > 4096 || STBTE_MAX_TILEMAP_Y > 4096\n#error \"Maximum editable map size is 4096 x 4096\"\n#endif\n#if STBTE_MAX_LAYERS > 32\n#error \"Maximum layers allowed is 32\"\n#endif\n#if STBTE_UNDO_BUFFER_COUNT & (STBTE_UNDO_BUFFER_COUNT-1)\n#error \"Undo buffer size must be a power of 2\"\n#endif\n\n#if STBTE_MAX_PROPERTIES == 0\n#define STBTE__NO_PROPS\n#endif\n\n#ifdef STBTE__NO_PROPS\n#undef STBTE_MAX_PROPERTIES\n#define STBTE_MAX_PROPERTIES 1  // so we can declare arrays\n#endif\n\ntypedef struct\n{\n   short x,y;\n} stbte__link;\n\nenum\n{\n   STBTE__base,\n   STBTE__outline,\n   STBTE__text,\n\n   STBTE__num_color_aspects,\n};\n\nenum\n{\n   STBTE__idle,\n   STBTE__over,\n   STBTE__down,\n   STBTE__over_down,\n   STBTE__selected,\n   STBTE__selected_over,\n   STBTE__disabled,\n   STBTE__num_color_states,\n};\n\nenum\n{\n   STBTE__cexpander,\n   STBTE__ctoolbar,\n   STBTE__ctoolbar_button,\n   STBTE__cpanel,\n   STBTE__cpanel_sider,\n   STBTE__cpanel_sizer,\n   STBTE__cscrollbar,\n   STBTE__cmapsize,\n   STBTE__clayer_button,\n   STBTE__clayer_hide,\n   STBTE__clayer_lock,\n   STBTE__clayer_solo,\n   STBTE__ccategory_button,\n\n   STBTE__num_color_modes,\n};\n\n#ifdef STBTE__COLORPICKER\nstatic char *stbte__color_names[] =\n{\n   \"expander\", \"toolbar\", \"tool button\", \"panel\",\n   \"panel c1\", \"panel c2\", \"scollbar\", \"map button\",\n   \"layer\", \"hide\", \"lock\", \"solo\",\n   \"category\",\n};\n#endif // STBTE__COLORPICKER\n\n      // idle,    over,     down,    over&down, selected, sel&over, disabled\nstatic int stbte__color_table[STBTE__num_color_modes][STBTE__num_color_aspects][STBTE__num_color_states] =\n{\n   {\n      { 0x000000, 0x84987c, 0xdcdca8, 0xdcdca8, 0x40c040, 0x60d060, 0x505050, },\n      { 0xa4b090, 0xe0ec80, 0xffffc0, 0xffffc0, 0x80ff80, 0x80ff80, 0x606060, },\n      { 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x909090, },\n   }, {\n      { 0x808890, 0x606060, 0x606060, 0x606060, 0x606060, 0x606060, 0x606060, },\n      { 0x605860, 0x606060, 0x606060, 0x606060, 0x606060, 0x606060, 0x606060, },\n      { 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, },\n   }, {\n      { 0x3c5068, 0x7088a8, 0x647488, 0x94b4dc, 0x8890c4, 0x9caccc, 0x404040, },\n      { 0x889cb8, 0x889cb8, 0x889cb8, 0x889cb8, 0x84c4e8, 0xacc8ff, 0x0c0c08, },\n      { 0xbcc4cc, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x707074, },\n   }, {\n      { 0x403848, 0x403010, 0x403010, 0x403010, 0x403010, 0x403010, 0x303024, },\n      { 0x68546c, 0xc08040, 0xc08040, 0xc08040, 0xc08040, 0xc08040, 0x605030, },\n      { 0xf4e4ff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x909090, },\n   }, {\n      { 0xb4b04c, 0xacac60, 0xc0ffc0, 0xc0ffc0, 0x40c040, 0x60d060, 0x505050, },\n      { 0xa0a04c, 0xd0d04c, 0xffff80, 0xffff80, 0x80ff80, 0x80ff80, 0x606060, },\n      { 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x909090, },\n   }, {\n      { 0x40c440, 0x60d060, 0xc0ffc0, 0xc0ffc0, 0x40c040, 0x60d060, 0x505050, },\n      { 0x40c040, 0x80ff80, 0x80ff80, 0x80ff80, 0x80ff80, 0x80ff80, 0x606060, },\n      { 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x909090, },\n   }, {\n      { 0x9090ac, 0xa0a0b8, 0xbcb8cc, 0xbcb8cc, 0x909040, 0x909040, 0x909040, },\n      { 0xa0a0b8, 0xb0b4d0, 0xa0a0b8, 0xa0a0b8, 0xa0a050, 0xa0a050, 0xa0a050, },\n      { 0x808088, 0x808030, 0x808030, 0x808030, 0x808030, 0x808030, 0x808030, },\n   }, {\n      { 0x704c70, 0x885c8c, 0x9c68a4, 0xb870bc, 0xb490bc, 0xb490bc, 0x302828, },\n      { 0x646064, 0xcca8d4, 0xc060c0, 0xa07898, 0xe0b8e0, 0xe0b8e0, 0x403838, },\n      { 0xdccce4, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x909090, },\n   }, {\n      { 0x704c70, 0x885c8c, 0x9c68a4, 0xb870bc, 0xb490bc, 0xb490bc, 0x302828, },\n      { 0xb09cb4, 0xcca8d4, 0xc060c0, 0xa07898, 0xe0b8e0, 0xe0b8e0, 0x403838, },\n      { 0xdccce4, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0xffffff, 0x909090, },\n   }, {\n      { 0x646494, 0x888cb8, 0xb0b0b0, 0xb0b0cc, 0x9c9cf4, 0x8888b0, 0x50506c, },\n      { 0x9090a4, 0xb0b4d4, 0xb0b0dc, 0xb0b0cc, 0xd0d0fc, 0xd0d4f0, 0x606060, },\n      { 0xb4b4d4, 0xe4e4ff, 0xffffff, 0xffffff, 0xe0e4ff, 0xececff, 0x909090, },\n   }, {\n      { 0x646444, 0x888c64, 0xb0b0b0, 0xb0b088, 0xaca858, 0x88886c, 0x505050, },\n      { 0x88886c, 0xb0b490, 0xb0b0b0, 0xb0b088, 0xd8d898, 0xd0d4b0, 0x606060, },\n      { 0xb4b49c, 0xffffd8, 0xffffff, 0xffffd4, 0xffffdc, 0xffffcc, 0x909090, },\n   }, {\n      { 0x906464, 0xb48c8c, 0xd4b0b0, 0xdcb0b0, 0xff9c9c, 0xc88888, 0x505050, },\n      { 0xb47c80, 0xd4b4b8, 0xc4a8a8, 0xdcb0b0, 0xffc0c0, 0xfce8ec, 0x606060, },\n      { 0xe0b4b4, 0xffdcd8, 0xffd8d4, 0xffe0e4, 0xffece8, 0xffffff, 0x909090, },\n   }, {\n      { 0x403848, 0x403848, 0x403848, 0x886894, 0x7c80c8, 0x7c80c8, 0x302828, },\n      { 0x403848, 0x403848, 0x403848, 0x403848, 0x7c80c8, 0x7c80c8, 0x403838, },\n      { 0xc8c4c8, 0xffffff, 0xffffff, 0xffffff, 0xe8e8ec, 0xffffff, 0x909090, },\n   },\n};\n\n#define STBTE_COLOR_TILEMAP_BACKGROUND      0x000000\n#define STBTE_COLOR_TILEMAP_BORDER          0x203060\n#define STBTE_COLOR_TILEMAP_HIGHLIGHT       0xffffff\n#define STBTE_COLOR_GRID                    0x404040\n#define STBTE_COLOR_SELECTION_OUTLINE1      0xdfdfdf\n#define STBTE_COLOR_SELECTION_OUTLINE2      0x303030\n#define STBTE_COLOR_TILEPALETTE_OUTLINE     0xffffff\n#define STBTE_COLOR_TILEPALETTE_BACKGROUND  0x000000\n\n#ifndef STBTE_LINK_COLOR\n#define STBTE_LINK_COLOR(src,sp,dest,dp)    0x5030ff\n#endif\n\n#ifndef STBTE_LINK_COLOR_DRAWING\n#define STBTE_LINK_COLOR_DRAWING            0xff40ff\n#endif\n\n#ifndef STBTE_LINK_COLOR_DISALLOWED\n#define STBTE_LINK_COLOR_DISALLOWED         0x602060\n#endif\n\n\n// disabled, selected, down, over\nstatic unsigned char stbte__state_to_index[2][2][2][2] =\n{\n   {\n      { { STBTE__idle    , STBTE__over          }, { STBTE__down    , STBTE__over_down }, },\n      { { STBTE__selected, STBTE__selected_over }, { STBTE__down    , STBTE__over_down }, },\n   },{\n      { { STBTE__disabled, STBTE__disabled      }, { STBTE__disabled, STBTE__disabled  }, },\n      { { STBTE__selected, STBTE__selected_over }, { STBTE__disabled, STBTE__disabled  }, },\n   }\n};\n#define STBTE__INDEX_FOR_STATE(disable,select,down,over) stbte__state_to_index[disable][select][down][over]\n#define STBTE__INDEX_FOR_ID(id,disable,select) STBTE__INDEX_FOR_STATE(disable,select,STBTE__IS_ACTIVE(id),STBTE__IS_HOT(id))\n\n#define STBTE__FONT_HEIGHT    9\nstatic short stbte__font_offset[95+16];\nstatic short stbte__fontdata[769] =\n{\n   4,9,6,9,9,9,9,8,9,8,4,9,7,7,7,7,4,2,6,8,6,6,7,3,4,4,8,6,3,6,2,6,6,6,6,6,6,\n   6,6,6,6,6,2,3,5,4,5,6,6,6,6,6,6,6,6,6,6,6,6,7,6,7,7,7,6,7,6,6,6,6,7,7,6,6,\n   6,4,6,4,7,7,3,6,6,5,6,6,5,6,6,4,5,6,4,7,6,6,6,6,6,6,6,6,6,7,6,6,6,5,2,5,8,\n   0,0,0,0,2,253,130,456,156,8,72,184,64,2,125,66,64,160,64,146,511,146,146,\n   511,146,146,511,146,511,257,341,297,341,297,341,257,511,16,56,124,16,16,16,\n   124,56,16,96,144,270,261,262,136,80,48,224,192,160,80,40,22,14,15,3,448,496,\n   496,240,232,20,10,5,2,112,232,452,450,225,113,58,28,63,30,60,200,455,257,\n   257,0,0,0,257,257,455,120,204,132,132,159,14,4,4,14,159,132,132,204,120,8,\n   24,56,120,56,24,8,32,48,56,60,56,48,32,0,0,0,0,111,111,7,7,0,0,7,7,34,127,\n   127,34,34,127,127,34,36,46,107,107,58,18,99,51,24,12,102,99,48,122,79,93,\n   55,114,80,4,7,3,62,127,99,65,65,99,127,62,8,42,62,28,28,62,42,8,8,8,62,62,\n   8,8,128,224,96,8,8,8,8,8,8,96,96,96,48,24,12,6,3,62,127,89,77,127,62,64,66,\n   127,127,64,64,98,115,89,77,71,66,33,97,73,93,119,35,24,28,22,127,127,16,39,\n   103,69,69,125,57,62,127,73,73,121,48,1,1,113,121,15,7,54,127,73,73,127,54,\n   6,79,73,105,63,30,54,54,128,246,118,8,28,54,99,65,20,20,20,20,65,99,54,28,\n   8,2,3,105,109,7,2,30,63,33,45,47,46,124,126,19,19,126,124,127,127,73,73,127,\n   54,62,127,65,65,99,34,127,127,65,99,62,28,127,127,73,73,73,65,127,127,9,9,\n   9,1,62,127,65,73,121,121,127,127,8,8,127,127,65,65,127,127,65,65,32,96,64,\n   64,127,63,127,127,8,28,54,99,65,127,127,64,64,64,64,127,127,6,12,6,127,127,\n   127,127,6,12,24,127,127,62,127,65,65,65,127,62,127,127,9,9,15,6,62,127,65,\n   81,49,127,94,127,127,9,25,127,102,70,79,73,73,121,49,1,1,127,127,1,1,63,127,\n   64,64,127,63,15,31,48,96,48,31,15,127,127,48,24,48,127,127,99,119,28,28,119,\n   99,7,15,120,120,15,7,97,113,89,77,71,67,127,127,65,65,3,6,12,24,48,96,65,\n   65,127,127,8,12,6,3,6,12,8,64,64,64,64,64,64,64,3,7,4,32,116,84,84,124,120,\n   127,127,68,68,124,56,56,124,68,68,68,56,124,68,68,127,127,56,124,84,84,92,\n   24,8,124,126,10,10,56,380,324,324,508,252,127,127,4,4,124,120,72,122,122,\n   64,256,256,256,506,250,126,126,16,56,104,64,66,126,126,64,124,124,24,56,28,\n   124,120,124,124,4,4,124,120,56,124,68,68,124,56,508,508,68,68,124,56,56,124,\n   68,68,508,508,124,124,4,4,12,8,72,92,84,84,116,36,4,4,62,126,68,68,60,124,\n   64,64,124,124,28,60,96,96,60,28,28,124,112,56,112,124,28,68,108,56,56,108,\n   68,284,316,352,320,508,252,68,100,116,92,76,68,8,62,119,65,65,127,127,65,\n   65,119,62,8,16,24,12,12,24,24,12,4,\n};\n\ntypedef struct\n{\n   short id;\n   unsigned short category_id;\n   char *category;\n   unsigned int layermask;\n} stbte__tileinfo;\n\n#define MAX_LAYERMASK    (1 << (8*sizeof(unsigned int)))\n\ntypedef short stbte__tiledata;\n\n#define STBTE__NO_TILE   -1\n\nenum\n{\n   STBTE__panel_toolbar,\n   STBTE__panel_colorpick,\n   STBTE__panel_info,\n   STBTE__panel_layers,\n   STBTE__panel_props,\n   STBTE__panel_categories,\n   STBTE__panel_tiles,\n\n   STBTE__num_panel,\n};\n\nenum\n{\n   STBTE__side_left,\n   STBTE__side_right,\n   STBTE__side_top,\n   STBTE__side_bottom,\n};\n\nenum\n{\n   STBTE__tool_select,\n   STBTE__tool_brush,\n   STBTE__tool_erase,\n   STBTE__tool_rect,\n   STBTE__tool_eyedrop,\n   STBTE__tool_fill,\n   STBTE__tool_link,\n\n   STBTE__tool_showgrid,\n   STBTE__tool_showlinks,\n\n   STBTE__tool_undo,\n   STBTE__tool_redo,\n   // copy/cut/paste aren't included here because they're displayed differently\n\n   STBTE__num_tool,\n};\n\n// icons are stored in the 0-31 range of ASCII in the font\nstatic int toolchar[] = { 26,24,25,20,23,22,18, 19,17, 29,28, };\n\nenum\n{\n   STBTE__propmode_default,\n   STBTE__propmode_always,\n   STBTE__propmode_never,\n};\n\nenum\n{\n   STBTE__paint,\n\n   // from here down does hittesting\n   STBTE__tick,\n   STBTE__mousemove,\n   STBTE__mousewheel,\n   STBTE__leftdown,\n   STBTE__leftup,\n   STBTE__rightdown,\n   STBTE__rightup,\n};\n\ntypedef struct\n{\n   int expanded, mode;\n   int delta_height;     // number of rows they've requested for this\n   int side;\n   int width,height;\n   int x0,y0;\n} stbte__panel;\n\ntypedef struct\n{\n   int x0,y0,x1,y1,color;\n} stbte__colorrect;\n\n#define STBTE__MAX_DELAYRECT 256\n\ntypedef struct\n{\n   int tool, active_event;\n   int active_id, hot_id, next_hot_id;\n   int event;\n   int mx,my, dx,dy;\n   int ms_time;\n   int shift, scrollkey;\n   int initted;\n   int side_extended[2];\n   stbte__colorrect delayrect[STBTE__MAX_DELAYRECT];\n   int delaycount;\n   int show_grid, show_links;\n   int brush_state; // used to decide which kind of erasing\n   int eyedrop_x, eyedrop_y, eyedrop_last_layer;\n   int pasting, paste_x, paste_y;\n   int scrolling, start_x, start_y;\n   int last_mouse_x, last_mouse_y;\n   int accum_x, accum_y;\n   int linking;\n   int dragging;\n   int drag_x, drag_y, drag_w, drag_h;\n   int drag_offx, drag_offy, drag_dest_x, drag_dest_y;\n   int undoing;\n   int has_selection, select_x0, select_y0, select_x1, select_y1;\n   int sx,sy;\n   int x0,y0,x1,y1, left_width, right_width; // configurable widths\n   float alert_timer;\n   const char *alert_msg;\n   float dt;\n   stbte__panel panel[STBTE__num_panel];\n   short copybuffer[STBTE_MAX_COPY][STBTE_MAX_LAYERS];\n   float copyprops[STBTE_MAX_COPY][STBTE_MAX_PROPERTIES];\n#ifdef STBTE_ALLOW_LINK\n   stbte__link copylinks[STBTE_MAX_COPY];\n#endif\n   int copy_src_x, copy_src_y;\n   stbte_tilemap *copy_src;\n   int copy_width,copy_height,has_copy,copy_has_props;\n} stbte__ui_t;\n\n// there's only one UI system at a time, so we can globalize this\nstatic stbte__ui_t stbte__ui = { STBTE__tool_brush, 0 };\n\n#define STBTE__INACTIVE()     (stbte__ui.active_id == 0)\n#define STBTE__IS_ACTIVE(id)  (stbte__ui.active_id == (id))\n#define STBTE__IS_HOT(id)     (stbte__ui.hot_id    == (id))\n\n#define STBTE__BUTTON_HEIGHT            (STBTE__FONT_HEIGHT + 2 * STBTE__BUTTON_INTERNAL_SPACING)\n#define STBTE__BUTTON_INTERNAL_SPACING  (2 + (STBTE__FONT_HEIGHT>>4))\n\ntypedef struct\n{\n   const char *name;\n   int locked;\n   int hidden;\n} stbte__layer;\n\nenum\n{\n   STBTE__unlocked,\n   STBTE__protected,\n   STBTE__locked,\n};\n\nstruct stbte_tilemap\n{\n    stbte__tiledata data[STBTE_MAX_TILEMAP_Y][STBTE_MAX_TILEMAP_X][STBTE_MAX_LAYERS];\n    float props[STBTE_MAX_TILEMAP_Y][STBTE_MAX_TILEMAP_X][STBTE_MAX_PROPERTIES];\n    #ifdef STBTE_ALLOW_LINK\n    stbte__link link[STBTE_MAX_TILEMAP_Y][STBTE_MAX_TILEMAP_X];\n    int linkcount[STBTE_MAX_TILEMAP_Y][STBTE_MAX_TILEMAP_X];\n    #endif\n    int max_x, max_y, num_layers;\n    int spacing_x, spacing_y;\n    int palette_spacing_x, palette_spacing_y;\n    int scroll_x,scroll_y;\n    int cur_category, cur_tile, cur_layer;\n    char *categories[STBTE_MAX_CATEGORIES];\n    int num_categories, category_scroll;\n    stbte__tileinfo *tiles;\n    int num_tiles, max_tiles, digits;\n    unsigned char undo_available_valid;\n    unsigned char undo_available;\n    unsigned char redo_available;\n    unsigned char padding;\n    int cur_palette_count;\n    int palette_scroll;\n    int tileinfo_dirty;\n    stbte__layer layerinfo[STBTE_MAX_LAYERS];\n    int has_layer_names;\n    int layername_width;\n    int layer_scroll;\n    int propmode;\n    int solo_layer;\n    int undo_pos, undo_len, redo_len;\n    short background_tile;\n    unsigned char id_in_use[32768>>3];\n    short *undo_buffer;\n};\n\nstatic char *default_category = (char*) \"[unassigned]\";\n\nstatic void stbte__init_gui(void)\n{\n   int i,n;\n   stbte__ui.initted = 1;\n   // init UI state\n   stbte__ui.show_links = 1;\n   for (i=0; i < STBTE__num_panel; ++i) {\n      stbte__ui.panel[i].expanded     = 1; // visible if not autohidden\n      stbte__ui.panel[i].delta_height = 0;\n      stbte__ui.panel[i].side         = STBTE__side_left;\n   }\n   stbte__ui.panel[STBTE__panel_toolbar  ].side = STBTE__side_top;\n   stbte__ui.panel[STBTE__panel_colorpick].side = STBTE__side_right;\n\n   if (stbte__ui.left_width == 0)\n      stbte__ui.left_width = 80;\n   if (stbte__ui.right_width == 0)\n      stbte__ui.right_width = 80;\n\n   // init font\n   n=95+16;\n   for (i=0; i < 95+16; ++i) {\n      stbte__font_offset[i] = n;\n      n += stbte__fontdata[i];\n   }\n}\n\nstbte_tilemap *stbte_create_map(int map_x, int map_y, int map_layers, int spacing_x, int spacing_y, int max_tiles)\n{\n   int i;\n   stbte_tilemap *tm;\n   STBTE_ASSERT(map_layers >= 0 && map_layers <= STBTE_MAX_LAYERS);\n   STBTE_ASSERT(map_x >= 0 && map_x <= STBTE_MAX_TILEMAP_X);\n   STBTE_ASSERT(map_y >= 0 && map_y <= STBTE_MAX_TILEMAP_Y);\n   if (map_x < 0 || map_y < 0 || map_layers < 0 ||\n       map_x > STBTE_MAX_TILEMAP_X || map_y > STBTE_MAX_TILEMAP_Y || map_layers > STBTE_MAX_LAYERS)\n      return NULL;\n\n   if (!stbte__ui.initted)\n      stbte__init_gui();\n\n   tm = (stbte_tilemap *) malloc(sizeof(*tm) + sizeof(*tm->tiles) * max_tiles + STBTE_UNDO_BUFFER_BYTES);\n   if (tm == NULL)\n      return NULL;\n\n   tm->tiles = (stbte__tileinfo *) (tm+1);\n   tm->undo_buffer = (short *) (tm->tiles + max_tiles);\n   tm->num_layers = map_layers;\n   tm->max_x = map_x;\n   tm->max_y = map_y;\n   tm->spacing_x = spacing_x;\n   tm->spacing_y = spacing_y;\n   tm->scroll_x = 0;\n   tm->scroll_y = 0;\n   tm->palette_scroll = 0;\n   tm->palette_spacing_x = spacing_x+1;\n   tm->palette_spacing_y = spacing_y+1;\n   tm->cur_category = -1;\n   tm->cur_tile = 0;\n   tm->solo_layer = -1;\n   tm->undo_len = 0;\n   tm->redo_len = 0;\n   tm->undo_pos = 0;\n   tm->category_scroll = 0;\n   tm->layer_scroll = 0;\n   tm->propmode = 0;\n   tm->has_layer_names = 0;\n   tm->layername_width = 0;\n   tm->undo_available_valid = 0;\n\n   for (i=0; i < tm->num_layers; ++i) {\n      tm->layerinfo[i].hidden = 0;\n      tm->layerinfo[i].locked = STBTE__unlocked;\n      tm->layerinfo[i].name   = 0;\n   }\n\n   tm->background_tile = STBTE__NO_TILE;\n   stbte_clear_map(tm);\n\n   tm->max_tiles = max_tiles;\n   tm->num_tiles = 0;\n   for (i=0; i < 32768/8; ++i)\n      tm->id_in_use[i] = 0;\n   tm->tileinfo_dirty = 1;\n   return tm;\n}\n\nvoid stbte_set_background_tile(stbte_tilemap *tm, short id)\n{\n   int i;\n   STBTE_ASSERT(id >= -1);\n   // STBTE_ASSERT(id < 32768);\n   if (id < -1)\n      return;\n   for (i=0; i < STBTE_MAX_TILEMAP_X * STBTE_MAX_TILEMAP_Y; ++i)\n      if (tm->data[0][i][0] == -1)\n         tm->data[0][i][0] = id;\n   tm->background_tile = id;\n}\n\nvoid stbte_set_spacing(stbte_tilemap *tm, int spacing_x, int spacing_y, int palette_spacing_x, int palette_spacing_y)\n{\n   tm->spacing_x = spacing_x;\n   tm->spacing_y = spacing_y;\n   tm->palette_spacing_x = palette_spacing_x;\n   tm->palette_spacing_y = palette_spacing_y;\n}\n\nvoid stbte_set_sidewidths(int left, int right)\n{\n   stbte__ui.left_width  = left;\n   stbte__ui.right_width = right;\n}\n\nvoid stbte_set_display(int x0, int y0, int x1, int y1)\n{\n   stbte__ui.x0 = x0;\n   stbte__ui.y0 = y0;\n   stbte__ui.x1 = x1;\n   stbte__ui.y1 = y1;\n}\n\nvoid stbte_define_tile(stbte_tilemap *tm, unsigned short id, unsigned int layermask, const char * category_c)\n{\n   char *category = (char *) category_c;\n   STBTE_ASSERT(id < 32768);\n   STBTE_ASSERT(tm->num_tiles < tm->max_tiles);\n   STBTE_ASSERT((tm->id_in_use[id>>3]&(1<<(id&7))) == 0);\n   if (id >= 32768 || tm->num_tiles >= tm->max_tiles || (tm->id_in_use[id>>3]&(1<<(id&7))))\n      return;\n\n   if (category == NULL)\n      category = (char*) default_category;\n   tm->id_in_use[id>>3] |= 1 << (id&7);\n   tm->tiles[tm->num_tiles].category    = category;\n   tm->tiles[tm->num_tiles].id        = id;\n   tm->tiles[tm->num_tiles].layermask = layermask;\n   ++tm->num_tiles;\n   tm->tileinfo_dirty = 1;\n}\n\nstatic int stbte__text_width(const char *str);\n\nvoid stbte_set_layername(stbte_tilemap *tm, int layer, const char *layername)\n{\n   STBTE_ASSERT(layer >= 0 && layer < tm->num_layers);\n   if (layer >= 0 && layer < tm->num_layers) {\n      int width;\n      tm->layerinfo[layer].name = layername;\n      tm->has_layer_names = 1;\n      width = stbte__text_width(layername);\n      tm->layername_width = (width > tm->layername_width ? width : tm->layername_width);\n   }\n}\n\nvoid stbte_get_dimensions(stbte_tilemap *tm, int *max_x, int *max_y)\n{\n   *max_x = tm->max_x;\n   *max_y = tm->max_y;\n}\n\nshort* stbte_get_tile(stbte_tilemap *tm, int x, int y)\n{\n   STBTE_ASSERT(x >= 0 && x < tm->max_x && y >= 0 && y < tm->max_y);\n   if (x < 0 || x >= STBTE_MAX_TILEMAP_X || y < 0 || y >= STBTE_MAX_TILEMAP_Y)\n      return NULL;\n   return tm->data[y][x];\n}\n\nfloat *stbte_get_properties(stbte_tilemap *tm, int x, int y)\n{\n   STBTE_ASSERT(x >= 0 && x < tm->max_x && y >= 0 && y < tm->max_y);\n   if (x < 0 || x >= STBTE_MAX_TILEMAP_X || y < 0 || y >= STBTE_MAX_TILEMAP_Y)\n      return NULL;\n   return tm->props[y][x];\n}\n\nvoid stbte_get_link(stbte_tilemap *tm, int x, int y, int *destx, int *desty)\n{\n   int gx=-1,gy=-1;\n   STBTE_ASSERT(x >= 0 && x < tm->max_x && y >= 0 && y < tm->max_y);\n#ifdef STBTE_ALLOW_LINK\n   if (x >= 0 && x < STBTE_MAX_TILEMAP_X && y >= 0 && y < STBTE_MAX_TILEMAP_Y) {\n      gx = tm->link[y][x].x;\n      gy = tm->link[y][x].y;\n      if (gx >= 0)\n         if (!STBTE_ALLOW_LINK(tm->data[y][x], tm->props[y][x], tm->data[gy][gx], tm->props[gy][gx]))\n            gx = gy = -1;\n   }\n#endif\n   *destx = gx;\n   *desty = gy;\n}\n\nvoid stbte_set_property(stbte_tilemap *tm, int x, int y, int n, float val)\n{\n   tm->props[y][x][n] = val;\n}\n\n#ifdef STBTE_ALLOW_LINK\nstatic void stbte__set_link(stbte_tilemap *tm, int src_x, int src_y, int dest_x, int dest_y, int undo_mode);\n#endif\n\nenum\n{\n   STBTE__undo_none,\n   STBTE__undo_record,\n   STBTE__undo_block,\n};\n\nvoid stbte_set_link(stbte_tilemap *tm, int x, int y, int destx, int desty)\n{\n#ifdef STBTE_ALLOW_LINK\n   stbte__set_link(tm, x, y, destx, desty, STBTE__undo_none);\n#else\n   STBTE_ASSERT(0);\n#endif\n}\n\n\n// returns an array of map_layers shorts. each short is either\n// one of the tile_id values from define_tile, or STBTE_EMPTY\n\nvoid stbte_set_dimensions(stbte_tilemap *tm, int map_x, int map_y)\n{\n   STBTE_ASSERT(map_x >= 0 && map_x <= STBTE_MAX_TILEMAP_X);\n   STBTE_ASSERT(map_y >= 0 && map_y <= STBTE_MAX_TILEMAP_Y);\n   if (map_x < 0 || map_y < 0 || map_x > STBTE_MAX_TILEMAP_X || map_y > STBTE_MAX_TILEMAP_Y)\n      return;\n   tm->max_x = map_x;\n   tm->max_y = map_y;\n}\n\nvoid stbte_clear_map(stbte_tilemap *tm)\n{\n   int i,j;\n   for (i=0; i < STBTE_MAX_TILEMAP_X * STBTE_MAX_TILEMAP_Y; ++i) {\n      tm->data[0][i][0] = tm->background_tile;\n      for (j=1; j < tm->num_layers; ++j)\n         tm->data[0][i][j] = STBTE__NO_TILE;\n      for (j=0; j < STBTE_MAX_PROPERTIES; ++j)\n         tm->props[0][i][j] = 0;\n      #ifdef STBTE_ALLOW_LINK\n      tm->link[0][i].x = -1;\n      tm->link[0][i].y = -1;\n      tm->linkcount[0][i] = 0;\n      #endif\n   }\n}\n\nvoid stbte_set_tile(stbte_tilemap *tm, int x, int y, int layer, signed short tile)\n{\n   STBTE_ASSERT(x >= 0 && x < tm->max_x && y >= 0 && y < tm->max_y);\n   STBTE_ASSERT(layer >= 0 && layer < tm->num_layers);\n   STBTE_ASSERT(tile >= -1);\n   //STBTE_ASSERT(tile < 32768);\n   if (x < 0 || x >= STBTE_MAX_TILEMAP_X || y < 0 || y >= STBTE_MAX_TILEMAP_Y)\n      return;\n   if (layer < 0 || layer >= tm->num_layers || tile < -1)\n      return;\n   tm->data[y][x][layer] = tile;\n}\n\nstatic void stbte__choose_category(stbte_tilemap *tm, int category)\n{\n   int i,n=0;\n   tm->cur_category = category;\n   for (i=0; i < tm->num_tiles; ++i)\n      if (tm->tiles[i].category_id == category || category == -1)\n         ++n;\n   tm->cur_palette_count = n;\n   tm->palette_scroll = 0;\n}\n\nstatic int stbte__strequal(char *p, char *q)\n{\n   while (*p)\n      if (*p++ != *q++) return 0;\n   return *q == 0;\n}\n\nstatic void stbte__compute_tileinfo(stbte_tilemap *tm)\n{\n   int i,j;\n\n   tm->num_categories=0;\n\n   for (i=0; i < tm->num_tiles; ++i) {\n      stbte__tileinfo *t = &tm->tiles[i];\n      // find category\n      for (j=0; j < tm->num_categories; ++j)\n         if (stbte__strequal(t->category, tm->categories[j]))\n            goto found;\n      tm->categories[j] = t->category;\n      ++tm->num_categories;\n     found:\n      t->category_id = (unsigned short) j;\n   }\n\n   // currently number of categories can never decrease because you\n   // can't remove tile definitions, but let's get it right anyway\n   if (tm->cur_category > tm->num_categories) {\n      tm->cur_category = -1;\n   }\n\n   stbte__choose_category(tm, tm->cur_category);\n\n   tm->tileinfo_dirty = 0;\n}\n\nstatic void stbte__prepare_tileinfo(stbte_tilemap *tm)\n{\n   if (tm->tileinfo_dirty)\n      stbte__compute_tileinfo(tm);\n}\n\n\n/////////////////////// undo system ////////////////////////\n\n// the undo system works by storing \"commands\" into a buffer, and\n// then playing back those commands. undo and redo have to store\n// the commands in different order.\n//\n// the commands are:\n//\n// 1)  end_of_undo_record\n//       -1:short\n//\n// 2)  end_of_redo_record\n//       -2:short\n//\n// 3)  tile update\n//       tile_id:short (-1..32767)\n//       x_coord:short\n//       y_coord:short\n//       layer:short (0..31)\n//\n// 4)  property update (also used for links)\n//       value_hi:short\n//       value_lo:short\n//       y_coord:short\n//       x_coord:short\n//       property:short (256+prop#)\n//\n// Since we use a circular buffer, we might overwrite the undo storage.\n// To detect this, before playing back commands we scan back and see\n// if we see an end_of_undo_record before hitting the relevant boundary,\n// it's wholly contained.\n//\n// When we read back through, we see them in reverse order, so\n// we'll see the layer number or property number first\n//\n// To be clearer about the circular buffer, there are two cases:\n//     1. a single record is larger than the whole buffer.\n//        this is caught because the end_of_undo_record will\n//        get overwritten.\n//     2. multiple records written are larger than the whole\n//        buffer, so some of them have been overwritten by\n//        the later ones. this is handled by explicitly tracking\n//        the undo length; we never try to parse the data that\n//        got overwritten\n\n// given two points, compute the length between them\n#define stbte__wrap(pos)            ((pos) & (STBTE__UNDO_BUFFER_COUNT-1))\n\n#define STBTE__undo_record  -2\n#define STBTE__redo_record  -3\n#define STBTE__undo_junk    -4  // this is written underneath the undo pointer, never used\n\nstatic void stbte__write_undo(stbte_tilemap *tm, short value)\n{\n   int pos = tm->undo_pos;\n   tm->undo_buffer[pos] = value;\n   tm->undo_pos = stbte__wrap(pos+1);\n   tm->undo_len += (tm->undo_len < STBTE__UNDO_BUFFER_COUNT-2);\n   tm->redo_len -= (tm->redo_len > 0);\n   tm->undo_available_valid = 0;\n}\n\nstatic void stbte__write_redo(stbte_tilemap *tm, short value)\n{\n   int pos = tm->undo_pos;\n   tm->undo_buffer[pos] = value;\n   tm->undo_pos = stbte__wrap(pos-1);\n   tm->redo_len += (tm->redo_len < STBTE__UNDO_BUFFER_COUNT-2);\n   tm->undo_len -= (tm->undo_len > 0);\n   tm->undo_available_valid = 0;\n}\n\nstatic void stbte__begin_undo(stbte_tilemap *tm)\n{\n   tm->redo_len = 0;\n   stbte__write_undo(tm, STBTE__undo_record);\n   stbte__ui.undoing = 1;\n   stbte__ui.alert_msg = 0; // clear alert if they start doing something\n}\n\nstatic void stbte__end_undo(stbte_tilemap *tm)\n{\n   if (stbte__ui.undoing) {\n      // check if anything got written\n      int pos = stbte__wrap(tm->undo_pos-1);\n      if (tm->undo_buffer[pos] == STBTE__undo_record) {\n         // empty undo record, move back\n         tm->undo_pos = pos;\n         STBTE_ASSERT(tm->undo_len > 0);\n         tm->undo_len -= 1;\n      }\n      tm->undo_buffer[tm->undo_pos] = STBTE__undo_junk;\n      // otherwise do nothing\n\n      stbte__ui.undoing = 0;\n   }\n}\n\nstatic void stbte__undo_record(stbte_tilemap *tm, int x, int y, int i, int v)\n{\n   STBTE_ASSERT(stbte__ui.undoing);\n   if (stbte__ui.undoing) {\n      stbte__write_undo(tm, v);\n      stbte__write_undo(tm, x);\n      stbte__write_undo(tm, y);\n      stbte__write_undo(tm, i);\n   }\n}\n\nstatic void stbte__redo_record(stbte_tilemap *tm, int x, int y, int i, int v)\n{\n   stbte__write_redo(tm, v);\n   stbte__write_redo(tm, x);\n   stbte__write_redo(tm, y);\n   stbte__write_redo(tm, i);\n}\n\nstatic float stbte__extract_float(short s0, short s1)\n{\n   union { float f; short s[2]; } converter;\n   converter.s[0] = s0;\n   converter.s[1] = s1;\n   return converter.f;\n}\n\nstatic short stbte__extract_short(float f, int slot)\n{\n   union { float f; short s[2]; } converter;\n   converter.f = f;\n   return converter.s[slot];\n}\n\nstatic void stbte__undo_record_prop(stbte_tilemap *tm, int x, int y, int i, short s0, short s1)\n{\n   STBTE_ASSERT(stbte__ui.undoing);\n   if (stbte__ui.undoing) {\n      stbte__write_undo(tm, s1);\n      stbte__write_undo(tm, s0);\n      stbte__write_undo(tm, x);\n      stbte__write_undo(tm, y);\n      stbte__write_undo(tm, 256+i);\n   }\n}\n\nstatic void stbte__undo_record_prop_float(stbte_tilemap *tm, int x, int y, int i, float f)\n{\n   stbte__undo_record_prop(tm, x,y,i, stbte__extract_short(f,0), stbte__extract_short(f,1));\n}\n\nstatic void stbte__redo_record_prop(stbte_tilemap *tm, int x, int y, int i, short s0, short s1)\n{\n   stbte__write_redo(tm, s1);\n   stbte__write_redo(tm, s0);\n   stbte__write_redo(tm, x);\n   stbte__write_redo(tm, y);\n   stbte__write_redo(tm, 256+i);\n}\n\n\nstatic int stbte__undo_find_end(stbte_tilemap *tm)\n{\n   // first scan through for the end record\n   int i, pos = stbte__wrap(tm->undo_pos-1);\n   for (i=0; i < tm->undo_len;) {\n      STBTE_ASSERT(tm->undo_buffer[pos] != STBTE__undo_junk);\n      if (tm->undo_buffer[pos] == STBTE__undo_record)\n         break;\n      if (tm->undo_buffer[pos] >= 255)\n         pos = stbte__wrap(pos-5), i += 5;\n      else\n         pos = stbte__wrap(pos-4), i += 4;\n   }\n   if (i >= tm->undo_len)\n      return -1;\n   return pos;\n}\n\nstatic void stbte__undo(stbte_tilemap *tm)\n{\n   int i, pos, endpos;\n   endpos = stbte__undo_find_end(tm);\n   if (endpos < 0)\n      return;\n\n   // we found a complete undo record\n   pos = stbte__wrap(tm->undo_pos-1);\n\n   // start a redo record\n   stbte__write_redo(tm, STBTE__redo_record);\n\n   // so now go back through undo and apply in reverse\n   // order, and copy it to redo\n   for (i=0; endpos != pos; i += 4) {\n      int x,y,n,v;\n      // get the undo entry\n      n = tm->undo_buffer[pos];\n      y = tm->undo_buffer[stbte__wrap(pos-1)];\n      x = tm->undo_buffer[stbte__wrap(pos-2)];\n      v = tm->undo_buffer[stbte__wrap(pos-3)];\n      if (n >= 255) {\n         short s0=0,s1=0;\n         int v2 = tm->undo_buffer[stbte__wrap(pos-4)];\n         pos = stbte__wrap(pos-5);\n         if (n > 255) {\n            float vf = stbte__extract_float(v, v2);\n            s0 = stbte__extract_short(tm->props[y][x][n-256], 0);\n            s1 = stbte__extract_short(tm->props[y][x][n-256], 1);\n            tm->props[y][x][n-256] = vf;\n         } else {\n#ifdef STBTE_ALLOW_LINK\n            s0 = tm->link[y][x].x;\n            s1 = tm->link[y][x].y;\n            stbte__set_link(tm, x,y, v, v2, STBTE__undo_none);\n#endif\n         }\n         // write the redo entry\n         stbte__redo_record_prop(tm, x, y, n-256, s0,s1);\n         // apply the undo entry\n      } else {\n         pos = stbte__wrap(pos-4);\n         // write the redo entry\n         stbte__redo_record(tm, x, y, n, tm->data[y][x][n]);\n         // apply the undo entry\n         tm->data[y][x][n] = (short) v;\n      }\n   }\n   // overwrite undo record with junk\n   tm->undo_buffer[tm->undo_pos] = STBTE__undo_junk;\n}\n\nstatic int stbte__redo_find_end(stbte_tilemap *tm)\n{\n   // first scan through for the end record\n   int i, pos = stbte__wrap(tm->undo_pos+1);\n   for (i=0; i < tm->redo_len;) {\n      STBTE_ASSERT(tm->undo_buffer[pos] != STBTE__undo_junk);\n      if (tm->undo_buffer[pos] == STBTE__redo_record)\n         break;\n      if (tm->undo_buffer[pos] >= 255)\n         pos = stbte__wrap(pos+5), i += 5;\n      else\n         pos = stbte__wrap(pos+4), i += 4;\n   }\n   if (i >= tm->redo_len)\n      return -1; // this should only ever happen if redo buffer is empty\n   return pos;\n}\n\nstatic void stbte__redo(stbte_tilemap *tm)\n{\n   // first scan through for the end record\n   int i, pos, endpos;\n   endpos = stbte__redo_find_end(tm);\n   if (endpos < 0)\n      return;\n\n   // we found a complete redo record\n   pos = stbte__wrap(tm->undo_pos+1);\n\n   // start an undo record\n   stbte__write_undo(tm, STBTE__undo_record);\n\n   for (i=0; pos != endpos; i += 4) {\n      int x,y,n,v;\n      n = tm->undo_buffer[pos];\n      y = tm->undo_buffer[stbte__wrap(pos+1)];\n      x = tm->undo_buffer[stbte__wrap(pos+2)];\n      v = tm->undo_buffer[stbte__wrap(pos+3)];\n      if (n >= 255) {\n         int v2 = tm->undo_buffer[stbte__wrap(pos+4)];\n         short s0=0,s1=0;\n         pos = stbte__wrap(pos+5);\n         if (n > 255) {\n            float vf = stbte__extract_float(v, v2);\n            s0 = stbte__extract_short(tm->props[y][x][n-256],0);\n            s1 = stbte__extract_short(tm->props[y][x][n-256],1);\n            tm->props[y][x][n-256] = vf;\n         } else {\n#ifdef STBTE_ALLOW_LINK\n            s0 = tm->link[y][x].x;\n            s1 = tm->link[y][x].y;\n            stbte__set_link(tm, x,y,v,v2, STBTE__undo_none);\n#endif\n         }\n         // don't use stbte__undo_record_prop because it's guarded\n         stbte__write_undo(tm, s1);\n         stbte__write_undo(tm, s0);\n         stbte__write_undo(tm, x);\n         stbte__write_undo(tm, y);\n         stbte__write_undo(tm, n);\n      } else {\n         pos = stbte__wrap(pos+4);\n         // don't use stbte__undo_record because it's guarded\n         stbte__write_undo(tm, tm->data[y][x][n]);\n         stbte__write_undo(tm, x);\n         stbte__write_undo(tm, y);\n         stbte__write_undo(tm, n);\n         tm->data[y][x][n] = (short) v;\n      }\n   }\n   tm->undo_buffer[tm->undo_pos] = STBTE__undo_junk;\n}\n\n// because detecting that undo is available\nstatic void stbte__recompute_undo_available(stbte_tilemap *tm)\n{\n   tm->undo_available = (stbte__undo_find_end(tm) >= 0);\n   tm->redo_available = (stbte__redo_find_end(tm) >= 0);\n}\n\nstatic int stbte__undo_available(stbte_tilemap *tm)\n{\n   if (!tm->undo_available_valid)\n      stbte__recompute_undo_available(tm);\n   return tm->undo_available;\n}\n\nstatic int stbte__redo_available(stbte_tilemap *tm)\n{\n   if (!tm->undo_available_valid)\n      stbte__recompute_undo_available(tm);\n   return tm->redo_available;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifdef STBTE_ALLOW_LINK\nstatic void stbte__set_link(stbte_tilemap *tm, int src_x, int src_y, int dest_x, int dest_y, int undo_mode)\n{\n   stbte__link *a;\n   STBTE_ASSERT(src_x >= 0 && src_x < STBTE_MAX_TILEMAP_X && src_y >= 0 && src_y < STBTE_MAX_TILEMAP_Y);\n   a = &tm->link[src_y][src_x];\n   // check if it's a do nothing\n   if (a->x == dest_x && a->y == dest_y)\n      return;\n   if (undo_mode != STBTE__undo_none ) {\n      if (undo_mode == STBTE__undo_block) stbte__begin_undo(tm);\n      stbte__undo_record_prop(tm, src_x, src_y, -1, a->x, a->y);\n      if (undo_mode == STBTE__undo_block) stbte__end_undo(tm);\n   }\n   // check if there's an existing link\n   if (a->x >= 0) {\n      // decrement existing link refcount\n      STBTE_ASSERT(tm->linkcount[a->y][a->x] > 0);\n      --tm->linkcount[a->y][a->x];\n   }\n   // increment new dest\n   if (dest_x >= 0) {\n      ++tm->linkcount[dest_y][dest_x];\n   }\n   a->x = dest_x;\n   a->y = dest_y;\n}\n#endif\n\n\nstatic void stbte__draw_rect(int x0, int y0, int x1, int y1, unsigned int color)\n{\n   STBTE_DRAW_RECT(x0,y0,x1,y1, color);\n}\n\n#ifdef STBTE_ALLOW_LINK\nstatic void stbte__draw_line(int x0, int y0, int x1, int y1, unsigned int color)\n{\n   int temp;\n   if (x1 < x0) temp=x0,x0=x1,x1=temp;\n   if (y1 < y0) temp=y0,y0=y1,y1=temp;\n   stbte__draw_rect(x0,y0,x1+1,y1+1,color);\n}\n\nstatic void stbte__draw_link(int x0, int y0, int x1, int y1, unsigned int color)\n{\n   stbte__draw_line(x0,y0,x0,y1, color);\n   stbte__draw_line(x0,y1,x1,y1, color);\n}\n#endif\n\nstatic void stbte__draw_frame(int x0, int y0, int x1, int y1, unsigned int color)\n{\n   stbte__draw_rect(x0,y0,x1-1,y0+1,color);\n   stbte__draw_rect(x1-1,y0,x1,y1-1,color);\n   stbte__draw_rect(x0+1,y1-1,x1,y1,color);\n   stbte__draw_rect(x0,y0+1,x0+1,y1,color);\n}\n\nstatic int stbte__get_char_width(int ch)\n{\n   return stbte__fontdata[ch-16];\n}\n\nstatic short *stbte__get_char_bitmap(int ch)\n{\n   return stbte__fontdata + stbte__font_offset[ch-16];\n}\n\nstatic void stbte__draw_bitmask_as_columns(int x, int y, short bitmask, int color)\n{\n   int start_i = -1, i=0;\n   while (bitmask) {\n      if (bitmask & (1<<i)) {\n         if (start_i < 0)\n            start_i = i;\n      } else if (start_i >= 0) {\n         stbte__draw_rect(x, y+start_i, x+1, y+i, color);\n         start_i = -1;\n         bitmask &= ~((1<<i)-1); // clear all the old bits; we don't clear them as we go to save code\n      }\n      ++i;\n   }\n}\n\nstatic void stbte__draw_bitmap(int x, int y, int w, short *bitmap, int color)\n{\n   int i;\n   for (i=0; i < w; ++i)\n      stbte__draw_bitmask_as_columns(x+i, y, *bitmap++, color);\n}\n\nstatic void stbte__draw_text_core(int x, int y, const char *str, int w, int color, int digitspace)\n{\n   int x_end = x+w;\n   while (*str) {\n      int c = *str++;\n      int cw = stbte__get_char_width(c);\n      if (x + cw > x_end)\n         break;\n      stbte__draw_bitmap(x, y, cw, stbte__get_char_bitmap(c), color);\n      if (digitspace && c == ' ')\n         cw = stbte__get_char_width('0');\n      x += cw+1;\n   }\n}\n\nstatic void stbte__draw_text(int x, int y, const char *str, int w, int color)\n{\n   stbte__draw_text_core(x,y,str,w,color,0);\n}\n\nstatic int stbte__text_width(const char *str)\n{\n   int x = 0;\n   while (*str) {\n      int c = *str++;\n      int cw = stbte__get_char_width(c);\n      x += cw+1;\n   }\n   return x;\n}\n\nstatic void stbte__draw_frame_delayed(int x0, int y0, int x1, int y1, int color)\n{\n   if (stbte__ui.delaycount < STBTE__MAX_DELAYRECT) {\n      stbte__colorrect r = { x0,y0,x1,y1,color };\n      stbte__ui.delayrect[stbte__ui.delaycount++] = r;\n   }\n}\n\nstatic void stbte__flush_delay(void)\n{\n   stbte__colorrect *r;\n   int i;\n   r = stbte__ui.delayrect;\n   for (i=0; i < stbte__ui.delaycount; ++i,++r)\n      stbte__draw_frame(r->x0,r->y0,r->x1,r->y1,r->color);\n   stbte__ui.delaycount = 0;\n}\n\nstatic void stbte__activate(int id)\n{\n   stbte__ui.active_id = id;\n   stbte__ui.active_event = stbte__ui.event;\n   stbte__ui.accum_x = 0;\n   stbte__ui.accum_y = 0;\n}\n\nstatic int stbte__hittest(int x0, int y0, int x1, int y1, int id)\n{\n   int over =    stbte__ui.mx >= x0 && stbte__ui.my >= y0\n              && stbte__ui.mx <  x1 && stbte__ui.my <  y1;\n\n   if (over && stbte__ui.event >= STBTE__tick)\n      stbte__ui.next_hot_id = id;\n\n   return over;\n}\n\nstatic int stbte__button_core(int id)\n{\n   switch (stbte__ui.event) {\n      case STBTE__leftdown:\n         if (stbte__ui.hot_id == id && STBTE__INACTIVE())\n            stbte__activate(id);\n         break;\n      case STBTE__leftup:\n         if (stbte__ui.active_id == id && STBTE__IS_HOT(id)) {\n            stbte__activate(0);\n            return 1;\n         }\n         break;\n      case STBTE__rightdown:\n         if (stbte__ui.hot_id == id && STBTE__INACTIVE())\n            stbte__activate(id);\n         break;\n      case STBTE__rightup:\n         if (stbte__ui.active_id == id && STBTE__IS_HOT(id)) {\n            stbte__activate(0);\n            return -1;\n         }\n         break;\n   }\n   return 0;\n}\n\nstatic void stbte__draw_box(int x0, int y0, int x1, int y1, int colormode, int colorindex)\n{\n   stbte__draw_rect (x0,y0,x1,y1, stbte__color_table[colormode][STBTE__base   ][colorindex]);\n   stbte__draw_frame(x0,y0,x1,y1, stbte__color_table[colormode][STBTE__outline][colorindex]);\n}\n\nstatic void stbte__draw_textbox(int x0, int y0, int x1, int y1, char *text, int xoff, int yoff, int colormode, int colorindex)\n{\n   stbte__draw_box(x0,y0,x1,y1,colormode,colorindex);\n   stbte__draw_text(x0+xoff,y0+yoff, text, x1-x0-xoff-1, stbte__color_table[colormode][STBTE__text][colorindex]);\n}\n\nstatic int stbte__button(int colormode, const char *label, int x, int y, int textoff, int width, int id, int toggled, int disabled)\n{\n   int x0=x,y0=y, x1=x+width,y1=y+STBTE__BUTTON_HEIGHT;\n   int s = STBTE__BUTTON_INTERNAL_SPACING;\n\n   if(!disabled) stbte__hittest(x0,y0,x1,y1,id);\n\n   if (stbte__ui.event == STBTE__paint)\n      stbte__draw_textbox(x0,y0,x1,y1, (char*) label,s+textoff,s, colormode, STBTE__INDEX_FOR_ID(id,disabled,toggled));\n   if (disabled)\n      return 0;\n   return (stbte__button_core(id) == 1);\n}\n\nstatic int stbte__button_icon(int colormode, char ch, int x, int y, int width, int id, int toggled, int disabled)\n{\n   int x0=x,y0=y, x1=x+width,y1=y+STBTE__BUTTON_HEIGHT;\n   int s = STBTE__BUTTON_INTERNAL_SPACING;\n\n   stbte__hittest(x0,y0,x1,y1,id);\n\n   if (stbte__ui.event == STBTE__paint) {\n      char label[2] = { ch, 0 };\n      int pad = (9 - stbte__get_char_width(ch))/2;\n      stbte__draw_textbox(x0,y0,x1,y1, label,s+pad,s, colormode, STBTE__INDEX_FOR_ID(id,disabled,toggled));\n   }\n   if (disabled)\n      return 0;\n   return (stbte__button_core(id) == 1);\n}\n\nstatic int stbte__minibutton(int colormode, int x, int y, int ch, int id)\n{\n   int x0 = x, y0 = y, x1 = x+8, y1 = y+7;\n   stbte__hittest(x0,y0,x1,y1,id);\n   if (stbte__ui.event == STBTE__paint) {\n      char str[2] = { (char)ch, 0 };\n      stbte__draw_textbox(x0,y0,x1,y1, str,1,0,colormode, STBTE__INDEX_FOR_ID(id,0,0));\n   }\n   return stbte__button_core(id);\n}\n\nstatic int stbte__layerbutton(int x, int y, int ch, int id, int toggled, int disabled, int colormode)\n{\n   int x0 = x, y0 = y, x1 = x+10, y1 = y+11;\n   if(!disabled) stbte__hittest(x0,y0,x1,y1,id);\n   if (stbte__ui.event == STBTE__paint) {\n      char str[2] = { (char)ch, 0 };\n      int off = (9-stbte__get_char_width(ch))/2;\n      stbte__draw_textbox(x0,y0,x1,y1, str, off+1,2, colormode, STBTE__INDEX_FOR_ID(id,disabled,toggled));\n   }\n   if (disabled)\n      return 0;\n   return stbte__button_core(id);\n}\n\nstatic int stbte__microbutton(int x, int y, int size, int id, int colormode)\n{\n   int x0 = x, y0 = y, x1 = x+size, y1 = y+size;\n   stbte__hittest(x0,y0,x1,y1,id);\n   if (stbte__ui.event == STBTE__paint) {\n      stbte__draw_box(x0,y0,x1,y1, colormode, STBTE__INDEX_FOR_ID(id,0,0));\n   }\n   return stbte__button_core(id);\n}\n\nstatic int stbte__microbutton_dragger(int x, int y, int size, int id, int *pos)\n{\n   int x0 = x, y0 = y, x1 = x+size, y1 = y+size;\n   stbte__hittest(x0,y0,x1,y1,id);\n   switch (stbte__ui.event) {\n      case STBTE__paint:\n         stbte__draw_box(x0,y0,x1,y1, STBTE__cexpander, STBTE__INDEX_FOR_ID(id,0,0));\n         break;\n      case STBTE__leftdown:\n         if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n            stbte__activate(id);\n            stbte__ui.sx = stbte__ui.mx - *pos;\n         }\n         break;\n      case STBTE__mousemove:\n         if (STBTE__IS_ACTIVE(id) && stbte__ui.active_event == STBTE__leftdown) {\n            *pos = stbte__ui.mx - stbte__ui.sx;\n         }\n         break;\n      case STBTE__leftup:\n         if (STBTE__IS_ACTIVE(id))\n            stbte__activate(0);\n         break;\n      default:\n         return stbte__button_core(id);\n   }\n   return 0;\n}\n\nstatic int stbte__category_button(const char *label, int x, int y, int width, int id, int toggled)\n{\n   int x0=x,y0=y, x1=x+width,y1=y+STBTE__BUTTON_HEIGHT;\n   int s = STBTE__BUTTON_INTERNAL_SPACING;\n\n   stbte__hittest(x0,y0,x1,y1,id);\n\n   if (stbte__ui.event == STBTE__paint)\n      stbte__draw_textbox(x0,y0,x1,y1, (char*) label, s,s, STBTE__ccategory_button, STBTE__INDEX_FOR_ID(id,0,toggled));\n\n   return (stbte__button_core(id) == 1);\n}\n\nenum\n{\n   STBTE__none,\n   STBTE__begin,\n   STBTE__end,\n   STBTE__change,\n};\n\n// returns -1 if value changes, 1 at end of drag\nstatic int stbte__slider(int x0, int w, int y, int range, int *value, int id)\n{\n   int x1 = x0+w;\n   int pos = *value * w / (range+1);\n   stbte__hittest(x0,y-2,x1,y+3,id);\n   int event_mouse_move = STBTE__change;\n   switch (stbte__ui.event) {\n      case STBTE__paint:\n         stbte__draw_rect(x0,y,x1,y+1, 0x808080);\n         stbte__draw_rect(x0+pos-1,y-1,x0+pos+2,y+2, 0xffffff);\n         break;\n      case STBTE__leftdown:\n         if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n            stbte__activate(id);\n            event_mouse_move = STBTE__begin;\n         }\n         // fall through\n      case STBTE__mousemove:\n         if (STBTE__IS_ACTIVE(id)) {\n            int v = (stbte__ui.mx-x0)*(range+1)/w;\n            if (v < 0) v = 0; else if (v > range) v = range;\n            *value = v;\n            return event_mouse_move;\n         }\n         break;\n      case STBTE__leftup:\n         if (STBTE__IS_ACTIVE(id)) {\n            stbte__activate(0);\n            return STBTE__end;\n         }\n         break;\n   }\n   return STBTE__none;\n}\n\n#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)\n   #define stbte__sprintf      sprintf_s\n   #define stbte__sizeof(s)    , sizeof(s)\n#else\n   #define stbte__sprintf      sprintf\n   #define stbte__sizeof(s)\n#endif\n\nstatic int stbte__float_control(int x0, int y0, int w, float minv, float maxv, float scale, const char *fmt, float *value, int colormode, int id)\n{\n   int x1 = x0+w;\n   int y1 = y0+11;\n   stbte__hittest(x0,y0,x1,y1,id);\n   switch (stbte__ui.event) {\n      case STBTE__paint: {\n         char text[32];\n         stbte__sprintf(text stbte__sizeof(text), fmt ? fmt : \"%6.2f\", *value);\n         stbte__draw_textbox(x0,y0,x1,y1, text, 1,2, colormode, STBTE__INDEX_FOR_ID(id,0,0));\n         break;\n      }\n      case STBTE__leftdown:\n      case STBTE__rightdown:\n         if (STBTE__IS_HOT(id) && STBTE__INACTIVE())\n            stbte__activate(id);\n         return STBTE__begin;\n         break;\n      case STBTE__leftup:\n      case STBTE__rightup:\n         if (STBTE__IS_ACTIVE(id)) {\n            stbte__activate(0);\n            return STBTE__end;\n         }\n         break;\n      case STBTE__mousemove:\n         if (STBTE__IS_ACTIVE(id)) {\n            float v = *value, delta;\n            int ax = stbte__ui.accum_x/STBTE_FLOAT_CONTROL_GRANULARITY;\n            int ay = stbte__ui.accum_y/STBTE_FLOAT_CONTROL_GRANULARITY;\n            stbte__ui.accum_x -= ax*STBTE_FLOAT_CONTROL_GRANULARITY;\n            stbte__ui.accum_y -= ay*STBTE_FLOAT_CONTROL_GRANULARITY;\n            if (stbte__ui.shift) {\n               if (stbte__ui.active_event == STBTE__leftdown)\n                  delta = ax * 16.0f + ay;\n               else\n                  delta = ax / 16.0f + ay / 256.0f;\n            } else {\n               if (stbte__ui.active_event == STBTE__leftdown)\n                  delta = ax*10.0f + ay;\n               else\n                  delta = ax * 0.1f + ay * 0.01f;\n            }\n            v += delta * scale;\n            if (v < minv) v = minv;\n            if (v > maxv) v = maxv;\n            *value = v;\n            return STBTE__change;\n         }\n         break;\n   }\n   return STBTE__none;\n}\n\nstatic void stbte__scrollbar(int x, int y0, int y1, int *val, int v0, int v1, int num_vis, int id)\n{\n   int thumbpos;\n   if (v1 - v0 <= num_vis)\n      return;\n\n   // generate thumbpos from numvis\n   thumbpos = y0+2 + (y1-y0-4) * *val / (v1 - v0 - num_vis);\n   if (thumbpos < y0) thumbpos = y0;\n   if (thumbpos >= y1) thumbpos = y1;\n   stbte__hittest(x-1,y0,x+2,y1,id);\n   switch (stbte__ui.event) {\n      case STBTE__paint:\n         stbte__draw_rect(x,y0,x+1,y1, stbte__color_table[STBTE__cscrollbar][STBTE__text][STBTE__idle]);\n         stbte__draw_box(x-1,thumbpos-3,x+2,thumbpos+4, STBTE__cscrollbar, STBTE__INDEX_FOR_ID(id,0,0));\n         break;\n      case STBTE__leftdown:\n         if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n            // check if it's over the thumb\n            stbte__activate(id);\n            *val = ((stbte__ui.my-y0) * (v1 - v0 - num_vis) + (y1-y0)/2)/ (y1-y0);\n         }\n         break;\n      case STBTE__mousemove:\n         if (STBTE__IS_ACTIVE(id) && stbte__ui.mx >= x-15 && stbte__ui.mx <= x+15)\n            *val = ((stbte__ui.my-y0) * (v1 - v0 - num_vis) + (y1-y0)/2)/ (y1-y0);\n         break;\n      case STBTE__leftup:\n         if (STBTE__IS_ACTIVE(id))\n            stbte__activate(0);\n         break;\n\n   }\n\n   if (*val >= v1-num_vis)\n      *val = v1-num_vis;\n   if (*val <= v0)\n      *val = v0;\n}\n\n\nstatic void stbte__compute_digits(stbte_tilemap *tm)\n{\n   if (tm->max_x >= 1000 || tm->max_y >= 1000)\n      tm->digits = 4;\n   else if (tm->max_x >= 100 || tm->max_y >= 100)\n      tm->digits = 3;\n   else\n      tm->digits = 2;\n}\n\nstatic int stbte__is_single_selection(void)\n{\n   return stbte__ui.has_selection\n       && stbte__ui.select_x0 == stbte__ui.select_x1\n       && stbte__ui.select_y0 == stbte__ui.select_y1;\n}\n\ntypedef struct\n{\n   int width, height;\n   int x,y;\n   int active;\n   float retracted;\n} stbte__region_t;\n\nstatic stbte__region_t stbte__region[4];\n\n#define STBTE__TOOLBAR_ICON_SIZE   (9+2*2)\n#define STBTE__TOOLBAR_PASTE_SIZE  (34+2*2)\n\n// This routine computes where every panel goes onscreen: computes\n// a minimum width for each side based on which panels are on that\n// side, and accounts for width-dependent layout of certain panels.\nstatic void stbte__compute_panel_locations(stbte_tilemap *tm)\n{\n   int i, limit, w, k;\n   int window_width  = stbte__ui.x1 - stbte__ui.x0;\n   int window_height = stbte__ui.y1 - stbte__ui.y0;\n   int min_width[STBTE__num_panel]={0,0,0,0,0,0,0};\n   int height[STBTE__num_panel]={0,0,0,0,0,0,0};\n   int panel_active[STBTE__num_panel]={1,0,1,1,1,1,1};\n   int vpos[4] = { 0,0,0,0 };\n   stbte__panel *p = stbte__ui.panel;\n   stbte__panel *pt = &p[STBTE__panel_toolbar];\n#ifdef STBTE__NO_PROPS\n   int props = 0;\n#else\n   int props = 1;\n#endif\n\n   for (i=0; i < 4; ++i) {\n      stbte__region[i].active = 0;\n      stbte__region[i].width = 0;\n      stbte__region[i].height = 0;\n   }\n\n   // compute number of digits needs for info panel\n   stbte__compute_digits(tm);\n\n   // determine which panels are active\n   panel_active[STBTE__panel_categories] = tm->num_categories != 0;\n   panel_active[STBTE__panel_layers    ] = tm->num_layers     >  1;\n#ifdef STBTE__COLORPICKER\n   panel_active[STBTE__panel_colorpick ] = 1;\n#endif\n\n   panel_active[STBTE__panel_props     ] = props && stbte__is_single_selection();\n\n   // compute minimum widths for each panel (assuming they're on sides not top)\n   min_width[STBTE__panel_info      ] = 8 + 11 + 7*tm->digits+17+7;               // estimate min width of \"w:0000\"\n   min_width[STBTE__panel_colorpick ] = 120;\n   min_width[STBTE__panel_tiles     ] = 4 + tm->palette_spacing_x + 5;            // 5 for scrollbar\n   min_width[STBTE__panel_categories] = 4 + 42 + 5;                               // 42 is enough to show ~7 chars; 5 for scrollbar\n   min_width[STBTE__panel_layers    ] = 4 + 54 + 30*tm->has_layer_names;          // 2 digits plus 3 buttons plus scrollbar\n   min_width[STBTE__panel_toolbar   ] = 4 + STBTE__TOOLBAR_PASTE_SIZE;            // wide enough for 'Paste' button\n   min_width[STBTE__panel_props     ] = 80;                    // narrowest info panel\n\n   // compute minimum widths for left & right panels based on the above\n   stbte__region[0].width = stbte__ui.left_width;\n   stbte__region[1].width = stbte__ui.right_width;\n\n   for (i=0; i < STBTE__num_panel; ++i) {\n      if (panel_active[i]) {\n         int side = stbte__ui.panel[i].side;\n         if (min_width[i] > stbte__region[side].width)\n            stbte__region[side].width = min_width[i];\n         stbte__region[side].active = 1;\n      }\n   }\n\n   // now compute the heights of each panel\n\n   // if toolbar at top, compute its size & push the left and right start points down\n   if (stbte__region[STBTE__side_top].active) {\n      int height = STBTE__TOOLBAR_ICON_SIZE+2;\n      pt->x0     = stbte__ui.x0;\n      pt->y0     = stbte__ui.y0;\n      pt->width  = window_width;\n      pt->height = height;\n      vpos[STBTE__side_left] = vpos[STBTE__side_right] = height;\n   } else {\n      int num_rows = STBTE__num_tool * ((stbte__region[pt->side].width-4)/STBTE__TOOLBAR_ICON_SIZE);\n      height[STBTE__panel_toolbar] = num_rows*13 + 3*15 + 4; // 3*15 for cut/copy/paste, which are stacked vertically\n   }\n\n   for (i=0; i < 4; ++i)\n      stbte__region[i].y = stbte__ui.y0 + vpos[i];\n\n   for (i=0; i < 2; ++i) {\n      int anim = (int) (stbte__region[i].width * stbte__region[i].retracted);\n      stbte__region[i].x = (i == STBTE__side_left) ? stbte__ui.x0 - anim : stbte__ui.x1 - stbte__region[i].width + anim;\n   }\n\n   // color picker\n   height[STBTE__panel_colorpick] = 300;\n\n   // info panel\n   w = stbte__region[p[STBTE__panel_info].side].width;\n   p[STBTE__panel_info].mode = (w >= 8 + (11+7*tm->digits+17)*2 + 4);\n   if (p[STBTE__panel_info].mode)\n      height[STBTE__panel_info] = 5 + 11*2 + 2 + tm->palette_spacing_y;\n   else\n      height[STBTE__panel_info] = 5 + 11*4 + 2 + tm->palette_spacing_y;\n\n   // layers\n   limit = 6 + stbte__ui.panel[STBTE__panel_layers].delta_height;\n   height[STBTE__panel_layers] = (tm->num_layers > limit ? limit : tm->num_layers)*15 + 7 + (tm->has_layer_names ? 0 : 11) + props*13;\n\n   // categories\n   limit = 6 + stbte__ui.panel[STBTE__panel_categories].delta_height;\n   height[STBTE__panel_categories] = (tm->num_categories+1 > limit ? limit : tm->num_categories+1)*11 + 14;\n   if (stbte__ui.panel[STBTE__panel_categories].side == stbte__ui.panel[STBTE__panel_categories].side)\n      height[STBTE__panel_categories] -= 4;\n\n   // palette\n   k =  (stbte__region[p[STBTE__panel_tiles].side].width - 8) / tm->palette_spacing_x;\n   if (k == 0) k = 1;\n   height[STBTE__panel_tiles] = ((tm->num_tiles+k-1)/k) * tm->palette_spacing_y + 8;\n\n   // properties panel\n   height[STBTE__panel_props] = 9 + STBTE_MAX_PROPERTIES*14;\n\n   // now compute the locations of all the panels\n   for (i=0; i < STBTE__num_panel; ++i) {\n      if (panel_active[i]) {\n         int side = p[i].side;\n         if (side == STBTE__side_left || side == STBTE__side_right) {\n            p[i].width  = stbte__region[side].width;\n            p[i].x0     = stbte__region[side].x;\n            p[i].y0     = stbte__ui.y0 + vpos[side];\n            p[i].height = height[i];\n            vpos[side] += height[i];\n            if (vpos[side] > window_height) {\n               vpos[side] = window_height;\n               p[i].height = stbte__ui.y1 - p[i].y0;\n            }\n         } else {\n            ; // it's at top, it's already been explicitly set up earlier\n         }\n      } else {\n         // inactive panel\n         p[i].height = 0;\n         p[i].width  = 0;\n         p[i].x0     = stbte__ui.x1;\n         p[i].y0     = stbte__ui.y1;\n      }\n   }\n}\n\n// unique identifiers for imgui\nenum\n{\n   STBTE__map=1,\n   STBTE__region,\n   STBTE__panel,                          // panel background to hide map, and misc controls\n   STBTE__info,                           // info data\n   STBTE__toolbarA, STBTE__toolbarB,      // toolbar buttons: param is tool number\n   STBTE__palette,                        // palette selectors: param is tile index\n   STBTE__categories,                     // category selectors: param is category index\n   STBTE__layer,                          //\n   STBTE__solo, STBTE__hide, STBTE__lock, // layer controls: param is layer\n   STBTE__scrollbar,                      // param is panel ID\n   STBTE__panel_mover,                    // p1 is panel ID, p2 is destination side\n   STBTE__panel_sizer,                    // param panel ID\n   STBTE__scrollbar_id,\n   STBTE__colorpick_id,\n   STBTE__prop_flag,\n   STBTE__prop_float,\n   STBTE__prop_int,\n};\n\n// id is:      [      24-bit data     : 7-bit identifier ]\n// map id is:  [  12-bit y : 12 bit x : 7-bit identifier ]\n\n#define STBTE__ID(n,p)     ((n) + ((p)<<7))\n#define STBTE__ID2(n,p,q)  STBTE__ID(n, ((p)<<12)+(q) )\n#define STBTE__IDMAP(x,y)  STBTE__ID2(STBTE__map, x,y)\n\nstatic void stbte__activate_map(int x, int y)\n{\n   stbte__ui.active_id = STBTE__IDMAP(x,y);\n   stbte__ui.active_event = stbte__ui.event;\n   stbte__ui.sx = x;\n   stbte__ui.sy = y;\n}\n\nstatic void stbte__alert(const char *msg)\n{\n   stbte__ui.alert_msg = msg;\n   stbte__ui.alert_timer = 3;\n}\n\n#define STBTE__BG(tm,layer) ((layer) == 0 ? (tm)->background_tile : STBTE__NO_TILE)\n\n\n\nstatic void stbte__brush_predict(stbte_tilemap *tm, short result[])\n{\n   stbte__tileinfo *ti;\n   int i;\n\n   if (tm->cur_tile < 0) return;\n\n   ti = &tm->tiles[tm->cur_tile];\n\n   // find lowest legit layer to paint it on, and put it there\n   for (i=0; i < tm->num_layers; ++i) {\n      // check if object is allowed on layer\n      if (!(ti->layermask & (1 << i)))\n         continue;\n\n      if (i != tm->solo_layer) {\n         // if there's a selected layer, can only paint on that\n         if (tm->cur_layer >= 0 && i != tm->cur_layer)\n            continue;\n\n         // if the layer is hidden, we can't see it\n         if (tm->layerinfo[i].hidden)\n            continue;\n\n         // if the layer is locked, we can't write to it\n         if (tm->layerinfo[i].locked == STBTE__locked)\n            continue;\n\n         // if the layer is non-empty and protected, can't write to it\n         if (tm->layerinfo[i].locked == STBTE__protected && result[i] != STBTE__BG(tm,i))\n            continue;\n      }\n\n      result[i] = ti->id;\n      return;\n   }\n}\n\nstatic void stbte__brush(stbte_tilemap *tm, int x, int y)\n{\n   stbte__tileinfo *ti;\n\n   // find lowest legit layer to paint it on, and put it there\n   int i;\n\n   if (tm->cur_tile < 0) return;\n\n   ti = &tm->tiles[tm->cur_tile];\n\n   for (i=0; i < tm->num_layers; ++i) {\n      // check if object is allowed on layer\n      if (!(ti->layermask & (1 << i)))\n         continue;\n\n      if (i != tm->solo_layer) {\n         // if there's a selected layer, can only paint on that\n         if (tm->cur_layer >= 0 && i != tm->cur_layer)\n            continue;\n\n         // if the layer is hidden, we can't see it\n         if (tm->layerinfo[i].hidden)\n            continue;\n\n         // if the layer is locked, we can't write to it\n         if (tm->layerinfo[i].locked == STBTE__locked)\n            continue;\n\n         // if the layer is non-empty and protected, can't write to it\n         if (tm->layerinfo[i].locked == STBTE__protected && tm->data[y][x][i] != STBTE__BG(tm,i))\n            continue;\n      }\n\n      stbte__undo_record(tm,x,y,i,tm->data[y][x][i]);\n      tm->data[y][x][i] = ti->id;\n      return;\n   }\n\n   //stbte__alert(\"Selected tile not valid on active layer(s)\");\n}\n\nenum\n{\n   STBTE__erase_none = -1,\n   STBTE__erase_brushonly = 0,\n   STBTE__erase_any = 1,\n   STBTE__erase_all = 2,\n};\n\nstatic int stbte__erase_predict(stbte_tilemap *tm, short result[], int allow_any)\n{\n   stbte__tileinfo *ti = tm->cur_tile >= 0 ? &tm->tiles[tm->cur_tile] : NULL;\n   int i;\n\n   if (allow_any == STBTE__erase_none)\n      return allow_any;\n\n   // first check if only one layer is legit\n   i = tm->cur_layer;\n   if (tm->solo_layer >= 0)\n      i = tm->solo_layer;\n\n   // if only one layer is legit, directly process that one for clarity\n   if (i >= 0) {\n      short bg = (i == 0 ? tm->background_tile : -1);\n      if (tm->solo_layer < 0) {\n         // check that we're allowed to write to it\n         if (tm->layerinfo[i].hidden) return STBTE__erase_none;\n         if (tm->layerinfo[i].locked) return STBTE__erase_none;\n      }\n      if (result[i] == bg)\n         return STBTE__erase_none; // didn't erase anything\n      if (ti && result[i] == ti->id && (i != 0 || ti->id != tm->background_tile)) {\n         result[i] = bg;\n         return STBTE__erase_brushonly;\n      }\n      if (allow_any == STBTE__erase_any) {\n         result[i] = bg;\n         return STBTE__erase_any;\n      }\n      return STBTE__erase_none;\n   }\n\n   // if multiple layers are legit, first scan all for brush data\n\n   if (ti && allow_any != STBTE__erase_all) {\n      for (i=tm->num_layers-1; i >= 0; --i) {\n         if (result[i] != ti->id)\n            continue;\n         if (tm->layerinfo[i].locked || tm->layerinfo[i].hidden)\n            continue;\n         if (i == 0 && result[i] == tm->background_tile)\n            return STBTE__erase_none;\n         result[i] = STBTE__BG(tm,i);\n         return STBTE__erase_brushonly;\n      }\n   }\n\n   if (allow_any != STBTE__erase_any && allow_any != STBTE__erase_all)\n      return STBTE__erase_none;\n\n   // apply layer filters, erase from top\n   for (i=tm->num_layers-1; i >= 0; --i) {\n      if (result[i] < 0)\n         continue;\n      if (tm->layerinfo[i].locked || tm->layerinfo[i].hidden)\n         continue;\n      if (i == 0 && result[i] == tm->background_tile)\n         return STBTE__erase_none;\n      result[i] = STBTE__BG(tm,i);\n      if (allow_any != STBTE__erase_all)\n         return STBTE__erase_any;\n   }\n\n   if (allow_any == STBTE__erase_all)\n      return allow_any;\n   return STBTE__erase_none;\n}\n\nstatic int stbte__erase(stbte_tilemap *tm, int x, int y, int allow_any)\n{\n   stbte__tileinfo *ti = tm->cur_tile >= 0 ? &tm->tiles[tm->cur_tile] : NULL;\n   int i;\n\n   if (allow_any == STBTE__erase_none)\n      return allow_any;\n\n   // first check if only one layer is legit\n   i = tm->cur_layer;\n   if (tm->solo_layer >= 0)\n      i = tm->solo_layer;\n\n   // if only one layer is legit, directly process that one for clarity\n   if (i >= 0) {\n      short bg = (i == 0 ? tm->background_tile : -1);\n      if (tm->solo_layer < 0) {\n         // check that we're allowed to write to it\n         if (tm->layerinfo[i].hidden) return STBTE__erase_none;\n         if (tm->layerinfo[i].locked) return STBTE__erase_none;\n      }\n      if (tm->data[y][x][i] == bg)\n         return -1; // didn't erase anything\n      if (ti && tm->data[y][x][i] == ti->id && (i != 0 || ti->id != tm->background_tile)) {\n         stbte__undo_record(tm,x,y,i,tm->data[y][x][i]);\n         tm->data[y][x][i] = bg;\n         return STBTE__erase_brushonly;\n      }\n      if (allow_any == STBTE__erase_any) {\n         stbte__undo_record(tm,x,y,i,tm->data[y][x][i]);\n         tm->data[y][x][i] = bg;\n         return STBTE__erase_any;\n      }\n      return STBTE__erase_none;\n   }\n\n   // if multiple layers are legit, first scan all for brush data\n\n   if (ti && allow_any != STBTE__erase_all) {\n      for (i=tm->num_layers-1; i >= 0; --i) {\n         if (tm->data[y][x][i] != ti->id)\n            continue;\n         if (tm->layerinfo[i].locked || tm->layerinfo[i].hidden)\n            continue;\n         if (i == 0 && tm->data[y][x][i] == tm->background_tile)\n            return STBTE__erase_none;\n         stbte__undo_record(tm,x,y,i,tm->data[y][x][i]);\n         tm->data[y][x][i] = STBTE__BG(tm,i);\n         return STBTE__erase_brushonly;\n      }\n   }\n\n   if (allow_any != STBTE__erase_any && allow_any != STBTE__erase_all)\n      return STBTE__erase_none;\n\n   // apply layer filters, erase from top\n   for (i=tm->num_layers-1; i >= 0; --i) {\n      if (tm->data[y][x][i] < 0)\n         continue;\n      if (tm->layerinfo[i].locked || tm->layerinfo[i].hidden)\n         continue;\n      if (i == 0 && tm->data[y][x][i] == tm->background_tile)\n         return STBTE__erase_none;\n      stbte__undo_record(tm,x,y,i,tm->data[y][x][i]);\n      tm->data[y][x][i] = STBTE__BG(tm,i);\n      if (allow_any != STBTE__erase_all)\n         return STBTE__erase_any;\n   }\n   if (allow_any == STBTE__erase_all)\n      return allow_any;\n   return STBTE__erase_none;\n}\n\nstatic int stbte__find_tile(stbte_tilemap *tm, int tile_id)\n{\n   int i;\n   for (i=0; i < tm->num_tiles; ++i)\n      if (tm->tiles[i].id == tile_id)\n         return i;\n   stbte__alert(\"Eyedropped tile that isn't in tileset\");\n   return -1;\n}\n\nstatic void stbte__eyedrop(stbte_tilemap *tm, int x, int y)\n{\n   int i,j;\n\n   // flush eyedropper state\n   if (stbte__ui.eyedrop_x != x || stbte__ui.eyedrop_y != y) {\n      stbte__ui.eyedrop_x = x;\n      stbte__ui.eyedrop_y = y;\n      stbte__ui.eyedrop_last_layer = tm->num_layers;\n   }\n\n   // if only one layer is active, query that\n   i = tm->cur_layer;\n   if (tm->solo_layer >= 0)\n      i = tm->solo_layer;\n   if (i >= 0) {\n      if (tm->data[y][x][i] == STBTE__NO_TILE)\n         return;\n      tm->cur_tile = stbte__find_tile(tm, tm->data[y][x][i]);\n      return;\n   }\n\n   // if multiple layers, continue from previous\n   i = stbte__ui.eyedrop_last_layer;\n   for (j=0; j < tm->num_layers; ++j) {\n      if (--i < 0)\n         i = tm->num_layers-1;\n      if (tm->layerinfo[i].hidden)\n         continue;\n      if (tm->data[y][x][i] == STBTE__NO_TILE)\n         continue;\n      stbte__ui.eyedrop_last_layer = i;\n      tm->cur_tile = stbte__find_tile(tm, tm->data[y][x][i]);\n      return;\n   }\n}\n\nstatic int stbte__should_copy_properties(stbte_tilemap *tm)\n{\n   int i;\n   if (tm->propmode == STBTE__propmode_always)\n      return 1;\n   if (tm->propmode == STBTE__propmode_never)\n      return 0;\n   if (tm->solo_layer >= 0 || tm->cur_layer >= 0)\n      return 0;\n   for (i=0; i < tm->num_layers; ++i)\n      if (tm->layerinfo[i].hidden || tm->layerinfo[i].locked)\n         return 0;\n   return 1;\n}\n\n// compute the result of pasting into a tile non-destructively so we can preview it\nstatic void stbte__paste_stack(stbte_tilemap *tm, short result[], short dest[], short src[], int dragging)\n{\n   int i;\n\n   // special case single-layer\n   i = tm->cur_layer;\n   if (tm->solo_layer >= 0)\n      i = tm->solo_layer;\n   if (i >= 0) {\n      if (tm->solo_layer < 0) {\n         // check that we're allowed to write to it\n         if (tm->layerinfo[i].hidden) return;\n         if (tm->layerinfo[i].locked == STBTE__locked) return;\n         // if protected, dest has to be empty\n         if (tm->layerinfo[i].locked == STBTE__protected && dest[i] != STBTE__BG(tm,i)) return;\n         // if dragging w/o copy, we will try to erase stuff, which protection disallows\n         if (dragging && tm->layerinfo[i].locked == STBTE__protected)\n             return;\n      }\n      result[i] = dest[i];\n      if (src[i] != STBTE__BG(tm,i))\n         result[i] = src[i];\n      return;\n   }\n\n   for (i=0; i < tm->num_layers; ++i) {\n      result[i] = dest[i];\n      if (src[i] != STBTE__NO_TILE)\n         if (!tm->layerinfo[i].hidden && tm->layerinfo[i].locked != STBTE__locked)\n            if (tm->layerinfo[i].locked == STBTE__unlocked || (!dragging && dest[i] == STBTE__BG(tm,i)))\n               result[i] = src[i];\n   }\n}\n\n// compute the result of dragging away from a tile\nstatic void stbte__clear_stack(stbte_tilemap *tm, short result[])\n{\n   int i;\n   // special case single-layer\n   i = tm->cur_layer;\n   if (tm->solo_layer >= 0)\n      i = tm->solo_layer;\n   if (i >= 0)\n      result[i] = STBTE__BG(tm,i);\n   else\n      for (i=0; i < tm->num_layers; ++i)\n         if (!tm->layerinfo[i].hidden && tm->layerinfo[i].locked == STBTE__unlocked)\n            result[i] = STBTE__BG(tm,i);\n}\n\n// check if some map square is active\n#define STBTE__IS_MAP_ACTIVE()  ((stbte__ui.active_id & 127) == STBTE__map)\n#define STBTE__IS_MAP_HOT()     ((stbte__ui.hot_id & 127) == STBTE__map)\n\nstatic void stbte__fillrect(stbte_tilemap *tm, int x0, int y0, int x1, int y1, int fill)\n{\n   int i,j;\n\n   stbte__begin_undo(tm);\n   if (x0 > x1) i=x0,x0=x1,x1=i;\n   if (y0 > y1) j=y0,y0=y1,y1=j;\n   for (j=y0; j <= y1; ++j)\n      for (i=x0; i <= x1; ++i)\n         if (fill)\n            stbte__brush(tm, i,j);\n         else\n            stbte__erase(tm, i,j,STBTE__erase_any);\n   stbte__end_undo(tm);\n   // suppress warning from brush\n   stbte__ui.alert_msg = 0;\n}\n\nstatic void stbte__select_rect(stbte_tilemap *tm, int x0, int y0, int x1, int y1)\n{\n   stbte__ui.has_selection = 1;\n   stbte__ui.select_x0 = (x0 < x1 ? x0 : x1);\n   stbte__ui.select_x1 = (x0 < x1 ? x1 : x0);\n   stbte__ui.select_y0 = (y0 < y1 ? y0 : y1);\n   stbte__ui.select_y1 = (y0 < y1 ? y1 : y0);\n}\n\nstatic void stbte__copy_properties(float *dest, float *src)\n{\n   int i;\n   for (i=0; i < STBTE_MAX_PROPERTIES; ++i)\n      dest[i] = src[i];\n}\n\nstatic void stbte__copy_cut(stbte_tilemap *tm, int cut)\n{\n   int i,j,n,w,h,p=0;\n   int copy_props = stbte__should_copy_properties(tm);\n   if (!stbte__ui.has_selection)\n      return;\n   w = stbte__ui.select_x1 - stbte__ui.select_x0 + 1;\n   h = stbte__ui.select_y1 - stbte__ui.select_y0 + 1;\n   if (STBTE_MAX_COPY / w < h) {\n      stbte__alert(\"Selection too large for copy buffer, increase STBTE_MAX_COPY\");\n      return;\n   }\n\n   for (i=0; i < w*h; ++i)\n      for (n=0; n < tm->num_layers; ++n)\n         stbte__ui.copybuffer[i][n] = STBTE__NO_TILE;\n\n   if (cut)\n      stbte__begin_undo(tm);\n   for (j=stbte__ui.select_y0; j <= stbte__ui.select_y1; ++j) {\n      for (i=stbte__ui.select_x0; i <= stbte__ui.select_x1; ++i) {\n         for (n=0; n < tm->num_layers; ++n) {\n            if (tm->solo_layer >= 0) {\n               if (tm->solo_layer != n)\n                  continue;\n            } else {\n               if (tm->cur_layer >= 0)\n                  if (tm->cur_layer != n)\n                     continue;\n               if (tm->layerinfo[n].hidden)\n                  continue;\n               if (cut && tm->layerinfo[n].locked)\n                  continue;\n            }\n            stbte__ui.copybuffer[p][n] = tm->data[j][i][n];\n            if (cut) {\n               stbte__undo_record(tm,i,j,n, tm->data[j][i][n]);\n               tm->data[j][i][n] = (n==0 ? tm->background_tile : -1);\n            }\n         }\n         if (copy_props) {\n            stbte__copy_properties(stbte__ui.copyprops[p], tm->props[j][i]);\n#ifdef STBTE_ALLOW_LINK\n            stbte__ui.copylinks[p] = tm->link[j][i];\n            if (cut)\n               stbte__set_link(tm, i,j,-1,-1, STBTE__undo_record);\n#endif\n         }\n         ++p;\n      }\n   }\n   if (cut)\n      stbte__end_undo(tm);\n   stbte__ui.copy_width = w;\n   stbte__ui.copy_height = h;\n   stbte__ui.has_copy = 1;\n   //stbte__ui.has_selection = 0;\n   stbte__ui.copy_has_props = copy_props;\n   stbte__ui.copy_src = tm; // used to give better semantics when copying links\n   stbte__ui.copy_src_x = stbte__ui.select_x0;\n   stbte__ui.copy_src_y = stbte__ui.select_y0;\n}\n\nstatic int stbte__in_rect(int x, int y, int x0, int y0, int w, int h)\n{\n   return x >= x0 && x < x0+w && y >= y0 && y < y0+h;\n}\n\n#ifdef STBTE_ALLOW_LINK\nstatic int stbte__in_src_rect(int x, int y)\n{\n   return stbte__in_rect(x,y, stbte__ui.copy_src_x, stbte__ui.copy_src_y, stbte__ui.copy_width, stbte__ui.copy_height);\n}\n\nstatic int stbte__in_dest_rect(int x, int y, int destx, int desty)\n{\n   return stbte__in_rect(x,y, destx, desty, stbte__ui.copy_width, stbte__ui.copy_height);\n}\n#endif\n\nstatic void stbte__paste(stbte_tilemap *tm, int mapx, int mapy)\n{\n   int w = stbte__ui.copy_width;\n   int h = stbte__ui.copy_height;\n   int i,j,k,p;\n   int x = mapx - (w>>1);\n   int y = mapy - (h>>1);\n   int copy_props = stbte__should_copy_properties(tm) && stbte__ui.copy_has_props;\n   if (stbte__ui.has_copy == 0)\n      return;\n   stbte__begin_undo(tm);\n   p = 0;\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i) {\n         if (y+j >= 0 && y+j < tm->max_y && x+i >= 0 && x+i < tm->max_x) {\n            // compute the new stack\n            short tilestack[STBTE_MAX_LAYERS];\n            for (k=0; k < tm->num_layers; ++k)\n               tilestack[k] = tm->data[y+j][x+i][k];\n            stbte__paste_stack(tm, tilestack, tilestack, stbte__ui.copybuffer[p], 0);\n            // update anything that changed\n            for (k=0; k < tm->num_layers; ++k) {\n               if (tilestack[k] != tm->data[y+j][x+i][k]) {\n                  stbte__undo_record(tm, x+i,y+j,k, tm->data[y+j][x+i][k]);\n                  tm->data[y+j][x+i][k] = tilestack[k];\n               }\n            }\n         }\n         if (copy_props) {\n#ifdef STBTE_ALLOW_LINK\n            // need to decide how to paste a link, so there's a few cases\n            int destx = -1, desty = -1;\n            stbte__link *link = &stbte__ui.copylinks[p];\n\n            // check if link is within-rect\n            if (stbte__in_src_rect(link->x, link->y)) {\n               // new link should point to copy (but only if copy is within map)\n               destx = x + (link->x - stbte__ui.copy_src_x);\n               desty = y + (link->y - stbte__ui.copy_src_y);\n            } else if (tm == stbte__ui.copy_src) {\n               // if same map, then preserve link unless target is overwritten\n               if (!stbte__in_dest_rect(link->x,link->y,x,y)) {\n                  destx = link->x;\n                  desty = link->y;\n               }\n            }\n            // this is necessary for offset-copy, but also in case max_x/max_y has changed\n            if (destx < 0 || destx >= tm->max_x || desty < 0 || desty >= tm->max_y)\n               destx = -1, desty = -1;\n            stbte__set_link(tm, x+i, y+j, destx, desty, STBTE__undo_record);\n#endif\n            for (k=0; k < STBTE_MAX_PROPERTIES; ++k) {\n               if (tm->props[y+j][x+i][k] != stbte__ui.copyprops[p][k])\n                  stbte__undo_record_prop_float(tm, x+i, y+j, k, tm->props[y+j][x+i][k]);\n            }\n            stbte__copy_properties(tm->props[y+j][x+i], stbte__ui.copyprops[p]);\n         }\n         ++p;\n      }\n   }\n   stbte__end_undo(tm);\n}\n\nstatic void stbte__drag_update(stbte_tilemap *tm, int mapx, int mapy, int copy_props)\n{\n   int w = stbte__ui.drag_w, h = stbte__ui.drag_h;\n   int ox,oy,i,deleted=0,written=0;\n   short temp[STBTE_MAX_LAYERS];\n   short *data = NULL;\n\n   STBTE__NOTUSED(deleted);\n   STBTE__NOTUSED(written);\n\n   if (!stbte__ui.shift) {\n      ox = mapx - stbte__ui.drag_x;\n      oy = mapy - stbte__ui.drag_y;\n      if (ox >= 0 && ox < w && oy >= 0 && oy < h) {\n         deleted=1;\n         for (i=0; i < tm->num_layers; ++i)\n            temp[i] = tm->data[mapy][mapx][i];\n         data = temp;\n         stbte__clear_stack(tm, data);\n      }\n   }\n   ox = mapx - stbte__ui.drag_dest_x;\n   oy = mapy - stbte__ui.drag_dest_y;\n   // if this map square is in the target drag region\n   if (ox >= 0 && ox < w && oy >= 0 && oy < h) {\n      // and the src map square is on the map\n      if (stbte__in_rect(stbte__ui.drag_x+ox, stbte__ui.drag_y+oy, 0, 0, tm->max_x, tm->max_y)) {\n         written = 1;\n         if (data == NULL) {\n            for (i=0; i < tm->num_layers; ++i)\n               temp[i] = tm->data[mapy][mapx][i];\n            data = temp;\n         }\n         stbte__paste_stack(tm, data, data, tm->data[stbte__ui.drag_y+oy][stbte__ui.drag_x+ox], !stbte__ui.shift);\n         if (copy_props) {\n            for (i=0; i < STBTE_MAX_PROPERTIES; ++i) {\n               if (tm->props[mapy][mapx][i] != tm->props[stbte__ui.drag_y+oy][stbte__ui.drag_x+ox][i]) {\n                  stbte__undo_record_prop_float(tm, mapx, mapy, i, tm->props[mapy][mapx][i]);\n                  tm->props[mapy][mapx][i] = tm->props[stbte__ui.drag_y+oy][stbte__ui.drag_x+ox][i];\n               }\n            }\n         }\n      }\n   }\n   if (data) {\n      for (i=0; i < tm->num_layers; ++i) {\n         if (tm->data[mapy][mapx][i] != data[i]) {\n            stbte__undo_record(tm, mapx, mapy, i, tm->data[mapy][mapx][i]);\n            tm->data[mapy][mapx][i] = data[i];\n         }\n      }\n   }\n   #ifdef STBTE_ALLOW_LINK\n   if (copy_props) {\n      int overwritten=0, moved=0, copied=0;\n      // since this function is called on EVERY tile, we can fix up even tiles not\n      // involved in the move\n\n      stbte__link *k;\n      // first, determine what src link ends up here\n      k = &tm->link[mapy][mapx]; // by default, it's the one currently here\n      if (deleted)               // if dragged away, it's erased\n         k = NULL;\n      if (written)               // if dragged into, it gets that link\n         k = &tm->link[stbte__ui.drag_y+oy][stbte__ui.drag_x+ox];\n\n      // now check whether the *target* gets moved or overwritten\n      if (k && k->x >= 0) {\n         overwritten = stbte__in_rect(k->x, k->y, stbte__ui.drag_dest_x, stbte__ui.drag_dest_y, w, h);\n         if (!stbte__ui.shift)\n            moved    = stbte__in_rect(k->x, k->y, stbte__ui.drag_x     , stbte__ui.drag_y     , w, h);\n         else\n            copied   = stbte__in_rect(k->x, k->y, stbte__ui.drag_x     , stbte__ui.drag_y     , w, h);\n      }\n\n      if (deleted || written || overwritten || moved || copied) {\n         // choose the final link value based on the above\n         if (k == NULL || k->x < 0)\n            stbte__set_link(tm, mapx, mapy, -1, -1, STBTE__undo_record);\n         else if (moved || (copied && written)) {\n            // if we move the target, we update to point to the new target;\n            // or, if we copy the target and the source is part of the copy, then update to new target\n            int x = k->x + (stbte__ui.drag_dest_x - stbte__ui.drag_x);\n            int y = k->y + (stbte__ui.drag_dest_y - stbte__ui.drag_y);\n            if (!(x >= 0 && y >= 0 && x < tm->max_x && y < tm->max_y))\n               x = -1, y = -1;\n            stbte__set_link(tm, mapx, mapy, x, y, STBTE__undo_record);\n         } else if (overwritten) {\n            stbte__set_link(tm, mapx, mapy, -1, -1, STBTE__undo_record);\n         } else\n            stbte__set_link(tm, mapx, mapy, k->x, k->y, STBTE__undo_record);\n      }\n   }\n   #endif\n}\n\nstatic void stbte__drag_place(stbte_tilemap *tm, int mapx, int mapy)\n{\n   int i,j;\n   int copy_props = stbte__should_copy_properties(tm);\n   int move_x = (stbte__ui.drag_dest_x - stbte__ui.drag_x);\n   int move_y = (stbte__ui.drag_dest_y - stbte__ui.drag_y);\n   if (move_x == 0 && move_y == 0)\n      return;\n\n   stbte__begin_undo(tm);\n   // we now need a 2D memmove-style mover that doesn't\n   // overwrite any data as it goes. this requires being\n   // direction sensitive in the same way as memmove\n   if (move_y > 0 || (move_y == 0 && move_x > 0)) {\n      for (j=tm->max_y-1; j >= 0; --j)\n         for (i=tm->max_x-1; i >= 0; --i)\n            stbte__drag_update(tm,i,j,copy_props);\n   } else {\n      for (j=0; j < tm->max_y; ++j)\n         for (i=0; i < tm->max_x; ++i)\n            stbte__drag_update(tm,i,j,copy_props);\n   }\n   stbte__end_undo(tm);\n\n   stbte__ui.has_selection = 1;\n   stbte__ui.select_x0 = stbte__ui.drag_dest_x;\n   stbte__ui.select_y0 = stbte__ui.drag_dest_y;\n   stbte__ui.select_x1 = stbte__ui.select_x0 + stbte__ui.drag_w - 1;\n   stbte__ui.select_y1 = stbte__ui.select_y0 + stbte__ui.drag_h - 1;\n}\n\nstatic void stbte__tile_paint(stbte_tilemap *tm, int sx, int sy, int mapx, int mapy, int layer)\n{\n   int i;\n   int id = STBTE__IDMAP(mapx,mapy);\n   int x0=sx, y0=sy;\n   int x1=sx+tm->spacing_x, y1=sy+tm->spacing_y;\n   stbte__hittest(x0,y0,x1,y1, id);\n   short *data = tm->data[mapy][mapx];\n   short temp[STBTE_MAX_LAYERS];\n\n   if (STBTE__IS_MAP_HOT()) {\n      if (stbte__ui.pasting) {\n         int ox = mapx - stbte__ui.paste_x;\n         int oy = mapy - stbte__ui.paste_y;\n         if (ox >= 0 && ox < stbte__ui.copy_width && oy >= 0 && oy < stbte__ui.copy_height) {\n            stbte__paste_stack(tm, temp, tm->data[mapy][mapx], stbte__ui.copybuffer[oy*stbte__ui.copy_width+ox], 0);\n            data = temp;\n         }\n      } else if (stbte__ui.dragging) {\n         int ox,oy;\n         for (i=0; i < tm->num_layers; ++i)\n            temp[i] = tm->data[mapy][mapx][i];\n         data = temp;\n\n         // if it's in the source area, remove things unless shift-dragging\n         ox = mapx - stbte__ui.drag_x;\n         oy = mapy - stbte__ui.drag_y;\n         if (!stbte__ui.shift && ox >= 0 && ox < stbte__ui.drag_w && oy >= 0 && oy < stbte__ui.drag_h) {\n            stbte__clear_stack(tm, temp);\n         }\n\n         ox = mapx - stbte__ui.drag_dest_x;\n         oy = mapy - stbte__ui.drag_dest_y;\n         if (ox >= 0 && ox < stbte__ui.drag_w && oy >= 0 && oy < stbte__ui.drag_h) {\n            stbte__paste_stack(tm, temp, temp, tm->data[stbte__ui.drag_y+oy][stbte__ui.drag_x+ox], !stbte__ui.shift);\n         }\n      } else if (STBTE__IS_MAP_ACTIVE()) {\n         if (stbte__ui.tool == STBTE__tool_rect) {\n            if ((stbte__ui.ms_time & 511) < 380) {\n               int ex = ((stbte__ui.hot_id >> 19) & 4095);\n               int ey = ((stbte__ui.hot_id >>  7) & 4095);\n               int sx = stbte__ui.sx;\n               int sy = stbte__ui.sy;\n\n               if (   ((mapx >= sx && mapx < ex+1) || (mapx >= ex && mapx < sx+1))\n                   && ((mapy >= sy && mapy < ey+1) || (mapy >= ey && mapy < sy+1))) {\n                  int i;\n                  for (i=0; i < tm->num_layers; ++i)\n                     temp[i] = tm->data[mapy][mapx][i];\n                  data = temp;\n                  if (stbte__ui.active_event == STBTE__leftdown)\n                     stbte__brush_predict(tm, temp);\n                  else\n                     stbte__erase_predict(tm, temp, STBTE__erase_any);\n               }\n            }\n         }\n      }\n   }\n\n   if (STBTE__IS_HOT(id) && STBTE__INACTIVE() && !stbte__ui.pasting) {\n      if (stbte__ui.tool == STBTE__tool_brush) {\n         if ((stbte__ui.ms_time & 511) < 300) {\n            data = temp;\n            for (i=0; i < tm->num_layers; ++i)\n               temp[i] = tm->data[mapy][mapx][i];\n            stbte__brush_predict(tm, temp);\n         }\n      }\n   }\n\n   {\n      i = layer;\n      if (i == tm->solo_layer || (!tm->layerinfo[i].hidden && tm->solo_layer < 0))\n         if (data[i] >= 0)\n            STBTE_DRAW_TILE(sx,sy, (unsigned short) data[i], 0, tm->props[mapy][mapx]);\n   }\n}\n\nstatic void stbte__tile(stbte_tilemap *tm, int sx, int sy, int mapx, int mapy)\n{\n   int tool = stbte__ui.tool;\n   int x0=sx, y0=sy;\n   int x1=sx+tm->spacing_x, y1=sy+tm->spacing_y;\n   int id = STBTE__IDMAP(mapx,mapy);\n   int over = stbte__hittest(x0,y0,x1,y1, id);\n   switch (stbte__ui.event) {\n      case STBTE__paint: {\n         if (stbte__ui.pasting || stbte__ui.dragging || stbte__ui.scrolling)\n            break;\n         if (stbte__ui.scrollkey && !STBTE__IS_MAP_ACTIVE())\n            break;\n         if (STBTE__IS_HOT(id) && STBTE__IS_MAP_ACTIVE() && (tool == STBTE__tool_rect || tool == STBTE__tool_select)) {\n            int rx0,ry0,rx1,ry1,t;\n            // compute the center of each rect\n            rx0 = x0 + tm->spacing_x/2;\n            ry0 = y0 + tm->spacing_y/2;\n            rx1 = rx0 + (stbte__ui.sx - mapx) * tm->spacing_x;\n            ry1 = ry0 + (stbte__ui.sy - mapy) * tm->spacing_y;\n            if (rx0 > rx1) t=rx0,rx0=rx1,rx1=t;\n            if (ry0 > ry1) t=ry0,ry0=ry1,ry1=t;\n            rx0 -= tm->spacing_x/2;\n            ry0 -= tm->spacing_y/2;\n            rx1 += tm->spacing_x/2;\n            ry1 += tm->spacing_y/2;\n            stbte__draw_frame(rx0-1,ry0-1,rx1+1,ry1+1, STBTE_COLOR_TILEMAP_HIGHLIGHT);\n            break;\n         }\n         if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n            stbte__draw_frame(x0-1,y0-1,x1+1,y1+1, STBTE_COLOR_TILEMAP_HIGHLIGHT);\n         }\n#ifdef STBTE_ALLOW_LINK\n         if (stbte__ui.show_links && tm->link[mapy][mapx].x >= 0) {\n            int tx = tm->link[mapy][mapx].x;\n            int ty = tm->link[mapy][mapx].y;\n            int lx0,ly0,lx1,ly1;\n            if (STBTE_ALLOW_LINK(tm->data[mapy][mapx], tm->props[mapy][mapx],\n                                 tm->data[ty  ][tx  ], tm->props[ty  ][tx  ]))\n            {\n               lx0 =  x0 + (tm->spacing_x >> 1) - 1;\n               ly0 =  y0 + (tm->spacing_y >> 1) - 1;\n               lx1 = lx0 + (tx - mapx) * tm->spacing_x + 2;\n               ly1 = ly0 + (ty - mapy) * tm->spacing_y + 2;\n               stbte__draw_link(lx0,ly0,lx1,ly1,\n                   STBTE_LINK_COLOR(tm->data[mapy][mapx], tm->props[mapy][mapx],\n                                    tm->data[ty  ][tx  ], tm->props[ty  ][tx]));\n            }\n         }\n#endif\n         break;\n      }\n   }\n\n   if (stbte__ui.pasting) {\n      switch (stbte__ui.event) {\n         case STBTE__leftdown:\n            if (STBTE__IS_HOT(id)) {\n               stbte__ui.pasting = 0;\n               stbte__paste(tm, mapx, mapy);\n               stbte__activate(0);\n            }\n            break;\n         case STBTE__leftup:\n            // just clear it no matter what, since they might click away to clear it\n            stbte__activate(0);\n            break;\n         case STBTE__rightdown:\n            if (STBTE__IS_HOT(id)) {\n               stbte__activate(0);\n               stbte__ui.pasting = 0;\n            }\n            break;\n      }\n      return;\n   }\n\n   if (stbte__ui.scrolling) {\n      if (stbte__ui.event == STBTE__leftup) {\n         stbte__activate(0);\n         stbte__ui.scrolling = 0;\n      }\n      if (stbte__ui.event == STBTE__mousemove) {\n         tm->scroll_x += (stbte__ui.start_x - stbte__ui.mx);\n         tm->scroll_y += (stbte__ui.start_y - stbte__ui.my);\n         stbte__ui.start_x = stbte__ui.mx;\n         stbte__ui.start_y = stbte__ui.my;\n      }\n      return;\n   }\n\n   // regardless of tool, leftdown is a scrolldrag\n   if (STBTE__IS_HOT(id) && stbte__ui.scrollkey && stbte__ui.event == STBTE__leftdown) {\n      stbte__ui.scrolling = 1;\n      stbte__ui.start_x = stbte__ui.mx;\n      stbte__ui.start_y = stbte__ui.my;\n      return;\n   }\n\n   switch (tool) {\n      case STBTE__tool_brush:\n         switch (stbte__ui.event) {\n            case STBTE__mousemove:\n               if (STBTE__IS_MAP_ACTIVE() && over) {\n                  // don't brush/erase same tile multiple times unless they move away and back @TODO should just be only once, but that needs another data structure\n                  if (!STBTE__IS_ACTIVE(id)) {\n                     if (stbte__ui.active_event == STBTE__leftdown)\n                        stbte__brush(tm, mapx, mapy);\n                     else\n                        stbte__erase(tm, mapx, mapy, stbte__ui.brush_state);\n                     stbte__ui.active_id = id; // switch to this map square so we don't rebrush IT multiple times\n                  }\n               }\n               break;\n            case STBTE__leftdown:\n               if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n                  stbte__activate(id);\n                  stbte__begin_undo(tm);\n                  stbte__brush(tm, mapx, mapy);\n               }\n               break;\n            case STBTE__rightdown:\n               if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n                  stbte__activate(id);\n                  stbte__begin_undo(tm);\n                  if (stbte__erase(tm, mapx, mapy, STBTE__erase_any) == STBTE__erase_brushonly)\n                     stbte__ui.brush_state = STBTE__erase_brushonly;\n                  else\n                     stbte__ui.brush_state = STBTE__erase_any;\n               }\n               break;\n            case STBTE__leftup:\n            case STBTE__rightup:\n               if (STBTE__IS_MAP_ACTIVE()) {\n                  stbte__end_undo(tm);\n                  stbte__activate(0);\n               }\n               break;\n         }\n         break;\n\n#ifdef STBTE_ALLOW_LINK\n      case STBTE__tool_link:\n         switch (stbte__ui.event) {\n            case STBTE__leftdown:\n               if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n                  stbte__activate(id);\n                  stbte__ui.linking = 1;\n                  stbte__ui.sx = mapx;\n                  stbte__ui.sy = mapy;\n                  // @TODO: undo\n               }\n               break;\n            case STBTE__leftup:\n               if (STBTE__IS_HOT(id) && STBTE__IS_MAP_ACTIVE()) {\n                  if ((mapx != stbte__ui.sx || mapy != stbte__ui.sy) &&\n                         STBTE_ALLOW_LINK(tm->data[stbte__ui.sy][stbte__ui.sx], tm->props[stbte__ui.sy][stbte__ui.sx],\n                                          tm->data[mapy][mapx], tm->props[mapy][mapx]))\n                     stbte__set_link(tm, stbte__ui.sx, stbte__ui.sy, mapx, mapy, STBTE__undo_block);\n                  else\n                     stbte__set_link(tm, stbte__ui.sx, stbte__ui.sy, -1,-1, STBTE__undo_block);\n                  stbte__ui.linking = 0;\n                  stbte__activate(0);\n               }\n               break;\n\n            case STBTE__rightdown:\n               if (STBTE__IS_ACTIVE(id)) {\n                  stbte__activate(0);\n                  stbte__ui.linking = 0;\n               }\n               break;\n         }\n         break;\n#endif\n\n      case STBTE__tool_erase:\n         switch (stbte__ui.event) {\n            case STBTE__mousemove:\n               if (STBTE__IS_MAP_ACTIVE() && over)\n                  stbte__erase(tm, mapx, mapy, STBTE__erase_all);\n               break;\n            case STBTE__leftdown:\n               if (STBTE__IS_HOT(id) && STBTE__INACTIVE()) {\n                  stbte__activate(id);\n                  stbte__begin_undo(tm);\n                  stbte__erase(tm, mapx, mapy, STBTE__erase_all);\n               }\n               break;\n            case STBTE__leftup:\n               if (STBTE__IS_MAP_ACTIVE()) {\n                  stbte__end_undo(tm);\n                  stbte__activate(0);\n               }\n               break;\n         }\n         break;\n\n      case STBTE__tool_select:\n         if (STBTE__IS_HOT(id)) {\n            switch (stbte__ui.event) {\n               case STBTE__leftdown:\n                  if (STBTE__INACTIVE()) {\n                     // if we're clicking in an existing selection...\n                     if (stbte__ui.has_selection) {\n                        if (  mapx >= stbte__ui.select_x0 && mapx <= stbte__ui.select_x1\n                           && mapy >= stbte__ui.select_y0 && mapy <= stbte__ui.select_y1)\n                        {\n                           stbte__ui.dragging = 1;\n                           stbte__ui.drag_x = stbte__ui.select_x0;\n                           stbte__ui.drag_y = stbte__ui.select_y0;\n                           stbte__ui.drag_w = stbte__ui.select_x1 - stbte__ui.select_x0 + 1;\n                           stbte__ui.drag_h = stbte__ui.select_y1 - stbte__ui.select_y0 + 1;\n                           stbte__ui.drag_offx = mapx - stbte__ui.select_x0;\n                           stbte__ui.drag_offy = mapy - stbte__ui.select_y0;\n                        }\n                     }\n                     stbte__ui.has_selection = 0; // no selection until it completes\n                     stbte__activate_map(mapx,mapy);\n                  }\n                  break;\n               case STBTE__leftup:\n                  if (STBTE__IS_MAP_ACTIVE()) {\n                     if (stbte__ui.dragging) {\n                        stbte__drag_place(tm, mapx,mapy);\n                        stbte__ui.dragging = 0;\n                        stbte__activate(0);\n                     } else {\n                        stbte__select_rect(tm, stbte__ui.sx, stbte__ui.sy, mapx, mapy);\n                        stbte__activate(0);\n                     }\n                  }\n                  break;\n               case STBTE__rightdown:\n                  stbte__ui.has_selection = 0;\n                  break;\n            }\n         }\n         break;\n\n      case STBTE__tool_rect:\n         if (STBTE__IS_HOT(id)) {\n            switch (stbte__ui.event) {\n               case STBTE__leftdown:\n                  if (STBTE__INACTIVE())\n                     stbte__activate_map(mapx,mapy);\n                  break;\n               case STBTE__leftup:\n                  if (STBTE__IS_MAP_ACTIVE()) {\n                     stbte__fillrect(tm, stbte__ui.sx, stbte__ui.sy, mapx, mapy, 1);\n                     stbte__activate(0);\n                  }\n                  break;\n               case STBTE__rightdown:\n                  if (STBTE__INACTIVE())\n                     stbte__activate_map(mapx,mapy);\n                  break;\n               case STBTE__rightup:\n                  if (STBTE__IS_MAP_ACTIVE()) {\n                     stbte__fillrect(tm, stbte__ui.sx, stbte__ui.sy, mapx, mapy, 0);\n                     stbte__activate(0);\n                  }\n                  break;\n            }\n         }\n         break;\n\n\n      case STBTE__tool_eyedrop:\n         switch (stbte__ui.event) {\n            case STBTE__leftdown:\n               if (STBTE__IS_HOT(id) && STBTE__INACTIVE())\n                  stbte__eyedrop(tm,mapx,mapy);\n               break;\n         }\n         break;\n   }\n}\n\nstatic void stbte__start_paste(stbte_tilemap *tm)\n{\n   if (stbte__ui.has_copy) {\n      stbte__ui.pasting = 1;\n      stbte__activate(STBTE__ID(STBTE__toolbarB,3));\n   }\n}\n\nstatic void stbte__toolbar(stbte_tilemap *tm, int x0, int y0, int w, int h)\n{\n   int i;\n   int estimated_width = 13 * STBTE__num_tool + 8+8+ 120+4 - 30;\n   int x = x0 + w/2 - estimated_width/2;\n   int y = y0+1;\n\n   for (i=0; i < STBTE__num_tool; ++i) {\n      int highlight=0, disable=0;\n      highlight = (stbte__ui.tool == i);\n      if (i == STBTE__tool_undo || i == STBTE__tool_showgrid)\n          x += 8;\n      if (i == STBTE__tool_showgrid && stbte__ui.show_grid)\n         highlight = 1;\n      if (i == STBTE__tool_showlinks && stbte__ui.show_links)\n         highlight = 1;\n      if (i == STBTE__tool_fill)\n         continue;\n      #ifndef STBTE_ALLOW_LINK\n      if (i == STBTE__tool_link || i == STBTE__tool_showlinks)\n         disable = 1;\n      #endif\n      if (i == STBTE__tool_undo && !stbte__undo_available(tm))\n         disable = 1;\n      if (i == STBTE__tool_redo && !stbte__redo_available(tm))\n         disable = 1;\n      if (stbte__button_icon(STBTE__ctoolbar_button, toolchar[i], x, y, 13, STBTE__ID(STBTE__toolbarA, i), highlight, disable)) {\n         switch (i) {\n            case STBTE__tool_eyedrop:\n               stbte__ui.eyedrop_last_layer = tm->num_layers; // flush eyedropper state\n               // fallthrough\n            default:\n               stbte__ui.tool = i;\n               stbte__ui.has_selection = 0;\n               break;\n            case STBTE__tool_showlinks:\n               stbte__ui.show_links = !stbte__ui.show_links;\n               break;\n            case STBTE__tool_showgrid:\n               stbte__ui.show_grid = (stbte__ui.show_grid+1)%3;\n               break;\n            case STBTE__tool_undo:\n               stbte__undo(tm);\n               break;\n            case STBTE__tool_redo:\n               stbte__redo(tm);\n               break;\n         }\n      }\n      x += 13;\n   }\n\n   x += 8;\n   if (stbte__button(STBTE__ctoolbar_button, \"cut\"  , x, y,10, 40, STBTE__ID(STBTE__toolbarB,0), 0, !stbte__ui.has_selection))\n      stbte__copy_cut(tm, 1);\n   x += 42;\n   if (stbte__button(STBTE__ctoolbar_button, \"copy\" , x, y, 5, 40, STBTE__ID(STBTE__toolbarB,1), 0, !stbte__ui.has_selection))\n      stbte__copy_cut(tm, 0);\n   x += 42;\n   if (stbte__button(STBTE__ctoolbar_button, \"paste\", x, y, 0, 40, STBTE__ID(STBTE__toolbarB,2), stbte__ui.pasting, !stbte__ui.has_copy))\n      stbte__start_paste(tm);\n}\n\n#define STBTE__TEXTCOLOR(n)  stbte__color_table[n][STBTE__text][STBTE__idle]\n\nstatic int stbte__info_value(const char *label, int x, int y, int val, int digits, int id)\n{\n   if (stbte__ui.event == STBTE__paint) {\n      int off = 9-stbte__get_char_width(label[0]);\n      char text[16];\n      stbte__sprintf(text stbte__sizeof(text), label, digits, val);\n      stbte__draw_text_core(x+off,y, text, 999, STBTE__TEXTCOLOR(STBTE__cpanel),1);\n   }\n   if (id) {\n      x += 9+7*digits+4;\n      if (stbte__minibutton(STBTE__cmapsize, x,y, '+', STBTE__ID2(id,1,0)))\n         val += (stbte__ui.shift ? 10 : 1);\n      x += 9;\n      if (stbte__minibutton(STBTE__cmapsize, x,y, '-', STBTE__ID2(id,2,0)))\n         val -= (stbte__ui.shift ? 10 : 1);\n      if (val < 1) val = 1; else if (val > 4096) val = 4096;\n   }\n   return val;\n}\n\nstatic void stbte__info(stbte_tilemap *tm, int x0, int y0, int w, int h)\n{\n   int mode = stbte__ui.panel[STBTE__panel_info].mode;\n   int s = 11+7*tm->digits+4+15;\n   int x,y;\n   int in_region;\n\n   x = x0+2;\n   y = y0+2;\n   tm->max_x = stbte__info_value(\"w:%*d\",x,y, tm->max_x, tm->digits, STBTE__ID(STBTE__info,0));\n   if (mode)\n      x += s;\n   else\n      y += 11;\n   tm->max_y = stbte__info_value(\"h:%*d\",x,y, tm->max_y, tm->digits, STBTE__ID(STBTE__info,1));\n   x = x0+2;\n   y += 11;\n   in_region = (stbte__ui.hot_id & 127) == STBTE__map;\n   stbte__info_value(in_region ? \"x:%*d\" : \"x:\",x,y, (stbte__ui.hot_id>>19)&4095, tm->digits, 0);\n   if (mode)\n      x += s;\n   else\n      y += 11;\n   stbte__info_value(in_region ? \"y:%*d\" : \"y:\",x,y, (stbte__ui.hot_id>> 7)&4095, tm->digits, 0);\n   y += 15;\n   x = x0+2;\n   stbte__draw_text(x,y,\"brush:\",40,STBTE__TEXTCOLOR(STBTE__cpanel));\n   if (tm->cur_tile >= 0)\n      STBTE_DRAW_TILE(x+43,y-3,tm->tiles[tm->cur_tile].id,1,0);\n}\n\nstatic void stbte__layers(stbte_tilemap *tm, int x0, int y0, int w, int h)\n{\n   static const char *propmodes[3] = {\n      \"default\", \"always\", \"never\"\n   };\n   int num_rows;\n   int i, y, n;\n   int x1 = x0+w;\n   int y1 = y0+h;\n   int xoff = 20;\n\n   if (tm->has_layer_names) {\n      int side = stbte__ui.panel[STBTE__panel_layers].side;\n      xoff = stbte__region[side].width - 42;\n      xoff = (xoff < tm->layername_width + 10 ? xoff : tm->layername_width + 10);\n   }\n\n   x0 += 2;\n   y0 += 5;\n   if (!tm->has_layer_names) {\n      if (stbte__ui.event == STBTE__paint) {\n         stbte__draw_text(x0,y0, \"Layers\", w-4, STBTE__TEXTCOLOR(STBTE__cpanel));\n      }\n      y0 += 11;\n   }\n   num_rows = (y1-y0)/15;\n#ifndef STBTE_NO_PROPS\n   --num_rows;\n#endif\n   y = y0;\n   for (i=0; i < tm->num_layers; ++i) {\n      char text[3], *str = (char *) tm->layerinfo[i].name;\n      static char lockedchar[3] = { 'U', 'P', 'L' };\n      int locked = tm->layerinfo[i].locked;\n      int disabled = (tm->solo_layer >= 0 && tm->solo_layer != i);\n      if (i-tm->layer_scroll >= 0 && i-tm->layer_scroll < num_rows) {\n         if (str == NULL)\n            stbte__sprintf(str=text stbte__sizeof(text), \"%2d\", i+1);\n         if (stbte__button(STBTE__clayer_button, str, x0,y,(i+1<10)*2,xoff-2, STBTE__ID(STBTE__layer,i), tm->cur_layer==i,0))\n            tm->cur_layer = (tm->cur_layer == i ? -1 : i);\n         if (stbte__layerbutton(x0+xoff +  0,y+1,'H',STBTE__ID(STBTE__hide,i), tm->layerinfo[i].hidden,disabled,STBTE__clayer_hide))\n            tm->layerinfo[i].hidden = !tm->layerinfo[i].hidden;\n         if (stbte__layerbutton(x0+xoff + 12,y+1,lockedchar[locked],STBTE__ID(STBTE__lock,i), locked!=0,disabled,STBTE__clayer_lock))\n            tm->layerinfo[i].locked = (locked+1)%3;\n         if (stbte__layerbutton(x0+xoff + 24,y+1,'S',STBTE__ID(STBTE__solo,i), tm->solo_layer==i,0,STBTE__clayer_solo))\n            tm->solo_layer = (tm->solo_layer == i ? -1 : i);\n         y += 15;\n      }\n   }\n   stbte__scrollbar(x1-4, y0,y-2, &tm->layer_scroll, 0, tm->num_layers, num_rows, STBTE__ID(STBTE__scrollbar_id, STBTE__layer));\n#ifndef STBTE_NO_PROPS\n   n = stbte__text_width(\"prop:\")+2;\n   stbte__draw_text(x0,y+2, \"prop:\", w, STBTE__TEXTCOLOR(STBTE__cpanel));\n   i = w - n - 4;\n   if (i > 50) i = 50;\n   if (stbte__button(STBTE__clayer_button, propmodes[tm->propmode], x0+n,y,0,i, STBTE__ID(STBTE__layer,256), 0,0))\n      tm->propmode = (tm->propmode+1)%3;\n#endif\n}\n\nstatic void stbte__categories(stbte_tilemap *tm, int x0, int y0, int w, int h)\n{\n   int s=11, x,y, i;\n   int num_rows = h / s;\n\n   w -= 4;\n   x = x0+2;\n   y = y0+4;\n   if (tm->category_scroll == 0) {\n      if (stbte__category_button(\"*ALL*\", x,y, w, STBTE__ID(STBTE__categories, 65535), tm->cur_category == -1)) {\n         stbte__choose_category(tm, -1);\n      }\n      y += s;\n   }\n\n   for (i=0; i < tm->num_categories; ++i) {\n      if (i+1 - tm->category_scroll >= 0 && i+1 - tm->category_scroll < num_rows) {\n         if (y + 10 > y0+h)\n            return;\n         if (stbte__category_button(tm->categories[i], x,y,w, STBTE__ID(STBTE__categories,i), tm->cur_category == i))\n            stbte__choose_category(tm, i);\n         y += s;\n      }\n   }\n   stbte__scrollbar(x0+w, y0+4, y0+h-4, &tm->category_scroll, 0, tm->num_categories+1, num_rows, STBTE__ID(STBTE__scrollbar_id, STBTE__categories));\n}\n\nstatic void stbte__tile_in_palette(stbte_tilemap *tm, int x, int y, int slot)\n{\n   stbte__tileinfo *t = &tm->tiles[slot];\n   int x0=x, y0=y, x1 = x+tm->palette_spacing_x - 1, y1 = y+tm->palette_spacing_y;\n   int id = STBTE__ID(STBTE__palette, slot);\n   stbte__hittest(x0,y0,x1,y1, id);\n   switch (stbte__ui.event) {\n      case STBTE__paint:\n         stbte__draw_rect(x,y,x+tm->palette_spacing_x-1,y+tm->palette_spacing_x-1, STBTE_COLOR_TILEPALETTE_BACKGROUND);\n         STBTE_DRAW_TILE(x,y,id, slot == tm->cur_tile,0);\n         if (slot == tm->cur_tile)\n            stbte__draw_frame_delayed(x-1,y-1,x+tm->palette_spacing_x,y+tm->palette_spacing_y, STBTE_COLOR_TILEPALETTE_OUTLINE);\n         break;\n      default:\n         if (stbte__button_core(id))\n            tm->cur_tile = slot;\n         break;\n   }\n}\n\nstatic void stbte__palette_of_tiles(stbte_tilemap *tm, int x0, int y0, int w, int h)\n{\n   int i,x,y;\n   int num_vis_rows = (h-6) / tm->palette_spacing_y;\n   int num_columns = (w-2-6) / tm->palette_spacing_x;\n   int num_total_rows;\n   int column,row;\n   int x1 = x0+w, y1=y0+h;\n   x = x0+2;\n   y = y0+6;\n\n   if (num_columns == 0)\n      return;\n\n   num_total_rows = (tm->cur_palette_count + num_columns-1) / num_columns; // ceil()\n\n   column = 0;\n   row    = -tm->palette_scroll;\n   for (i=0; i < tm->num_tiles; ++i) {\n      stbte__tileinfo *t = &tm->tiles[i];\n\n      // filter based on category\n      if (tm->cur_category >= 0 && t->category_id != tm->cur_category)\n         continue;\n\n      // display it\n      if (row >= 0 && row < num_vis_rows) {\n         x = x0 + 2 + tm->palette_spacing_x * column;\n         y = y0 + 6 + tm->palette_spacing_y * row;\n         stbte__tile_in_palette(tm,x,y,i);\n      }\n\n      ++column;\n      if (column == num_columns) {\n         column = 0;\n         ++row;\n      }\n   }\n   stbte__flush_delay();\n   stbte__scrollbar(x1-4, y0+6, y1-2, &tm->palette_scroll, 0, num_total_rows, num_vis_rows, STBTE__ID(STBTE__scrollbar_id, STBTE__palette));\n}\n\nstatic float stbte__saved;\nstatic void stbte__props_panel(stbte_tilemap *tm, int x0, int y0, int w, int h)\n{\n   int x1 = x0+w;\n   int i;\n   int y = y0 + 5, x = x0+2;\n   int slider_width = 60;\n   int mx,my;\n   float *p;\n   short *data;\n   if (!stbte__is_single_selection())\n      return;\n   mx = stbte__ui.select_x0;\n   my = stbte__ui.select_y0;\n   p = tm->props[my][mx];\n   data = tm->data[my][mx];\n   STBTE__NOTUSED(data);\n   for (i=0; i < STBTE_MAX_PROPERTIES; ++i) {\n      unsigned int n = STBTE_PROP_TYPE(i, data, p);\n      if (n) {\n         char *s = (char*) STBTE_PROP_NAME(i, data, p);\n         if (s == NULL) s = (char*) \"\";\n         switch (n & 3) {\n            case STBTE_PROP_bool: {\n               int flag = (int) p[i];\n               if (stbte__layerbutton(x,y, flag ? 'x' : ' ', STBTE__ID(STBTE__prop_flag,i), flag, 0, 2)) {\n                  stbte__begin_undo(tm);\n                  stbte__undo_record_prop_float(tm,mx,my,i,(float) flag);\n                  p[i] = (float) !flag;\n                  stbte__end_undo(tm);\n               }\n               stbte__draw_text(x+13,y+1,s,x1-(x+13)-2,STBTE__TEXTCOLOR(STBTE__cpanel));\n               y += 13;\n               break;\n            }\n            case STBTE_PROP_int: {\n               int a = (int) STBTE_PROP_MIN(i,data,p);\n               int b = (int) STBTE_PROP_MAX(i,data,p);\n               int v = (int) p[i] - a;\n               if (a+v != p[i] || v < 0 || v > b-a) {\n                  if (v < 0) v = 0;\n                  if (v > b-a) v = b-a;\n                  p[i] = (float) (a+v); // @TODO undo\n               }\n               switch (stbte__slider(x, slider_width, y+7, b-a, &v, STBTE__ID(STBTE__prop_int,i)))\n               {\n                  case STBTE__begin:\n                     stbte__saved = p[i];\n                     // fallthrough\n                  case STBTE__change:\n                     p[i] = (float) (a+v); // @TODO undo\n                     break;\n                  case STBTE__end:\n                     if (p[i] != stbte__saved) {\n                        stbte__begin_undo(tm);\n                        stbte__undo_record_prop_float(tm,mx,my,i,stbte__saved);\n                        stbte__end_undo(tm);\n                     }\n                     break;\n               }\n               stbte__draw_text(x+slider_width+2,y+2, s, x1-1-(x+slider_width+2), STBTE__TEXTCOLOR(STBTE__cpanel));\n               y += 12;\n               break;\n            }\n            case STBTE_PROP_float: {\n               float a = (float) STBTE_PROP_MIN(i, data,p);\n               float b = (float) STBTE_PROP_MAX(i, data,p);\n               float c = STBTE_PROP_FLOAT_SCALE(i, data, p);\n               float old;\n               if (p[i] < a || p[i] > b) {\n                  // @TODO undo\n                  if (p[i] < a) p[i] = a;\n                  if (p[i] > b) p[i] = b;\n               }\n               old = p[i];\n               switch (stbte__float_control(x, y, 50, a, b, c, \"%8.4f\", &p[i], STBTE__layer,STBTE__ID(STBTE__prop_float,i))) {\n                  case STBTE__begin:\n                     stbte__saved = old;\n                     break;\n                  case STBTE__end:\n                     if (stbte__saved != p[i]) {\n                        stbte__begin_undo(tm);\n                        stbte__undo_record_prop_float(tm,mx,my,i, stbte__saved);\n                        stbte__end_undo(tm);\n                     }\n                     break;\n               }\n               stbte__draw_text(x+53,y+1, s, x1-1-(x+53), STBTE__TEXTCOLOR(STBTE__cpanel));\n               y += 12;\n               break;\n            }\n         }\n      }\n   }\n}\n\nstatic int stbte__cp_mode, stbte__cp_aspect, stbte__save, stbte__cp_altered;\n#ifdef STBTE__COLORPICKER\nstatic int stbte__cp_state, stbte__cp_index, stbte__color_copy;\nstatic void stbte__dump_colorstate(void)\n{\n   int i,j,k;\n   printf(\"static int stbte__color_table[STBTE__num_color_modes][STBTE__num_color_aspects][STBTE__num_color_states] =\\n\");\n   printf(\"{\\n\");\n   printf(\"   {\\n\");\n   for (k=0; k < STBTE__num_color_modes; ++k) {\n      for (j=0; j < STBTE__num_color_aspects; ++j) {\n         printf(\"      { \");\n         for (i=0; i < STBTE__num_color_states; ++i) {\n            printf(\"0x%06x, \", stbte__color_table[k][j][i]);\n         }\n         printf(\"},\\n\");\n      }\n      if (k+1 < STBTE__num_color_modes)\n         printf(\"   }, {\\n\");\n      else\n         printf(\"   },\\n\");\n   }\n   printf(\"};\\n\");\n}\n\nstatic void stbte__colorpicker(int x0, int y0, int w, int h)\n{\n   int x1 = x0+w, y1 = y0+h, x,y, i;\n\n   x =  x0+2; y = y0+6;\n\n   y += 5;\n   x += 8;\n\n\n   {\n      int color = stbte__color_table[stbte__cp_mode][stbte__cp_aspect][stbte__cp_index];\n      int rgb[3];\n      if (stbte__cp_altered && stbte__cp_index == STBTE__idle)\n         color = stbte__save;\n\n      if (stbte__minibutton(STBTE__cmapsize, x1-20,y+ 5, 'C', STBTE__ID2(STBTE__colorpick_id,4,0)))\n         stbte__color_copy = color;\n      if (stbte__minibutton(STBTE__cmapsize, x1-20,y+15, 'P', STBTE__ID2(STBTE__colorpick_id,4,1)))\n         color = stbte__color_copy;\n\n      rgb[0] = color >> 16; rgb[1] = (color>>8)&255; rgb[2] = color & 255;\n      for (i=0; i < 3; ++i) {\n         if (stbte__slider(x+8,64, y, 255, rgb+i, STBTE__ID2(STBTE__colorpick_id,3,i)) > 0)\n            stbte__dump_colorstate();\n         y += 15;\n      }\n      if (stbte__ui.event != STBTE__paint && stbte__ui.event != STBTE__tick)\n         stbte__color_table[stbte__cp_mode][stbte__cp_aspect][stbte__cp_index] = (rgb[0]<<16)|(rgb[1]<<8)|(rgb[2]);\n   }\n\n   y += 5;\n\n   // states\n   x = x0+2+35;\n   if (stbte__ui.event == STBTE__paint) {\n      static char *states[] = { \"idle\", \"over\", \"down\", \"down&over\", \"selected\", \"selected&over\", \"disabled\" };\n      stbte__draw_text(x, y+1, states[stbte__cp_index], x1-x-1, 0xffffff);\n   }\n\n   x = x0+24; y += 12;\n\n   for (i=3; i >= 0; --i) {\n      int state = 0 != (stbte__cp_state & (1 << i));\n      if (stbte__layerbutton(x,y, \"OASD\"[i], STBTE__ID2(STBTE__colorpick_id, 0,i), state,0, STBTE__clayer_button)) {\n         stbte__cp_state ^= (1 << i);\n         stbte__cp_index = stbte__state_to_index[0][0][0][stbte__cp_state];\n      }\n      x += 16;\n   }\n   x = x0+2; y += 18;\n\n   for (i=0; i < 3; ++i) {\n      static char *labels[] = { \"Base\", \"Edge\", \"Text\" };\n      if (stbte__button(STBTE__ctoolbar_button, labels[i], x,y,0,36, STBTE__ID2(STBTE__colorpick_id,1,i), stbte__cp_aspect==i,0))\n         stbte__cp_aspect = i;\n      x += 40;\n   }\n\n   y += 18;\n   x = x0+2;\n\n   for (i=0; i < STBTE__num_color_modes; ++i) {\n      if (stbte__button(STBTE__ctoolbar_button, stbte__color_names[i], x, y, 0,80, STBTE__ID2(STBTE__colorpick_id,2,i), stbte__cp_mode == i,0))\n         stbte__cp_mode = i;\n      y += 12;\n   }\n\n   // make the currently selected aspect flash, unless we're actively dragging color slider etc\n   if (stbte__ui.event == STBTE__tick) {\n      stbte__save = stbte__color_table[stbte__cp_mode][stbte__cp_aspect][STBTE__idle];\n      if ((stbte__ui.active_id & 127) != STBTE__colorpick_id) {\n         if ((stbte__ui.ms_time & 2047) < 200) {\n            stbte__color_table[stbte__cp_mode][stbte__cp_aspect][STBTE__idle] ^= 0x1f1f1f;\n            stbte__cp_altered = 1;\n         }\n      }\n   }\n}\n#endif\n\nstatic void stbte__editor_traverse(stbte_tilemap *tm)\n{\n   int i,j,i0,j0,i1,j1,n;\n\n   if (tm == NULL)\n      return;\n   if (stbte__ui.x0 == stbte__ui.x1 || stbte__ui.y0 == stbte__ui.y1)\n      return;\n\n   stbte__prepare_tileinfo(tm);\n\n   stbte__compute_panel_locations(tm); // @OPTIMIZE: we don't need to recompute this every time\n\n   if (stbte__ui.event == STBTE__paint) {\n      // fill screen with border\n      stbte__draw_rect(stbte__ui.x0, stbte__ui.y0, stbte__ui.x1, stbte__ui.y1, STBTE_COLOR_TILEMAP_BORDER);\n      // fill tilemap with tilemap background\n      stbte__draw_rect(stbte__ui.x0 - tm->scroll_x, stbte__ui.y0 - tm->scroll_y,\n                       stbte__ui.x0 - tm->scroll_x + tm->spacing_x * tm->max_x,\n                       stbte__ui.y0 - tm->scroll_y + tm->spacing_y * tm->max_y, STBTE_COLOR_TILEMAP_BACKGROUND);\n   }\n\n   // step 1: traverse all the tilemap data...\n\n   i0 = (tm->scroll_x - tm->spacing_x) / tm->spacing_x;\n   j0 = (tm->scroll_y - tm->spacing_y) / tm->spacing_y;\n   i1 = (tm->scroll_x + stbte__ui.x1 - stbte__ui.x0) / tm->spacing_x + 1;\n   j1 = (tm->scroll_y + stbte__ui.y1 - stbte__ui.y0) / tm->spacing_y + 1;\n\n   if (i0 < 0) i0 = 0;\n   if (j0 < 0) j0 = 0;\n   if (i1 > tm->max_x) i1 = tm->max_x;\n   if (j1 > tm->max_y) j1 = tm->max_y;\n\n   if (stbte__ui.event == STBTE__paint) {\n      // draw all of layer 0, then all of layer 1, etc, instead of old\n      // way which drew entire stack of each tile at once\n      for (n=0; n < tm->num_layers; ++n) {\n         for (j=j0; j < j1; ++j) {\n            for (i=i0; i < i1; ++i) {\n               int x = stbte__ui.x0 + i * tm->spacing_x - tm->scroll_x;\n               int y = stbte__ui.y0 + j * tm->spacing_y - tm->scroll_y;\n               stbte__tile_paint(tm, x, y, i, j, n);\n            }\n         }\n         if (n == 0 && stbte__ui.show_grid == 1) {\n            int x = stbte__ui.x0 + i0 * tm->spacing_x - tm->scroll_x;\n            int y = stbte__ui.y0 + j0 * tm->spacing_y - tm->scroll_y;\n            for (i=0; x < stbte__ui.x1 && i <= i1; ++i, x += tm->spacing_x)\n               stbte__draw_rect(x, stbte__ui.y0, x+1, stbte__ui.y1, STBTE_COLOR_GRID);\n            for (j=0; y < stbte__ui.y1 && j <= j1; ++j, y += tm->spacing_y)\n               stbte__draw_rect(stbte__ui.x0, y, stbte__ui.x1, y+1, STBTE_COLOR_GRID);\n         }\n      }\n   }\n\n   if (stbte__ui.event == STBTE__paint) {\n      // draw grid on top of everything except UI\n      if (stbte__ui.show_grid == 2) {\n         int x = stbte__ui.x0 + i0 * tm->spacing_x - tm->scroll_x;\n         int y = stbte__ui.y0 + j0 * tm->spacing_y - tm->scroll_y;\n         for (i=0; x < stbte__ui.x1 && i <= i1; ++i, x += tm->spacing_x)\n            stbte__draw_rect(x, stbte__ui.y0, x+1, stbte__ui.y1, STBTE_COLOR_GRID);\n         for (j=0; y < stbte__ui.y1 && j <= j1; ++j, y += tm->spacing_y)\n            stbte__draw_rect(stbte__ui.x0, y, stbte__ui.x1, y+1, STBTE_COLOR_GRID);\n      }\n   }\n\n   for (j=j0; j < j1; ++j) {\n      for (i=i0; i < i1; ++i) {\n         int x = stbte__ui.x0 + i * tm->spacing_x - tm->scroll_x;\n         int y = stbte__ui.y0 + j * tm->spacing_y - tm->scroll_y;\n         stbte__tile(tm, x, y, i, j);\n      }\n   }\n\n   if (stbte__ui.event == STBTE__paint) {\n      // draw the selection border\n      if (stbte__ui.has_selection) {\n         int x0,y0,x1,y1;\n         x0 = stbte__ui.x0 + (stbte__ui.select_x0    ) * tm->spacing_x - tm->scroll_x;\n         y0 = stbte__ui.y0 + (stbte__ui.select_y0    ) * tm->spacing_y - tm->scroll_y;\n         x1 = stbte__ui.x0 + (stbte__ui.select_x1 + 1) * tm->spacing_x - tm->scroll_x + 1;\n         y1 = stbte__ui.y0 + (stbte__ui.select_y1 + 1) * tm->spacing_y - tm->scroll_y + 1;\n         stbte__draw_frame(x0,y0,x1,y1, (stbte__ui.ms_time & 256 ? STBTE_COLOR_SELECTION_OUTLINE1 : STBTE_COLOR_SELECTION_OUTLINE2));\n      }\n\n      stbte__flush_delay(); // draw a dynamic link on top of the queued links\n\n      #ifdef STBTE_ALLOW_LINK\n      if (stbte__ui.linking && STBTE__IS_MAP_HOT()) {\n         int x0,y0,x1,y1;\n         int color;\n         int ex = ((stbte__ui.hot_id >> 19) & 4095);\n         int ey = ((stbte__ui.hot_id >>  7) & 4095);\n         x0 = stbte__ui.x0 + (stbte__ui.sx    ) * tm->spacing_x - tm->scroll_x + (tm->spacing_x>>1)+1;\n         y0 = stbte__ui.y0 + (stbte__ui.sy    ) * tm->spacing_y - tm->scroll_y + (tm->spacing_y>>1)+1;\n         x1 = stbte__ui.x0 + (ex              ) * tm->spacing_x - tm->scroll_x + (tm->spacing_x>>1)-1;\n         y1 = stbte__ui.y0 + (ey              ) * tm->spacing_y - tm->scroll_y + (tm->spacing_y>>1)-1;\n         if (STBTE_ALLOW_LINK(tm->data[stbte__ui.sy][stbte__ui.sx], tm->props[stbte__ui.sy][stbte__ui.sx], tm->data[ey][ex], tm->props[ey][ex]))\n            color = STBTE_LINK_COLOR_DRAWING;\n         else\n            color = STBTE_LINK_COLOR_DISALLOWED;\n         stbte__draw_link(x0,y0,x1,y1, color);\n      }\n      #endif\n   }\n   stbte__flush_delay();\n\n   // step 2: traverse the panels\n   for (i=0; i < STBTE__num_panel; ++i) {\n      stbte__panel *p = &stbte__ui.panel[i];\n      if (stbte__ui.event == STBTE__paint) {\n         stbte__draw_box(p->x0,p->y0,p->x0+p->width,p->y0+p->height, STBTE__cpanel, STBTE__idle);\n      }\n      // obscure tilemap data underneath panel\n      stbte__hittest(p->x0,p->y0,p->x0+p->width,p->y0+p->height, STBTE__ID2(STBTE__panel, i, 0));\n      switch (i) {\n         case STBTE__panel_toolbar:\n            if (stbte__ui.event == STBTE__paint)\n               stbte__draw_rect(p->x0,p->y0,p->x0+p->width,p->y0+p->height, stbte__color_table[STBTE__ctoolbar][STBTE__base][STBTE__idle]);\n            stbte__toolbar(tm,p->x0,p->y0,p->width,p->height);\n            break;\n         case STBTE__panel_info:\n            stbte__info(tm,p->x0,p->y0,p->width,p->height);\n            break;\n         case STBTE__panel_layers:\n            stbte__layers(tm,p->x0,p->y0,p->width,p->height);\n            break;\n         case STBTE__panel_categories:\n            stbte__categories(tm,p->x0,p->y0,p->width,p->height);\n            break;\n         case STBTE__panel_colorpick:\n#ifdef STBTE__COLORPICKER\n            stbte__colorpicker(p->x0,p->y0,p->width,p->height);\n#endif\n            break;\n         case STBTE__panel_tiles:\n            // erase boundary between categories and tiles if they're on same side\n            if (stbte__ui.event == STBTE__paint && p->side == stbte__ui.panel[STBTE__panel_categories].side)\n               stbte__draw_rect(p->x0+1,p->y0-1,p->x0+p->width-1,p->y0+1, stbte__color_table[STBTE__cpanel][STBTE__base][STBTE__idle]);\n            stbte__palette_of_tiles(tm,p->x0,p->y0,p->width,p->height);\n            break;\n         case STBTE__panel_props:\n            stbte__props_panel(tm,p->x0,p->y0,p->width,p->height);\n            break;\n      }\n      // draw the panel side selectors\n      for (j=0; j < 2; ++j) {\n         int result;\n         if (i == STBTE__panel_toolbar) continue;\n         result = stbte__microbutton(p->x0+p->width - 1 - 2*4 + 4*j,p->y0+2,3, STBTE__ID2(STBTE__panel, i, j+1), STBTE__cpanel_sider+j);\n         if (result) {\n            switch (j) {\n               case 0: p->side = result > 0 ? STBTE__side_left : STBTE__side_right; break;\n               case 1: p->delta_height += result; break;\n            }\n         }\n      }\n   }\n\n   if (stbte__ui.panel[STBTE__panel_categories].delta_height < -5) stbte__ui.panel[STBTE__panel_categories].delta_height = -5;\n   if (stbte__ui.panel[STBTE__panel_layers    ].delta_height < -5) stbte__ui.panel[STBTE__panel_layers    ].delta_height = -5;\n\n\n   // step 3: traverse the regions to place expander controls on them\n   for (i=0; i < 2; ++i) {\n      if (stbte__region[i].active) {\n         int x = stbte__region[i].x;\n         int width;\n         if (i == STBTE__side_left)\n            width =  stbte__ui.left_width , x += stbte__region[i].width + 1;\n         else\n            width = -stbte__ui.right_width, x -= 6;\n         if (stbte__microbutton_dragger(x, stbte__region[i].y+2, 5, STBTE__ID(STBTE__region,i), &width)) {\n            // if non-0, it is expanding, so retract it\n            if (stbte__region[i].retracted == 0.0)\n               stbte__region[i].retracted = 0.01f;\n            else\n               stbte__region[i].retracted = 0.0;\n         }\n         if (i == STBTE__side_left)\n            stbte__ui.left_width  =  width;\n         else\n            stbte__ui.right_width = -width;\n         if (stbte__ui.event == STBTE__tick) {\n            if (stbte__region[i].retracted && stbte__region[i].retracted < 1.0f) {\n               stbte__region[i].retracted += stbte__ui.dt*4;\n               if (stbte__region[i].retracted > 1)\n                  stbte__region[i].retracted = 1;\n            }\n         }\n      }\n   }\n\n   if (stbte__ui.event == STBTE__paint && stbte__ui.alert_msg) {\n      int w = stbte__text_width(stbte__ui.alert_msg);\n      int x = (stbte__ui.x0+stbte__ui.x1)/2;\n      int y = (stbte__ui.y0+stbte__ui.y1)*5/6;\n      stbte__draw_rect (x-w/2-4,y-8, x+w/2+4,y+8, 0x604020);\n      stbte__draw_frame(x-w/2-4,y-8, x+w/2+4,y+8, 0x906030);\n      stbte__draw_text (x-w/2,y-4, stbte__ui.alert_msg, w+1, 0xff8040);\n   }\n\n#ifdef STBTE_SHOW_CURSOR\n   if (stbte__ui.event == STBTE__paint)\n      stbte__draw_bitmap(stbte__ui.mx, stbte__ui.my, stbte__get_char_width(26), stbte__get_char_bitmap(26), 0xe0e0e0);\n#endif\n\n   if (stbte__ui.event == STBTE__tick && stbte__ui.alert_msg) {\n      stbte__ui.alert_timer -= stbte__ui.dt;\n      if (stbte__ui.alert_timer < 0) {\n         stbte__ui.alert_timer = 0;\n         stbte__ui.alert_msg = 0;\n      }\n   }\n\n   if (stbte__ui.event == STBTE__paint) {\n      stbte__color_table[stbte__cp_mode][stbte__cp_aspect][STBTE__idle] = stbte__save;\n      stbte__cp_altered = 0;\n   }\n}\n\nstatic void stbte__do_event(stbte_tilemap *tm)\n{\n   stbte__ui.next_hot_id = 0;\n   stbte__editor_traverse(tm);\n   stbte__ui.hot_id = stbte__ui.next_hot_id;\n\n   // automatically cancel on mouse-up in case the object that triggered it\n   // doesn't exist anymore\n   if (stbte__ui.active_id) {\n      if (stbte__ui.event == STBTE__leftup || stbte__ui.event == STBTE__rightup) {\n         if (!stbte__ui.pasting) {\n            stbte__activate(0);\n            if (stbte__ui.undoing)\n               stbte__end_undo(tm);\n            stbte__ui.scrolling = 0;\n            stbte__ui.dragging = 0;\n            stbte__ui.linking = 0;\n         }\n      }\n   }\n\n   // we could do this stuff in the widgets directly, but it would keep recomputing\n   // the same thing on every tile, which seems dumb.\n\n   if (stbte__ui.pasting) {\n      if (STBTE__IS_MAP_HOT()) {\n         // compute pasting location based on last hot\n         stbte__ui.paste_x = ((stbte__ui.hot_id >> 19) & 4095) - (stbte__ui.copy_width >> 1);\n         stbte__ui.paste_y = ((stbte__ui.hot_id >>  7) & 4095) - (stbte__ui.copy_height >> 1);\n      }\n   }\n   if (stbte__ui.dragging) {\n      if (STBTE__IS_MAP_HOT()) {\n         stbte__ui.drag_dest_x = ((stbte__ui.hot_id >> 19) & 4095) - stbte__ui.drag_offx;\n         stbte__ui.drag_dest_y = ((stbte__ui.hot_id >>  7) & 4095) - stbte__ui.drag_offy;\n      }\n   }\n}\n\nstatic void stbte__set_event(int event, int x, int y)\n{\n   stbte__ui.event = event;\n   stbte__ui.mx    = x;\n   stbte__ui.my    = y;\n   stbte__ui.dx    = x - stbte__ui.last_mouse_x;\n   stbte__ui.dy    = y - stbte__ui.last_mouse_y;\n   stbte__ui.last_mouse_x = x;\n   stbte__ui.last_mouse_y = y;\n   stbte__ui.accum_x += stbte__ui.dx;\n   stbte__ui.accum_y += stbte__ui.dy;\n}\n\nvoid stbte_draw(stbte_tilemap *tm)\n{\n   stbte__ui.event = STBTE__paint;\n   stbte__editor_traverse(tm);\n}\n\nvoid stbte_mouse_move(stbte_tilemap *tm, int x, int y, int shifted, int scrollkey)\n{\n   stbte__set_event(STBTE__mousemove, x,y);\n   stbte__ui.shift = shifted;\n   stbte__ui.scrollkey = scrollkey;\n   stbte__do_event(tm);\n}\n\nvoid stbte_mouse_button(stbte_tilemap *tm, int x, int y, int right, int down, int shifted, int scrollkey)\n{\n   static int events[2][2] = { { STBTE__leftup , STBTE__leftdown  },\n                               { STBTE__rightup, STBTE__rightdown } };\n   stbte__set_event(events[right][down], x,y);\n   stbte__ui.shift = shifted;\n   stbte__ui.scrollkey = scrollkey;\n\n   stbte__do_event(tm);\n}\n\nvoid stbte_mouse_wheel(stbte_tilemap *tm, int x, int y, int vscroll)\n{\n   // not implemented yet -- need different way of hittesting\n}\n\nvoid stbte_action(stbte_tilemap *tm, enum stbte_action act)\n{\n   switch (act) {\n      case STBTE_tool_select:      stbte__ui.tool = STBTE__tool_select;               break;\n      case STBTE_tool_brush:       stbte__ui.tool = STBTE__tool_brush;                break;\n      case STBTE_tool_erase:       stbte__ui.tool = STBTE__tool_erase;                break;\n      case STBTE_tool_rectangle:   stbte__ui.tool = STBTE__tool_rect;                 break;\n      case STBTE_tool_eyedropper:  stbte__ui.tool = STBTE__tool_eyedrop;              break;\n      case STBTE_tool_link:        stbte__ui.tool = STBTE__tool_link;                 break;\n      case STBTE_act_toggle_grid:  stbte__ui.show_grid = (stbte__ui.show_grid+1) % 3; break;\n      case STBTE_act_toggle_links: stbte__ui.show_links ^= 1;                         break;\n      case STBTE_act_undo:         stbte__undo(tm);                                   break;\n      case STBTE_act_redo:         stbte__redo(tm);                                   break;\n      case STBTE_act_cut:          stbte__copy_cut(tm, 1);                            break;\n      case STBTE_act_copy:         stbte__copy_cut(tm, 0);                            break;\n      case STBTE_act_paste:        stbte__start_paste(tm);                            break;\n      case STBTE_scroll_left:      tm->scroll_x -= tm->spacing_x;                     break;\n      case STBTE_scroll_right:     tm->scroll_x += tm->spacing_x;                     break;\n      case STBTE_scroll_up:        tm->scroll_y -= tm->spacing_y;                     break;\n      case STBTE_scroll_down:      tm->scroll_y += tm->spacing_y;                     break;\n   }\n}\n\nvoid stbte_tick(stbte_tilemap *tm, float dt)\n{\n   stbte__ui.event = STBTE__tick;\n   stbte__ui.dt    = dt;\n   stbte__do_event(tm);\n   stbte__ui.ms_time += (int) (dt * 1024) + 1; // make sure if time is superfast it always updates a little\n}\n\nvoid stbte_mouse_sdl(stbte_tilemap *tm, const void *sdl_event, float xs, float ys, int xo, int yo)\n{\n#ifdef _SDL_H\n   SDL_Event *event = (SDL_Event *) sdl_event;\n   SDL_Keymod km = SDL_GetModState();\n   int shift = (km & KMOD_LCTRL) || (km & KMOD_RCTRL);\n   int scrollkey = 0 != SDL_GetKeyboardState(NULL)[SDL_SCANCODE_SPACE];\n   switch (event->type) {\n      case SDL_MOUSEMOTION:\n         stbte_mouse_move(tm, (int) (xs*event->motion.x+xo), (int) (ys*event->motion.y+yo), shift, scrollkey);\n         break;\n      case SDL_MOUSEBUTTONUP:\n         stbte_mouse_button(tm, (int) (xs*event->button.x+xo), (int) (ys*event->button.y+yo), event->button.button != SDL_BUTTON_LEFT, 0, shift, scrollkey);\n         break;\n      case SDL_MOUSEBUTTONDOWN:\n         stbte_mouse_button(tm, (int) (xs*event->button.x+xo), (int) (ys*event->button.y+yo), event->button.button != SDL_BUTTON_LEFT, 1, shift, scrollkey);\n         break;\n      case SDL_MOUSEWHEEL:\n         stbte_mouse_wheel(tm, stbte__ui.mx, stbte__ui.my, event->wheel.y);\n         break;\n   }\n#else\n   STBTE__NOTUSED(tm);\n   STBTE__NOTUSED(sdl_event);\n   STBTE__NOTUSED(xs);\n   STBTE__NOTUSED(ys);\n   STBTE__NOTUSED(xo);\n   STBTE__NOTUSED(yo);\n#endif\n}\n\n#endif // STB_TILEMAP_EDITOR_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_truetype.h",
    "content": "// stb_truetype.h - v1.26 - public domain\n// authored from 2009-2021 by Sean Barrett / RAD Game Tools\n//\n// =======================================================================\n//\n//    NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES\n//\n// This library does no range checking of the offsets found in the file,\n// meaning an attacker can use it to read arbitrary memory.\n//\n// =======================================================================\n//\n//   This library processes TrueType files:\n//        parse files\n//        extract glyph metrics\n//        extract glyph shapes\n//        render glyphs to one-channel bitmaps with antialiasing (box filter)\n//        render glyphs to one-channel SDF bitmaps (signed-distance field/function)\n//\n//   Todo:\n//        non-MS cmaps\n//        crashproof on bad data\n//        hinting? (no longer patented)\n//        cleartype-style AA?\n//        optimize: use simple memory allocator for intermediates\n//        optimize: build edge-list directly from curves\n//        optimize: rasterize directly from curves?\n//\n// ADDITIONAL CONTRIBUTORS\n//\n//   Mikko Mononen: compound shape support, more cmap formats\n//   Tor Andersson: kerning, subpixel rendering\n//   Dougall Johnson: OpenType / Type 2 font handling\n//   Daniel Ribeiro Maciel: basic GPOS-based kerning\n//\n//   Misc other:\n//       Ryan Gordon\n//       Simon Glass\n//       github:IntellectualKitty\n//       Imanol Celaya\n//       Daniel Ribeiro Maciel\n//\n//   Bug/warning reports/fixes:\n//       \"Zer\" on mollyrocket       Fabian \"ryg\" Giesen   github:NiLuJe\n//       Cass Everitt               Martins Mozeiko       github:aloucks\n//       stoiko (Haemimont Games)   Cap Petschulat        github:oyvindjam\n//       Brian Hook                 Omar Cornut           github:vassvik\n//       Walter van Niftrik         Ryan Griege\n//       David Gow                  Peter LaValle\n//       David Given                Sergey Popov\n//       Ivan-Assen Ivanov          Giumo X. Clanjor\n//       Anthony Pesch              Higor Euripedes\n//       Johan Duparc               Thomas Fields\n//       Hou Qiming                 Derek Vinyard\n//       Rob Loach                  Cort Stratton\n//       Kenney Phillis Jr.         Brian Costabile\n//       Ken Voskuil (kaesve)       Yakov Galka\n//\n// VERSION HISTORY\n//\n//   1.26 (2021-08-28) fix broken rasterizer\n//   1.25 (2021-07-11) many fixes\n//   1.24 (2020-02-05) fix warning\n//   1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)\n//   1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined\n//   1.21 (2019-02-25) fix warning\n//   1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()\n//   1.19 (2018-02-11) GPOS kerning, STBTT_fmod\n//   1.18 (2018-01-29) add missing function\n//   1.17 (2017-07-23) make more arguments const; doc fix\n//   1.16 (2017-07-12) SDF support\n//   1.15 (2017-03-03) make more arguments const\n//   1.14 (2017-01-16) num-fonts-in-TTC function\n//   1.13 (2017-01-02) support OpenType fonts, certain Apple fonts\n//   1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual\n//   1.11 (2016-04-02) fix unused-variable warning\n//   1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef\n//   1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly\n//   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges\n//   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;\n//                     variant PackFontRanges to pack and render in separate phases;\n//                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);\n//                     fixed an assert() bug in the new rasterizer\n//                     replace assert() with STBTT_assert() in new rasterizer\n//\n//   Full history can be found at the end of this file.\n//\n// LICENSE\n//\n//   See end of file for license information.\n//\n// USAGE\n//\n//   Include this file in whatever places need to refer to it. In ONE C/C++\n//   file, write:\n//      #define STB_TRUETYPE_IMPLEMENTATION\n//   before the #include of this file. This expands out the actual\n//   implementation into that C/C++ file.\n//\n//   To make the implementation private to the file that generates the implementation,\n//      #define STBTT_STATIC\n//\n//   Simple 3D API (don't ship this, but it's fine for tools and quick start)\n//           stbtt_BakeFontBitmap()               -- bake a font to a bitmap for use as texture\n//           stbtt_GetBakedQuad()                 -- compute quad to draw for a given char\n//\n//   Improved 3D API (more shippable):\n//           #include \"stb_rect_pack.h\"           -- optional, but you really want it\n//           stbtt_PackBegin()\n//           stbtt_PackSetOversampling()          -- for improved quality on small fonts\n//           stbtt_PackFontRanges()               -- pack and renders\n//           stbtt_PackEnd()\n//           stbtt_GetPackedQuad()\n//\n//   \"Load\" a font file from a memory buffer (you have to keep the buffer loaded)\n//           stbtt_InitFont()\n//           stbtt_GetFontOffsetForIndex()        -- indexing for TTC font collections\n//           stbtt_GetNumberOfFonts()             -- number of fonts for TTC font collections\n//\n//   Render a unicode codepoint to a bitmap\n//           stbtt_GetCodepointBitmap()           -- allocates and returns a bitmap\n//           stbtt_MakeCodepointBitmap()          -- renders into bitmap you provide\n//           stbtt_GetCodepointBitmapBox()        -- how big the bitmap must be\n//\n//   Character advance/positioning\n//           stbtt_GetCodepointHMetrics()\n//           stbtt_GetFontVMetrics()\n//           stbtt_GetFontVMetricsOS2()\n//           stbtt_GetCodepointKernAdvance()\n//\n//   Starting with version 1.06, the rasterizer was replaced with a new,\n//   faster and generally-more-precise rasterizer. The new rasterizer more\n//   accurately measures pixel coverage for anti-aliasing, except in the case\n//   where multiple shapes overlap, in which case it overestimates the AA pixel\n//   coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If\n//   this turns out to be a problem, you can re-enable the old rasterizer with\n//        #define STBTT_RASTERIZER_VERSION 1\n//   which will incur about a 15% speed hit.\n//\n// ADDITIONAL DOCUMENTATION\n//\n//   Immediately after this block comment are a series of sample programs.\n//\n//   After the sample programs is the \"header file\" section. This section\n//   includes documentation for each API function.\n//\n//   Some important concepts to understand to use this library:\n//\n//      Codepoint\n//         Characters are defined by unicode codepoints, e.g. 65 is\n//         uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is\n//         the hiragana for \"ma\".\n//\n//      Glyph\n//         A visual character shape (every codepoint is rendered as\n//         some glyph)\n//\n//      Glyph index\n//         A font-specific integer ID representing a glyph\n//\n//      Baseline\n//         Glyph shapes are defined relative to a baseline, which is the\n//         bottom of uppercase characters. Characters extend both above\n//         and below the baseline.\n//\n//      Current Point\n//         As you draw text to the screen, you keep track of a \"current point\"\n//         which is the origin of each character. The current point's vertical\n//         position is the baseline. Even \"baked fonts\" use this model.\n//\n//      Vertical Font Metrics\n//         The vertical qualities of the font, used to vertically position\n//         and space the characters. See docs for stbtt_GetFontVMetrics.\n//\n//      Font Size in Pixels or Points\n//         The preferred interface for specifying font sizes in stb_truetype\n//         is to specify how tall the font's vertical extent should be in pixels.\n//         If that sounds good enough, skip the next paragraph.\n//\n//         Most font APIs instead use \"points\", which are a common typographic\n//         measurement for describing font size, defined as 72 points per inch.\n//         stb_truetype provides a point API for compatibility. However, true\n//         \"per inch\" conventions don't make much sense on computer displays\n//         since different monitors have different number of pixels per\n//         inch. For example, Windows traditionally uses a convention that\n//         there are 96 pixels per inch, thus making 'inch' measurements have\n//         nothing to do with inches, and thus effectively defining a point to\n//         be 1.333 pixels. Additionally, the TrueType font data provides\n//         an explicit scale factor to scale a given font's glyphs to points,\n//         but the author has observed that this scale factor is often wrong\n//         for non-commercial fonts, thus making fonts scaled in points\n//         according to the TrueType spec incoherently sized in practice.\n//\n// DETAILED USAGE:\n//\n//  Scale:\n//    Select how high you want the font to be, in points or pixels.\n//    Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute\n//    a scale factor SF that will be used by all other functions.\n//\n//  Baseline:\n//    You need to select a y-coordinate that is the baseline of where\n//    your text will appear. Call GetFontBoundingBox to get the baseline-relative\n//    bounding box for all characters. SF*-y0 will be the distance in pixels\n//    that the worst-case character could extend above the baseline, so if\n//    you want the top edge of characters to appear at the top of the\n//    screen where y=0, then you would set the baseline to SF*-y0.\n//\n//  Current point:\n//    Set the current point where the first character will appear. The\n//    first character could extend left of the current point; this is font\n//    dependent. You can either choose a current point that is the leftmost\n//    point and hope, or add some padding, or check the bounding box or\n//    left-side-bearing of the first character to be displayed and set\n//    the current point based on that.\n//\n//  Displaying a character:\n//    Compute the bounding box of the character. It will contain signed values\n//    relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,\n//    then the character should be displayed in the rectangle from\n//    <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).\n//\n//  Advancing for the next character:\n//    Call GlyphHMetrics, and compute 'current_point += SF * advance'.\n//\n//\n// ADVANCED USAGE\n//\n//   Quality:\n//\n//    - Use the functions with Subpixel at the end to allow your characters\n//      to have subpixel positioning. Since the font is anti-aliased, not\n//      hinted, this is very import for quality. (This is not possible with\n//      baked fonts.)\n//\n//    - Kerning is now supported, and if you're supporting subpixel rendering\n//      then kerning is worth using to give your text a polished look.\n//\n//   Performance:\n//\n//    - Convert Unicode codepoints to glyph indexes and operate on the glyphs;\n//      if you don't do this, stb_truetype is forced to do the conversion on\n//      every call.\n//\n//    - There are a lot of memory allocations. We should modify it to take\n//      a temp buffer and allocate from the temp buffer (without freeing),\n//      should help performance a lot.\n//\n// NOTES\n//\n//   The system uses the raw data found in the .ttf file without changing it\n//   and without building auxiliary data structures. This is a bit inefficient\n//   on little-endian systems (the data is big-endian), but assuming you're\n//   caching the bitmaps or glyph shapes this shouldn't be a big deal.\n//\n//   It appears to be very hard to programmatically determine what font a\n//   given file is in a general way. I provide an API for this, but I don't\n//   recommend it.\n//\n//\n// PERFORMANCE MEASUREMENTS FOR 1.06:\n//\n//                      32-bit     64-bit\n//   Previous release:  8.83 s     7.68 s\n//   Pool allocations:  7.72 s     6.34 s\n//   Inline sort     :  6.54 s     5.65 s\n//   New rasterizer  :  5.63 s     5.00 s\n\n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n////\n////  SAMPLE PROGRAMS\n////\n//\n//  Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless.\n//  See \"tests/truetype_demo_win32.c\" for a complete version.\n#if 0\n#define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation\n#include \"stb_truetype.h\"\n\nunsigned char ttf_buffer[1<<20];\nunsigned char temp_bitmap[512*512];\n\nstbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs\nGLuint ftex;\n\nvoid my_stbtt_initfont(void)\n{\n   fread(ttf_buffer, 1, 1<<20, fopen(\"c:/windows/fonts/times.ttf\", \"rb\"));\n   stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!\n   // can free ttf_buffer at this point\n   glGenTextures(1, &ftex);\n   glBindTexture(GL_TEXTURE_2D, ftex);\n   glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);\n   // can free temp_bitmap at this point\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n}\n\nvoid my_stbtt_print(float x, float y, char *text)\n{\n   // assume orthographic projection with units = screen pixels, origin at top left\n   glEnable(GL_BLEND);\n   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n   glEnable(GL_TEXTURE_2D);\n   glBindTexture(GL_TEXTURE_2D, ftex);\n   glBegin(GL_QUADS);\n   while (*text) {\n      if (*text >= 32 && *text < 128) {\n         stbtt_aligned_quad q;\n         stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9\n         glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0);\n         glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0);\n         glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1);\n         glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1);\n      }\n      ++text;\n   }\n   glEnd();\n}\n#endif\n//\n//\n//////////////////////////////////////////////////////////////////////////////\n//\n// Complete program (this compiles): get a single bitmap, print as ASCII art\n//\n#if 0\n#include <stdio.h>\n#define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation\n#include \"stb_truetype.h\"\n\nchar ttf_buffer[1<<25];\n\nint main(int argc, char **argv)\n{\n   stbtt_fontinfo font;\n   unsigned char *bitmap;\n   int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);\n\n   fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : \"c:/windows/fonts/arialbd.ttf\", \"rb\"));\n\n   stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));\n   bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);\n\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i)\n         putchar(\" .:ioVM@\"[bitmap[j*w+i]>>5]);\n      putchar('\\n');\n   }\n   return 0;\n}\n#endif\n//\n// Output:\n//\n//     .ii.\n//    @@@@@@.\n//   V@Mio@@o\n//   :i.  V@V\n//     :oM@@M\n//   :@@@MM@M\n//   @@o  o@M\n//  :@@.  M@M\n//   @@@o@@@@\n//   :M@@V:@@.\n//\n//////////////////////////////////////////////////////////////////////////////\n//\n// Complete program: print \"Hello World!\" banner, with bugs\n//\n#if 0\nchar buffer[24<<20];\nunsigned char screen[20][79];\n\nint main(int arg, char **argv)\n{\n   stbtt_fontinfo font;\n   int i,j,ascent,baseline,ch=0;\n   float scale, xpos=2; // leave a little padding in case the character extends left\n   char *text = \"Heljo World!\"; // intentionally misspelled to show 'lj' brokenness\n\n   fread(buffer, 1, 1000000, fopen(\"c:/windows/fonts/arialbd.ttf\", \"rb\"));\n   stbtt_InitFont(&font, buffer, 0);\n\n   scale = stbtt_ScaleForPixelHeight(&font, 15);\n   stbtt_GetFontVMetrics(&font, &ascent,0,0);\n   baseline = (int) (ascent*scale);\n\n   while (text[ch]) {\n      int advance,lsb,x0,y0,x1,y1;\n      float x_shift = xpos - (float) floor(xpos);\n      stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);\n      stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);\n      stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);\n      // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong\n      // because this API is really for baking character bitmaps into textures. if you want to render\n      // a sequence of characters, you really need to render each bitmap to a temp buffer, then\n      // \"alpha blend\" that into the working buffer\n      xpos += (advance * scale);\n      if (text[ch+1])\n         xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);\n      ++ch;\n   }\n\n   for (j=0; j < 20; ++j) {\n      for (i=0; i < 78; ++i)\n         putchar(\" .:ioVM@\"[screen[j][i]>>5]);\n      putchar('\\n');\n   }\n\n   return 0;\n}\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////\n////\n////   INTEGRATION WITH YOUR CODEBASE\n////\n////   The following sections allow you to supply alternate definitions\n////   of C library functions used by stb_truetype, e.g. if you don't\n////   link with the C runtime library.\n\n#ifdef STB_TRUETYPE_IMPLEMENTATION\n   // #define your own (u)stbtt_int8/16/32 before including to override this\n   #ifndef stbtt_uint8\n   typedef unsigned char   stbtt_uint8;\n   typedef signed   char   stbtt_int8;\n   typedef unsigned short  stbtt_uint16;\n   typedef signed   short  stbtt_int16;\n   typedef unsigned int    stbtt_uint32;\n   typedef signed   int    stbtt_int32;\n   #endif\n\n   typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];\n   typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];\n\n   // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h\n   #ifndef STBTT_ifloor\n   #include <math.h>\n   #define STBTT_ifloor(x)   ((int) floor(x))\n   #define STBTT_iceil(x)    ((int) ceil(x))\n   #endif\n\n   #ifndef STBTT_sqrt\n   #include <math.h>\n   #define STBTT_sqrt(x)      sqrt(x)\n   #define STBTT_pow(x,y)     pow(x,y)\n   #endif\n\n   #ifndef STBTT_fmod\n   #include <math.h>\n   #define STBTT_fmod(x,y)    fmod(x,y)\n   #endif\n\n   #ifndef STBTT_cos\n   #include <math.h>\n   #define STBTT_cos(x)       cos(x)\n   #define STBTT_acos(x)      acos(x)\n   #endif\n\n   #ifndef STBTT_fabs\n   #include <math.h>\n   #define STBTT_fabs(x)      fabs(x)\n   #endif\n\n   // #define your own functions \"STBTT_malloc\" / \"STBTT_free\" to avoid malloc.h\n   #ifndef STBTT_malloc\n   #include <stdlib.h>\n   #define STBTT_malloc(x,u)  ((void)(u),malloc(x))\n   #define STBTT_free(x,u)    ((void)(u),free(x))\n   #endif\n\n   #ifndef STBTT_assert\n   #include <assert.h>\n   #define STBTT_assert(x)    assert(x)\n   #endif\n\n   #ifndef STBTT_strlen\n   #include <string.h>\n   #define STBTT_strlen(x)    strlen(x)\n   #endif\n\n   #ifndef STBTT_memcpy\n   #include <string.h>\n   #define STBTT_memcpy       memcpy\n   #define STBTT_memset       memset\n   #endif\n#endif\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n////\n////   INTERFACE\n////\n////\n\n#ifndef __STB_INCLUDE_STB_TRUETYPE_H__\n#define __STB_INCLUDE_STB_TRUETYPE_H__\n\n#ifdef STBTT_STATIC\n#define STBTT_DEF static\n#else\n#define STBTT_DEF extern\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// private structure\ntypedef struct\n{\n   unsigned char *data;\n   int cursor;\n   int size;\n} stbtt__buf;\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// TEXTURE BAKING API\n//\n// If you use this API, you only have to call two functions ever.\n//\n\ntypedef struct\n{\n   unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap\n   float xoff,yoff,xadvance;\n} stbtt_bakedchar;\n\nSTBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)\n                                float pixel_height,                     // height of font in pixels\n                                unsigned char *pixels, int pw, int ph,  // bitmap to be filled in\n                                int first_char, int num_chars,          // characters to bake\n                                stbtt_bakedchar *chardata);             // you allocate this, it's num_chars long\n// if return is positive, the first unused row of the bitmap\n// if return is negative, returns the negative of the number of characters that fit\n// if return is 0, no characters fit and no rows were used\n// This uses a very crappy packing.\n\ntypedef struct\n{\n   float x0,y0,s0,t0; // top-left\n   float x1,y1,s1,t1; // bottom-right\n} stbtt_aligned_quad;\n\nSTBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph,  // same data as above\n                               int char_index,             // character to display\n                               float *xpos, float *ypos,   // pointers to current position in screen pixel space\n                               stbtt_aligned_quad *q,      // output: quad to draw\n                               int opengl_fillrule);       // true if opengl fill rule; false if DX9 or earlier\n// Call GetBakedQuad with char_index = 'character - first_char', and it\n// creates the quad you need to draw and advances the current position.\n//\n// The coordinate system used assumes y increases downwards.\n//\n// Characters will extend both above and below the current position;\n// see discussion of \"BASELINE\" above.\n//\n// It's inefficient; you might want to c&p it and optimize it.\n\nSTBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);\n// Query the font vertical metrics without having to create a font first.\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// NEW TEXTURE BAKING API\n//\n// This provides options for packing multiple fonts into one atlas, not\n// perfectly but better than nothing.\n\ntypedef struct\n{\n   unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap\n   float xoff,yoff,xadvance;\n   float xoff2,yoff2;\n} stbtt_packedchar;\n\ntypedef struct stbtt_pack_context stbtt_pack_context;\ntypedef struct stbtt_fontinfo stbtt_fontinfo;\n#ifndef STB_RECT_PACK_VERSION\ntypedef struct stbrp_rect stbrp_rect;\n#endif\n\nSTBTT_DEF int  stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);\n// Initializes a packing context stored in the passed-in stbtt_pack_context.\n// Future calls using this context will pack characters into the bitmap passed\n// in here: a 1-channel bitmap that is width * height. stride_in_bytes is\n// the distance from one row to the next (or 0 to mean they are packed tightly\n// together). \"padding\" is the amount of padding to leave between each\n// character (normally you want '1' for bitmaps you'll use as textures with\n// bilinear filtering).\n//\n// Returns 0 on failure, 1 on success.\n\nSTBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc);\n// Cleans up the packing context and frees all memory.\n\n#define STBTT_POINT_SIZE(x)   (-(x))\n\nSTBTT_DEF int  stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,\n                                int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);\n// Creates character bitmaps from the font_index'th font found in fontdata (use\n// font_index=0 if you don't know what that is). It creates num_chars_in_range\n// bitmaps for characters with unicode values starting at first_unicode_char_in_range\n// and increasing. Data for how to render them is stored in chardata_for_range;\n// pass these to stbtt_GetPackedQuad to get back renderable quads.\n//\n// font_size is the full height of the character from ascender to descender,\n// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed\n// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()\n// and pass that result as 'font_size':\n//       ...,                  20 , ... // font max minus min y is 20 pixels tall\n//       ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall\n\ntypedef struct\n{\n   float font_size;\n   int first_unicode_codepoint_in_range;  // if non-zero, then the chars are continuous, and this is the first codepoint\n   int *array_of_unicode_codepoints;       // if non-zero, then this is an array of unicode codepoints\n   int num_chars;\n   stbtt_packedchar *chardata_for_range; // output\n   unsigned char h_oversample, v_oversample; // don't set these, they're used internally\n} stbtt_pack_range;\n\nSTBTT_DEF int  stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);\n// Creates character bitmaps from multiple ranges of characters stored in\n// ranges. This will usually create a better-packed bitmap than multiple\n// calls to stbtt_PackFontRange. Note that you can call this multiple\n// times within a single PackBegin/PackEnd.\n\nSTBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);\n// Oversampling a font increases the quality by allowing higher-quality subpixel\n// positioning, and is especially valuable at smaller text sizes.\n//\n// This function sets the amount of oversampling for all following calls to\n// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given\n// pack context. The default (no oversampling) is achieved by h_oversample=1\n// and v_oversample=1. The total number of pixels required is\n// h_oversample*v_oversample larger than the default; for example, 2x2\n// oversampling requires 4x the storage of 1x1. For best results, render\n// oversampled textures with bilinear filtering. Look at the readme in\n// stb/tests/oversample for information about oversampled fonts\n//\n// To use with PackFontRangesGather etc., you must set it before calls\n// call to PackFontRangesGatherRects.\n\nSTBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);\n// If skip != 0, this tells stb_truetype to skip any codepoints for which\n// there is no corresponding glyph. If skip=0, which is the default, then\n// codepoints without a glyph recived the font's \"missing character\" glyph,\n// typically an empty box by convention.\n\nSTBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph,  // same data as above\n                               int char_index,             // character to display\n                               float *xpos, float *ypos,   // pointers to current position in screen pixel space\n                               stbtt_aligned_quad *q,      // output: quad to draw\n                               int align_to_integer);\n\nSTBTT_DEF int  stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);\nSTBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);\nSTBTT_DEF int  stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);\n// Calling these functions in sequence is roughly equivalent to calling\n// stbtt_PackFontRanges(). If you more control over the packing of multiple\n// fonts, or if you want to pack custom data into a font texture, take a look\n// at the source to of stbtt_PackFontRanges() and create a custom version\n// using these functions, e.g. call GatherRects multiple times,\n// building up a single array of rects, then call PackRects once,\n// then call RenderIntoRects repeatedly. This may result in a\n// better packing than calling PackFontRanges multiple times\n// (or it may not).\n\n// this is an opaque structure that you shouldn't mess with which holds\n// all the context needed from PackBegin to PackEnd.\nstruct stbtt_pack_context {\n   void *user_allocator_context;\n   void *pack_info;\n   int   width;\n   int   height;\n   int   stride_in_bytes;\n   int   padding;\n   int   skip_missing;\n   unsigned int   h_oversample, v_oversample;\n   unsigned char *pixels;\n   void  *nodes;\n};\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// FONT LOADING\n//\n//\n\nSTBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);\n// This function will determine the number of fonts in a font file.  TrueType\n// collection (.ttc) files may contain multiple fonts, while TrueType font\n// (.ttf) files only contain one font. The number of fonts can be used for\n// indexing with the previous function where the index is between zero and one\n// less than the total fonts. If an error occurs, -1 is returned.\n\nSTBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);\n// Each .ttf/.ttc file may have more than one font. Each font has a sequential\n// index number starting from 0. Call this function to get the font offset for\n// a given index; it returns -1 if the index is out of range. A regular .ttf\n// file will only define one font and it always be at offset 0, so it will\n// return '0' for index 0, and -1 for all other indices.\n\n// The following structure is defined publicly so you can declare one on\n// the stack or as a global or etc, but you should treat it as opaque.\nstruct stbtt_fontinfo\n{\n   void           * userdata;\n   unsigned char  * data;              // pointer to .ttf file\n   int              fontstart;         // offset of start of font\n\n   int numGlyphs;                     // number of glyphs, needed for range checking\n\n   int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf\n   int index_map;                     // a cmap mapping for our chosen character encoding\n   int indexToLocFormat;              // format needed to map from glyph index to glyph\n\n   stbtt__buf cff;                    // cff font data\n   stbtt__buf charstrings;            // the charstring index\n   stbtt__buf gsubrs;                 // global charstring subroutines index\n   stbtt__buf subrs;                  // private charstring subroutines index\n   stbtt__buf fontdicts;              // array of font dicts\n   stbtt__buf fdselect;               // map from glyph to fontdict\n};\n\nSTBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);\n// Given an offset into the file that defines a font, this function builds\n// the necessary cached info for the rest of the system. You must allocate\n// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't\n// need to do anything special to free it, because the contents are pure\n// value data with no additional data structures. Returns 0 on failure.\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// CHARACTER TO GLYPH-INDEX CONVERSIOn\n\nSTBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);\n// If you're going to perform multiple operations on the same character\n// and you want a speed-up, call this function with the character you're\n// going to process, then use glyph-based functions instead of the\n// codepoint-based functions.\n// Returns 0 if the character codepoint is not defined in the font.\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// CHARACTER PROPERTIES\n//\n\nSTBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);\n// computes a scale factor to produce a font whose \"height\" is 'pixels' tall.\n// Height is measured as the distance from the highest ascender to the lowest\n// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics\n// and computing:\n//       scale = pixels / (ascent - descent)\n// so if you prefer to measure height by the ascent only, use a similar calculation.\n\nSTBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);\n// computes a scale factor to produce a font whose EM size is mapped to\n// 'pixels' tall. This is probably what traditional APIs compute, but\n// I'm not positive.\n\nSTBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);\n// ascent is the coordinate above the baseline the font extends; descent\n// is the coordinate below the baseline the font extends (i.e. it is typically negative)\n// lineGap is the spacing between one row's descent and the next row's ascent...\n// so you should advance the vertical position by \"*ascent - *descent + *lineGap\"\n//   these are expressed in unscaled coordinates, so you must multiply by\n//   the scale factor for a given size\n\nSTBTT_DEF int  stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);\n// analogous to GetFontVMetrics, but returns the \"typographic\" values from the OS/2\n// table (specific to MS/Windows TTF files).\n//\n// Returns 1 on success (table present), 0 on failure.\n\nSTBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);\n// the bounding box around all possible characters\n\nSTBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);\n// leftSideBearing is the offset from the current horizontal position to the left edge of the character\n// advanceWidth is the offset from the current horizontal position to the next horizontal position\n//   these are expressed in unscaled coordinates\n\nSTBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);\n// an additional amount to add to the 'advance' value between ch1 and ch2\n\nSTBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);\n// Gets the bounding box of the visible part of the glyph, in unscaled coordinates\n\nSTBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);\nSTBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);\nSTBTT_DEF int  stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);\n// as above, but takes one or more glyph indices for greater efficiency\n\ntypedef struct stbtt_kerningentry\n{\n   int glyph1; // use stbtt_FindGlyphIndex\n   int glyph2;\n   int advance;\n} stbtt_kerningentry;\n\nSTBTT_DEF int  stbtt_GetKerningTableLength(const stbtt_fontinfo *info);\nSTBTT_DEF int  stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length);\n// Retrieves a complete list of all of the kerning pairs provided by the font\n// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write.\n// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1)\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// GLYPH SHAPES (you probably don't need these, but they have to go before\n// the bitmaps for C declaration-order reasons)\n//\n\n#ifndef STBTT_vmove // you can predefine these to use different values (but why?)\n   enum {\n      STBTT_vmove=1,\n      STBTT_vline,\n      STBTT_vcurve,\n      STBTT_vcubic\n   };\n#endif\n\n#ifndef stbtt_vertex // you can predefine this to use different values\n                   // (we share this with other code at RAD)\n   #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file\n   typedef struct\n   {\n      stbtt_vertex_type x,y,cx,cy,cx1,cy1;\n      unsigned char type,padding;\n   } stbtt_vertex;\n#endif\n\nSTBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);\n// returns non-zero if nothing is drawn for this glyph\n\nSTBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);\nSTBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);\n// returns # of vertices and fills *vertices with the pointer to them\n//   these are expressed in \"unscaled\" coordinates\n//\n// The shape is a series of contours. Each one starts with\n// a STBTT_moveto, then consists of a series of mixed\n// STBTT_lineto and STBTT_curveto segments. A lineto\n// draws a line from previous endpoint to its x,y; a curveto\n// draws a quadratic bezier from previous endpoint to\n// its x,y, using cx,cy as the bezier control point.\n\nSTBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);\n// frees the data allocated above\n\nSTBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl);\nSTBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg);\nSTBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg);\n// fills svg with the character's SVG data.\n// returns data size or 0 if SVG not found.\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// BITMAP RENDERING\n//\n\nSTBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);\n// frees the bitmap allocated below\n\nSTBTT_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);\n// allocates a large-enough single-channel 8bpp bitmap and renders the\n// specified character/glyph at the specified scale into it, with\n// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).\n// *width & *height are filled out with the width & height of the bitmap,\n// which is stored left-to-right, top-to-bottom.\n//\n// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap\n\nSTBTT_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);\n// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel\n// shift for the character\n\nSTBTT_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);\n// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap\n// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap\n// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the\n// width and height and positioning info for it first.\n\nSTBTT_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);\n// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel\n// shift for the character\n\nSTBTT_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);\n// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering\n// is performed (see stbtt_PackSetOversampling)\n\nSTBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\n// get the bbox of the bitmap centered around the glyph origin; so the\n// bitmap width is ix1-ix0, height is iy1-iy0, and location to place\n// the bitmap top left is (leftSideBearing*scale,iy0).\n// (Note that the bitmap uses y-increases-down, but the shape uses\n// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)\n\nSTBTT_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);\n// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel\n// shift for the character\n\n// the following functions are equivalent to the above functions, but operate\n// on glyph indices instead of Unicode codepoints (for efficiency)\nSTBTT_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);\nSTBTT_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);\nSTBTT_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);\nSTBTT_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);\nSTBTT_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);\nSTBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\nSTBTT_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);\n\n\n// @TODO: don't expose this structure\ntypedef struct\n{\n   int w,h,stride;\n   unsigned char *pixels;\n} stbtt__bitmap;\n\n// rasterize a shape with quadratic beziers into a bitmap\nSTBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result,        // 1-channel bitmap to draw into\n                               float flatness_in_pixels,     // allowable error of curve in pixels\n                               stbtt_vertex *vertices,       // array of vertices defining shape\n                               int num_verts,                // number of vertices in above array\n                               float scale_x, float scale_y, // scale applied to input vertices\n                               float shift_x, float shift_y, // translation applied to input vertices\n                               int x_off, int y_off,         // another translation applied to input\n                               int invert,                   // if non-zero, vertically flip shape\n                               void *userdata);              // context for to STBTT_MALLOC\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Signed Distance Function (or Field) rendering\n\nSTBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);\n// frees the SDF bitmap allocated below\n\nSTBTT_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);\nSTBTT_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);\n// These functions compute a discretized SDF field for a single character, suitable for storing\n// in a single-channel texture, sampling with bilinear filtering, and testing against\n// larger than some threshold to produce scalable fonts.\n//        info              --  the font\n//        scale             --  controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap\n//        glyph/codepoint   --  the character to generate the SDF for\n//        padding           --  extra \"pixels\" around the character which are filled with the distance to the character (not 0),\n//                                 which allows effects like bit outlines\n//        onedge_value      --  value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)\n//        pixel_dist_scale  --  what value the SDF should increase by when moving one SDF \"pixel\" away from the edge (on the 0..255 scale)\n//                                 if positive, > onedge_value is inside; if negative, < onedge_value is inside\n//        width,height      --  output height & width of the SDF bitmap (including padding)\n//        xoff,yoff         --  output origin of the character\n//        return value      --  a 2D array of bytes 0..255, width*height in size\n//\n// pixel_dist_scale & onedge_value are a scale & bias that allows you to make\n// optimal use of the limited 0..255 for your application, trading off precision\n// and special effects. SDF values outside the range 0..255 are clamped to 0..255.\n//\n// Example:\n//      scale = stbtt_ScaleForPixelHeight(22)\n//      padding = 5\n//      onedge_value = 180\n//      pixel_dist_scale = 180/5.0 = 36.0\n//\n//      This will create an SDF bitmap in which the character is about 22 pixels\n//      high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled\n//      shape, sample the SDF at each pixel and fill the pixel if the SDF value\n//      is greater than or equal to 180/255. (You'll actually want to antialias,\n//      which is beyond the scope of this example.) Additionally, you can compute\n//      offset outlines (e.g. to stroke the character border inside & outside,\n//      or only outside). For example, to fill outside the character up to 3 SDF\n//      pixels, you would compare against (180-36.0*3)/255 = 72/255. The above\n//      choice of variables maps a range from 5 pixels outside the shape to\n//      2 pixels inside the shape to 0..255; this is intended primarily for apply\n//      outside effects only (the interior range is needed to allow proper\n//      antialiasing of the font at *smaller* sizes)\n//\n// The function computes the SDF analytically at each SDF pixel, not by e.g.\n// building a higher-res bitmap and approximating it. In theory the quality\n// should be as high as possible for an SDF of this size & representation, but\n// unclear if this is true in practice (perhaps building a higher-res bitmap\n// and computing from that can allow drop-out prevention).\n//\n// The algorithm has not been optimized at all, so expect it to be slow\n// if computing lots of characters or very large sizes.\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Finding the right font...\n//\n// You should really just solve this offline, keep your own tables\n// of what font is what, and don't try to get it out of the .ttf file.\n// That's because getting it out of the .ttf file is really hard, because\n// the names in the file can appear in many possible encodings, in many\n// possible languages, and e.g. if you need a case-insensitive comparison,\n// the details of that depend on the encoding & language in a complex way\n// (actually underspecified in truetype, but also gigantic).\n//\n// But you can use the provided functions in two possible ways:\n//     stbtt_FindMatchingFont() will use *case-sensitive* comparisons on\n//             unicode-encoded names to try to find the font you want;\n//             you can run this before calling stbtt_InitFont()\n//\n//     stbtt_GetFontNameString() lets you get any of the various strings\n//             from the file yourself and do your own comparisons on them.\n//             You have to have called stbtt_InitFont() first.\n\n\nSTBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);\n// returns the offset (not index) of the font that matches, or -1 if none\n//   if you use STBTT_MACSTYLE_DONTCARE, use a font name like \"Arial Bold\".\n//   if you use any other flag, use a font name like \"Arial\"; this checks\n//     the 'macStyle' header field; i don't know if fonts set this consistently\n#define STBTT_MACSTYLE_DONTCARE     0\n#define STBTT_MACSTYLE_BOLD         1\n#define STBTT_MACSTYLE_ITALIC       2\n#define STBTT_MACSTYLE_UNDERSCORE   4\n#define STBTT_MACSTYLE_NONE         8   // <= not same as 0, this makes us check the bitfield is 0\n\nSTBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);\n// returns 1/0 whether the first string interpreted as utf8 is identical to\n// the second string interpreted as big-endian utf16... useful for strings from next func\n\nSTBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);\n// returns the string (which may be big-endian double byte, e.g. for unicode)\n// and puts the length in bytes in *length.\n//\n// some of the values for the IDs are below; for more see the truetype spec:\n//     http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html\n//     http://www.microsoft.com/typography/otspec/name.htm\n\nenum { // platformID\n   STBTT_PLATFORM_ID_UNICODE   =0,\n   STBTT_PLATFORM_ID_MAC       =1,\n   STBTT_PLATFORM_ID_ISO       =2,\n   STBTT_PLATFORM_ID_MICROSOFT =3\n};\n\nenum { // encodingID for STBTT_PLATFORM_ID_UNICODE\n   STBTT_UNICODE_EID_UNICODE_1_0    =0,\n   STBTT_UNICODE_EID_UNICODE_1_1    =1,\n   STBTT_UNICODE_EID_ISO_10646      =2,\n   STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,\n   STBTT_UNICODE_EID_UNICODE_2_0_FULL=4\n};\n\nenum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT\n   STBTT_MS_EID_SYMBOL        =0,\n   STBTT_MS_EID_UNICODE_BMP   =1,\n   STBTT_MS_EID_SHIFTJIS      =2,\n   STBTT_MS_EID_UNICODE_FULL  =10\n};\n\nenum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes\n   STBTT_MAC_EID_ROMAN        =0,   STBTT_MAC_EID_ARABIC       =4,\n   STBTT_MAC_EID_JAPANESE     =1,   STBTT_MAC_EID_HEBREW       =5,\n   STBTT_MAC_EID_CHINESE_TRAD =2,   STBTT_MAC_EID_GREEK        =6,\n   STBTT_MAC_EID_KOREAN       =3,   STBTT_MAC_EID_RUSSIAN      =7\n};\n\nenum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...\n       // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs\n   STBTT_MS_LANG_ENGLISH     =0x0409,   STBTT_MS_LANG_ITALIAN     =0x0410,\n   STBTT_MS_LANG_CHINESE     =0x0804,   STBTT_MS_LANG_JAPANESE    =0x0411,\n   STBTT_MS_LANG_DUTCH       =0x0413,   STBTT_MS_LANG_KOREAN      =0x0412,\n   STBTT_MS_LANG_FRENCH      =0x040c,   STBTT_MS_LANG_RUSSIAN     =0x0419,\n   STBTT_MS_LANG_GERMAN      =0x0407,   STBTT_MS_LANG_SPANISH     =0x0409,\n   STBTT_MS_LANG_HEBREW      =0x040d,   STBTT_MS_LANG_SWEDISH     =0x041D\n};\n\nenum { // languageID for STBTT_PLATFORM_ID_MAC\n   STBTT_MAC_LANG_ENGLISH      =0 ,   STBTT_MAC_LANG_JAPANESE     =11,\n   STBTT_MAC_LANG_ARABIC       =12,   STBTT_MAC_LANG_KOREAN       =23,\n   STBTT_MAC_LANG_DUTCH        =4 ,   STBTT_MAC_LANG_RUSSIAN      =32,\n   STBTT_MAC_LANG_FRENCH       =1 ,   STBTT_MAC_LANG_SPANISH      =6 ,\n   STBTT_MAC_LANG_GERMAN       =2 ,   STBTT_MAC_LANG_SWEDISH      =5 ,\n   STBTT_MAC_LANG_HEBREW       =10,   STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,\n   STBTT_MAC_LANG_ITALIAN      =3 ,   STBTT_MAC_LANG_CHINESE_TRAD =19\n};\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // __STB_INCLUDE_STB_TRUETYPE_H__\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n////\n////   IMPLEMENTATION\n////\n////\n\n#ifdef STB_TRUETYPE_IMPLEMENTATION\n\n#ifndef STBTT_MAX_OVERSAMPLE\n#define STBTT_MAX_OVERSAMPLE   8\n#endif\n\n#if STBTT_MAX_OVERSAMPLE > 255\n#error \"STBTT_MAX_OVERSAMPLE cannot be > 255\"\n#endif\n\ntypedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];\n\n#ifndef STBTT_RASTERIZER_VERSION\n#define STBTT_RASTERIZER_VERSION 2\n#endif\n\n#ifdef _MSC_VER\n#define STBTT__NOTUSED(v)  (void)(v)\n#else\n#define STBTT__NOTUSED(v)  (void)sizeof(v)\n#endif\n\n//////////////////////////////////////////////////////////////////////////\n//\n// stbtt__buf helpers to parse data from file\n//\n\nstatic stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)\n{\n   if (b->cursor >= b->size)\n      return 0;\n   return b->data[b->cursor++];\n}\n\nstatic stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)\n{\n   if (b->cursor >= b->size)\n      return 0;\n   return b->data[b->cursor];\n}\n\nstatic void stbtt__buf_seek(stbtt__buf *b, int o)\n{\n   STBTT_assert(!(o > b->size || o < 0));\n   b->cursor = (o > b->size || o < 0) ? b->size : o;\n}\n\nstatic void stbtt__buf_skip(stbtt__buf *b, int o)\n{\n   stbtt__buf_seek(b, b->cursor + o);\n}\n\nstatic stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)\n{\n   stbtt_uint32 v = 0;\n   int i;\n   STBTT_assert(n >= 1 && n <= 4);\n   for (i = 0; i < n; i++)\n      v = (v << 8) | stbtt__buf_get8(b);\n   return v;\n}\n\nstatic stbtt__buf stbtt__new_buf(const void *p, size_t size)\n{\n   stbtt__buf r;\n   STBTT_assert(size < 0x40000000);\n   r.data = (stbtt_uint8*) p;\n   r.size = (int) size;\n   r.cursor = 0;\n   return r;\n}\n\n#define stbtt__buf_get16(b)  stbtt__buf_get((b), 2)\n#define stbtt__buf_get32(b)  stbtt__buf_get((b), 4)\n\nstatic stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)\n{\n   stbtt__buf r = stbtt__new_buf(NULL, 0);\n   if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;\n   r.data = b->data + o;\n   r.size = s;\n   return r;\n}\n\nstatic stbtt__buf stbtt__cff_get_index(stbtt__buf *b)\n{\n   int count, start, offsize;\n   start = b->cursor;\n   count = stbtt__buf_get16(b);\n   if (count) {\n      offsize = stbtt__buf_get8(b);\n      STBTT_assert(offsize >= 1 && offsize <= 4);\n      stbtt__buf_skip(b, offsize * count);\n      stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);\n   }\n   return stbtt__buf_range(b, start, b->cursor - start);\n}\n\nstatic stbtt_uint32 stbtt__cff_int(stbtt__buf *b)\n{\n   int b0 = stbtt__buf_get8(b);\n   if (b0 >= 32 && b0 <= 246)       return b0 - 139;\n   else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;\n   else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;\n   else if (b0 == 28)               return stbtt__buf_get16(b);\n   else if (b0 == 29)               return stbtt__buf_get32(b);\n   STBTT_assert(0);\n   return 0;\n}\n\nstatic void stbtt__cff_skip_operand(stbtt__buf *b) {\n   int v, b0 = stbtt__buf_peek8(b);\n   STBTT_assert(b0 >= 28);\n   if (b0 == 30) {\n      stbtt__buf_skip(b, 1);\n      while (b->cursor < b->size) {\n         v = stbtt__buf_get8(b);\n         if ((v & 0xF) == 0xF || (v >> 4) == 0xF)\n            break;\n      }\n   } else {\n      stbtt__cff_int(b);\n   }\n}\n\nstatic stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)\n{\n   stbtt__buf_seek(b, 0);\n   while (b->cursor < b->size) {\n      int start = b->cursor, end, op;\n      while (stbtt__buf_peek8(b) >= 28)\n         stbtt__cff_skip_operand(b);\n      end = b->cursor;\n      op = stbtt__buf_get8(b);\n      if (op == 12)  op = stbtt__buf_get8(b) | 0x100;\n      if (op == key) return stbtt__buf_range(b, start, end-start);\n   }\n   return stbtt__buf_range(b, 0, 0);\n}\n\nstatic void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)\n{\n   int i;\n   stbtt__buf operands = stbtt__dict_get(b, key);\n   for (i = 0; i < outcount && operands.cursor < operands.size; i++)\n      out[i] = stbtt__cff_int(&operands);\n}\n\nstatic int stbtt__cff_index_count(stbtt__buf *b)\n{\n   stbtt__buf_seek(b, 0);\n   return stbtt__buf_get16(b);\n}\n\nstatic stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)\n{\n   int count, offsize, start, end;\n   stbtt__buf_seek(&b, 0);\n   count = stbtt__buf_get16(&b);\n   offsize = stbtt__buf_get8(&b);\n   STBTT_assert(i >= 0 && i < count);\n   STBTT_assert(offsize >= 1 && offsize <= 4);\n   stbtt__buf_skip(&b, i*offsize);\n   start = stbtt__buf_get(&b, offsize);\n   end = stbtt__buf_get(&b, offsize);\n   return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);\n}\n\n//////////////////////////////////////////////////////////////////////////\n//\n// accessors to parse data from file\n//\n\n// on platforms that don't allow misaligned reads, if we want to allow\n// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE\n\n#define ttBYTE(p)     (* (stbtt_uint8 *) (p))\n#define ttCHAR(p)     (* (stbtt_int8 *) (p))\n#define ttFixed(p)    ttLONG(p)\n\nstatic stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }\nstatic stbtt_int16 ttSHORT(stbtt_uint8 *p)   { return p[0]*256 + p[1]; }\nstatic stbtt_uint32 ttULONG(stbtt_uint8 *p)  { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }\nstatic stbtt_int32 ttLONG(stbtt_uint8 *p)    { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }\n\n#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))\n#define stbtt_tag(p,str)           stbtt_tag4(p,str[0],str[1],str[2],str[3])\n\nstatic int stbtt__isfont(stbtt_uint8 *font)\n{\n   // check the version number\n   if (stbtt_tag4(font, '1',0,0,0))  return 1; // TrueType 1\n   if (stbtt_tag(font, \"typ1\"))   return 1; // TrueType with type 1 font -- we don't support this!\n   if (stbtt_tag(font, \"OTTO\"))   return 1; // OpenType with CFF\n   if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0\n   if (stbtt_tag(font, \"true\"))   return 1; // Apple specification for TrueType fonts\n   return 0;\n}\n\n// @OPTIMIZE: binary search\nstatic stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)\n{\n   stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);\n   stbtt_uint32 tabledir = fontstart + 12;\n   stbtt_int32 i;\n   for (i=0; i < num_tables; ++i) {\n      stbtt_uint32 loc = tabledir + 16*i;\n      if (stbtt_tag(data+loc+0, tag))\n         return ttULONG(data+loc+8);\n   }\n   return 0;\n}\n\nstatic int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)\n{\n   // if it's just a font, there's only one valid index\n   if (stbtt__isfont(font_collection))\n      return index == 0 ? 0 : -1;\n\n   // check if it's a TTC\n   if (stbtt_tag(font_collection, \"ttcf\")) {\n      // version 1?\n      if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {\n         stbtt_int32 n = ttLONG(font_collection+8);\n         if (index >= n)\n            return -1;\n         return ttULONG(font_collection+12+index*4);\n      }\n   }\n   return -1;\n}\n\nstatic int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)\n{\n   // if it's just a font, there's only one valid font\n   if (stbtt__isfont(font_collection))\n      return 1;\n\n   // check if it's a TTC\n   if (stbtt_tag(font_collection, \"ttcf\")) {\n      // version 1?\n      if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {\n         return ttLONG(font_collection+8);\n      }\n   }\n   return 0;\n}\n\nstatic stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)\n{\n   stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };\n   stbtt__buf pdict;\n   stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);\n   if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);\n   pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);\n   stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);\n   if (!subrsoff) return stbtt__new_buf(NULL, 0);\n   stbtt__buf_seek(&cff, private_loc[1]+subrsoff);\n   return stbtt__cff_get_index(&cff);\n}\n\n// since most people won't use this, find this table the first time it's needed\nstatic int stbtt__get_svg(stbtt_fontinfo *info)\n{\n   stbtt_uint32 t;\n   if (info->svg < 0) {\n      t = stbtt__find_table(info->data, info->fontstart, \"SVG \");\n      if (t) {\n         stbtt_uint32 offset = ttULONG(info->data + t + 2);\n         info->svg = t + offset;\n      } else {\n         info->svg = 0;\n      }\n   }\n   return info->svg;\n}\n\nstatic int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)\n{\n   stbtt_uint32 cmap, t;\n   stbtt_int32 i,numTables;\n\n   info->data = data;\n   info->fontstart = fontstart;\n   info->cff = stbtt__new_buf(NULL, 0);\n\n   cmap = stbtt__find_table(data, fontstart, \"cmap\");       // required\n   info->loca = stbtt__find_table(data, fontstart, \"loca\"); // required\n   info->head = stbtt__find_table(data, fontstart, \"head\"); // required\n   info->glyf = stbtt__find_table(data, fontstart, \"glyf\"); // required\n   info->hhea = stbtt__find_table(data, fontstart, \"hhea\"); // required\n   info->hmtx = stbtt__find_table(data, fontstart, \"hmtx\"); // required\n   info->kern = stbtt__find_table(data, fontstart, \"kern\"); // not required\n   info->gpos = stbtt__find_table(data, fontstart, \"GPOS\"); // not required\n\n   if (!cmap || !info->head || !info->hhea || !info->hmtx)\n      return 0;\n   if (info->glyf) {\n      // required for truetype\n      if (!info->loca) return 0;\n   } else {\n      // initialization for CFF / Type2 fonts (OTF)\n      stbtt__buf b, topdict, topdictidx;\n      stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;\n      stbtt_uint32 cff;\n\n      cff = stbtt__find_table(data, fontstart, \"CFF \");\n      if (!cff) return 0;\n\n      info->fontdicts = stbtt__new_buf(NULL, 0);\n      info->fdselect = stbtt__new_buf(NULL, 0);\n\n      // @TODO this should use size from table (not 512MB)\n      info->cff = stbtt__new_buf(data+cff, 512*1024*1024);\n      b = info->cff;\n\n      // read the header\n      stbtt__buf_skip(&b, 2);\n      stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize\n\n      // @TODO the name INDEX could list multiple fonts,\n      // but we just use the first one.\n      stbtt__cff_get_index(&b);  // name INDEX\n      topdictidx = stbtt__cff_get_index(&b);\n      topdict = stbtt__cff_index_get(topdictidx, 0);\n      stbtt__cff_get_index(&b);  // string INDEX\n      info->gsubrs = stbtt__cff_get_index(&b);\n\n      stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);\n      stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);\n      stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);\n      stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);\n      info->subrs = stbtt__get_subrs(b, topdict);\n\n      // we only support Type 2 charstrings\n      if (cstype != 2) return 0;\n      if (charstrings == 0) return 0;\n\n      if (fdarrayoff) {\n         // looks like a CID font\n         if (!fdselectoff) return 0;\n         stbtt__buf_seek(&b, fdarrayoff);\n         info->fontdicts = stbtt__cff_get_index(&b);\n         info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);\n      }\n\n      stbtt__buf_seek(&b, charstrings);\n      info->charstrings = stbtt__cff_get_index(&b);\n   }\n\n   t = stbtt__find_table(data, fontstart, \"maxp\");\n   if (t)\n      info->numGlyphs = ttUSHORT(data+t+4);\n   else\n      info->numGlyphs = 0xffff;\n\n   info->svg = -1;\n\n   // find a cmap encoding table we understand *now* to avoid searching\n   // later. (todo: could make this installable)\n   // the same regardless of glyph.\n   numTables = ttUSHORT(data + cmap + 2);\n   info->index_map = 0;\n   for (i=0; i < numTables; ++i) {\n      stbtt_uint32 encoding_record = cmap + 4 + 8 * i;\n      // find an encoding we understand:\n      switch(ttUSHORT(data+encoding_record)) {\n         case STBTT_PLATFORM_ID_MICROSOFT:\n            switch (ttUSHORT(data+encoding_record+2)) {\n               case STBTT_MS_EID_UNICODE_BMP:\n               case STBTT_MS_EID_UNICODE_FULL:\n                  // MS/Unicode\n                  info->index_map = cmap + ttULONG(data+encoding_record+4);\n                  break;\n            }\n            break;\n        case STBTT_PLATFORM_ID_UNICODE:\n            // Mac/iOS has these\n            // all the encodingIDs are unicode, so we don't bother to check it\n            info->index_map = cmap + ttULONG(data+encoding_record+4);\n            break;\n      }\n   }\n   if (info->index_map == 0)\n      return 0;\n\n   info->indexToLocFormat = ttUSHORT(data+info->head + 50);\n   return 1;\n}\n\nSTBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)\n{\n   stbtt_uint8 *data = info->data;\n   stbtt_uint32 index_map = info->index_map;\n\n   stbtt_uint16 format = ttUSHORT(data + index_map + 0);\n   if (format == 0) { // apple byte encoding\n      stbtt_int32 bytes = ttUSHORT(data + index_map + 2);\n      if (unicode_codepoint < bytes-6)\n         return ttBYTE(data + index_map + 6 + unicode_codepoint);\n      return 0;\n   } else if (format == 6) {\n      stbtt_uint32 first = ttUSHORT(data + index_map + 6);\n      stbtt_uint32 count = ttUSHORT(data + index_map + 8);\n      if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)\n         return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);\n      return 0;\n   } else if (format == 2) {\n      STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean\n      return 0;\n   } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges\n      stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;\n      stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;\n      stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);\n      stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;\n\n      // do a binary search of the segments\n      stbtt_uint32 endCount = index_map + 14;\n      stbtt_uint32 search = endCount;\n\n      if (unicode_codepoint > 0xffff)\n         return 0;\n\n      // they lie from endCount .. endCount + segCount\n      // but searchRange is the nearest power of two, so...\n      if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))\n         search += rangeShift*2;\n\n      // now decrement to bias correctly to find smallest\n      search -= 2;\n      while (entrySelector) {\n         stbtt_uint16 end;\n         searchRange >>= 1;\n         end = ttUSHORT(data + search + searchRange*2);\n         if (unicode_codepoint > end)\n            search += searchRange*2;\n         --entrySelector;\n      }\n      search += 2;\n\n      {\n         stbtt_uint16 offset, start, last;\n         stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);\n\n         start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);\n         last = ttUSHORT(data + endCount + 2*item);\n         if (unicode_codepoint < start || unicode_codepoint > last)\n            return 0;\n\n         offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);\n         if (offset == 0)\n            return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));\n\n         return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);\n      }\n   } else if (format == 12 || format == 13) {\n      stbtt_uint32 ngroups = ttULONG(data+index_map+12);\n      stbtt_int32 low,high;\n      low = 0; high = (stbtt_int32)ngroups;\n      // Binary search the right group.\n      while (low < high) {\n         stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high\n         stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);\n         stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);\n         if ((stbtt_uint32) unicode_codepoint < start_char)\n            high = mid;\n         else if ((stbtt_uint32) unicode_codepoint > end_char)\n            low = mid+1;\n         else {\n            stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);\n            if (format == 12)\n               return start_glyph + unicode_codepoint-start_char;\n            else // format == 13\n               return start_glyph;\n         }\n      }\n      return 0; // not found\n   }\n   // @TODO\n   STBTT_assert(0);\n   return 0;\n}\n\nSTBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)\n{\n   return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);\n}\n\nstatic void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)\n{\n   v->type = type;\n   v->x = (stbtt_int16) x;\n   v->y = (stbtt_int16) y;\n   v->cx = (stbtt_int16) cx;\n   v->cy = (stbtt_int16) cy;\n}\n\nstatic int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)\n{\n   int g1,g2;\n\n   STBTT_assert(!info->cff.size);\n\n   if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range\n   if (info->indexToLocFormat >= 2)    return -1; // unknown index->glyph map format\n\n   if (info->indexToLocFormat == 0) {\n      g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;\n      g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;\n   } else {\n      g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);\n      g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);\n   }\n\n   return g1==g2 ? -1 : g1; // if length is 0, return -1\n}\n\nstatic int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);\n\nSTBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)\n{\n   if (info->cff.size) {\n      stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);\n   } else {\n      int g = stbtt__GetGlyfOffset(info, glyph_index);\n      if (g < 0) return 0;\n\n      if (x0) *x0 = ttSHORT(info->data + g + 2);\n      if (y0) *y0 = ttSHORT(info->data + g + 4);\n      if (x1) *x1 = ttSHORT(info->data + g + 6);\n      if (y1) *y1 = ttSHORT(info->data + g + 8);\n   }\n   return 1;\n}\n\nSTBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)\n{\n   return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);\n}\n\nSTBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)\n{\n   stbtt_int16 numberOfContours;\n   int g;\n   if (info->cff.size)\n      return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;\n   g = stbtt__GetGlyfOffset(info, glyph_index);\n   if (g < 0) return 1;\n   numberOfContours = ttSHORT(info->data + g);\n   return numberOfContours == 0;\n}\n\nstatic int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,\n    stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)\n{\n   if (start_off) {\n      if (was_off)\n         stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);\n      stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);\n   } else {\n      if (was_off)\n         stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);\n      else\n         stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);\n   }\n   return num_vertices;\n}\n\nstatic int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\n{\n   stbtt_int16 numberOfContours;\n   stbtt_uint8 *endPtsOfContours;\n   stbtt_uint8 *data = info->data;\n   stbtt_vertex *vertices=0;\n   int num_vertices=0;\n   int g = stbtt__GetGlyfOffset(info, glyph_index);\n\n   *pvertices = NULL;\n\n   if (g < 0) return 0;\n\n   numberOfContours = ttSHORT(data + g);\n\n   if (numberOfContours > 0) {\n      stbtt_uint8 flags=0,flagcount;\n      stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;\n      stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;\n      stbtt_uint8 *points;\n      endPtsOfContours = (data + g + 10);\n      ins = ttUSHORT(data + g + 10 + numberOfContours * 2);\n      points = data + g + 10 + numberOfContours * 2 + 2 + ins;\n\n      n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);\n\n      m = n + 2*numberOfContours;  // a loose bound on how many vertices we might need\n      vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);\n      if (vertices == 0)\n         return 0;\n\n      next_move = 0;\n      flagcount=0;\n\n      // in first pass, we load uninterpreted data into the allocated array\n      // above, shifted to the end of the array so we won't overwrite it when\n      // we create our final data starting from the front\n\n      off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated\n\n      // first load flags\n\n      for (i=0; i < n; ++i) {\n         if (flagcount == 0) {\n            flags = *points++;\n            if (flags & 8)\n               flagcount = *points++;\n         } else\n            --flagcount;\n         vertices[off+i].type = flags;\n      }\n\n      // now load x coordinates\n      x=0;\n      for (i=0; i < n; ++i) {\n         flags = vertices[off+i].type;\n         if (flags & 2) {\n            stbtt_int16 dx = *points++;\n            x += (flags & 16) ? dx : -dx; // ???\n         } else {\n            if (!(flags & 16)) {\n               x = x + (stbtt_int16) (points[0]*256 + points[1]);\n               points += 2;\n            }\n         }\n         vertices[off+i].x = (stbtt_int16) x;\n      }\n\n      // now load y coordinates\n      y=0;\n      for (i=0; i < n; ++i) {\n         flags = vertices[off+i].type;\n         if (flags & 4) {\n            stbtt_int16 dy = *points++;\n            y += (flags & 32) ? dy : -dy; // ???\n         } else {\n            if (!(flags & 32)) {\n               y = y + (stbtt_int16) (points[0]*256 + points[1]);\n               points += 2;\n            }\n         }\n         vertices[off+i].y = (stbtt_int16) y;\n      }\n\n      // now convert them to our format\n      num_vertices=0;\n      sx = sy = cx = cy = scx = scy = 0;\n      for (i=0; i < n; ++i) {\n         flags = vertices[off+i].type;\n         x     = (stbtt_int16) vertices[off+i].x;\n         y     = (stbtt_int16) vertices[off+i].y;\n\n         if (next_move == i) {\n            if (i != 0)\n               num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);\n\n            // now start the new one\n            start_off = !(flags & 1);\n            if (start_off) {\n               // if we start off with an off-curve point, then when we need to find a point on the curve\n               // where we can start, and we need to save some state for when we wraparound.\n               scx = x;\n               scy = y;\n               if (!(vertices[off+i+1].type & 1)) {\n                  // next point is also a curve point, so interpolate an on-point curve\n                  sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;\n                  sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;\n               } else {\n                  // otherwise just use the next point as our start point\n                  sx = (stbtt_int32) vertices[off+i+1].x;\n                  sy = (stbtt_int32) vertices[off+i+1].y;\n                  ++i; // we're using point i+1 as the starting point, so skip it\n               }\n            } else {\n               sx = x;\n               sy = y;\n            }\n            stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);\n            was_off = 0;\n            next_move = 1 + ttUSHORT(endPtsOfContours+j*2);\n            ++j;\n         } else {\n            if (!(flags & 1)) { // if it's a curve\n               if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint\n                  stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);\n               cx = x;\n               cy = y;\n               was_off = 1;\n            } else {\n               if (was_off)\n                  stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);\n               else\n                  stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);\n               was_off = 0;\n            }\n         }\n      }\n      num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);\n   } else if (numberOfContours < 0) {\n      // Compound shapes.\n      int more = 1;\n      stbtt_uint8 *comp = data + g + 10;\n      num_vertices = 0;\n      vertices = 0;\n      while (more) {\n         stbtt_uint16 flags, gidx;\n         int comp_num_verts = 0, i;\n         stbtt_vertex *comp_verts = 0, *tmp = 0;\n         float mtx[6] = {1,0,0,1,0,0}, m, n;\n\n         flags = ttSHORT(comp); comp+=2;\n         gidx = ttSHORT(comp); comp+=2;\n\n         if (flags & 2) { // XY values\n            if (flags & 1) { // shorts\n               mtx[4] = ttSHORT(comp); comp+=2;\n               mtx[5] = ttSHORT(comp); comp+=2;\n            } else {\n               mtx[4] = ttCHAR(comp); comp+=1;\n               mtx[5] = ttCHAR(comp); comp+=1;\n            }\n         }\n         else {\n            // @TODO handle matching point\n            STBTT_assert(0);\n         }\n         if (flags & (1<<3)) { // WE_HAVE_A_SCALE\n            mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\n            mtx[1] = mtx[2] = 0;\n         } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE\n            mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;\n            mtx[1] = mtx[2] = 0;\n            mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\n         } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO\n            mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;\n            mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;\n            mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;\n            mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\n         }\n\n         // Find transformation scales.\n         m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);\n         n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);\n\n         // Get indexed glyph.\n         comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);\n         if (comp_num_verts > 0) {\n            // Transform vertices.\n            for (i = 0; i < comp_num_verts; ++i) {\n               stbtt_vertex* v = &comp_verts[i];\n               stbtt_vertex_type x,y;\n               x=v->x; y=v->y;\n               v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));\n               v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));\n               x=v->cx; y=v->cy;\n               v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));\n               v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));\n            }\n            // Append vertices.\n            tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);\n            if (!tmp) {\n               if (vertices) STBTT_free(vertices, info->userdata);\n               if (comp_verts) STBTT_free(comp_verts, info->userdata);\n               return 0;\n            }\n            if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));\n            STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));\n            if (vertices) STBTT_free(vertices, info->userdata);\n            vertices = tmp;\n            STBTT_free(comp_verts, info->userdata);\n            num_vertices += comp_num_verts;\n         }\n         // More components ?\n         more = flags & (1<<5);\n      }\n   } else {\n      // numberOfCounters == 0, do nothing\n   }\n\n   *pvertices = vertices;\n   return num_vertices;\n}\n\ntypedef struct\n{\n   int bounds;\n   int started;\n   float first_x, first_y;\n   float x, y;\n   stbtt_int32 min_x, max_x, min_y, max_y;\n\n   stbtt_vertex *pvertices;\n   int num_vertices;\n} stbtt__csctx;\n\n#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}\n\nstatic void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)\n{\n   if (x > c->max_x || !c->started) c->max_x = x;\n   if (y > c->max_y || !c->started) c->max_y = y;\n   if (x < c->min_x || !c->started) c->min_x = x;\n   if (y < c->min_y || !c->started) c->min_y = y;\n   c->started = 1;\n}\n\nstatic 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)\n{\n   if (c->bounds) {\n      stbtt__track_vertex(c, x, y);\n      if (type == STBTT_vcubic) {\n         stbtt__track_vertex(c, cx, cy);\n         stbtt__track_vertex(c, cx1, cy1);\n      }\n   } else {\n      stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);\n      c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;\n      c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;\n   }\n   c->num_vertices++;\n}\n\nstatic void stbtt__csctx_close_shape(stbtt__csctx *ctx)\n{\n   if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)\n      stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);\n}\n\nstatic void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)\n{\n   stbtt__csctx_close_shape(ctx);\n   ctx->first_x = ctx->x = ctx->x + dx;\n   ctx->first_y = ctx->y = ctx->y + dy;\n   stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);\n}\n\nstatic void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)\n{\n   ctx->x += dx;\n   ctx->y += dy;\n   stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);\n}\n\nstatic void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)\n{\n   float cx1 = ctx->x + dx1;\n   float cy1 = ctx->y + dy1;\n   float cx2 = cx1 + dx2;\n   float cy2 = cy1 + dy2;\n   ctx->x = cx2 + dx3;\n   ctx->y = cy2 + dy3;\n   stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);\n}\n\nstatic stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)\n{\n   int count = stbtt__cff_index_count(&idx);\n   int bias = 107;\n   if (count >= 33900)\n      bias = 32768;\n   else if (count >= 1240)\n      bias = 1131;\n   n += bias;\n   if (n < 0 || n >= count)\n      return stbtt__new_buf(NULL, 0);\n   return stbtt__cff_index_get(idx, n);\n}\n\nstatic stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)\n{\n   stbtt__buf fdselect = info->fdselect;\n   int nranges, start, end, v, fmt, fdselector = -1, i;\n\n   stbtt__buf_seek(&fdselect, 0);\n   fmt = stbtt__buf_get8(&fdselect);\n   if (fmt == 0) {\n      // untested\n      stbtt__buf_skip(&fdselect, glyph_index);\n      fdselector = stbtt__buf_get8(&fdselect);\n   } else if (fmt == 3) {\n      nranges = stbtt__buf_get16(&fdselect);\n      start = stbtt__buf_get16(&fdselect);\n      for (i = 0; i < nranges; i++) {\n         v = stbtt__buf_get8(&fdselect);\n         end = stbtt__buf_get16(&fdselect);\n         if (glyph_index >= start && glyph_index < end) {\n            fdselector = v;\n            break;\n         }\n         start = end;\n      }\n   }\n   if (fdselector == -1) stbtt__new_buf(NULL, 0);\n   return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));\n}\n\nstatic int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)\n{\n   int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;\n   int has_subrs = 0, clear_stack;\n   float s[48];\n   stbtt__buf subr_stack[10], subrs = info->subrs, b;\n   float f;\n\n#define STBTT__CSERR(s) (0)\n\n   // this currently ignores the initial width value, which isn't needed if we have hmtx\n   b = stbtt__cff_index_get(info->charstrings, glyph_index);\n   while (b.cursor < b.size) {\n      i = 0;\n      clear_stack = 1;\n      b0 = stbtt__buf_get8(&b);\n      switch (b0) {\n      // @TODO implement hinting\n      case 0x13: // hintmask\n      case 0x14: // cntrmask\n         if (in_header)\n            maskbits += (sp / 2); // implicit \"vstem\"\n         in_header = 0;\n         stbtt__buf_skip(&b, (maskbits + 7) / 8);\n         break;\n\n      case 0x01: // hstem\n      case 0x03: // vstem\n      case 0x12: // hstemhm\n      case 0x17: // vstemhm\n         maskbits += (sp / 2);\n         break;\n\n      case 0x15: // rmoveto\n         in_header = 0;\n         if (sp < 2) return STBTT__CSERR(\"rmoveto stack\");\n         stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);\n         break;\n      case 0x04: // vmoveto\n         in_header = 0;\n         if (sp < 1) return STBTT__CSERR(\"vmoveto stack\");\n         stbtt__csctx_rmove_to(c, 0, s[sp-1]);\n         break;\n      case 0x16: // hmoveto\n         in_header = 0;\n         if (sp < 1) return STBTT__CSERR(\"hmoveto stack\");\n         stbtt__csctx_rmove_to(c, s[sp-1], 0);\n         break;\n\n      case 0x05: // rlineto\n         if (sp < 2) return STBTT__CSERR(\"rlineto stack\");\n         for (; i + 1 < sp; i += 2)\n            stbtt__csctx_rline_to(c, s[i], s[i+1]);\n         break;\n\n      // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical\n      // starting from a different place.\n\n      case 0x07: // vlineto\n         if (sp < 1) return STBTT__CSERR(\"vlineto stack\");\n         goto vlineto;\n      case 0x06: // hlineto\n         if (sp < 1) return STBTT__CSERR(\"hlineto stack\");\n         for (;;) {\n            if (i >= sp) break;\n            stbtt__csctx_rline_to(c, s[i], 0);\n            i++;\n      vlineto:\n            if (i >= sp) break;\n            stbtt__csctx_rline_to(c, 0, s[i]);\n            i++;\n         }\n         break;\n\n      case 0x1F: // hvcurveto\n         if (sp < 4) return STBTT__CSERR(\"hvcurveto stack\");\n         goto hvcurveto;\n      case 0x1E: // vhcurveto\n         if (sp < 4) return STBTT__CSERR(\"vhcurveto stack\");\n         for (;;) {\n            if (i + 3 >= sp) break;\n            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);\n            i += 4;\n      hvcurveto:\n            if (i + 3 >= sp) break;\n            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]);\n            i += 4;\n         }\n         break;\n\n      case 0x08: // rrcurveto\n         if (sp < 6) return STBTT__CSERR(\"rcurveline stack\");\n         for (; i + 5 < sp; i += 6)\n            stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);\n         break;\n\n      case 0x18: // rcurveline\n         if (sp < 8) return STBTT__CSERR(\"rcurveline stack\");\n         for (; i + 5 < sp - 2; i += 6)\n            stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);\n         if (i + 1 >= sp) return STBTT__CSERR(\"rcurveline stack\");\n         stbtt__csctx_rline_to(c, s[i], s[i+1]);\n         break;\n\n      case 0x19: // rlinecurve\n         if (sp < 8) return STBTT__CSERR(\"rlinecurve stack\");\n         for (; i + 1 < sp - 6; i += 2)\n            stbtt__csctx_rline_to(c, s[i], s[i+1]);\n         if (i + 5 >= sp) return STBTT__CSERR(\"rlinecurve stack\");\n         stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);\n         break;\n\n      case 0x1A: // vvcurveto\n      case 0x1B: // hhcurveto\n         if (sp < 4) return STBTT__CSERR(\"(vv|hh)curveto stack\");\n         f = 0.0;\n         if (sp & 1) { f = s[i]; i++; }\n         for (; i + 3 < sp; i += 4) {\n            if (b0 == 0x1B)\n               stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);\n            else\n               stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);\n            f = 0.0;\n         }\n         break;\n\n      case 0x0A: // callsubr\n         if (!has_subrs) {\n            if (info->fdselect.size)\n               subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);\n            has_subrs = 1;\n         }\n         // FALLTHROUGH\n      case 0x1D: // callgsubr\n         if (sp < 1) return STBTT__CSERR(\"call(g|)subr stack\");\n         v = (int) s[--sp];\n         if (subr_stack_height >= 10) return STBTT__CSERR(\"recursion limit\");\n         subr_stack[subr_stack_height++] = b;\n         b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);\n         if (b.size == 0) return STBTT__CSERR(\"subr not found\");\n         b.cursor = 0;\n         clear_stack = 0;\n         break;\n\n      case 0x0B: // return\n         if (subr_stack_height <= 0) return STBTT__CSERR(\"return outside subr\");\n         b = subr_stack[--subr_stack_height];\n         clear_stack = 0;\n         break;\n\n      case 0x0E: // endchar\n         stbtt__csctx_close_shape(c);\n         return 1;\n\n      case 0x0C: { // two-byte escape\n         float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;\n         float dx, dy;\n         int b1 = stbtt__buf_get8(&b);\n         switch (b1) {\n         // @TODO These \"flex\" implementations ignore the flex-depth and resolution,\n         // and always draw beziers.\n         case 0x22: // hflex\n            if (sp < 7) return STBTT__CSERR(\"hflex stack\");\n            dx1 = s[0];\n            dx2 = s[1];\n            dy2 = s[2];\n            dx3 = s[3];\n            dx4 = s[4];\n            dx5 = s[5];\n            dx6 = s[6];\n            stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);\n            stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);\n            break;\n\n         case 0x23: // flex\n            if (sp < 13) return STBTT__CSERR(\"flex stack\");\n            dx1 = s[0];\n            dy1 = s[1];\n            dx2 = s[2];\n            dy2 = s[3];\n            dx3 = s[4];\n            dy3 = s[5];\n            dx4 = s[6];\n            dy4 = s[7];\n            dx5 = s[8];\n            dy5 = s[9];\n            dx6 = s[10];\n            dy6 = s[11];\n            //fd is s[12]\n            stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);\n            stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);\n            break;\n\n         case 0x24: // hflex1\n            if (sp < 9) return STBTT__CSERR(\"hflex1 stack\");\n            dx1 = s[0];\n            dy1 = s[1];\n            dx2 = s[2];\n            dy2 = s[3];\n            dx3 = s[4];\n            dx4 = s[5];\n            dx5 = s[6];\n            dy5 = s[7];\n            dx6 = s[8];\n            stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);\n            stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));\n            break;\n\n         case 0x25: // flex1\n            if (sp < 11) return STBTT__CSERR(\"flex1 stack\");\n            dx1 = s[0];\n            dy1 = s[1];\n            dx2 = s[2];\n            dy2 = s[3];\n            dx3 = s[4];\n            dy3 = s[5];\n            dx4 = s[6];\n            dy4 = s[7];\n            dx5 = s[8];\n            dy5 = s[9];\n            dx6 = dy6 = s[10];\n            dx = dx1+dx2+dx3+dx4+dx5;\n            dy = dy1+dy2+dy3+dy4+dy5;\n            if (STBTT_fabs(dx) > STBTT_fabs(dy))\n               dy6 = -dy;\n            else\n               dx6 = -dx;\n            stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);\n            stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);\n            break;\n\n         default:\n            return STBTT__CSERR(\"unimplemented\");\n         }\n      } break;\n\n      default:\n         if (b0 != 255 && b0 != 28 && b0 < 32)\n            return STBTT__CSERR(\"reserved operator\");\n\n         // push immediate\n         if (b0 == 255) {\n            f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;\n         } else {\n            stbtt__buf_skip(&b, -1);\n            f = (float)(stbtt_int16)stbtt__cff_int(&b);\n         }\n         if (sp >= 48) return STBTT__CSERR(\"push stack overflow\");\n         s[sp++] = f;\n         clear_stack = 0;\n         break;\n      }\n      if (clear_stack) sp = 0;\n   }\n   return STBTT__CSERR(\"no endchar\");\n\n#undef STBTT__CSERR\n}\n\nstatic int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\n{\n   // runs the charstring twice, once to count and once to output (to avoid realloc)\n   stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);\n   stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);\n   if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {\n      *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);\n      output_ctx.pvertices = *pvertices;\n      if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {\n         STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);\n         return output_ctx.num_vertices;\n      }\n   }\n   *pvertices = NULL;\n   return 0;\n}\n\nstatic int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)\n{\n   stbtt__csctx c = STBTT__CSCTX_INIT(1);\n   int r = stbtt__run_charstring(info, glyph_index, &c);\n   if (x0)  *x0 = r ? c.min_x : 0;\n   if (y0)  *y0 = r ? c.min_y : 0;\n   if (x1)  *x1 = r ? c.max_x : 0;\n   if (y1)  *y1 = r ? c.max_y : 0;\n   return r ? c.num_vertices : 0;\n}\n\nSTBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\n{\n   if (!info->cff.size)\n      return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);\n   else\n      return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);\n}\n\nSTBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)\n{\n   stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);\n   if (glyph_index < numOfLongHorMetrics) {\n      if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*glyph_index);\n      if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);\n   } else {\n      if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));\n      if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));\n   }\n}\n\nSTBTT_DEF int  stbtt_GetKerningTableLength(const stbtt_fontinfo *info)\n{\n   stbtt_uint8 *data = info->data + info->kern;\n\n   // we only look at the first table. it must be 'horizontal' and format 0.\n   if (!info->kern)\n      return 0;\n   if (ttUSHORT(data+2) < 1) // number of tables, need at least 1\n      return 0;\n   if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format\n      return 0;\n\n   return ttUSHORT(data+10);\n}\n\nSTBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length)\n{\n   stbtt_uint8 *data = info->data + info->kern;\n   int k, length;\n\n   // we only look at the first table. it must be 'horizontal' and format 0.\n   if (!info->kern)\n      return 0;\n   if (ttUSHORT(data+2) < 1) // number of tables, need at least 1\n      return 0;\n   if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format\n      return 0;\n\n   length = ttUSHORT(data+10);\n   if (table_length < length)\n      length = table_length;\n\n   for (k = 0; k < length; k++)\n   {\n      table[k].glyph1 = ttUSHORT(data+18+(k*6));\n      table[k].glyph2 = ttUSHORT(data+20+(k*6));\n      table[k].advance = ttSHORT(data+22+(k*6));\n   }\n\n   return length;\n}\n\nstatic int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)\n{\n   stbtt_uint8 *data = info->data + info->kern;\n   stbtt_uint32 needle, straw;\n   int l, r, m;\n\n   // we only look at the first table. it must be 'horizontal' and format 0.\n   if (!info->kern)\n      return 0;\n   if (ttUSHORT(data+2) < 1) // number of tables, need at least 1\n      return 0;\n   if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format\n      return 0;\n\n   l = 0;\n   r = ttUSHORT(data+10) - 1;\n   needle = glyph1 << 16 | glyph2;\n   while (l <= r) {\n      m = (l + r) >> 1;\n      straw = ttULONG(data+18+(m*6)); // note: unaligned read\n      if (needle < straw)\n         r = m - 1;\n      else if (needle > straw)\n         l = m + 1;\n      else\n         return ttSHORT(data+22+(m*6));\n   }\n   return 0;\n}\n\nstatic stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)\n{\n   stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);\n   switch (coverageFormat) {\n      case 1: {\n         stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);\n\n         // Binary search.\n         stbtt_int32 l=0, r=glyphCount-1, m;\n         int straw, needle=glyph;\n         while (l <= r) {\n            stbtt_uint8 *glyphArray = coverageTable + 4;\n            stbtt_uint16 glyphID;\n            m = (l + r) >> 1;\n            glyphID = ttUSHORT(glyphArray + 2 * m);\n            straw = glyphID;\n            if (needle < straw)\n               r = m - 1;\n            else if (needle > straw)\n               l = m + 1;\n            else {\n               return m;\n            }\n         }\n         break;\n      }\n\n      case 2: {\n         stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);\n         stbtt_uint8 *rangeArray = coverageTable + 4;\n\n         // Binary search.\n         stbtt_int32 l=0, r=rangeCount-1, m;\n         int strawStart, strawEnd, needle=glyph;\n         while (l <= r) {\n            stbtt_uint8 *rangeRecord;\n            m = (l + r) >> 1;\n            rangeRecord = rangeArray + 6 * m;\n            strawStart = ttUSHORT(rangeRecord);\n            strawEnd = ttUSHORT(rangeRecord + 2);\n            if (needle < strawStart)\n               r = m - 1;\n            else if (needle > strawEnd)\n               l = m + 1;\n            else {\n               stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);\n               return startCoverageIndex + glyph - strawStart;\n            }\n         }\n         break;\n      }\n\n      default: return -1; // unsupported\n   }\n\n   return -1;\n}\n\nstatic stbtt_int32  stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)\n{\n   stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);\n   switch (classDefFormat)\n   {\n      case 1: {\n         stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);\n         stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);\n         stbtt_uint8 *classDef1ValueArray = classDefTable + 6;\n\n         if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)\n            return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));\n         break;\n      }\n\n      case 2: {\n         stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);\n         stbtt_uint8 *classRangeRecords = classDefTable + 4;\n\n         // Binary search.\n         stbtt_int32 l=0, r=classRangeCount-1, m;\n         int strawStart, strawEnd, needle=glyph;\n         while (l <= r) {\n            stbtt_uint8 *classRangeRecord;\n            m = (l + r) >> 1;\n            classRangeRecord = classRangeRecords + 6 * m;\n            strawStart = ttUSHORT(classRangeRecord);\n            strawEnd = ttUSHORT(classRangeRecord + 2);\n            if (needle < strawStart)\n               r = m - 1;\n            else if (needle > strawEnd)\n               l = m + 1;\n            else\n               return (stbtt_int32)ttUSHORT(classRangeRecord + 4);\n         }\n         break;\n      }\n\n      default:\n         return -1; // Unsupported definition type, return an error.\n   }\n\n   // \"All glyphs not assigned to a class fall into class 0\". (OpenType spec)\n   return 0;\n}\n\n// Define to STBTT_assert(x) if you want to break on unimplemented formats.\n#define STBTT_GPOS_TODO_assert(x)\n\nstatic stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)\n{\n   stbtt_uint16 lookupListOffset;\n   stbtt_uint8 *lookupList;\n   stbtt_uint16 lookupCount;\n   stbtt_uint8 *data;\n   stbtt_int32 i, sti;\n\n   if (!info->gpos) return 0;\n\n   data = info->data + info->gpos;\n\n   if (ttUSHORT(data+0) != 1) return 0; // Major version 1\n   if (ttUSHORT(data+2) != 0) return 0; // Minor version 0\n\n   lookupListOffset = ttUSHORT(data+8);\n   lookupList = data + lookupListOffset;\n   lookupCount = ttUSHORT(lookupList);\n\n   for (i=0; i<lookupCount; ++i) {\n      stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);\n      stbtt_uint8 *lookupTable = lookupList + lookupOffset;\n\n      stbtt_uint16 lookupType = ttUSHORT(lookupTable);\n      stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);\n      stbtt_uint8 *subTableOffsets = lookupTable + 6;\n      if (lookupType != 2) // Pair Adjustment Positioning Subtable\n         continue;\n\n      for (sti=0; sti<subTableCount; sti++) {\n         stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);\n         stbtt_uint8 *table = lookupTable + subtableOffset;\n         stbtt_uint16 posFormat = ttUSHORT(table);\n         stbtt_uint16 coverageOffset = ttUSHORT(table + 2);\n         stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);\n         if (coverageIndex == -1) continue;\n\n         switch (posFormat) {\n            case 1: {\n               stbtt_int32 l, r, m;\n               int straw, needle;\n               stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);\n               stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);\n               if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats?\n                  stbtt_int32 valueRecordPairSizeInBytes = 2;\n                  stbtt_uint16 pairSetCount = ttUSHORT(table + 8);\n                  stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);\n                  stbtt_uint8 *pairValueTable = table + pairPosOffset;\n                  stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);\n                  stbtt_uint8 *pairValueArray = pairValueTable + 2;\n\n                  if (coverageIndex >= pairSetCount) return 0;\n\n                  needle=glyph2;\n                  r=pairValueCount-1;\n                  l=0;\n\n                  // Binary search.\n                  while (l <= r) {\n                     stbtt_uint16 secondGlyph;\n                     stbtt_uint8 *pairValue;\n                     m = (l + r) >> 1;\n                     pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;\n                     secondGlyph = ttUSHORT(pairValue);\n                     straw = secondGlyph;\n                     if (needle < straw)\n                        r = m - 1;\n                     else if (needle > straw)\n                        l = m + 1;\n                     else {\n                        stbtt_int16 xAdvance = ttSHORT(pairValue + 2);\n                        return xAdvance;\n                     }\n                  }\n               } else\n                  return 0;\n               break;\n            }\n\n            case 2: {\n               stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);\n               stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);\n               if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats?\n                  stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);\n                  stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);\n                  int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);\n                  int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);\n\n                  stbtt_uint16 class1Count = ttUSHORT(table + 12);\n                  stbtt_uint16 class2Count = ttUSHORT(table + 14);\n                  stbtt_uint8 *class1Records, *class2Records;\n                  stbtt_int16 xAdvance;\n\n                  if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed\n                  if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed\n\n                  class1Records = table + 16;\n                  class2Records = class1Records + 2 * (glyph1class * class2Count);\n                  xAdvance = ttSHORT(class2Records + 2 * glyph2class);\n                  return xAdvance;\n               } else\n                  return 0;\n               break;\n            }\n\n            default:\n               return 0; // Unsupported position format\n         }\n      }\n   }\n\n   return 0;\n}\n\nSTBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)\n{\n   int xAdvance = 0;\n\n   if (info->gpos)\n      xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);\n   else if (info->kern)\n      xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);\n\n   return xAdvance;\n}\n\nSTBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)\n{\n   if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs\n      return 0;\n   return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));\n}\n\nSTBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)\n{\n   stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);\n}\n\nSTBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)\n{\n   if (ascent ) *ascent  = ttSHORT(info->data+info->hhea + 4);\n   if (descent) *descent = ttSHORT(info->data+info->hhea + 6);\n   if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);\n}\n\nSTBTT_DEF int  stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)\n{\n   int tab = stbtt__find_table(info->data, info->fontstart, \"OS/2\");\n   if (!tab)\n      return 0;\n   if (typoAscent ) *typoAscent  = ttSHORT(info->data+tab + 68);\n   if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);\n   if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);\n   return 1;\n}\n\nSTBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)\n{\n   *x0 = ttSHORT(info->data + info->head + 36);\n   *y0 = ttSHORT(info->data + info->head + 38);\n   *x1 = ttSHORT(info->data + info->head + 40);\n   *y1 = ttSHORT(info->data + info->head + 42);\n}\n\nSTBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)\n{\n   int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);\n   return (float) height / fheight;\n}\n\nSTBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)\n{\n   int unitsPerEm = ttUSHORT(info->data + info->head + 18);\n   return pixels / unitsPerEm;\n}\n\nSTBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)\n{\n   STBTT_free(v, info->userdata);\n}\n\nSTBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl)\n{\n   int i;\n   stbtt_uint8 *data = info->data;\n   stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info);\n\n   int numEntries = ttUSHORT(svg_doc_list);\n   stbtt_uint8 *svg_docs = svg_doc_list + 2;\n\n   for(i=0; i<numEntries; i++) {\n      stbtt_uint8 *svg_doc = svg_docs + (12 * i);\n      if ((gl >= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2)))\n         return svg_doc;\n   }\n   return 0;\n}\n\nSTBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg)\n{\n   stbtt_uint8 *data = info->data;\n   stbtt_uint8 *svg_doc;\n\n   if (info->svg == 0)\n      return 0;\n\n   svg_doc = stbtt_FindSVGDoc(info, gl);\n   if (svg_doc != NULL) {\n      *svg = (char *) data + info->svg + ttULONG(svg_doc + 4);\n      return ttULONG(svg_doc + 8);\n   } else {\n      return 0;\n   }\n}\n\nSTBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg)\n{\n   return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// antialiasing software rasterizer\n//\n\nSTBTT_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)\n{\n   int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning\n   if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {\n      // e.g. space character\n      if (ix0) *ix0 = 0;\n      if (iy0) *iy0 = 0;\n      if (ix1) *ix1 = 0;\n      if (iy1) *iy1 = 0;\n   } else {\n      // move to integral bboxes (treating pixels as little squares, what pixels get touched)?\n      if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);\n      if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);\n      if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);\n      if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);\n   }\n}\n\nSTBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)\n{\n   stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);\n}\n\nSTBTT_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)\n{\n   stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);\n}\n\nSTBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)\n{\n   stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  Rasterizer\n\ntypedef struct stbtt__hheap_chunk\n{\n   struct stbtt__hheap_chunk *next;\n} stbtt__hheap_chunk;\n\ntypedef struct stbtt__hheap\n{\n   struct stbtt__hheap_chunk *head;\n   void   *first_free;\n   int    num_remaining_in_head_chunk;\n} stbtt__hheap;\n\nstatic void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)\n{\n   if (hh->first_free) {\n      void *p = hh->first_free;\n      hh->first_free = * (void **) p;\n      return p;\n   } else {\n      if (hh->num_remaining_in_head_chunk == 0) {\n         int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);\n         stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);\n         if (c == NULL)\n            return NULL;\n         c->next = hh->head;\n         hh->head = c;\n         hh->num_remaining_in_head_chunk = count;\n      }\n      --hh->num_remaining_in_head_chunk;\n      return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;\n   }\n}\n\nstatic void stbtt__hheap_free(stbtt__hheap *hh, void *p)\n{\n   *(void **) p = hh->first_free;\n   hh->first_free = p;\n}\n\nstatic void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)\n{\n   stbtt__hheap_chunk *c = hh->head;\n   while (c) {\n      stbtt__hheap_chunk *n = c->next;\n      STBTT_free(c, userdata);\n      c = n;\n   }\n}\n\ntypedef struct stbtt__edge {\n   float x0,y0, x1,y1;\n   int invert;\n} stbtt__edge;\n\n\ntypedef struct stbtt__active_edge\n{\n   struct stbtt__active_edge *next;\n   #if STBTT_RASTERIZER_VERSION==1\n   int x,dx;\n   float ey;\n   int direction;\n   #elif STBTT_RASTERIZER_VERSION==2\n   float fx,fdx,fdy;\n   float direction;\n   float sy;\n   float ey;\n   #else\n   #error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\n   #endif\n} stbtt__active_edge;\n\n#if STBTT_RASTERIZER_VERSION == 1\n#define STBTT_FIXSHIFT   10\n#define STBTT_FIX        (1 << STBTT_FIXSHIFT)\n#define STBTT_FIXMASK    (STBTT_FIX-1)\n\nstatic stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)\n{\n   stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);\n   float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);\n   STBTT_assert(z != NULL);\n   if (!z) return z;\n\n   // round dx down to avoid overshooting\n   if (dxdy < 0)\n      z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);\n   else\n      z->dx = STBTT_ifloor(STBTT_FIX * dxdy);\n\n   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\n   z->x -= off_x * STBTT_FIX;\n\n   z->ey = e->y1;\n   z->next = 0;\n   z->direction = e->invert ? 1 : -1;\n   return z;\n}\n#elif STBTT_RASTERIZER_VERSION == 2\nstatic stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)\n{\n   stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);\n   float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);\n   STBTT_assert(z != NULL);\n   //STBTT_assert(e->y0 <= start_point);\n   if (!z) return z;\n   z->fdx = dxdy;\n   z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;\n   z->fx = e->x0 + dxdy * (start_point - e->y0);\n   z->fx -= off_x;\n   z->direction = e->invert ? 1.0f : -1.0f;\n   z->sy = e->y0;\n   z->ey = e->y1;\n   z->next = 0;\n   return z;\n}\n#else\n#error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\n#endif\n\n#if STBTT_RASTERIZER_VERSION == 1\n// note: this routine clips fills that extend off the edges... ideally this\n// wouldn't happen, but it could happen if the truetype glyph bounding boxes\n// are wrong, or if the user supplies a too-small bitmap\nstatic void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)\n{\n   // non-zero winding fill\n   int x0=0, w=0;\n\n   while (e) {\n      if (w == 0) {\n         // if we're currently at zero, we need to record the edge start point\n         x0 = e->x; w += e->direction;\n      } else {\n         int x1 = e->x; w += e->direction;\n         // if we went to zero, we need to draw\n         if (w == 0) {\n            int i = x0 >> STBTT_FIXSHIFT;\n            int j = x1 >> STBTT_FIXSHIFT;\n\n            if (i < len && j >= 0) {\n               if (i == j) {\n                  // x0,x1 are the same pixel, so compute combined coverage\n                  scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);\n               } else {\n                  if (i >= 0) // add antialiasing for x0\n                     scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);\n                  else\n                     i = -1; // clip\n\n                  if (j < len) // add antialiasing for x1\n                     scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);\n                  else\n                     j = len; // clip\n\n                  for (++i; i < j; ++i) // fill pixels between x0 and x1\n                     scanline[i] = scanline[i] + (stbtt_uint8) max_weight;\n               }\n            }\n         }\n      }\n\n      e = e->next;\n   }\n}\n\nstatic void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)\n{\n   stbtt__hheap hh = { 0, 0, 0 };\n   stbtt__active_edge *active = NULL;\n   int y,j=0;\n   int max_weight = (255 / vsubsample);  // weight per vertical scanline\n   int s; // vertical subsample index\n   unsigned char scanline_data[512], *scanline;\n\n   if (result->w > 512)\n      scanline = (unsigned char *) STBTT_malloc(result->w, userdata);\n   else\n      scanline = scanline_data;\n\n   y = off_y * vsubsample;\n   e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;\n\n   while (j < result->h) {\n      STBTT_memset(scanline, 0, result->w);\n      for (s=0; s < vsubsample; ++s) {\n         // find center of pixel for this scanline\n         float scan_y = y + 0.5f;\n         stbtt__active_edge **step = &active;\n\n         // update all active edges;\n         // remove all active edges that terminate before the center of this scanline\n         while (*step) {\n            stbtt__active_edge * z = *step;\n            if (z->ey <= scan_y) {\n               *step = z->next; // delete from list\n               STBTT_assert(z->direction);\n               z->direction = 0;\n               stbtt__hheap_free(&hh, z);\n            } else {\n               z->x += z->dx; // advance to position for current scanline\n               step = &((*step)->next); // advance through list\n            }\n         }\n\n         // resort the list if needed\n         for(;;) {\n            int changed=0;\n            step = &active;\n            while (*step && (*step)->next) {\n               if ((*step)->x > (*step)->next->x) {\n                  stbtt__active_edge *t = *step;\n                  stbtt__active_edge *q = t->next;\n\n                  t->next = q->next;\n                  q->next = t;\n                  *step = q;\n                  changed = 1;\n               }\n               step = &(*step)->next;\n            }\n            if (!changed) break;\n         }\n\n         // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline\n         while (e->y0 <= scan_y) {\n            if (e->y1 > scan_y) {\n               stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);\n               if (z != NULL) {\n                  // find insertion point\n                  if (active == NULL)\n                     active = z;\n                  else if (z->x < active->x) {\n                     // insert at front\n                     z->next = active;\n                     active = z;\n                  } else {\n                     // find thing to insert AFTER\n                     stbtt__active_edge *p = active;\n                     while (p->next && p->next->x < z->x)\n                        p = p->next;\n                     // at this point, p->next->x is NOT < z->x\n                     z->next = p->next;\n                     p->next = z;\n                  }\n               }\n            }\n            ++e;\n         }\n\n         // now process all active edges in XOR fashion\n         if (active)\n            stbtt__fill_active_edges(scanline, result->w, active, max_weight);\n\n         ++y;\n      }\n      STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);\n      ++j;\n   }\n\n   stbtt__hheap_cleanup(&hh, userdata);\n\n   if (scanline != scanline_data)\n      STBTT_free(scanline, userdata);\n}\n\n#elif STBTT_RASTERIZER_VERSION == 2\n\n// the edge passed in here does not cross the vertical line at x or the vertical line at x+1\n// (i.e. it has already been clipped to those)\nstatic void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)\n{\n   if (y0 == y1) return;\n   STBTT_assert(y0 < y1);\n   STBTT_assert(e->sy <= e->ey);\n   if (y0 > e->ey) return;\n   if (y1 < e->sy) return;\n   if (y0 < e->sy) {\n      x0 += (x1-x0) * (e->sy - y0) / (y1-y0);\n      y0 = e->sy;\n   }\n   if (y1 > e->ey) {\n      x1 += (x1-x0) * (e->ey - y1) / (y1-y0);\n      y1 = e->ey;\n   }\n\n   if (x0 == x)\n      STBTT_assert(x1 <= x+1);\n   else if (x0 == x+1)\n      STBTT_assert(x1 >= x);\n   else if (x0 <= x)\n      STBTT_assert(x1 <= x);\n   else if (x0 >= x+1)\n      STBTT_assert(x1 >= x+1);\n   else\n      STBTT_assert(x1 >= x && x1 <= x+1);\n\n   if (x0 <= x && x1 <= x)\n      scanline[x] += e->direction * (y1-y0);\n   else if (x0 >= x+1 && x1 >= x+1)\n      ;\n   else {\n      STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);\n      scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position\n   }\n}\n\nstatic float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width)\n{\n   STBTT_assert(top_width >= 0);\n   STBTT_assert(bottom_width >= 0);\n   return (top_width + bottom_width) / 2.0f * height;\n}\n\nstatic float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1)\n{\n   return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0);\n}\n\nstatic float stbtt__sized_triangle_area(float height, float width)\n{\n   return height * width / 2;\n}\n\nstatic void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)\n{\n   float y_bottom = y_top+1;\n\n   while (e) {\n      // brute force every pixel\n\n      // compute intersection points with top & bottom\n      STBTT_assert(e->ey >= y_top);\n\n      if (e->fdx == 0) {\n         float x0 = e->fx;\n         if (x0 < len) {\n            if (x0 >= 0) {\n               stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);\n               stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);\n            } else {\n               stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);\n            }\n         }\n      } else {\n         float x0 = e->fx;\n         float dx = e->fdx;\n         float xb = x0 + dx;\n         float x_top, x_bottom;\n         float sy0,sy1;\n         float dy = e->fdy;\n         STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);\n\n         // compute endpoints of line segment clipped to this scanline (if the\n         // line segment starts on this scanline. x0 is the intersection of the\n         // line with y_top, but that may be off the line segment.\n         if (e->sy > y_top) {\n            x_top = x0 + dx * (e->sy - y_top);\n            sy0 = e->sy;\n         } else {\n            x_top = x0;\n            sy0 = y_top;\n         }\n         if (e->ey < y_bottom) {\n            x_bottom = x0 + dx * (e->ey - y_top);\n            sy1 = e->ey;\n         } else {\n            x_bottom = xb;\n            sy1 = y_bottom;\n         }\n\n         if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {\n            // from here on, we don't have to range check x values\n\n            if ((int) x_top == (int) x_bottom) {\n               float height;\n               // simple case, only spans one pixel\n               int x = (int) x_top;\n               height = (sy1 - sy0) * e->direction;\n               STBTT_assert(x >= 0 && x < len);\n               scanline[x]      += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f);\n               scanline_fill[x] += height; // everything right of this pixel is filled\n            } else {\n               int x,x1,x2;\n               float y_crossing, y_final, step, sign, area;\n               // covers 2+ pixels\n               if (x_top > x_bottom) {\n                  // flip scanline vertically; signed area is the same\n                  float t;\n                  sy0 = y_bottom - (sy0 - y_top);\n                  sy1 = y_bottom - (sy1 - y_top);\n                  t = sy0, sy0 = sy1, sy1 = t;\n                  t = x_bottom, x_bottom = x_top, x_top = t;\n                  dx = -dx;\n                  dy = -dy;\n                  t = x0, x0 = xb, xb = t;\n               }\n               STBTT_assert(dy >= 0);\n               STBTT_assert(dx >= 0);\n\n               x1 = (int) x_top;\n               x2 = (int) x_bottom;\n               // compute intersection with y axis at x1+1\n               y_crossing = y_top + dy * (x1+1 - x0);\n\n               // compute intersection with y axis at x2\n               y_final = y_top + dy * (x2 - x0);\n\n               //           x1    x_top                            x2    x_bottom\n               //     y_top  +------|-----+------------+------------+--------|---+------------+\n               //            |            |            |            |            |            |\n               //            |            |            |            |            |            |\n               //       sy0  |      Txxxxx|............|............|............|............|\n               // y_crossing |            *xxxxx.......|............|............|............|\n               //            |            |     xxxxx..|............|............|............|\n               //            |            |     /-   xx*xxxx........|............|............|\n               //            |            | dy <       |    xxxxxx..|............|............|\n               //   y_final  |            |     \\-     |          xx*xxx.........|............|\n               //       sy1  |            |            |            |   xxxxxB...|............|\n               //            |            |            |            |            |            |\n               //            |            |            |            |            |            |\n               //  y_bottom  +------------+------------+------------+------------+------------+\n               //\n               // goal is to measure the area covered by '.' in each pixel\n\n               // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057\n               // @TODO: maybe test against sy1 rather than y_bottom?\n               if (y_crossing > y_bottom)\n                  y_crossing = y_bottom;\n\n               sign = e->direction;\n\n               // area of the rectangle covered from sy0..y_crossing\n               area = sign * (y_crossing-sy0);\n\n               // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing)\n               scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top);\n\n               // check if final y_crossing is blown up; no test case for this\n               if (y_final > y_bottom) {\n                  y_final = y_bottom;\n                  dy = (y_final - y_crossing ) / (x2 - (x1+1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom\n               }\n\n               // in second pixel, area covered by line segment found in first pixel\n               // is always a rectangle 1 wide * the height of that line segment; this\n               // is exactly what the variable 'area' stores. it also gets a contribution\n               // from the line segment within it. the THIRD pixel will get the first\n               // pixel's rectangle contribution, the second pixel's rectangle contribution,\n               // and its own contribution. the 'own contribution' is the same in every pixel except\n               // the leftmost and rightmost, a trapezoid that slides down in each pixel.\n               // the second pixel's contribution to the third pixel will be the\n               // rectangle 1 wide times the height change in the second pixel, which is dy.\n\n               step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x,\n               // which multiplied by 1-pixel-width is how much pixel area changes for each step in x\n               // so the area advances by 'step' every time\n\n               for (x = x1+1; x < x2; ++x) {\n                  scanline[x] += area + step/2; // area of trapezoid is 1*step/2\n                  area += step;\n               }\n               STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down\n               STBTT_assert(sy1 > y_final-0.01f);\n\n               // area covered in the last pixel is the rectangle from all the pixels to the left,\n               // plus the trapezoid filled by the line segment in this pixel all the way to the right edge\n               scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f);\n\n               // the rest of the line is filled based on the total height of the line segment in this pixel\n               scanline_fill[x2] += sign * (sy1-sy0);\n            }\n         } else {\n            // if edge goes outside of box we're drawing, we require\n            // clipping logic. since this does not match the intended use\n            // of this library, we use a different, very slow brute\n            // force implementation\n            // note though that this does happen some of the time because\n            // x_top and x_bottom can be extrapolated at the top & bottom of\n            // the shape and actually lie outside the bounding box\n            int x;\n            for (x=0; x < len; ++x) {\n               // cases:\n               //\n               // there can be up to two intersections with the pixel. any intersection\n               // with left or right edges can be handled by splitting into two (or three)\n               // regions. intersections with top & bottom do not necessitate case-wise logic.\n               //\n               // the old way of doing this found the intersections with the left & right edges,\n               // then used some simple logic to produce up to three segments in sorted order\n               // from top-to-bottom. however, this had a problem: if an x edge was epsilon\n               // across the x border, then the corresponding y position might not be distinct\n               // from the other y segment, and it might ignored as an empty segment. to avoid\n               // that, we need to explicitly produce segments based on x positions.\n\n               // rename variables to clearly-defined pairs\n               float y0 = y_top;\n               float x1 = (float) (x);\n               float x2 = (float) (x+1);\n               float x3 = xb;\n               float y3 = y_bottom;\n\n               // x = e->x + e->dx * (y-y_top)\n               // (y-y_top) = (x - e->x) / e->dx\n               // y = (x - e->x) / e->dx + y_top\n               float y1 = (x - x0) / dx + y_top;\n               float y2 = (x+1 - x0) / dx + y_top;\n\n               if (x0 < x1 && x3 > x2) {         // three segments descending down-right\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);\n               } else if (x3 < x1 && x0 > x2) {  // three segments descending down-left\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);\n               } else if (x0 < x1 && x3 > x1) {  // two segments across x, down-right\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);\n               } else if (x3 < x1 && x0 > x1) {  // two segments across x, down-left\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);\n               } else if (x0 < x2 && x3 > x2) {  // two segments across x+1, down-right\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);\n               } else if (x3 < x2 && x0 > x2) {  // two segments across x+1, down-left\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);\n               } else {  // one segment\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);\n               }\n            }\n         }\n      }\n      e = e->next;\n   }\n}\n\n// directly AA rasterize edges w/o supersampling\nstatic void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)\n{\n   stbtt__hheap hh = { 0, 0, 0 };\n   stbtt__active_edge *active = NULL;\n   int y,j=0, i;\n   float scanline_data[129], *scanline, *scanline2;\n\n   STBTT__NOTUSED(vsubsample);\n\n   if (result->w > 64)\n      scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);\n   else\n      scanline = scanline_data;\n\n   scanline2 = scanline + result->w;\n\n   y = off_y;\n   e[n].y0 = (float) (off_y + result->h) + 1;\n\n   while (j < result->h) {\n      // find center of pixel for this scanline\n      float scan_y_top    = y + 0.0f;\n      float scan_y_bottom = y + 1.0f;\n      stbtt__active_edge **step = &active;\n\n      STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));\n      STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));\n\n      // update all active edges;\n      // remove all active edges that terminate before the top of this scanline\n      while (*step) {\n         stbtt__active_edge * z = *step;\n         if (z->ey <= scan_y_top) {\n            *step = z->next; // delete from list\n            STBTT_assert(z->direction);\n            z->direction = 0;\n            stbtt__hheap_free(&hh, z);\n         } else {\n            step = &((*step)->next); // advance through list\n         }\n      }\n\n      // insert all edges that start before the bottom of this scanline\n      while (e->y0 <= scan_y_bottom) {\n         if (e->y0 != e->y1) {\n            stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);\n            if (z != NULL) {\n               if (j == 0 && off_y != 0) {\n                  if (z->ey < scan_y_top) {\n                     // this can happen due to subpixel positioning and some kind of fp rounding error i think\n                     z->ey = scan_y_top;\n                  }\n               }\n               STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds\n               // insert at front\n               z->next = active;\n               active = z;\n            }\n         }\n         ++e;\n      }\n\n      // now process all active edges\n      if (active)\n         stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);\n\n      {\n         float sum = 0;\n         for (i=0; i < result->w; ++i) {\n            float k;\n            int m;\n            sum += scanline2[i];\n            k = scanline[i] + sum;\n            k = (float) STBTT_fabs(k)*255 + 0.5f;\n            m = (int) k;\n            if (m > 255) m = 255;\n            result->pixels[j*result->stride + i] = (unsigned char) m;\n         }\n      }\n      // advance all the edges\n      step = &active;\n      while (*step) {\n         stbtt__active_edge *z = *step;\n         z->fx += z->fdx; // advance to position for current scanline\n         step = &((*step)->next); // advance through list\n      }\n\n      ++y;\n      ++j;\n   }\n\n   stbtt__hheap_cleanup(&hh, userdata);\n\n   if (scanline != scanline_data)\n      STBTT_free(scanline, userdata);\n}\n#else\n#error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\n#endif\n\n#define STBTT__COMPARE(a,b)  ((a)->y0 < (b)->y0)\n\nstatic void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)\n{\n   int i,j;\n   for (i=1; i < n; ++i) {\n      stbtt__edge t = p[i], *a = &t;\n      j = i;\n      while (j > 0) {\n         stbtt__edge *b = &p[j-1];\n         int c = STBTT__COMPARE(a,b);\n         if (!c) break;\n         p[j] = p[j-1];\n         --j;\n      }\n      if (i != j)\n         p[j] = t;\n   }\n}\n\nstatic void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)\n{\n   /* threshold for transitioning to insertion sort */\n   while (n > 12) {\n      stbtt__edge t;\n      int c01,c12,c,m,i,j;\n\n      /* compute median of three */\n      m = n >> 1;\n      c01 = STBTT__COMPARE(&p[0],&p[m]);\n      c12 = STBTT__COMPARE(&p[m],&p[n-1]);\n      /* if 0 >= mid >= end, or 0 < mid < end, then use mid */\n      if (c01 != c12) {\n         /* otherwise, we'll need to swap something else to middle */\n         int z;\n         c = STBTT__COMPARE(&p[0],&p[n-1]);\n         /* 0>mid && mid<n:  0>n => n; 0<n => 0 */\n         /* 0<mid && mid>n:  0>n => 0; 0<n => n */\n         z = (c == c12) ? 0 : n-1;\n         t = p[z];\n         p[z] = p[m];\n         p[m] = t;\n      }\n      /* now p[m] is the median-of-three */\n      /* swap it to the beginning so it won't move around */\n      t = p[0];\n      p[0] = p[m];\n      p[m] = t;\n\n      /* partition loop */\n      i=1;\n      j=n-1;\n      for(;;) {\n         /* handling of equality is crucial here */\n         /* for sentinels & efficiency with duplicates */\n         for (;;++i) {\n            if (!STBTT__COMPARE(&p[i], &p[0])) break;\n         }\n         for (;;--j) {\n            if (!STBTT__COMPARE(&p[0], &p[j])) break;\n         }\n         /* make sure we haven't crossed */\n         if (i >= j) break;\n         t = p[i];\n         p[i] = p[j];\n         p[j] = t;\n\n         ++i;\n         --j;\n      }\n      /* recurse on smaller side, iterate on larger */\n      if (j < (n-i)) {\n         stbtt__sort_edges_quicksort(p,j);\n         p = p+i;\n         n = n-i;\n      } else {\n         stbtt__sort_edges_quicksort(p+i, n-i);\n         n = j;\n      }\n   }\n}\n\nstatic void stbtt__sort_edges(stbtt__edge *p, int n)\n{\n   stbtt__sort_edges_quicksort(p, n);\n   stbtt__sort_edges_ins_sort(p, n);\n}\n\ntypedef struct\n{\n   float x,y;\n} stbtt__point;\n\nstatic 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)\n{\n   float y_scale_inv = invert ? -scale_y : scale_y;\n   stbtt__edge *e;\n   int n,i,j,k,m;\n#if STBTT_RASTERIZER_VERSION == 1\n   int vsubsample = result->h < 8 ? 15 : 5;\n#elif STBTT_RASTERIZER_VERSION == 2\n   int vsubsample = 1;\n#else\n   #error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\n#endif\n   // vsubsample should divide 255 evenly; otherwise we won't reach full opacity\n\n   // now we have to blow out the windings into explicit edge lists\n   n = 0;\n   for (i=0; i < windings; ++i)\n      n += wcount[i];\n\n   e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel\n   if (e == 0) return;\n   n = 0;\n\n   m=0;\n   for (i=0; i < windings; ++i) {\n      stbtt__point *p = pts + m;\n      m += wcount[i];\n      j = wcount[i]-1;\n      for (k=0; k < wcount[i]; j=k++) {\n         int a=k,b=j;\n         // skip the edge if horizontal\n         if (p[j].y == p[k].y)\n            continue;\n         // add edge from j to k to the list\n         e[n].invert = 0;\n         if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {\n            e[n].invert = 1;\n            a=j,b=k;\n         }\n         e[n].x0 = p[a].x * scale_x + shift_x;\n         e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;\n         e[n].x1 = p[b].x * scale_x + shift_x;\n         e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;\n         ++n;\n      }\n   }\n\n   // now sort the edges by their highest point (should snap to integer, and then by x)\n   //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);\n   stbtt__sort_edges(e, n);\n\n   // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule\n   stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);\n\n   STBTT_free(e, userdata);\n}\n\nstatic void stbtt__add_point(stbtt__point *points, int n, float x, float y)\n{\n   if (!points) return; // during first pass, it's unallocated\n   points[n].x = x;\n   points[n].y = y;\n}\n\n// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching\nstatic 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)\n{\n   // midpoint\n   float mx = (x0 + 2*x1 + x2)/4;\n   float my = (y0 + 2*y1 + y2)/4;\n   // versus directly drawn line\n   float dx = (x0+x2)/2 - mx;\n   float dy = (y0+y2)/2 - my;\n   if (n > 16) // 65536 segments on one curve better be enough!\n      return 1;\n   if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA\n      stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);\n      stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);\n   } else {\n      stbtt__add_point(points, *num_points,x2,y2);\n      *num_points = *num_points+1;\n   }\n   return 1;\n}\n\nstatic 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)\n{\n   // @TODO this \"flatness\" calculation is just made-up nonsense that seems to work well enough\n   float dx0 = x1-x0;\n   float dy0 = y1-y0;\n   float dx1 = x2-x1;\n   float dy1 = y2-y1;\n   float dx2 = x3-x2;\n   float dy2 = y3-y2;\n   float dx = x3-x0;\n   float dy = y3-y0;\n   float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));\n   float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);\n   float flatness_squared = longlen*longlen-shortlen*shortlen;\n\n   if (n > 16) // 65536 segments on one curve better be enough!\n      return;\n\n   if (flatness_squared > objspace_flatness_squared) {\n      float x01 = (x0+x1)/2;\n      float y01 = (y0+y1)/2;\n      float x12 = (x1+x2)/2;\n      float y12 = (y1+y2)/2;\n      float x23 = (x2+x3)/2;\n      float y23 = (y2+y3)/2;\n\n      float xa = (x01+x12)/2;\n      float ya = (y01+y12)/2;\n      float xb = (x12+x23)/2;\n      float yb = (y12+y23)/2;\n\n      float mx = (xa+xb)/2;\n      float my = (ya+yb)/2;\n\n      stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);\n      stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);\n   } else {\n      stbtt__add_point(points, *num_points,x3,y3);\n      *num_points = *num_points+1;\n   }\n}\n\n// returns number of contours\nstatic stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)\n{\n   stbtt__point *points=0;\n   int num_points=0;\n\n   float objspace_flatness_squared = objspace_flatness * objspace_flatness;\n   int i,n=0,start=0, pass;\n\n   // count how many \"moves\" there are to get the contour count\n   for (i=0; i < num_verts; ++i)\n      if (vertices[i].type == STBTT_vmove)\n         ++n;\n\n   *num_contours = n;\n   if (n == 0) return 0;\n\n   *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);\n\n   if (*contour_lengths == 0) {\n      *num_contours = 0;\n      return 0;\n   }\n\n   // make two passes through the points so we don't need to realloc\n   for (pass=0; pass < 2; ++pass) {\n      float x=0,y=0;\n      if (pass == 1) {\n         points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);\n         if (points == NULL) goto error;\n      }\n      num_points = 0;\n      n= -1;\n      for (i=0; i < num_verts; ++i) {\n         switch (vertices[i].type) {\n            case STBTT_vmove:\n               // start the next contour\n               if (n >= 0)\n                  (*contour_lengths)[n] = num_points - start;\n               ++n;\n               start = num_points;\n\n               x = vertices[i].x, y = vertices[i].y;\n               stbtt__add_point(points, num_points++, x,y);\n               break;\n            case STBTT_vline:\n               x = vertices[i].x, y = vertices[i].y;\n               stbtt__add_point(points, num_points++, x, y);\n               break;\n            case STBTT_vcurve:\n               stbtt__tesselate_curve(points, &num_points, x,y,\n                                        vertices[i].cx, vertices[i].cy,\n                                        vertices[i].x,  vertices[i].y,\n                                        objspace_flatness_squared, 0);\n               x = vertices[i].x, y = vertices[i].y;\n               break;\n            case STBTT_vcubic:\n               stbtt__tesselate_cubic(points, &num_points, x,y,\n                                        vertices[i].cx, vertices[i].cy,\n                                        vertices[i].cx1, vertices[i].cy1,\n                                        vertices[i].x,  vertices[i].y,\n                                        objspace_flatness_squared, 0);\n               x = vertices[i].x, y = vertices[i].y;\n               break;\n         }\n      }\n      (*contour_lengths)[n] = num_points - start;\n   }\n\n   return points;\nerror:\n   STBTT_free(points, userdata);\n   STBTT_free(*contour_lengths, userdata);\n   *contour_lengths = 0;\n   *num_contours = 0;\n   return NULL;\n}\n\nSTBTT_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)\n{\n   float scale            = scale_x > scale_y ? scale_y : scale_x;\n   int winding_count      = 0;\n   int *winding_lengths   = NULL;\n   stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);\n   if (windings) {\n      stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);\n      STBTT_free(winding_lengths, userdata);\n      STBTT_free(windings, userdata);\n   }\n}\n\nSTBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)\n{\n   STBTT_free(bitmap, userdata);\n}\n\nSTBTT_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)\n{\n   int ix0,iy0,ix1,iy1;\n   stbtt__bitmap gbm;\n   stbtt_vertex *vertices;\n   int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);\n\n   if (scale_x == 0) scale_x = scale_y;\n   if (scale_y == 0) {\n      if (scale_x == 0) {\n         STBTT_free(vertices, info->userdata);\n         return NULL;\n      }\n      scale_y = scale_x;\n   }\n\n   stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);\n\n   // now we get the size\n   gbm.w = (ix1 - ix0);\n   gbm.h = (iy1 - iy0);\n   gbm.pixels = NULL; // in case we error\n\n   if (width ) *width  = gbm.w;\n   if (height) *height = gbm.h;\n   if (xoff  ) *xoff   = ix0;\n   if (yoff  ) *yoff   = iy0;\n\n   if (gbm.w && gbm.h) {\n      gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);\n      if (gbm.pixels) {\n         gbm.stride = gbm.w;\n\n         stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);\n      }\n   }\n   STBTT_free(vertices, info->userdata);\n   return gbm.pixels;\n}\n\nSTBTT_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)\n{\n   return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);\n}\n\nSTBTT_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)\n{\n   int ix0,iy0;\n   stbtt_vertex *vertices;\n   int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);\n   stbtt__bitmap gbm;\n\n   stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);\n   gbm.pixels = output;\n   gbm.w = out_w;\n   gbm.h = out_h;\n   gbm.stride = out_stride;\n\n   if (gbm.w && gbm.h)\n      stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);\n\n   STBTT_free(vertices, info->userdata);\n}\n\nSTBTT_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)\n{\n   stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);\n}\n\nSTBTT_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)\n{\n   return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);\n}\n\nSTBTT_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)\n{\n   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));\n}\n\nSTBTT_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)\n{\n   stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));\n}\n\nSTBTT_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)\n{\n   return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);\n}\n\nSTBTT_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)\n{\n   stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// bitmap baking\n//\n// This is SUPER-CRAPPY packing to keep source code small\n\nstatic int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)\n                                float pixel_height,                     // height of font in pixels\n                                unsigned char *pixels, int pw, int ph,  // bitmap to be filled in\n                                int first_char, int num_chars,          // characters to bake\n                                stbtt_bakedchar *chardata)\n{\n   float scale;\n   int x,y,bottom_y, i;\n   stbtt_fontinfo f;\n   f.userdata = NULL;\n   if (!stbtt_InitFont(&f, data, offset))\n      return -1;\n   STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels\n   x=y=1;\n   bottom_y = 1;\n\n   scale = stbtt_ScaleForPixelHeight(&f, pixel_height);\n\n   for (i=0; i < num_chars; ++i) {\n      int advance, lsb, x0,y0,x1,y1,gw,gh;\n      int g = stbtt_FindGlyphIndex(&f, first_char + i);\n      stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);\n      stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);\n      gw = x1-x0;\n      gh = y1-y0;\n      if (x + gw + 1 >= pw)\n         y = bottom_y, x = 1; // advance to next row\n      if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row\n         return -i;\n      STBTT_assert(x+gw < pw);\n      STBTT_assert(y+gh < ph);\n      stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);\n      chardata[i].x0 = (stbtt_int16) x;\n      chardata[i].y0 = (stbtt_int16) y;\n      chardata[i].x1 = (stbtt_int16) (x + gw);\n      chardata[i].y1 = (stbtt_int16) (y + gh);\n      chardata[i].xadvance = scale * advance;\n      chardata[i].xoff     = (float) x0;\n      chardata[i].yoff     = (float) y0;\n      x = x + gw + 1;\n      if (y+gh+1 > bottom_y)\n         bottom_y = y+gh+1;\n   }\n   return bottom_y;\n}\n\nSTBTT_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)\n{\n   float d3d_bias = opengl_fillrule ? 0 : -0.5f;\n   float ipw = 1.0f / pw, iph = 1.0f / ph;\n   const stbtt_bakedchar *b = chardata + char_index;\n   int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);\n   int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);\n\n   q->x0 = round_x + d3d_bias;\n   q->y0 = round_y + d3d_bias;\n   q->x1 = round_x + b->x1 - b->x0 + d3d_bias;\n   q->y1 = round_y + b->y1 - b->y0 + d3d_bias;\n\n   q->s0 = b->x0 * ipw;\n   q->t0 = b->y0 * iph;\n   q->s1 = b->x1 * ipw;\n   q->t1 = b->y1 * iph;\n\n   *xpos += b->xadvance;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// rectangle packing replacement routines if you don't have stb_rect_pack.h\n//\n\n#ifndef STB_RECT_PACK_VERSION\n\ntypedef int stbrp_coord;\n\n////////////////////////////////////////////////////////////////////////////////////\n//                                                                                //\n//                                                                                //\n// COMPILER WARNING ?!?!?                                                         //\n//                                                                                //\n//                                                                                //\n// if you get a compile warning due to these symbols being defined more than      //\n// once, move #include \"stb_rect_pack.h\" before #include \"stb_truetype.h\"         //\n//                                                                                //\n////////////////////////////////////////////////////////////////////////////////////\n\ntypedef struct\n{\n   int width,height;\n   int x,y,bottom_y;\n} stbrp_context;\n\ntypedef struct\n{\n   unsigned char x;\n} stbrp_node;\n\nstruct stbrp_rect\n{\n   stbrp_coord x,y;\n   int id,w,h,was_packed;\n};\n\nstatic void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)\n{\n   con->width  = pw;\n   con->height = ph;\n   con->x = 0;\n   con->y = 0;\n   con->bottom_y = 0;\n   STBTT__NOTUSED(nodes);\n   STBTT__NOTUSED(num_nodes);\n}\n\nstatic void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)\n{\n   int i;\n   for (i=0; i < num_rects; ++i) {\n      if (con->x + rects[i].w > con->width) {\n         con->x = 0;\n         con->y = con->bottom_y;\n      }\n      if (con->y + rects[i].h > con->height)\n         break;\n      rects[i].x = con->x;\n      rects[i].y = con->y;\n      rects[i].was_packed = 1;\n      con->x += rects[i].w;\n      if (con->y + rects[i].h > con->bottom_y)\n         con->bottom_y = con->y + rects[i].h;\n   }\n   for (   ; i < num_rects; ++i)\n      rects[i].was_packed = 0;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// bitmap baking\n//\n// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If\n// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.\n\nSTBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)\n{\n   stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context)            ,alloc_context);\n   int            num_nodes = pw - padding;\n   stbrp_node    *nodes   = (stbrp_node    *) STBTT_malloc(sizeof(*nodes  ) * num_nodes,alloc_context);\n\n   if (context == NULL || nodes == NULL) {\n      if (context != NULL) STBTT_free(context, alloc_context);\n      if (nodes   != NULL) STBTT_free(nodes  , alloc_context);\n      return 0;\n   }\n\n   spc->user_allocator_context = alloc_context;\n   spc->width = pw;\n   spc->height = ph;\n   spc->pixels = pixels;\n   spc->pack_info = context;\n   spc->nodes = nodes;\n   spc->padding = padding;\n   spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;\n   spc->h_oversample = 1;\n   spc->v_oversample = 1;\n   spc->skip_missing = 0;\n\n   stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);\n\n   if (pixels)\n      STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels\n\n   return 1;\n}\n\nSTBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc)\n{\n   STBTT_free(spc->nodes    , spc->user_allocator_context);\n   STBTT_free(spc->pack_info, spc->user_allocator_context);\n}\n\nSTBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)\n{\n   STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);\n   STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);\n   if (h_oversample <= STBTT_MAX_OVERSAMPLE)\n      spc->h_oversample = h_oversample;\n   if (v_oversample <= STBTT_MAX_OVERSAMPLE)\n      spc->v_oversample = v_oversample;\n}\n\nSTBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)\n{\n   spc->skip_missing = skip;\n}\n\n#define STBTT__OVER_MASK  (STBTT_MAX_OVERSAMPLE-1)\n\nstatic void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)\n{\n   unsigned char buffer[STBTT_MAX_OVERSAMPLE];\n   int safe_w = w - kernel_width;\n   int j;\n   STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze\n   for (j=0; j < h; ++j) {\n      int i;\n      unsigned int total;\n      STBTT_memset(buffer, 0, kernel_width);\n\n      total = 0;\n\n      // make kernel_width a constant in common cases so compiler can optimize out the divide\n      switch (kernel_width) {\n         case 2:\n            for (i=0; i <= safe_w; ++i) {\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\n               pixels[i] = (unsigned char) (total / 2);\n            }\n            break;\n         case 3:\n            for (i=0; i <= safe_w; ++i) {\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\n               pixels[i] = (unsigned char) (total / 3);\n            }\n            break;\n         case 4:\n            for (i=0; i <= safe_w; ++i) {\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\n               pixels[i] = (unsigned char) (total / 4);\n            }\n            break;\n         case 5:\n            for (i=0; i <= safe_w; ++i) {\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\n               pixels[i] = (unsigned char) (total / 5);\n            }\n            break;\n         default:\n            for (i=0; i <= safe_w; ++i) {\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\n               pixels[i] = (unsigned char) (total / kernel_width);\n            }\n            break;\n      }\n\n      for (; i < w; ++i) {\n         STBTT_assert(pixels[i] == 0);\n         total -= buffer[i & STBTT__OVER_MASK];\n         pixels[i] = (unsigned char) (total / kernel_width);\n      }\n\n      pixels += stride_in_bytes;\n   }\n}\n\nstatic void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)\n{\n   unsigned char buffer[STBTT_MAX_OVERSAMPLE];\n   int safe_h = h - kernel_width;\n   int j;\n   STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze\n   for (j=0; j < w; ++j) {\n      int i;\n      unsigned int total;\n      STBTT_memset(buffer, 0, kernel_width);\n\n      total = 0;\n\n      // make kernel_width a constant in common cases so compiler can optimize out the divide\n      switch (kernel_width) {\n         case 2:\n            for (i=0; i <= safe_h; ++i) {\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 2);\n            }\n            break;\n         case 3:\n            for (i=0; i <= safe_h; ++i) {\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 3);\n            }\n            break;\n         case 4:\n            for (i=0; i <= safe_h; ++i) {\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 4);\n            }\n            break;\n         case 5:\n            for (i=0; i <= safe_h; ++i) {\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 5);\n            }\n            break;\n         default:\n            for (i=0; i <= safe_h; ++i) {\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\n               pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);\n            }\n            break;\n      }\n\n      for (; i < h; ++i) {\n         STBTT_assert(pixels[i*stride_in_bytes] == 0);\n         total -= buffer[i & STBTT__OVER_MASK];\n         pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);\n      }\n\n      pixels += 1;\n   }\n}\n\nstatic float stbtt__oversample_shift(int oversample)\n{\n   if (!oversample)\n      return 0.0f;\n\n   // The prefilter is a box filter of width \"oversample\",\n   // which shifts phase by (oversample - 1)/2 pixels in\n   // oversampled space. We want to shift in the opposite\n   // direction to counter this.\n   return (float)-(oversample - 1) / (2.0f * (float)oversample);\n}\n\n// rects array must be big enough to accommodate all characters in the given ranges\nSTBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)\n{\n   int i,j,k;\n   int missing_glyph_added = 0;\n\n   k=0;\n   for (i=0; i < num_ranges; ++i) {\n      float fh = ranges[i].font_size;\n      float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);\n      ranges[i].h_oversample = (unsigned char) spc->h_oversample;\n      ranges[i].v_oversample = (unsigned char) spc->v_oversample;\n      for (j=0; j < ranges[i].num_chars; ++j) {\n         int x0,y0,x1,y1;\n         int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];\n         int glyph = stbtt_FindGlyphIndex(info, codepoint);\n         if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) {\n            rects[k].w = rects[k].h = 0;\n         } else {\n            stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,\n                                            scale * spc->h_oversample,\n                                            scale * spc->v_oversample,\n                                            0,0,\n                                            &x0,&y0,&x1,&y1);\n            rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);\n            rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);\n            if (glyph == 0)\n               missing_glyph_added = 1;\n         }\n         ++k;\n      }\n   }\n\n   return k;\n}\n\nSTBTT_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)\n{\n   stbtt_MakeGlyphBitmapSubpixel(info,\n                                 output,\n                                 out_w - (prefilter_x - 1),\n                                 out_h - (prefilter_y - 1),\n                                 out_stride,\n                                 scale_x,\n                                 scale_y,\n                                 shift_x,\n                                 shift_y,\n                                 glyph);\n\n   if (prefilter_x > 1)\n      stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);\n\n   if (prefilter_y > 1)\n      stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);\n\n   *sub_x = stbtt__oversample_shift(prefilter_x);\n   *sub_y = stbtt__oversample_shift(prefilter_y);\n}\n\n// rects array must be big enough to accommodate all characters in the given ranges\nSTBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)\n{\n   int i,j,k, missing_glyph = -1, return_value = 1;\n\n   // save current values\n   int old_h_over = spc->h_oversample;\n   int old_v_over = spc->v_oversample;\n\n   k = 0;\n   for (i=0; i < num_ranges; ++i) {\n      float fh = ranges[i].font_size;\n      float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);\n      float recip_h,recip_v,sub_x,sub_y;\n      spc->h_oversample = ranges[i].h_oversample;\n      spc->v_oversample = ranges[i].v_oversample;\n      recip_h = 1.0f / spc->h_oversample;\n      recip_v = 1.0f / spc->v_oversample;\n      sub_x = stbtt__oversample_shift(spc->h_oversample);\n      sub_y = stbtt__oversample_shift(spc->v_oversample);\n      for (j=0; j < ranges[i].num_chars; ++j) {\n         stbrp_rect *r = &rects[k];\n         if (r->was_packed && r->w != 0 && r->h != 0) {\n            stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];\n            int advance, lsb, x0,y0,x1,y1;\n            int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];\n            int glyph = stbtt_FindGlyphIndex(info, codepoint);\n            stbrp_coord pad = (stbrp_coord) spc->padding;\n\n            // pad on left and top\n            r->x += pad;\n            r->y += pad;\n            r->w -= pad;\n            r->h -= pad;\n            stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);\n            stbtt_GetGlyphBitmapBox(info, glyph,\n                                    scale * spc->h_oversample,\n                                    scale * spc->v_oversample,\n                                    &x0,&y0,&x1,&y1);\n            stbtt_MakeGlyphBitmapSubpixel(info,\n                                          spc->pixels + r->x + r->y*spc->stride_in_bytes,\n                                          r->w - spc->h_oversample+1,\n                                          r->h - spc->v_oversample+1,\n                                          spc->stride_in_bytes,\n                                          scale * spc->h_oversample,\n                                          scale * spc->v_oversample,\n                                          0,0,\n                                          glyph);\n\n            if (spc->h_oversample > 1)\n               stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,\n                                  r->w, r->h, spc->stride_in_bytes,\n                                  spc->h_oversample);\n\n            if (spc->v_oversample > 1)\n               stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,\n                                  r->w, r->h, spc->stride_in_bytes,\n                                  spc->v_oversample);\n\n            bc->x0       = (stbtt_int16)  r->x;\n            bc->y0       = (stbtt_int16)  r->y;\n            bc->x1       = (stbtt_int16) (r->x + r->w);\n            bc->y1       = (stbtt_int16) (r->y + r->h);\n            bc->xadvance =                scale * advance;\n            bc->xoff     =       (float)  x0 * recip_h + sub_x;\n            bc->yoff     =       (float)  y0 * recip_v + sub_y;\n            bc->xoff2    =                (x0 + r->w) * recip_h + sub_x;\n            bc->yoff2    =                (y0 + r->h) * recip_v + sub_y;\n\n            if (glyph == 0)\n               missing_glyph = j;\n         } else if (spc->skip_missing) {\n            return_value = 0;\n         } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) {\n            ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph];\n         } else {\n            return_value = 0; // if any fail, report failure\n         }\n\n         ++k;\n      }\n   }\n\n   // restore original values\n   spc->h_oversample = old_h_over;\n   spc->v_oversample = old_v_over;\n\n   return return_value;\n}\n\nSTBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)\n{\n   stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);\n}\n\nSTBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)\n{\n   stbtt_fontinfo info;\n   int i,j,n, return_value = 1;\n   //stbrp_context *context = (stbrp_context *) spc->pack_info;\n   stbrp_rect    *rects;\n\n   // flag all characters as NOT packed\n   for (i=0; i < num_ranges; ++i)\n      for (j=0; j < ranges[i].num_chars; ++j)\n         ranges[i].chardata_for_range[j].x0 =\n         ranges[i].chardata_for_range[j].y0 =\n         ranges[i].chardata_for_range[j].x1 =\n         ranges[i].chardata_for_range[j].y1 = 0;\n\n   n = 0;\n   for (i=0; i < num_ranges; ++i)\n      n += ranges[i].num_chars;\n\n   rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);\n   if (rects == NULL)\n      return 0;\n\n   info.userdata = spc->user_allocator_context;\n   stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));\n\n   n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);\n\n   stbtt_PackFontRangesPackRects(spc, rects, n);\n\n   return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);\n\n   STBTT_free(rects, spc->user_allocator_context);\n   return return_value;\n}\n\nSTBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,\n            int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)\n{\n   stbtt_pack_range range;\n   range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;\n   range.array_of_unicode_codepoints = NULL;\n   range.num_chars                   = num_chars_in_range;\n   range.chardata_for_range          = chardata_for_range;\n   range.font_size                   = font_size;\n   return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);\n}\n\nSTBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)\n{\n   int i_ascent, i_descent, i_lineGap;\n   float scale;\n   stbtt_fontinfo info;\n   stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));\n   scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);\n   stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);\n   *ascent  = (float) i_ascent  * scale;\n   *descent = (float) i_descent * scale;\n   *lineGap = (float) i_lineGap * scale;\n}\n\nSTBTT_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)\n{\n   float ipw = 1.0f / pw, iph = 1.0f / ph;\n   const stbtt_packedchar *b = chardata + char_index;\n\n   if (align_to_integer) {\n      float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);\n      float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);\n      q->x0 = x;\n      q->y0 = y;\n      q->x1 = x + b->xoff2 - b->xoff;\n      q->y1 = y + b->yoff2 - b->yoff;\n   } else {\n      q->x0 = *xpos + b->xoff;\n      q->y0 = *ypos + b->yoff;\n      q->x1 = *xpos + b->xoff2;\n      q->y1 = *ypos + b->yoff2;\n   }\n\n   q->s0 = b->x0 * ipw;\n   q->t0 = b->y0 * iph;\n   q->s1 = b->x1 * ipw;\n   q->t1 = b->y1 * iph;\n\n   *xpos += b->xadvance;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// sdf computation\n//\n\n#define STBTT_min(a,b)  ((a) < (b) ? (a) : (b))\n#define STBTT_max(a,b)  ((a) < (b) ? (b) : (a))\n\nstatic int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])\n{\n   float q0perp = q0[1]*ray[0] - q0[0]*ray[1];\n   float q1perp = q1[1]*ray[0] - q1[0]*ray[1];\n   float q2perp = q2[1]*ray[0] - q2[0]*ray[1];\n   float roperp = orig[1]*ray[0] - orig[0]*ray[1];\n\n   float a = q0perp - 2*q1perp + q2perp;\n   float b = q1perp - q0perp;\n   float c = q0perp - roperp;\n\n   float s0 = 0., s1 = 0.;\n   int num_s = 0;\n\n   if (a != 0.0) {\n      float discr = b*b - a*c;\n      if (discr > 0.0) {\n         float rcpna = -1 / a;\n         float d = (float) STBTT_sqrt(discr);\n         s0 = (b+d) * rcpna;\n         s1 = (b-d) * rcpna;\n         if (s0 >= 0.0 && s0 <= 1.0)\n            num_s = 1;\n         if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {\n            if (num_s == 0) s0 = s1;\n            ++num_s;\n         }\n      }\n   } else {\n      // 2*b*s + c = 0\n      // s = -c / (2*b)\n      s0 = c / (-2 * b);\n      if (s0 >= 0.0 && s0 <= 1.0)\n         num_s = 1;\n   }\n\n   if (num_s == 0)\n      return 0;\n   else {\n      float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);\n      float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;\n\n      float q0d =   q0[0]*rayn_x +   q0[1]*rayn_y;\n      float q1d =   q1[0]*rayn_x +   q1[1]*rayn_y;\n      float q2d =   q2[0]*rayn_x +   q2[1]*rayn_y;\n      float rod = orig[0]*rayn_x + orig[1]*rayn_y;\n\n      float q10d = q1d - q0d;\n      float q20d = q2d - q0d;\n      float q0rd = q0d - rod;\n\n      hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;\n      hits[0][1] = a*s0+b;\n\n      if (num_s > 1) {\n         hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;\n         hits[1][1] = a*s1+b;\n         return 2;\n      } else {\n         return 1;\n      }\n   }\n}\n\nstatic int equal(float *a, float *b)\n{\n   return (a[0] == b[0] && a[1] == b[1]);\n}\n\nstatic int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)\n{\n   int i;\n   float orig[2], ray[2] = { 1, 0 };\n   float y_frac;\n   int winding = 0;\n\n   // make sure y never passes through a vertex of the shape\n   y_frac = (float) STBTT_fmod(y, 1.0f);\n   if (y_frac < 0.01f)\n      y += 0.01f;\n   else if (y_frac > 0.99f)\n      y -= 0.01f;\n\n   orig[0] = x;\n   orig[1] = y;\n\n   // test a ray from (-infinity,y) to (x,y)\n   for (i=0; i < nverts; ++i) {\n      if (verts[i].type == STBTT_vline) {\n         int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;\n         int x1 = (int) verts[i  ].x, y1 = (int) verts[i  ].y;\n         if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {\n            float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;\n            if (x_inter < x)\n               winding += (y0 < y1) ? 1 : -1;\n         }\n      }\n      if (verts[i].type == STBTT_vcurve) {\n         int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;\n         int x1 = (int) verts[i  ].cx, y1 = (int) verts[i  ].cy;\n         int x2 = (int) verts[i  ].x , y2 = (int) verts[i  ].y ;\n         int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));\n         int by = STBTT_max(y0,STBTT_max(y1,y2));\n         if (y > ay && y < by && x > ax) {\n            float q0[2],q1[2],q2[2];\n            float hits[2][2];\n            q0[0] = (float)x0;\n            q0[1] = (float)y0;\n            q1[0] = (float)x1;\n            q1[1] = (float)y1;\n            q2[0] = (float)x2;\n            q2[1] = (float)y2;\n            if (equal(q0,q1) || equal(q1,q2)) {\n               x0 = (int)verts[i-1].x;\n               y0 = (int)verts[i-1].y;\n               x1 = (int)verts[i  ].x;\n               y1 = (int)verts[i  ].y;\n               if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {\n                  float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;\n                  if (x_inter < x)\n                     winding += (y0 < y1) ? 1 : -1;\n               }\n            } else {\n               int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);\n               if (num_hits >= 1)\n                  if (hits[0][0] < 0)\n                     winding += (hits[0][1] < 0 ? -1 : 1);\n               if (num_hits >= 2)\n                  if (hits[1][0] < 0)\n                     winding += (hits[1][1] < 0 ? -1 : 1);\n            }\n         }\n      }\n   }\n   return winding;\n}\n\nstatic float stbtt__cuberoot( float x )\n{\n   if (x<0)\n      return -(float) STBTT_pow(-x,1.0f/3.0f);\n   else\n      return  (float) STBTT_pow( x,1.0f/3.0f);\n}\n\n// x^3 + a*x^2 + b*x + c = 0\nstatic int stbtt__solve_cubic(float a, float b, float c, float* r)\n{\n   float s = -a / 3;\n   float p = b - a*a / 3;\n   float q = a * (2*a*a - 9*b) / 27 + c;\n   float p3 = p*p*p;\n   float d = q*q + 4*p3 / 27;\n   if (d >= 0) {\n      float z = (float) STBTT_sqrt(d);\n      float u = (-q + z) / 2;\n      float v = (-q - z) / 2;\n      u = stbtt__cuberoot(u);\n      v = stbtt__cuberoot(v);\n      r[0] = s + u + v;\n      return 1;\n   } else {\n      float u = (float) STBTT_sqrt(-p/3);\n      float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative\n      float m = (float) STBTT_cos(v);\n      float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;\n      r[0] = s + u * 2 * m;\n      r[1] = s - u * (m + n);\n      r[2] = s - u * (m - n);\n\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?\n      //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);\n      //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);\n      return 3;\n   }\n}\n\nSTBTT_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)\n{\n   float scale_x = scale, scale_y = scale;\n   int ix0,iy0,ix1,iy1;\n   int w,h;\n   unsigned char *data;\n\n   if (scale == 0) return NULL;\n\n   stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);\n\n   // if empty, return NULL\n   if (ix0 == ix1 || iy0 == iy1)\n      return NULL;\n\n   ix0 -= padding;\n   iy0 -= padding;\n   ix1 += padding;\n   iy1 += padding;\n\n   w = (ix1 - ix0);\n   h = (iy1 - iy0);\n\n   if (width ) *width  = w;\n   if (height) *height = h;\n   if (xoff  ) *xoff   = ix0;\n   if (yoff  ) *yoff   = iy0;\n\n   // invert for y-downwards bitmaps\n   scale_y = -scale_y;\n\n   {\n      // distance from singular values (in the same units as the pixel grid)\n      const float eps = 1./1024, eps2 = eps*eps;\n      int x,y,i,j;\n      float *precompute;\n      stbtt_vertex *verts;\n      int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);\n      data = (unsigned char *) STBTT_malloc(w * h, info->userdata);\n      precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);\n\n      for (i=0,j=num_verts-1; i < num_verts; j=i++) {\n         if (verts[i].type == STBTT_vline) {\n            float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;\n            float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;\n            float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));\n            precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist;\n         } else if (verts[i].type == STBTT_vcurve) {\n            float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;\n            float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;\n            float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;\n            float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;\n            float len2 = bx*bx + by*by;\n            if (len2 >= eps2)\n               precompute[i] = 1.0f / len2;\n            else\n               precompute[i] = 0.0f;\n         } else\n            precompute[i] = 0.0f;\n      }\n\n      for (y=iy0; y < iy1; ++y) {\n         for (x=ix0; x < ix1; ++x) {\n            float val;\n            float min_dist = 999999.0f;\n            float sx = (float) x + 0.5f;\n            float sy = (float) y + 0.5f;\n            float x_gspace = (sx / scale_x);\n            float y_gspace = (sy / scale_y);\n\n            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\n\n            for (i=0; i < num_verts; ++i) {\n               float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;\n\n               if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) {\n                  float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;\n\n                  float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);\n                  if (dist2 < min_dist*min_dist)\n                     min_dist = (float) STBTT_sqrt(dist2);\n\n                  // coarse culling against bbox\n                  //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&\n                  //    sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)\n                  dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];\n                  STBTT_assert(i != 0);\n                  if (dist < min_dist) {\n                     // check position along line\n                     // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)\n                     // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)\n                     float dx = x1-x0, dy = y1-y0;\n                     float px = x0-sx, py = y0-sy;\n                     // 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\n                     // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve\n                     float t = -(px*dx + py*dy) / (dx*dx + dy*dy);\n                     if (t >= 0.0f && t <= 1.0f)\n                        min_dist = dist;\n                  }\n               } else if (verts[i].type == STBTT_vcurve) {\n                  float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;\n                  float x1 = verts[i  ].cx*scale_x, y1 = verts[i  ].cy*scale_y;\n                  float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);\n                  float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);\n                  float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);\n                  float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);\n                  // coarse culling against bbox to avoid computing cubic unnecessarily\n                  if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {\n                     int num=0;\n                     float ax = x1-x0, ay = y1-y0;\n                     float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;\n                     float mx = x0 - sx, my = y0 - sy;\n                     float res[3] = {0.f,0.f,0.f};\n                     float px,py,t,it,dist2;\n                     float a_inv = precompute[i];\n                     if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula\n                        float a = 3*(ax*bx + ay*by);\n                        float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);\n                        float c = mx*ax+my*ay;\n                        if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear\n                           if (STBTT_fabs(b) >= eps2) {\n                              res[num++] = -c/b;\n                           }\n                        } else {\n                           float discriminant = b*b - 4*a*c;\n                           if (discriminant < 0)\n                              num = 0;\n                           else {\n                              float root = (float) STBTT_sqrt(discriminant);\n                              res[0] = (-b - root)/(2*a);\n                              res[1] = (-b + root)/(2*a);\n                              num = 2; // don't bother distinguishing 1-solution case, as code below will still work\n                           }\n                        }\n                     } else {\n                        float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point\n                        float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;\n                        float d = (mx*ax+my*ay) * a_inv;\n                        num = stbtt__solve_cubic(b, c, d, res);\n                     }\n                     dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);\n                     if (dist2 < min_dist*min_dist)\n                        min_dist = (float) STBTT_sqrt(dist2);\n\n                     if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {\n                        t = res[0], it = 1.0f - t;\n                        px = it*it*x0 + 2*t*it*x1 + t*t*x2;\n                        py = it*it*y0 + 2*t*it*y1 + t*t*y2;\n                        dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);\n                        if (dist2 < min_dist * min_dist)\n                           min_dist = (float) STBTT_sqrt(dist2);\n                     }\n                     if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {\n                        t = res[1], it = 1.0f - t;\n                        px = it*it*x0 + 2*t*it*x1 + t*t*x2;\n                        py = it*it*y0 + 2*t*it*y1 + t*t*y2;\n                        dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);\n                        if (dist2 < min_dist * min_dist)\n                           min_dist = (float) STBTT_sqrt(dist2);\n                     }\n                     if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {\n                        t = res[2], it = 1.0f - t;\n                        px = it*it*x0 + 2*t*it*x1 + t*t*x2;\n                        py = it*it*y0 + 2*t*it*y1 + t*t*y2;\n                        dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);\n                        if (dist2 < min_dist * min_dist)\n                           min_dist = (float) STBTT_sqrt(dist2);\n                     }\n                  }\n               }\n            }\n            if (winding == 0)\n               min_dist = -min_dist;  // if outside the shape, value is negative\n            val = onedge_value + pixel_dist_scale * min_dist;\n            if (val < 0)\n               val = 0;\n            else if (val > 255)\n               val = 255;\n            data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;\n         }\n      }\n      STBTT_free(precompute, info->userdata);\n      STBTT_free(verts, info->userdata);\n   }\n   return data;\n}\n\nSTBTT_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)\n{\n   return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);\n}\n\nSTBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)\n{\n   STBTT_free(bitmap, userdata);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// font name matching -- recommended not to use this\n//\n\n// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string\nstatic stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)\n{\n   stbtt_int32 i=0;\n\n   // convert utf16 to utf8 and compare the results while converting\n   while (len2) {\n      stbtt_uint16 ch = s2[0]*256 + s2[1];\n      if (ch < 0x80) {\n         if (i >= len1) return -1;\n         if (s1[i++] != ch) return -1;\n      } else if (ch < 0x800) {\n         if (i+1 >= len1) return -1;\n         if (s1[i++] != 0xc0 + (ch >> 6)) return -1;\n         if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;\n      } else if (ch >= 0xd800 && ch < 0xdc00) {\n         stbtt_uint32 c;\n         stbtt_uint16 ch2 = s2[2]*256 + s2[3];\n         if (i+3 >= len1) return -1;\n         c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;\n         if (s1[i++] != 0xf0 + (c >> 18)) return -1;\n         if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;\n         if (s1[i++] != 0x80 + ((c >>  6) & 0x3f)) return -1;\n         if (s1[i++] != 0x80 + ((c      ) & 0x3f)) return -1;\n         s2 += 2; // plus another 2 below\n         len2 -= 2;\n      } else if (ch >= 0xdc00 && ch < 0xe000) {\n         return -1;\n      } else {\n         if (i+2 >= len1) return -1;\n         if (s1[i++] != 0xe0 + (ch >> 12)) return -1;\n         if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;\n         if (s1[i++] != 0x80 + ((ch     ) & 0x3f)) return -1;\n      }\n      s2 += 2;\n      len2 -= 2;\n   }\n   return i;\n}\n\nstatic int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)\n{\n   return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);\n}\n\n// returns results in whatever encoding you request... but note that 2-byte encodings\n// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare\nSTBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)\n{\n   stbtt_int32 i,count,stringOffset;\n   stbtt_uint8 *fc = font->data;\n   stbtt_uint32 offset = font->fontstart;\n   stbtt_uint32 nm = stbtt__find_table(fc, offset, \"name\");\n   if (!nm) return NULL;\n\n   count = ttUSHORT(fc+nm+2);\n   stringOffset = nm + ttUSHORT(fc+nm+4);\n   for (i=0; i < count; ++i) {\n      stbtt_uint32 loc = nm + 6 + 12 * i;\n      if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)\n          && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {\n         *length = ttUSHORT(fc+loc+8);\n         return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));\n      }\n   }\n   return NULL;\n}\n\nstatic int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)\n{\n   stbtt_int32 i;\n   stbtt_int32 count = ttUSHORT(fc+nm+2);\n   stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);\n\n   for (i=0; i < count; ++i) {\n      stbtt_uint32 loc = nm + 6 + 12 * i;\n      stbtt_int32 id = ttUSHORT(fc+loc+6);\n      if (id == target_id) {\n         // find the encoding\n         stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);\n\n         // is this a Unicode encoding?\n         if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {\n            stbtt_int32 slen = ttUSHORT(fc+loc+8);\n            stbtt_int32 off = ttUSHORT(fc+loc+10);\n\n            // check if there's a prefix match\n            stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);\n            if (matchlen >= 0) {\n               // check for target_id+1 immediately following, with same encoding & language\n               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) {\n                  slen = ttUSHORT(fc+loc+12+8);\n                  off = ttUSHORT(fc+loc+12+10);\n                  if (slen == 0) {\n                     if (matchlen == nlen)\n                        return 1;\n                  } else if (matchlen < nlen && name[matchlen] == ' ') {\n                     ++matchlen;\n                     if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))\n                        return 1;\n                  }\n               } else {\n                  // if nothing immediately following\n                  if (matchlen == nlen)\n                     return 1;\n               }\n            }\n         }\n\n         // @TODO handle other encodings\n      }\n   }\n   return 0;\n}\n\nstatic int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)\n{\n   stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);\n   stbtt_uint32 nm,hd;\n   if (!stbtt__isfont(fc+offset)) return 0;\n\n   // check italics/bold/underline flags in macStyle...\n   if (flags) {\n      hd = stbtt__find_table(fc, offset, \"head\");\n      if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;\n   }\n\n   nm = stbtt__find_table(fc, offset, \"name\");\n   if (!nm) return 0;\n\n   if (flags) {\n      // if we checked the macStyle flags, then just check the family and ignore the subfamily\n      if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))  return 1;\n      if (stbtt__matchpair(fc, nm, name, nlen,  1, -1))  return 1;\n      if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;\n   } else {\n      if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))  return 1;\n      if (stbtt__matchpair(fc, nm, name, nlen,  1,  2))  return 1;\n      if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;\n   }\n\n   return 0;\n}\n\nstatic int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)\n{\n   stbtt_int32 i;\n   for (i=0;;++i) {\n      stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);\n      if (off < 0) return off;\n      if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))\n         return off;\n   }\n}\n\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\n#endif\n\nSTBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,\n                                float pixel_height, unsigned char *pixels, int pw, int ph,\n                                int first_char, int num_chars, stbtt_bakedchar *chardata)\n{\n   return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);\n}\n\nSTBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)\n{\n   return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);\n}\n\nSTBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)\n{\n   return stbtt_GetNumberOfFonts_internal((unsigned char *) data);\n}\n\nSTBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)\n{\n   return stbtt_InitFont_internal(info, (unsigned char *) data, offset);\n}\n\nSTBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)\n{\n   return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);\n}\n\nSTBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)\n{\n   return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);\n}\n\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n\n#endif // STB_TRUETYPE_IMPLEMENTATION\n\n\n// FULL VERSION HISTORY\n//\n//   1.25 (2021-07-11) many fixes\n//   1.24 (2020-02-05) fix warning\n//   1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)\n//   1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined\n//   1.21 (2019-02-25) fix warning\n//   1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()\n//   1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod\n//   1.18 (2018-01-29) add missing function\n//   1.17 (2017-07-23) make more arguments const; doc fix\n//   1.16 (2017-07-12) SDF support\n//   1.15 (2017-03-03) make more arguments const\n//   1.14 (2017-01-16) num-fonts-in-TTC function\n//   1.13 (2017-01-02) support OpenType fonts, certain Apple fonts\n//   1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual\n//   1.11 (2016-04-02) fix unused-variable warning\n//   1.10 (2016-04-02) allow user-defined fabs() replacement\n//                     fix memory leak if fontsize=0.0\n//                     fix warning from duplicate typedef\n//   1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges\n//   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges\n//   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;\n//                     allow PackFontRanges to pack and render in separate phases;\n//                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);\n//                     fixed an assert() bug in the new rasterizer\n//                     replace assert() with STBTT_assert() in new rasterizer\n//   1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)\n//                     also more precise AA rasterizer, except if shapes overlap\n//                     remove need for STBTT_sort\n//   1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC\n//   1.04 (2015-04-15) typo in example\n//   1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes\n//   1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++\n//   1.01 (2014-12-08) fix subpixel position when oversampling to exactly match\n//                        non-oversampled; STBTT_POINT_SIZE for packed case only\n//   1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling\n//   0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)\n//   0.9  (2014-08-07) support certain mac/iOS fonts without an MS platformID\n//   0.8b (2014-07-07) fix a warning\n//   0.8  (2014-05-25) fix a few more warnings\n//   0.7  (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back\n//   0.6c (2012-07-24) improve documentation\n//   0.6b (2012-07-20) fix a few more warnings\n//   0.6  (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,\n//                        stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty\n//   0.5  (2011-12-09) bugfixes:\n//                        subpixel glyph renderer computed wrong bounding box\n//                        first vertex of shape can be off-curve (FreeSans)\n//   0.4b (2011-12-03) fixed an error in the font baking example\n//   0.4  (2011-12-01) kerning, subpixel rendering (tor)\n//                    bugfixes for:\n//                        codepoint-to-glyph conversion using table fmt=12\n//                        codepoint-to-glyph conversion using table fmt=4\n//                        stbtt_GetBakedQuad with non-square texture (Zer)\n//                    updated Hello World! sample to use kerning and subpixel\n//                    fixed some warnings\n//   0.3  (2009-06-24) cmap fmt=12, compound shapes (MM)\n//                    userdata, malloc-from-userdata, non-zero fill (stb)\n//   0.2  (2009-03-11) Fix unsigned/signed char warnings\n//   0.1  (2009-03-09) First public release\n//\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_vorbis.c",
    "content": "// Ogg Vorbis audio decoder - v1.22 - public domain\n// http://nothings.org/stb_vorbis/\n//\n// Original version written by Sean Barrett in 2007.\n//\n// Originally sponsored by RAD Game Tools. Seeking implementation\n// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,\n// Elias Software, Aras Pranckevicius, and Sean Barrett.\n//\n// LICENSE\n//\n//   See end of file for license information.\n//\n// Limitations:\n//\n//   - floor 0 not supported (used in old ogg vorbis files pre-2004)\n//   - lossless sample-truncation at beginning ignored\n//   - cannot concatenate multiple vorbis streams\n//   - sample positions are 32-bit, limiting seekable 192Khz\n//       files to around 6 hours (Ogg supports 64-bit)\n//\n// Feature contributors:\n//    Dougall Johnson (sample-exact seeking)\n//\n// Bugfix/warning contributors:\n//    Terje Mathisen     Niklas Frykholm     Andy Hill\n//    Casey Muratori     John Bolton         Gargaj\n//    Laurent Gomila     Marc LeBlanc        Ronny Chevalier\n//    Bernhard Wodo      Evan Balster        github:alxprd\n//    Tom Beaumont       Ingo Leitgeb        Nicolas Guillemot\n//    Phillip Bennefall  Rohit               Thiago Goulart\n//    github:manxorist   Saga Musix          github:infatum\n//    Timur Gagiev       Maxwell Koo         Peter Waller\n//    github:audinowho   Dougall Johnson     David Reid\n//    github:Clownacy    Pedro J. Estebanez  Remi Verschelde\n//    AnthoFoxo          github:morlat       Gabriel Ravier\n//\n// Partial history:\n//    1.22    - 2021-07-11 - various small fixes\n//    1.21    - 2021-07-02 - fix bug for files with no comments\n//    1.20    - 2020-07-11 - several small fixes\n//    1.19    - 2020-02-05 - warnings\n//    1.18    - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc.\n//    1.17    - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)\n//    1.16    - 2019-03-04 - fix warnings\n//    1.15    - 2019-02-07 - explicit failure if Ogg Skeleton data is found\n//    1.14    - 2018-02-11 - delete bogus dealloca usage\n//    1.13    - 2018-01-29 - fix truncation of last frame (hopefully)\n//    1.12    - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files\n//    1.11    - 2017-07-23 - fix MinGW compilation\n//    1.10    - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory\n//    1.09    - 2016-04-04 - back out 'truncation of last frame' fix from previous version\n//    1.08    - 2016-04-02 - warnings; setup memory leaks; truncation of last frame\n//    1.07    - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const\n//    1.06    - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)\n//                           some crash fixes when out of memory or with corrupt files\n//                           fix some inappropriately signed shifts\n//    1.05    - 2015-04-19 - don't define __forceinline if it's redundant\n//    1.04    - 2014-08-27 - fix missing const-correct case in API\n//    1.03    - 2014-08-07 - warning fixes\n//    1.02    - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows\n//    1.01    - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)\n//    1.0     - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;\n//                           (API change) report sample rate for decode-full-file funcs\n//\n// See end of file for full version history.\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  HEADER BEGINS HERE\n//\n\n#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H\n#define STB_VORBIS_INCLUDE_STB_VORBIS_H\n\n#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)\n#define STB_VORBIS_NO_STDIO 1\n#endif\n\n#ifndef STB_VORBIS_NO_STDIO\n#include <stdio.h>\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n///////////   THREAD SAFETY\n\n// Individual stb_vorbis* handles are not thread-safe; you cannot decode from\n// them from multiple threads at the same time. However, you can have multiple\n// stb_vorbis* handles and decode from them independently in multiple thrads.\n\n\n///////////   MEMORY ALLOCATION\n\n// normally stb_vorbis uses malloc() to allocate memory at startup,\n// and alloca() to allocate temporary memory during a frame on the\n// stack. (Memory consumption will depend on the amount of setup\n// data in the file and how you set the compile flags for speed\n// vs. size. In my test files the maximal-size usage is ~150KB.)\n//\n// You can modify the wrapper functions in the source (setup_malloc,\n// setup_temp_malloc, temp_malloc) to change this behavior, or you\n// can use a simpler allocation model: you pass in a buffer from\n// which stb_vorbis will allocate _all_ its memory (including the\n// temp memory). \"open\" may fail with a VORBIS_outofmem if you\n// do not pass in enough data; there is no way to determine how\n// much you do need except to succeed (at which point you can\n// query get_info to find the exact amount required. yes I know\n// this is lame).\n//\n// If you pass in a non-NULL buffer of the type below, allocation\n// will occur from it as described above. Otherwise just pass NULL\n// to use malloc()/alloca()\n\ntypedef struct\n{\n   char *alloc_buffer;\n   int   alloc_buffer_length_in_bytes;\n} stb_vorbis_alloc;\n\n\n///////////   FUNCTIONS USEABLE WITH ALL INPUT MODES\n\ntypedef struct stb_vorbis stb_vorbis;\n\ntypedef struct\n{\n   unsigned int sample_rate;\n   int channels;\n\n   unsigned int setup_memory_required;\n   unsigned int setup_temp_memory_required;\n   unsigned int temp_memory_required;\n\n   int max_frame_size;\n} stb_vorbis_info;\n\ntypedef struct\n{\n   char *vendor;\n\n   int comment_list_length;\n   char **comment_list;\n} stb_vorbis_comment;\n\n// get general information about the file\nextern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);\n\n// get ogg comments\nextern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f);\n\n// get the last error detected (clears it, too)\nextern int stb_vorbis_get_error(stb_vorbis *f);\n\n// close an ogg vorbis file and free all memory in use\nextern void stb_vorbis_close(stb_vorbis *f);\n\n// this function returns the offset (in samples) from the beginning of the\n// file that will be returned by the next decode, if it is known, or -1\n// otherwise. after a flush_pushdata() call, this may take a while before\n// it becomes valid again.\n// NOT WORKING YET after a seek with PULLDATA API\nextern int stb_vorbis_get_sample_offset(stb_vorbis *f);\n\n// returns the current seek point within the file, or offset from the beginning\n// of the memory buffer. In pushdata mode it returns 0.\nextern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);\n\n///////////   PUSHDATA API\n\n#ifndef STB_VORBIS_NO_PUSHDATA_API\n\n// this API allows you to get blocks of data from any source and hand\n// them to stb_vorbis. you have to buffer them; stb_vorbis will tell\n// you how much it used, and you have to give it the rest next time;\n// and stb_vorbis may not have enough data to work with and you will\n// need to give it the same data again PLUS more. Note that the Vorbis\n// specification does not bound the size of an individual frame.\n\nextern stb_vorbis *stb_vorbis_open_pushdata(\n         const unsigned char * datablock, int datablock_length_in_bytes,\n         int *datablock_memory_consumed_in_bytes,\n         int *error,\n         const stb_vorbis_alloc *alloc_buffer);\n// create a vorbis decoder by passing in the initial data block containing\n//    the ogg&vorbis headers (you don't need to do parse them, just provide\n//    the first N bytes of the file--you're told if it's not enough, see below)\n// on success, returns an stb_vorbis *, does not set error, returns the amount of\n//    data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;\n// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed\n// if returns NULL and *error is VORBIS_need_more_data, then the input block was\n//       incomplete and you need to pass in a larger block from the start of the file\n\nextern int stb_vorbis_decode_frame_pushdata(\n         stb_vorbis *f,\n         const unsigned char *datablock, int datablock_length_in_bytes,\n         int *channels,             // place to write number of float * buffers\n         float ***output,           // place to write float ** array of float * buffers\n         int *samples               // place to write number of output samples\n     );\n// decode a frame of audio sample data if possible from the passed-in data block\n//\n// return value: number of bytes we used from datablock\n//\n// possible cases:\n//     0 bytes used, 0 samples output (need more data)\n//     N bytes used, 0 samples output (resynching the stream, keep going)\n//     N bytes used, M samples output (one frame of data)\n// note that after opening a file, you will ALWAYS get one N-bytes,0-sample\n// frame, because Vorbis always \"discards\" the first frame.\n//\n// Note that on resynch, stb_vorbis will rarely consume all of the buffer,\n// instead only datablock_length_in_bytes-3 or less. This is because it wants\n// to avoid missing parts of a page header if they cross a datablock boundary,\n// without writing state-machiney code to record a partial detection.\n//\n// The number of channels returned are stored in *channels (which can be\n// NULL--it is always the same as the number of channels reported by\n// get_info). *output will contain an array of float* buffers, one per\n// channel. In other words, (*output)[0][0] contains the first sample from\n// the first channel, and (*output)[1][0] contains the first sample from\n// the second channel.\n//\n// *output points into stb_vorbis's internal output buffer storage; these\n// buffers are owned by stb_vorbis and application code should not free\n// them or modify their contents. They are transient and will be overwritten\n// once you ask for more data to get decoded, so be sure to grab any data\n// you need before then.\n\nextern void stb_vorbis_flush_pushdata(stb_vorbis *f);\n// inform stb_vorbis that your next datablock will not be contiguous with\n// previous ones (e.g. you've seeked in the data); future attempts to decode\n// frames will cause stb_vorbis to resynchronize (as noted above), and\n// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it\n// will begin decoding the _next_ frame.\n//\n// if you want to seek using pushdata, you need to seek in your file, then\n// call stb_vorbis_flush_pushdata(), then start calling decoding, then once\n// decoding is returning you data, call stb_vorbis_get_sample_offset, and\n// if you don't like the result, seek your file again and repeat.\n#endif\n\n\n//////////   PULLING INPUT API\n\n#ifndef STB_VORBIS_NO_PULLDATA_API\n// This API assumes stb_vorbis is allowed to pull data from a source--\n// either a block of memory containing the _entire_ vorbis stream, or a\n// FILE * that you or it create, or possibly some other reading mechanism\n// if you go modify the source to replace the FILE * case with some kind\n// of callback to your code. (But if you don't support seeking, you may\n// just want to go ahead and use pushdata.)\n\n#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)\nextern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);\n#endif\n#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)\nextern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);\n#endif\n// decode an entire file and output the data interleaved into a malloc()ed\n// buffer stored in *output. The return value is the number of samples\n// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.\n// When you're done with it, just free() the pointer returned in *output.\n\nextern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,\n                                  int *error, const stb_vorbis_alloc *alloc_buffer);\n// create an ogg vorbis decoder from an ogg vorbis stream in memory (note\n// this must be the entire stream!). on failure, returns NULL and sets *error\n\n#ifndef STB_VORBIS_NO_STDIO\nextern stb_vorbis * stb_vorbis_open_filename(const char *filename,\n                                  int *error, const stb_vorbis_alloc *alloc_buffer);\n// create an ogg vorbis decoder from a filename via fopen(). on failure,\n// returns NULL and sets *error (possibly to VORBIS_file_open_failure).\n\nextern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,\n                                  int *error, const stb_vorbis_alloc *alloc_buffer);\n// create an ogg vorbis decoder from an open FILE *, looking for a stream at\n// the _current_ seek point (ftell). on failure, returns NULL and sets *error.\n// note that stb_vorbis must \"own\" this stream; if you seek it in between\n// calls to stb_vorbis, it will become confused. Moreover, if you attempt to\n// perform stb_vorbis_seek_*() operations on this file, it will assume it\n// owns the _entire_ rest of the file after the start point. Use the next\n// function, stb_vorbis_open_file_section(), to limit it.\n\nextern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,\n                int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);\n// create an ogg vorbis decoder from an open FILE *, looking for a stream at\n// the _current_ seek point (ftell); the stream will be of length 'len' bytes.\n// on failure, returns NULL and sets *error. note that stb_vorbis must \"own\"\n// this stream; if you seek it in between calls to stb_vorbis, it will become\n// confused.\n#endif\n\nextern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);\nextern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);\n// these functions seek in the Vorbis file to (approximately) 'sample_number'.\n// after calling seek_frame(), the next call to get_frame_*() will include\n// the specified sample. after calling stb_vorbis_seek(), the next call to\n// stb_vorbis_get_samples_* will start with the specified sample. If you\n// do not need to seek to EXACTLY the target sample when using get_samples_*,\n// you can also use seek_frame().\n\nextern int stb_vorbis_seek_start(stb_vorbis *f);\n// this function is equivalent to stb_vorbis_seek(f,0)\n\nextern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);\nextern float        stb_vorbis_stream_length_in_seconds(stb_vorbis *f);\n// these functions return the total length of the vorbis stream\n\nextern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);\n// decode the next frame and return the number of samples. the number of\n// channels returned are stored in *channels (which can be NULL--it is always\n// the same as the number of channels reported by get_info). *output will\n// contain an array of float* buffers, one per channel. These outputs will\n// be overwritten on the next call to stb_vorbis_get_frame_*.\n//\n// You generally should not intermix calls to stb_vorbis_get_frame_*()\n// and stb_vorbis_get_samples_*(), since the latter calls the former.\n\n#ifndef STB_VORBIS_NO_INTEGER_CONVERSION\nextern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);\nextern int stb_vorbis_get_frame_short            (stb_vorbis *f, int num_c, short **buffer, int num_samples);\n#endif\n// decode the next frame and return the number of *samples* per channel.\n// Note that for interleaved data, you pass in the number of shorts (the\n// size of your array), but the return value is the number of samples per\n// channel, not the total number of samples.\n//\n// The data is coerced to the number of channels you request according to the\n// channel coercion rules (see below). You must pass in the size of your\n// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.\n// The maximum buffer size needed can be gotten from get_info(); however,\n// the Vorbis I specification implies an absolute maximum of 4096 samples\n// per channel.\n\n// Channel coercion rules:\n//    Let M be the number of channels requested, and N the number of channels present,\n//    and Cn be the nth channel; let stereo L be the sum of all L and center channels,\n//    and stereo R be the sum of all R and center channels (channel assignment from the\n//    vorbis spec).\n//        M    N       output\n//        1    k      sum(Ck) for all k\n//        2    *      stereo L, stereo R\n//        k    l      k > l, the first l channels, then 0s\n//        k    l      k <= l, the first k channels\n//    Note that this is not _good_ surround etc. mixing at all! It's just so\n//    you get something useful.\n\nextern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);\nextern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);\n// gets num_samples samples, not necessarily on a frame boundary--this requires\n// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.\n// Returns the number of samples stored per channel; it may be less than requested\n// at the end of the file. If there are no more samples in the file, returns 0.\n\n#ifndef STB_VORBIS_NO_INTEGER_CONVERSION\nextern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);\nextern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);\n#endif\n// gets num_samples samples, not necessarily on a frame boundary--this requires\n// buffering so you have to supply the buffers. Applies the coercion rules above\n// to produce 'channels' channels. Returns the number of samples stored per channel;\n// it may be less than requested at the end of the file. If there are no more\n// samples in the file, returns 0.\n\n#endif\n\n////////   ERROR CODES\n\nenum STBVorbisError\n{\n   VORBIS__no_error,\n\n   VORBIS_need_more_data=1,             // not a real error\n\n   VORBIS_invalid_api_mixing,           // can't mix API modes\n   VORBIS_outofmem,                     // not enough memory\n   VORBIS_feature_not_supported,        // uses floor 0\n   VORBIS_too_many_channels,            // STB_VORBIS_MAX_CHANNELS is too small\n   VORBIS_file_open_failure,            // fopen() failed\n   VORBIS_seek_without_length,          // can't seek in unknown-length file\n\n   VORBIS_unexpected_eof=10,            // file is truncated?\n   VORBIS_seek_invalid,                 // seek past EOF\n\n   // decoding errors (corrupt/invalid stream) -- you probably\n   // don't care about the exact details of these\n\n   // vorbis errors:\n   VORBIS_invalid_setup=20,\n   VORBIS_invalid_stream,\n\n   // ogg errors:\n   VORBIS_missing_capture_pattern=30,\n   VORBIS_invalid_stream_structure_version,\n   VORBIS_continued_packet_flag_invalid,\n   VORBIS_incorrect_stream_serial_number,\n   VORBIS_invalid_first_page,\n   VORBIS_bad_packet_type,\n   VORBIS_cant_find_last_page,\n   VORBIS_seek_failed,\n   VORBIS_ogg_skeleton_not_supported\n};\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H\n//\n//  HEADER ENDS HERE\n//\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef STB_VORBIS_HEADER_ONLY\n\n// global configuration settings (e.g. set these in the project/makefile),\n// or just set them in this file at the top (although ideally the first few\n// should be visible when the header file is compiled too, although it's not\n// crucial)\n\n// STB_VORBIS_NO_PUSHDATA_API\n//     does not compile the code for the various stb_vorbis_*_pushdata()\n//     functions\n// #define STB_VORBIS_NO_PUSHDATA_API\n\n// STB_VORBIS_NO_PULLDATA_API\n//     does not compile the code for the non-pushdata APIs\n// #define STB_VORBIS_NO_PULLDATA_API\n\n// STB_VORBIS_NO_STDIO\n//     does not compile the code for the APIs that use FILE *s internally\n//     or externally (implied by STB_VORBIS_NO_PULLDATA_API)\n// #define STB_VORBIS_NO_STDIO\n\n// STB_VORBIS_NO_INTEGER_CONVERSION\n//     does not compile the code for converting audio sample data from\n//     float to integer (implied by STB_VORBIS_NO_PULLDATA_API)\n// #define STB_VORBIS_NO_INTEGER_CONVERSION\n\n// STB_VORBIS_NO_FAST_SCALED_FLOAT\n//      does not use a fast float-to-int trick to accelerate float-to-int on\n//      most platforms which requires endianness be defined correctly.\n//#define STB_VORBIS_NO_FAST_SCALED_FLOAT\n\n\n// STB_VORBIS_MAX_CHANNELS [number]\n//     globally define this to the maximum number of channels you need.\n//     The spec does not put a restriction on channels except that\n//     the count is stored in a byte, so 255 is the hard limit.\n//     Reducing this saves about 16 bytes per value, so using 16 saves\n//     (255-16)*16 or around 4KB. Plus anything other memory usage\n//     I forgot to account for. Can probably go as low as 8 (7.1 audio),\n//     6 (5.1 audio), or 2 (stereo only).\n#ifndef STB_VORBIS_MAX_CHANNELS\n#define STB_VORBIS_MAX_CHANNELS    16  // enough for anyone?\n#endif\n\n// STB_VORBIS_PUSHDATA_CRC_COUNT [number]\n//     after a flush_pushdata(), stb_vorbis begins scanning for the\n//     next valid page, without backtracking. when it finds something\n//     that looks like a page, it streams through it and verifies its\n//     CRC32. Should that validation fail, it keeps scanning. But it's\n//     possible that _while_ streaming through to check the CRC32 of\n//     one candidate page, it sees another candidate page. This #define\n//     determines how many \"overlapping\" candidate pages it can search\n//     at once. Note that \"real\" pages are typically ~4KB to ~8KB, whereas\n//     garbage pages could be as big as 64KB, but probably average ~16KB.\n//     So don't hose ourselves by scanning an apparent 64KB page and\n//     missing a ton of real ones in the interim; so minimum of 2\n#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT\n#define STB_VORBIS_PUSHDATA_CRC_COUNT  4\n#endif\n\n// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]\n//     sets the log size of the huffman-acceleration table.  Maximum\n//     supported value is 24. with larger numbers, more decodings are O(1),\n//     but the table size is larger so worse cache missing, so you'll have\n//     to probe (and try multiple ogg vorbis files) to find the sweet spot.\n#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH\n#define STB_VORBIS_FAST_HUFFMAN_LENGTH   10\n#endif\n\n// STB_VORBIS_FAST_BINARY_LENGTH [number]\n//     sets the log size of the binary-search acceleration table. this\n//     is used in similar fashion to the fast-huffman size to set initial\n//     parameters for the binary search\n\n// STB_VORBIS_FAST_HUFFMAN_INT\n//     The fast huffman tables are much more efficient if they can be\n//     stored as 16-bit results instead of 32-bit results. This restricts\n//     the codebooks to having only 65535 possible outcomes, though.\n//     (At least, accelerated by the huffman table.)\n#ifndef STB_VORBIS_FAST_HUFFMAN_INT\n#define STB_VORBIS_FAST_HUFFMAN_SHORT\n#endif\n\n// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH\n//     If the 'fast huffman' search doesn't succeed, then stb_vorbis falls\n//     back on binary searching for the correct one. This requires storing\n//     extra tables with the huffman codes in sorted order. Defining this\n//     symbol trades off space for speed by forcing a linear search in the\n//     non-fast case, except for \"sparse\" codebooks.\n// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH\n\n// STB_VORBIS_DIVIDES_IN_RESIDUE\n//     stb_vorbis precomputes the result of the scalar residue decoding\n//     that would otherwise require a divide per chunk. you can trade off\n//     space for time by defining this symbol.\n// #define STB_VORBIS_DIVIDES_IN_RESIDUE\n\n// STB_VORBIS_DIVIDES_IN_CODEBOOK\n//     vorbis VQ codebooks can be encoded two ways: with every case explicitly\n//     stored, or with all elements being chosen from a small range of values,\n//     and all values possible in all elements. By default, stb_vorbis expands\n//     this latter kind out to look like the former kind for ease of decoding,\n//     because otherwise an integer divide-per-vector-element is required to\n//     unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can\n//     trade off storage for speed.\n//#define STB_VORBIS_DIVIDES_IN_CODEBOOK\n\n#ifdef STB_VORBIS_CODEBOOK_SHORTS\n#error \"STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats\"\n#endif\n\n// STB_VORBIS_DIVIDE_TABLE\n//     this replaces small integer divides in the floor decode loop with\n//     table lookups. made less than 1% difference, so disabled by default.\n\n// STB_VORBIS_NO_INLINE_DECODE\n//     disables the inlining of the scalar codebook fast-huffman decode.\n//     might save a little codespace; useful for debugging\n// #define STB_VORBIS_NO_INLINE_DECODE\n\n// STB_VORBIS_NO_DEFER_FLOOR\n//     Normally we only decode the floor without synthesizing the actual\n//     full curve. We can instead synthesize the curve immediately. This\n//     requires more memory and is very likely slower, so I don't think\n//     you'd ever want to do it except for debugging.\n// #define STB_VORBIS_NO_DEFER_FLOOR\n\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n\n#ifdef STB_VORBIS_NO_PULLDATA_API\n   #define STB_VORBIS_NO_INTEGER_CONVERSION\n   #define STB_VORBIS_NO_STDIO\n#endif\n\n#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)\n   #define STB_VORBIS_NO_STDIO 1\n#endif\n\n#ifndef STB_VORBIS_NO_INTEGER_CONVERSION\n#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT\n\n   // only need endianness for fast-float-to-int, which we don't\n   // use for pushdata\n\n   #ifndef STB_VORBIS_BIG_ENDIAN\n     #define STB_VORBIS_ENDIAN  0\n   #else\n     #define STB_VORBIS_ENDIAN  1\n   #endif\n\n#endif\n#endif\n\n\n#ifndef STB_VORBIS_NO_STDIO\n#include <stdio.h>\n#endif\n\n#ifndef STB_VORBIS_NO_CRT\n   #include <stdlib.h>\n   #include <string.h>\n   #include <assert.h>\n   #include <math.h>\n\n   // find definition of alloca if it's not in stdlib.h:\n   #if defined(_MSC_VER) || defined(__MINGW32__)\n      #include <malloc.h>\n   #endif\n   #if defined(__linux__) || defined(__linux) || defined(__sun__) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__)\n      #include <alloca.h>\n   #endif\n#else // STB_VORBIS_NO_CRT\n   #define NULL 0\n   #define malloc(s)   0\n   #define free(s)     ((void) 0)\n   #define realloc(s)  0\n#endif // STB_VORBIS_NO_CRT\n\n#include <limits.h>\n\n#ifdef __MINGW32__\n   // eff you mingw:\n   //     \"fixed\":\n   //         http://sourceforge.net/p/mingw-w64/mailman/message/32882927/\n   //     \"no that broke the build, reverted, who cares about C\":\n   //         http://sourceforge.net/p/mingw-w64/mailman/message/32890381/\n   #ifdef __forceinline\n   #undef __forceinline\n   #endif\n   #define __forceinline\n   #ifndef alloca\n   #define alloca __builtin_alloca\n   #endif\n#elif !defined(_MSC_VER)\n   #if __GNUC__\n      #define __forceinline inline\n   #else\n      #define __forceinline\n   #endif\n#endif\n\n#if STB_VORBIS_MAX_CHANNELS > 256\n#error \"Value of STB_VORBIS_MAX_CHANNELS outside of allowed range\"\n#endif\n\n#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24\n#error \"Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range\"\n#endif\n\n\n#if 0\n#include <crtdbg.h>\n#define CHECK(f)   _CrtIsValidHeapPointer(f->channel_buffers[1])\n#else\n#define CHECK(f)   ((void) 0)\n#endif\n\n#define MAX_BLOCKSIZE_LOG  13   // from specification\n#define MAX_BLOCKSIZE      (1 << MAX_BLOCKSIZE_LOG)\n\n\ntypedef unsigned char  uint8;\ntypedef   signed char   int8;\ntypedef unsigned short uint16;\ntypedef   signed short  int16;\ntypedef unsigned int   uint32;\ntypedef   signed int    int32;\n\n#ifndef TRUE\n#define TRUE 1\n#define FALSE 0\n#endif\n\ntypedef float codetype;\n\n#ifdef _MSC_VER\n#define STBV_NOTUSED(v)  (void)(v)\n#else\n#define STBV_NOTUSED(v)  (void)sizeof(v)\n#endif\n\n// @NOTE\n//\n// Some arrays below are tagged \"//varies\", which means it's actually\n// a variable-sized piece of data, but rather than malloc I assume it's\n// small enough it's better to just allocate it all together with the\n// main thing\n//\n// Most of the variables are specified with the smallest size I could pack\n// them into. It might give better performance to make them all full-sized\n// integers. It should be safe to freely rearrange the structures or change\n// the sizes larger--nothing relies on silently truncating etc., nor the\n// order of variables.\n\n#define FAST_HUFFMAN_TABLE_SIZE   (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)\n#define FAST_HUFFMAN_TABLE_MASK   (FAST_HUFFMAN_TABLE_SIZE - 1)\n\ntypedef struct\n{\n   int dimensions, entries;\n   uint8 *codeword_lengths;\n   float  minimum_value;\n   float  delta_value;\n   uint8  value_bits;\n   uint8  lookup_type;\n   uint8  sequence_p;\n   uint8  sparse;\n   uint32 lookup_values;\n   codetype *multiplicands;\n   uint32 *codewords;\n   #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT\n    int16  fast_huffman[FAST_HUFFMAN_TABLE_SIZE];\n   #else\n    int32  fast_huffman[FAST_HUFFMAN_TABLE_SIZE];\n   #endif\n   uint32 *sorted_codewords;\n   int    *sorted_values;\n   int     sorted_entries;\n} Codebook;\n\ntypedef struct\n{\n   uint8 order;\n   uint16 rate;\n   uint16 bark_map_size;\n   uint8 amplitude_bits;\n   uint8 amplitude_offset;\n   uint8 number_of_books;\n   uint8 book_list[16]; // varies\n} Floor0;\n\ntypedef struct\n{\n   uint8 partitions;\n   uint8 partition_class_list[32]; // varies\n   uint8 class_dimensions[16]; // varies\n   uint8 class_subclasses[16]; // varies\n   uint8 class_masterbooks[16]; // varies\n   int16 subclass_books[16][8]; // varies\n   uint16 Xlist[31*8+2]; // varies\n   uint8 sorted_order[31*8+2];\n   uint8 neighbors[31*8+2][2];\n   uint8 floor1_multiplier;\n   uint8 rangebits;\n   int values;\n} Floor1;\n\ntypedef union\n{\n   Floor0 floor0;\n   Floor1 floor1;\n} Floor;\n\ntypedef struct\n{\n   uint32 begin, end;\n   uint32 part_size;\n   uint8 classifications;\n   uint8 classbook;\n   uint8 **classdata;\n   int16 (*residue_books)[8];\n} Residue;\n\ntypedef struct\n{\n   uint8 magnitude;\n   uint8 angle;\n   uint8 mux;\n} MappingChannel;\n\ntypedef struct\n{\n   uint16 coupling_steps;\n   MappingChannel *chan;\n   uint8  submaps;\n   uint8  submap_floor[15]; // varies\n   uint8  submap_residue[15]; // varies\n} Mapping;\n\ntypedef struct\n{\n   uint8 blockflag;\n   uint8 mapping;\n   uint16 windowtype;\n   uint16 transformtype;\n} Mode;\n\ntypedef struct\n{\n   uint32  goal_crc;    // expected crc if match\n   int     bytes_left;  // bytes left in packet\n   uint32  crc_so_far;  // running crc\n   int     bytes_done;  // bytes processed in _current_ chunk\n   uint32  sample_loc;  // granule pos encoded in page\n} CRCscan;\n\ntypedef struct\n{\n   uint32 page_start, page_end;\n   uint32 last_decoded_sample;\n} ProbedPage;\n\nstruct stb_vorbis\n{\n  // user-accessible info\n   unsigned int sample_rate;\n   int channels;\n\n   unsigned int setup_memory_required;\n   unsigned int temp_memory_required;\n   unsigned int setup_temp_memory_required;\n\n   char *vendor;\n   int comment_list_length;\n   char **comment_list;\n\n  // input config\n#ifndef STB_VORBIS_NO_STDIO\n   FILE *f;\n   uint32 f_start;\n   int close_on_free;\n#endif\n\n   uint8 *stream;\n   uint8 *stream_start;\n   uint8 *stream_end;\n\n   uint32 stream_len;\n\n   uint8  push_mode;\n\n   // the page to seek to when seeking to start, may be zero\n   uint32 first_audio_page_offset;\n\n   // p_first is the page on which the first audio packet ends\n   // (but not necessarily the page on which it starts)\n   ProbedPage p_first, p_last;\n\n  // memory management\n   stb_vorbis_alloc alloc;\n   int setup_offset;\n   int temp_offset;\n\n  // run-time results\n   int eof;\n   enum STBVorbisError error;\n\n  // user-useful data\n\n  // header info\n   int blocksize[2];\n   int blocksize_0, blocksize_1;\n   int codebook_count;\n   Codebook *codebooks;\n   int floor_count;\n   uint16 floor_types[64]; // varies\n   Floor *floor_config;\n   int residue_count;\n   uint16 residue_types[64]; // varies\n   Residue *residue_config;\n   int mapping_count;\n   Mapping *mapping;\n   int mode_count;\n   Mode mode_config[64];  // varies\n\n   uint32 total_samples;\n\n  // decode buffer\n   float *channel_buffers[STB_VORBIS_MAX_CHANNELS];\n   float *outputs        [STB_VORBIS_MAX_CHANNELS];\n\n   float *previous_window[STB_VORBIS_MAX_CHANNELS];\n   int previous_length;\n\n   #ifndef STB_VORBIS_NO_DEFER_FLOOR\n   int16 *finalY[STB_VORBIS_MAX_CHANNELS];\n   #else\n   float *floor_buffers[STB_VORBIS_MAX_CHANNELS];\n   #endif\n\n   uint32 current_loc; // sample location of next frame to decode\n   int    current_loc_valid;\n\n  // per-blocksize precomputed data\n\n   // twiddle factors\n   float *A[2],*B[2],*C[2];\n   float *window[2];\n   uint16 *bit_reverse[2];\n\n  // current page/packet/segment streaming info\n   uint32 serial; // stream serial number for verification\n   int last_page;\n   int segment_count;\n   uint8 segments[255];\n   uint8 page_flag;\n   uint8 bytes_in_seg;\n   uint8 first_decode;\n   int next_seg;\n   int last_seg;  // flag that we're on the last segment\n   int last_seg_which; // what was the segment number of the last seg?\n   uint32 acc;\n   int valid_bits;\n   int packet_bytes;\n   int end_seg_with_known_loc;\n   uint32 known_loc_for_packet;\n   int discard_samples_deferred;\n   uint32 samples_output;\n\n  // push mode scanning\n   int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching\n#ifndef STB_VORBIS_NO_PUSHDATA_API\n   CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];\n#endif\n\n  // sample-access\n   int channel_buffer_start;\n   int channel_buffer_end;\n};\n\n#if defined(STB_VORBIS_NO_PUSHDATA_API)\n   #define IS_PUSH_MODE(f)   FALSE\n#elif defined(STB_VORBIS_NO_PULLDATA_API)\n   #define IS_PUSH_MODE(f)   TRUE\n#else\n   #define IS_PUSH_MODE(f)   ((f)->push_mode)\n#endif\n\ntypedef struct stb_vorbis vorb;\n\nstatic int error(vorb *f, enum STBVorbisError e)\n{\n   f->error = e;\n   if (!f->eof && e != VORBIS_need_more_data) {\n      f->error=e; // breakpoint for debugging\n   }\n   return 0;\n}\n\n\n// these functions are used for allocating temporary memory\n// while decoding. if you can afford the stack space, use\n// alloca(); otherwise, provide a temp buffer and it will\n// allocate out of those.\n\n#define array_size_required(count,size)  (count*(sizeof(void *)+(size)))\n\n#define temp_alloc(f,size)              (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))\n#define temp_free(f,p)                  (void)0\n#define temp_alloc_save(f)              ((f)->temp_offset)\n#define temp_alloc_restore(f,p)         ((f)->temp_offset = (p))\n\n#define temp_block_array(f,count,size)  make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)\n\n// given a sufficiently large block of memory, make an array of pointers to subblocks of it\nstatic void *make_block_array(void *mem, int count, int size)\n{\n   int i;\n   void ** p = (void **) mem;\n   char *q = (char *) (p + count);\n   for (i=0; i < count; ++i) {\n      p[i] = q;\n      q += size;\n   }\n   return p;\n}\n\nstatic void *setup_malloc(vorb *f, int sz)\n{\n   sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.\n   f->setup_memory_required += sz;\n   if (f->alloc.alloc_buffer) {\n      void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;\n      if (f->setup_offset + sz > f->temp_offset) return NULL;\n      f->setup_offset += sz;\n      return p;\n   }\n   return sz ? malloc(sz) : NULL;\n}\n\nstatic void setup_free(vorb *f, void *p)\n{\n   if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack\n   free(p);\n}\n\nstatic void *setup_temp_malloc(vorb *f, int sz)\n{\n   sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.\n   if (f->alloc.alloc_buffer) {\n      if (f->temp_offset - sz < f->setup_offset) return NULL;\n      f->temp_offset -= sz;\n      return (char *) f->alloc.alloc_buffer + f->temp_offset;\n   }\n   return malloc(sz);\n}\n\nstatic void setup_temp_free(vorb *f, void *p, int sz)\n{\n   if (f->alloc.alloc_buffer) {\n      f->temp_offset += (sz+7)&~7;\n      return;\n   }\n   free(p);\n}\n\n#define CRC32_POLY    0x04c11db7   // from spec\n\nstatic uint32 crc_table[256];\nstatic void crc32_init(void)\n{\n   int i,j;\n   uint32 s;\n   for(i=0; i < 256; i++) {\n      for (s=(uint32) i << 24, j=0; j < 8; ++j)\n         s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);\n      crc_table[i] = s;\n   }\n}\n\nstatic __forceinline uint32 crc32_update(uint32 crc, uint8 byte)\n{\n   return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];\n}\n\n\n// used in setup, and for huffman that doesn't go fast path\nstatic unsigned int bit_reverse(unsigned int n)\n{\n  n = ((n & 0xAAAAAAAA) >>  1) | ((n & 0x55555555) << 1);\n  n = ((n & 0xCCCCCCCC) >>  2) | ((n & 0x33333333) << 2);\n  n = ((n & 0xF0F0F0F0) >>  4) | ((n & 0x0F0F0F0F) << 4);\n  n = ((n & 0xFF00FF00) >>  8) | ((n & 0x00FF00FF) << 8);\n  return (n >> 16) | (n << 16);\n}\n\nstatic float square(float x)\n{\n   return x*x;\n}\n\n// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3\n// as required by the specification. fast(?) implementation from stb.h\n// @OPTIMIZE: called multiple times per-packet with \"constants\"; move to setup\nstatic int ilog(int32 n)\n{\n   static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };\n\n   if (n < 0) return 0; // signed n returns 0\n\n   // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)\n   if (n < (1 << 14))\n        if (n < (1 <<  4))            return  0 + log2_4[n      ];\n        else if (n < (1 <<  9))       return  5 + log2_4[n >>  5];\n             else                     return 10 + log2_4[n >> 10];\n   else if (n < (1 << 24))\n             if (n < (1 << 19))       return 15 + log2_4[n >> 15];\n             else                     return 20 + log2_4[n >> 20];\n        else if (n < (1 << 29))       return 25 + log2_4[n >> 25];\n             else                     return 30 + log2_4[n >> 30];\n}\n\n#ifndef M_PI\n  #define M_PI  3.14159265358979323846264f  // from CRC\n#endif\n\n// code length assigned to a value with no huffman encoding\n#define NO_CODE   255\n\n/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////\n//\n// these functions are only called at setup, and only a few times\n// per file\n\nstatic float float32_unpack(uint32 x)\n{\n   // from the specification\n   uint32 mantissa = x & 0x1fffff;\n   uint32 sign = x & 0x80000000;\n   uint32 exp = (x & 0x7fe00000) >> 21;\n   double res = sign ? -(double)mantissa : (double)mantissa;\n   return (float) ldexp((float)res, (int)exp-788);\n}\n\n\n// zlib & jpeg huffman tables assume that the output symbols\n// can either be arbitrarily arranged, or have monotonically\n// increasing frequencies--they rely on the lengths being sorted;\n// this makes for a very simple generation algorithm.\n// vorbis allows a huffman table with non-sorted lengths. This\n// requires a more sophisticated construction, since symbols in\n// order do not map to huffman codes \"in order\".\nstatic void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)\n{\n   if (!c->sparse) {\n      c->codewords      [symbol] = huff_code;\n   } else {\n      c->codewords       [count] = huff_code;\n      c->codeword_lengths[count] = len;\n      values             [count] = symbol;\n   }\n}\n\nstatic int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)\n{\n   int i,k,m=0;\n   uint32 available[32];\n\n   memset(available, 0, sizeof(available));\n   // find the first entry\n   for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;\n   if (k == n) { assert(c->sorted_entries == 0); return TRUE; }\n   assert(len[k] < 32); // no error return required, code reading lens checks this\n   // add to the list\n   add_entry(c, 0, k, m++, len[k], values);\n   // add all available leaves\n   for (i=1; i <= len[k]; ++i)\n      available[i] = 1U << (32-i);\n   // note that the above code treats the first case specially,\n   // but it's really the same as the following code, so they\n   // could probably be combined (except the initial code is 0,\n   // and I use 0 in available[] to mean 'empty')\n   for (i=k+1; i < n; ++i) {\n      uint32 res;\n      int z = len[i], y;\n      if (z == NO_CODE) continue;\n      assert(z < 32); // no error return required, code reading lens checks this\n      // find lowest available leaf (should always be earliest,\n      // which is what the specification calls for)\n      // note that this property, and the fact we can never have\n      // more than one free leaf at a given level, isn't totally\n      // trivial to prove, but it seems true and the assert never\n      // fires, so!\n      while (z > 0 && !available[z]) --z;\n      if (z == 0) { return FALSE; }\n      res = available[z];\n      available[z] = 0;\n      add_entry(c, bit_reverse(res), i, m++, len[i], values);\n      // propagate availability up the tree\n      if (z != len[i]) {\n         for (y=len[i]; y > z; --y) {\n            assert(available[y] == 0);\n            available[y] = res + (1 << (32-y));\n         }\n      }\n   }\n   return TRUE;\n}\n\n// accelerated huffman table allows fast O(1) match of all symbols\n// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH\nstatic void compute_accelerated_huffman(Codebook *c)\n{\n   int i, len;\n   for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)\n      c->fast_huffman[i] = -1;\n\n   len = c->sparse ? c->sorted_entries : c->entries;\n   #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT\n   if (len > 32767) len = 32767; // largest possible value we can encode!\n   #endif\n   for (i=0; i < len; ++i) {\n      if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {\n         uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];\n         // set table entries for all bit combinations in the higher bits\n         while (z < FAST_HUFFMAN_TABLE_SIZE) {\n             c->fast_huffman[z] = i;\n             z += 1 << c->codeword_lengths[i];\n         }\n      }\n   }\n}\n\n#ifdef _MSC_VER\n#define STBV_CDECL __cdecl\n#else\n#define STBV_CDECL\n#endif\n\nstatic int STBV_CDECL uint32_compare(const void *p, const void *q)\n{\n   uint32 x = * (uint32 *) p;\n   uint32 y = * (uint32 *) q;\n   return x < y ? -1 : x > y;\n}\n\nstatic int include_in_sort(Codebook *c, uint8 len)\n{\n   if (c->sparse) { assert(len != NO_CODE); return TRUE; }\n   if (len == NO_CODE) return FALSE;\n   if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;\n   return FALSE;\n}\n\n// if the fast table above doesn't work, we want to binary\n// search them... need to reverse the bits\nstatic void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)\n{\n   int i, len;\n   // build a list of all the entries\n   // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.\n   // this is kind of a frivolous optimization--I don't see any performance improvement,\n   // but it's like 4 extra lines of code, so.\n   if (!c->sparse) {\n      int k = 0;\n      for (i=0; i < c->entries; ++i)\n         if (include_in_sort(c, lengths[i]))\n            c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);\n      assert(k == c->sorted_entries);\n   } else {\n      for (i=0; i < c->sorted_entries; ++i)\n         c->sorted_codewords[i] = bit_reverse(c->codewords[i]);\n   }\n\n   qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);\n   c->sorted_codewords[c->sorted_entries] = 0xffffffff;\n\n   len = c->sparse ? c->sorted_entries : c->entries;\n   // now we need to indicate how they correspond; we could either\n   //   #1: sort a different data structure that says who they correspond to\n   //   #2: for each sorted entry, search the original list to find who corresponds\n   //   #3: for each original entry, find the sorted entry\n   // #1 requires extra storage, #2 is slow, #3 can use binary search!\n   for (i=0; i < len; ++i) {\n      int huff_len = c->sparse ? lengths[values[i]] : lengths[i];\n      if (include_in_sort(c,huff_len)) {\n         uint32 code = bit_reverse(c->codewords[i]);\n         int x=0, n=c->sorted_entries;\n         while (n > 1) {\n            // invariant: sc[x] <= code < sc[x+n]\n            int m = x + (n >> 1);\n            if (c->sorted_codewords[m] <= code) {\n               x = m;\n               n -= (n>>1);\n            } else {\n               n >>= 1;\n            }\n         }\n         assert(c->sorted_codewords[x] == code);\n         if (c->sparse) {\n            c->sorted_values[x] = values[i];\n            c->codeword_lengths[x] = huff_len;\n         } else {\n            c->sorted_values[x] = i;\n         }\n      }\n   }\n}\n\n// only run while parsing the header (3 times)\nstatic int vorbis_validate(uint8 *data)\n{\n   static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };\n   return memcmp(data, vorbis, 6) == 0;\n}\n\n// called from setup only, once per code book\n// (formula implied by specification)\nstatic int lookup1_values(int entries, int dim)\n{\n   int r = (int) floor(exp((float) log((float) entries) / dim));\n   if ((int) floor(pow((float) r+1, dim)) <= entries)   // (int) cast for MinGW warning;\n      ++r;                                              // floor() to avoid _ftol() when non-CRT\n   if (pow((float) r+1, dim) <= entries)\n      return -1;\n   if ((int) floor(pow((float) r, dim)) > entries)\n      return -1;\n   return r;\n}\n\n// called twice per file\nstatic void compute_twiddle_factors(int n, float *A, float *B, float *C)\n{\n   int n4 = n >> 2, n8 = n >> 3;\n   int k,k2;\n\n   for (k=k2=0; k < n4; ++k,k2+=2) {\n      A[k2  ] = (float)  cos(4*k*M_PI/n);\n      A[k2+1] = (float) -sin(4*k*M_PI/n);\n      B[k2  ] = (float)  cos((k2+1)*M_PI/n/2) * 0.5f;\n      B[k2+1] = (float)  sin((k2+1)*M_PI/n/2) * 0.5f;\n   }\n   for (k=k2=0; k < n8; ++k,k2+=2) {\n      C[k2  ] = (float)  cos(2*(k2+1)*M_PI/n);\n      C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);\n   }\n}\n\nstatic void compute_window(int n, float *window)\n{\n   int n2 = n >> 1, i;\n   for (i=0; i < n2; ++i)\n      window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));\n}\n\nstatic void compute_bitreverse(int n, uint16 *rev)\n{\n   int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions\n   int i, n8 = n >> 3;\n   for (i=0; i < n8; ++i)\n      rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;\n}\n\nstatic int init_blocksize(vorb *f, int b, int n)\n{\n   int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;\n   f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);\n   f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);\n   f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);\n   if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);\n   compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);\n   f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);\n   if (!f->window[b]) return error(f, VORBIS_outofmem);\n   compute_window(n, f->window[b]);\n   f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);\n   if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);\n   compute_bitreverse(n, f->bit_reverse[b]);\n   return TRUE;\n}\n\nstatic void neighbors(uint16 *x, int n, int *plow, int *phigh)\n{\n   int low = -1;\n   int high = 65536;\n   int i;\n   for (i=0; i < n; ++i) {\n      if (x[i] > low  && x[i] < x[n]) { *plow  = i; low = x[i]; }\n      if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }\n   }\n}\n\n// this has been repurposed so y is now the original index instead of y\ntypedef struct\n{\n   uint16 x,id;\n} stbv__floor_ordering;\n\nstatic int STBV_CDECL point_compare(const void *p, const void *q)\n{\n   stbv__floor_ordering *a = (stbv__floor_ordering *) p;\n   stbv__floor_ordering *b = (stbv__floor_ordering *) q;\n   return a->x < b->x ? -1 : a->x > b->x;\n}\n\n//\n/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////\n\n\n#if defined(STB_VORBIS_NO_STDIO)\n   #define USE_MEMORY(z)    TRUE\n#else\n   #define USE_MEMORY(z)    ((z)->stream)\n#endif\n\nstatic uint8 get8(vorb *z)\n{\n   if (USE_MEMORY(z)) {\n      if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }\n      return *z->stream++;\n   }\n\n   #ifndef STB_VORBIS_NO_STDIO\n   {\n   int c = fgetc(z->f);\n   if (c == EOF) { z->eof = TRUE; return 0; }\n   return c;\n   }\n   #endif\n}\n\nstatic uint32 get32(vorb *f)\n{\n   uint32 x;\n   x = get8(f);\n   x += get8(f) << 8;\n   x += get8(f) << 16;\n   x += (uint32) get8(f) << 24;\n   return x;\n}\n\nstatic int getn(vorb *z, uint8 *data, int n)\n{\n   if (USE_MEMORY(z)) {\n      if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }\n      memcpy(data, z->stream, n);\n      z->stream += n;\n      return 1;\n   }\n\n   #ifndef STB_VORBIS_NO_STDIO\n   if (fread(data, n, 1, z->f) == 1)\n      return 1;\n   else {\n      z->eof = 1;\n      return 0;\n   }\n   #endif\n}\n\nstatic void skip(vorb *z, int n)\n{\n   if (USE_MEMORY(z)) {\n      z->stream += n;\n      if (z->stream >= z->stream_end) z->eof = 1;\n      return;\n   }\n   #ifndef STB_VORBIS_NO_STDIO\n   {\n      long x = ftell(z->f);\n      fseek(z->f, x+n, SEEK_SET);\n   }\n   #endif\n}\n\nstatic int set_file_offset(stb_vorbis *f, unsigned int loc)\n{\n   #ifndef STB_VORBIS_NO_PUSHDATA_API\n   if (f->push_mode) return 0;\n   #endif\n   f->eof = 0;\n   if (USE_MEMORY(f)) {\n      if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {\n         f->stream = f->stream_end;\n         f->eof = 1;\n         return 0;\n      } else {\n         f->stream = f->stream_start + loc;\n         return 1;\n      }\n   }\n   #ifndef STB_VORBIS_NO_STDIO\n   if (loc + f->f_start < loc || loc >= 0x80000000) {\n      loc = 0x7fffffff;\n      f->eof = 1;\n   } else {\n      loc += f->f_start;\n   }\n   if (!fseek(f->f, loc, SEEK_SET))\n      return 1;\n   f->eof = 1;\n   fseek(f->f, f->f_start, SEEK_END);\n   return 0;\n   #endif\n}\n\n\nstatic uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };\n\nstatic int capture_pattern(vorb *f)\n{\n   if (0x4f != get8(f)) return FALSE;\n   if (0x67 != get8(f)) return FALSE;\n   if (0x67 != get8(f)) return FALSE;\n   if (0x53 != get8(f)) return FALSE;\n   return TRUE;\n}\n\n#define PAGEFLAG_continued_packet   1\n#define PAGEFLAG_first_page         2\n#define PAGEFLAG_last_page          4\n\nstatic int start_page_no_capturepattern(vorb *f)\n{\n   uint32 loc0,loc1,n;\n   if (f->first_decode && !IS_PUSH_MODE(f)) {\n      f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4;\n   }\n   // stream structure version\n   if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);\n   // header flag\n   f->page_flag = get8(f);\n   // absolute granule position\n   loc0 = get32(f);\n   loc1 = get32(f);\n   // @TODO: validate loc0,loc1 as valid positions?\n   // stream serial number -- vorbis doesn't interleave, so discard\n   get32(f);\n   //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);\n   // page sequence number\n   n = get32(f);\n   f->last_page = n;\n   // CRC32\n   get32(f);\n   // page_segments\n   f->segment_count = get8(f);\n   if (!getn(f, f->segments, f->segment_count))\n      return error(f, VORBIS_unexpected_eof);\n   // assume we _don't_ know any the sample position of any segments\n   f->end_seg_with_known_loc = -2;\n   if (loc0 != ~0U || loc1 != ~0U) {\n      int i;\n      // determine which packet is the last one that will complete\n      for (i=f->segment_count-1; i >= 0; --i)\n         if (f->segments[i] < 255)\n            break;\n      // 'i' is now the index of the _last_ segment of a packet that ends\n      if (i >= 0) {\n         f->end_seg_with_known_loc = i;\n         f->known_loc_for_packet   = loc0;\n      }\n   }\n   if (f->first_decode) {\n      int i,len;\n      len = 0;\n      for (i=0; i < f->segment_count; ++i)\n         len += f->segments[i];\n      len += 27 + f->segment_count;\n      f->p_first.page_end = f->p_first.page_start + len;\n      f->p_first.last_decoded_sample = loc0;\n   }\n   f->next_seg = 0;\n   return TRUE;\n}\n\nstatic int start_page(vorb *f)\n{\n   if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);\n   return start_page_no_capturepattern(f);\n}\n\nstatic int start_packet(vorb *f)\n{\n   while (f->next_seg == -1) {\n      if (!start_page(f)) return FALSE;\n      if (f->page_flag & PAGEFLAG_continued_packet)\n         return error(f, VORBIS_continued_packet_flag_invalid);\n   }\n   f->last_seg = FALSE;\n   f->valid_bits = 0;\n   f->packet_bytes = 0;\n   f->bytes_in_seg = 0;\n   // f->next_seg is now valid\n   return TRUE;\n}\n\nstatic int maybe_start_packet(vorb *f)\n{\n   if (f->next_seg == -1) {\n      int x = get8(f);\n      if (f->eof) return FALSE; // EOF at page boundary is not an error!\n      if (0x4f != x      ) return error(f, VORBIS_missing_capture_pattern);\n      if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);\n      if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);\n      if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);\n      if (!start_page_no_capturepattern(f)) return FALSE;\n      if (f->page_flag & PAGEFLAG_continued_packet) {\n         // set up enough state that we can read this packet if we want,\n         // e.g. during recovery\n         f->last_seg = FALSE;\n         f->bytes_in_seg = 0;\n         return error(f, VORBIS_continued_packet_flag_invalid);\n      }\n   }\n   return start_packet(f);\n}\n\nstatic int next_segment(vorb *f)\n{\n   int len;\n   if (f->last_seg) return 0;\n   if (f->next_seg == -1) {\n      f->last_seg_which = f->segment_count-1; // in case start_page fails\n      if (!start_page(f)) { f->last_seg = 1; return 0; }\n      if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);\n   }\n   len = f->segments[f->next_seg++];\n   if (len < 255) {\n      f->last_seg = TRUE;\n      f->last_seg_which = f->next_seg-1;\n   }\n   if (f->next_seg >= f->segment_count)\n      f->next_seg = -1;\n   assert(f->bytes_in_seg == 0);\n   f->bytes_in_seg = len;\n   return len;\n}\n\n#define EOP    (-1)\n#define INVALID_BITS  (-1)\n\nstatic int get8_packet_raw(vorb *f)\n{\n   if (!f->bytes_in_seg) {  // CLANG!\n      if (f->last_seg) return EOP;\n      else if (!next_segment(f)) return EOP;\n   }\n   assert(f->bytes_in_seg > 0);\n   --f->bytes_in_seg;\n   ++f->packet_bytes;\n   return get8(f);\n}\n\nstatic int get8_packet(vorb *f)\n{\n   int x = get8_packet_raw(f);\n   f->valid_bits = 0;\n   return x;\n}\n\nstatic int get32_packet(vorb *f)\n{\n   uint32 x;\n   x = get8_packet(f);\n   x += get8_packet(f) << 8;\n   x += get8_packet(f) << 16;\n   x += (uint32) get8_packet(f) << 24;\n   return x;\n}\n\nstatic void flush_packet(vorb *f)\n{\n   while (get8_packet_raw(f) != EOP);\n}\n\n// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important\n// as the huffman decoder?\nstatic uint32 get_bits(vorb *f, int n)\n{\n   uint32 z;\n\n   if (f->valid_bits < 0) return 0;\n   if (f->valid_bits < n) {\n      if (n > 24) {\n         // the accumulator technique below would not work correctly in this case\n         z = get_bits(f, 24);\n         z += get_bits(f, n-24) << 24;\n         return z;\n      }\n      if (f->valid_bits == 0) f->acc = 0;\n      while (f->valid_bits < n) {\n         int z = get8_packet_raw(f);\n         if (z == EOP) {\n            f->valid_bits = INVALID_BITS;\n            return 0;\n         }\n         f->acc += z << f->valid_bits;\n         f->valid_bits += 8;\n      }\n   }\n\n   assert(f->valid_bits >= n);\n   z = f->acc & ((1 << n)-1);\n   f->acc >>= n;\n   f->valid_bits -= n;\n   return z;\n}\n\n// @OPTIMIZE: primary accumulator for huffman\n// expand the buffer to as many bits as possible without reading off end of packet\n// it might be nice to allow f->valid_bits and f->acc to be stored in registers,\n// e.g. cache them locally and decode locally\nstatic __forceinline void prep_huffman(vorb *f)\n{\n   if (f->valid_bits <= 24) {\n      if (f->valid_bits == 0) f->acc = 0;\n      do {\n         int z;\n         if (f->last_seg && !f->bytes_in_seg) return;\n         z = get8_packet_raw(f);\n         if (z == EOP) return;\n         f->acc += (unsigned) z << f->valid_bits;\n         f->valid_bits += 8;\n      } while (f->valid_bits <= 24);\n   }\n}\n\nenum\n{\n   VORBIS_packet_id = 1,\n   VORBIS_packet_comment = 3,\n   VORBIS_packet_setup = 5\n};\n\nstatic int codebook_decode_scalar_raw(vorb *f, Codebook *c)\n{\n   int i;\n   prep_huffman(f);\n\n   if (c->codewords == NULL && c->sorted_codewords == NULL)\n      return -1;\n\n   // cases to use binary search: sorted_codewords && !c->codewords\n   //                             sorted_codewords && c->entries > 8\n   if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {\n      // binary search\n      uint32 code = bit_reverse(f->acc);\n      int x=0, n=c->sorted_entries, len;\n\n      while (n > 1) {\n         // invariant: sc[x] <= code < sc[x+n]\n         int m = x + (n >> 1);\n         if (c->sorted_codewords[m] <= code) {\n            x = m;\n            n -= (n>>1);\n         } else {\n            n >>= 1;\n         }\n      }\n      // x is now the sorted index\n      if (!c->sparse) x = c->sorted_values[x];\n      // x is now sorted index if sparse, or symbol otherwise\n      len = c->codeword_lengths[x];\n      if (f->valid_bits >= len) {\n         f->acc >>= len;\n         f->valid_bits -= len;\n         return x;\n      }\n\n      f->valid_bits = 0;\n      return -1;\n   }\n\n   // if small, linear search\n   assert(!c->sparse);\n   for (i=0; i < c->entries; ++i) {\n      if (c->codeword_lengths[i] == NO_CODE) continue;\n      if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {\n         if (f->valid_bits >= c->codeword_lengths[i]) {\n            f->acc >>= c->codeword_lengths[i];\n            f->valid_bits -= c->codeword_lengths[i];\n            return i;\n         }\n         f->valid_bits = 0;\n         return -1;\n      }\n   }\n\n   error(f, VORBIS_invalid_stream);\n   f->valid_bits = 0;\n   return -1;\n}\n\n#ifndef STB_VORBIS_NO_INLINE_DECODE\n\n#define DECODE_RAW(var, f,c)                                  \\\n   if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)        \\\n      prep_huffman(f);                                        \\\n   var = f->acc & FAST_HUFFMAN_TABLE_MASK;                    \\\n   var = c->fast_huffman[var];                                \\\n   if (var >= 0) {                                            \\\n      int n = c->codeword_lengths[var];                       \\\n      f->acc >>= n;                                           \\\n      f->valid_bits -= n;                                     \\\n      if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \\\n   } else {                                                   \\\n      var = codebook_decode_scalar_raw(f,c);                  \\\n   }\n\n#else\n\nstatic int codebook_decode_scalar(vorb *f, Codebook *c)\n{\n   int i;\n   if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)\n      prep_huffman(f);\n   // fast huffman table lookup\n   i = f->acc & FAST_HUFFMAN_TABLE_MASK;\n   i = c->fast_huffman[i];\n   if (i >= 0) {\n      f->acc >>= c->codeword_lengths[i];\n      f->valid_bits -= c->codeword_lengths[i];\n      if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }\n      return i;\n   }\n   return codebook_decode_scalar_raw(f,c);\n}\n\n#define DECODE_RAW(var,f,c)    var = codebook_decode_scalar(f,c);\n\n#endif\n\n#define DECODE(var,f,c)                                       \\\n   DECODE_RAW(var,f,c)                                        \\\n   if (c->sparse) var = c->sorted_values[var];\n\n#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK\n  #define DECODE_VQ(var,f,c)   DECODE_RAW(var,f,c)\n#else\n  #define DECODE_VQ(var,f,c)   DECODE(var,f,c)\n#endif\n\n\n\n\n\n\n// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case\n// where we avoid one addition\n#define CODEBOOK_ELEMENT(c,off)          (c->multiplicands[off])\n#define CODEBOOK_ELEMENT_FAST(c,off)     (c->multiplicands[off])\n#define CODEBOOK_ELEMENT_BASE(c)         (0)\n\nstatic int codebook_decode_start(vorb *f, Codebook *c)\n{\n   int z = -1;\n\n   // type 0 is only legal in a scalar context\n   if (c->lookup_type == 0)\n      error(f, VORBIS_invalid_stream);\n   else {\n      DECODE_VQ(z,f,c);\n      if (c->sparse) assert(z < c->sorted_entries);\n      if (z < 0) {  // check for EOP\n         if (!f->bytes_in_seg)\n            if (f->last_seg)\n               return z;\n         error(f, VORBIS_invalid_stream);\n      }\n   }\n   return z;\n}\n\nstatic int codebook_decode(vorb *f, Codebook *c, float *output, int len)\n{\n   int i,z = codebook_decode_start(f,c);\n   if (z < 0) return FALSE;\n   if (len > c->dimensions) len = c->dimensions;\n\n#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK\n   if (c->lookup_type == 1) {\n      float last = CODEBOOK_ELEMENT_BASE(c);\n      int div = 1;\n      for (i=0; i < len; ++i) {\n         int off = (z / div) % c->lookup_values;\n         float val = CODEBOOK_ELEMENT_FAST(c,off) + last;\n         output[i] += val;\n         if (c->sequence_p) last = val + c->minimum_value;\n         div *= c->lookup_values;\n      }\n      return TRUE;\n   }\n#endif\n\n   z *= c->dimensions;\n   if (c->sequence_p) {\n      float last = CODEBOOK_ELEMENT_BASE(c);\n      for (i=0; i < len; ++i) {\n         float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;\n         output[i] += val;\n         last = val + c->minimum_value;\n      }\n   } else {\n      float last = CODEBOOK_ELEMENT_BASE(c);\n      for (i=0; i < len; ++i) {\n         output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;\n      }\n   }\n\n   return TRUE;\n}\n\nstatic int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)\n{\n   int i,z = codebook_decode_start(f,c);\n   float last = CODEBOOK_ELEMENT_BASE(c);\n   if (z < 0) return FALSE;\n   if (len > c->dimensions) len = c->dimensions;\n\n#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK\n   if (c->lookup_type == 1) {\n      int div = 1;\n      for (i=0; i < len; ++i) {\n         int off = (z / div) % c->lookup_values;\n         float val = CODEBOOK_ELEMENT_FAST(c,off) + last;\n         output[i*step] += val;\n         if (c->sequence_p) last = val;\n         div *= c->lookup_values;\n      }\n      return TRUE;\n   }\n#endif\n\n   z *= c->dimensions;\n   for (i=0; i < len; ++i) {\n      float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;\n      output[i*step] += val;\n      if (c->sequence_p) last = val;\n   }\n\n   return TRUE;\n}\n\nstatic int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)\n{\n   int c_inter = *c_inter_p;\n   int p_inter = *p_inter_p;\n   int i,z, effective = c->dimensions;\n\n   // type 0 is only legal in a scalar context\n   if (c->lookup_type == 0)   return error(f, VORBIS_invalid_stream);\n\n   while (total_decode > 0) {\n      float last = CODEBOOK_ELEMENT_BASE(c);\n      DECODE_VQ(z,f,c);\n      #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK\n      assert(!c->sparse || z < c->sorted_entries);\n      #endif\n      if (z < 0) {\n         if (!f->bytes_in_seg)\n            if (f->last_seg) return FALSE;\n         return error(f, VORBIS_invalid_stream);\n      }\n\n      // if this will take us off the end of the buffers, stop short!\n      // we check by computing the length of the virtual interleaved\n      // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),\n      // and the length we'll be using (effective)\n      if (c_inter + p_inter*ch + effective > len * ch) {\n         effective = len*ch - (p_inter*ch - c_inter);\n      }\n\n   #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK\n      if (c->lookup_type == 1) {\n         int div = 1;\n         for (i=0; i < effective; ++i) {\n            int off = (z / div) % c->lookup_values;\n            float val = CODEBOOK_ELEMENT_FAST(c,off) + last;\n            if (outputs[c_inter])\n               outputs[c_inter][p_inter] += val;\n            if (++c_inter == ch) { c_inter = 0; ++p_inter; }\n            if (c->sequence_p) last = val;\n            div *= c->lookup_values;\n         }\n      } else\n   #endif\n      {\n         z *= c->dimensions;\n         if (c->sequence_p) {\n            for (i=0; i < effective; ++i) {\n               float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;\n               if (outputs[c_inter])\n                  outputs[c_inter][p_inter] += val;\n               if (++c_inter == ch) { c_inter = 0; ++p_inter; }\n               last = val;\n            }\n         } else {\n            for (i=0; i < effective; ++i) {\n               float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;\n               if (outputs[c_inter])\n                  outputs[c_inter][p_inter] += val;\n               if (++c_inter == ch) { c_inter = 0; ++p_inter; }\n            }\n         }\n      }\n\n      total_decode -= effective;\n   }\n   *c_inter_p = c_inter;\n   *p_inter_p = p_inter;\n   return TRUE;\n}\n\nstatic int predict_point(int x, int x0, int x1, int y0, int y1)\n{\n   int dy = y1 - y0;\n   int adx = x1 - x0;\n   // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?\n   int err = abs(dy) * (x - x0);\n   int off = err / adx;\n   return dy < 0 ? y0 - off : y0 + off;\n}\n\n// the following table is block-copied from the specification\nstatic float inverse_db_table[256] =\n{\n  1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,\n  1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,\n  1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,\n  2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,\n  2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,\n  3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,\n  4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,\n  6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,\n  7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,\n  1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,\n  1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,\n  1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,\n  2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,\n  2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,\n  3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,\n  4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,\n  5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,\n  7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,\n  9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,\n  1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,\n  1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,\n  2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,\n  2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,\n  3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,\n  4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,\n  5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,\n  7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,\n  9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,\n  0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,\n  0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,\n  0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,\n  0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,\n  0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,\n  0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,\n  0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,\n  0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,\n  0.00092223983f, 0.00098217216f, 0.0010459992f,  0.0011139742f,\n  0.0011863665f,  0.0012634633f,  0.0013455702f,  0.0014330129f,\n  0.0015261382f,  0.0016253153f,  0.0017309374f,  0.0018434235f,\n  0.0019632195f,  0.0020908006f,  0.0022266726f,  0.0023713743f,\n  0.0025254795f,  0.0026895994f,  0.0028643847f,  0.0030505286f,\n  0.0032487691f,  0.0034598925f,  0.0036847358f,  0.0039241906f,\n  0.0041792066f,  0.0044507950f,  0.0047400328f,  0.0050480668f,\n  0.0053761186f,  0.0057254891f,  0.0060975636f,  0.0064938176f,\n  0.0069158225f,  0.0073652516f,  0.0078438871f,  0.0083536271f,\n  0.0088964928f,  0.009474637f,   0.010090352f,   0.010746080f,\n  0.011444421f,   0.012188144f,   0.012980198f,   0.013823725f,\n  0.014722068f,   0.015678791f,   0.016697687f,   0.017782797f,\n  0.018938423f,   0.020169149f,   0.021479854f,   0.022875735f,\n  0.024362330f,   0.025945531f,   0.027631618f,   0.029427276f,\n  0.031339626f,   0.033376252f,   0.035545228f,   0.037855157f,\n  0.040315199f,   0.042935108f,   0.045725273f,   0.048696758f,\n  0.051861348f,   0.055231591f,   0.058820850f,   0.062643361f,\n  0.066714279f,   0.071049749f,   0.075666962f,   0.080584227f,\n  0.085821044f,   0.091398179f,   0.097337747f,   0.10366330f,\n  0.11039993f,    0.11757434f,    0.12521498f,    0.13335215f,\n  0.14201813f,    0.15124727f,    0.16107617f,    0.17154380f,\n  0.18269168f,    0.19456402f,    0.20720788f,    0.22067342f,\n  0.23501402f,    0.25028656f,    0.26655159f,    0.28387361f,\n  0.30232132f,    0.32196786f,    0.34289114f,    0.36517414f,\n  0.38890521f,    0.41417847f,    0.44109412f,    0.46975890f,\n  0.50028648f,    0.53279791f,    0.56742212f,    0.60429640f,\n  0.64356699f,    0.68538959f,    0.72993007f,    0.77736504f,\n  0.82788260f,    0.88168307f,    0.9389798f,     1.0f\n};\n\n\n// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,\n// note that you must produce bit-identical output to decode correctly;\n// this specific sequence of operations is specified in the spec (it's\n// drawing integer-quantized frequency-space lines that the encoder\n// expects to be exactly the same)\n//     ... also, isn't the whole point of Bresenham's algorithm to NOT\n// have to divide in the setup? sigh.\n#ifndef STB_VORBIS_NO_DEFER_FLOOR\n#define LINE_OP(a,b)   a *= b\n#else\n#define LINE_OP(a,b)   a = b\n#endif\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n#define DIVTAB_NUMER   32\n#define DIVTAB_DENOM   64\nint8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB\n#endif\n\nstatic __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)\n{\n   int dy = y1 - y0;\n   int adx = x1 - x0;\n   int ady = abs(dy);\n   int base;\n   int x=x0,y=y0;\n   int err = 0;\n   int sy;\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n   if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {\n      if (dy < 0) {\n         base = -integer_divide_table[ady][adx];\n         sy = base-1;\n      } else {\n         base =  integer_divide_table[ady][adx];\n         sy = base+1;\n      }\n   } else {\n      base = dy / adx;\n      if (dy < 0)\n         sy = base - 1;\n      else\n         sy = base+1;\n   }\n#else\n   base = dy / adx;\n   if (dy < 0)\n      sy = base - 1;\n   else\n      sy = base+1;\n#endif\n   ady -= abs(base) * adx;\n   if (x1 > n) x1 = n;\n   if (x < x1) {\n      LINE_OP(output[x], inverse_db_table[y&255]);\n      for (++x; x < x1; ++x) {\n         err += ady;\n         if (err >= adx) {\n            err -= adx;\n            y += sy;\n         } else\n            y += base;\n         LINE_OP(output[x], inverse_db_table[y&255]);\n      }\n   }\n}\n\nstatic int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)\n{\n   int k;\n   if (rtype == 0) {\n      int step = n / book->dimensions;\n      for (k=0; k < step; ++k)\n         if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))\n            return FALSE;\n   } else {\n      for (k=0; k < n; ) {\n         if (!codebook_decode(f, book, target+offset, n-k))\n            return FALSE;\n         k += book->dimensions;\n         offset += book->dimensions;\n      }\n   }\n   return TRUE;\n}\n\n// n is 1/2 of the blocksize --\n// specification: \"Correct per-vector decode length is [n]/2\"\nstatic void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)\n{\n   int i,j,pass;\n   Residue *r = f->residue_config + rn;\n   int rtype = f->residue_types[rn];\n   int c = r->classbook;\n   int classwords = f->codebooks[c].dimensions;\n   unsigned int actual_size = rtype == 2 ? n*2 : n;\n   unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);\n   unsigned int limit_r_end   = (r->end   < actual_size ? r->end   : actual_size);\n   int n_read = limit_r_end - limit_r_begin;\n   int part_read = n_read / r->part_size;\n   int temp_alloc_point = temp_alloc_save(f);\n   #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n   uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));\n   #else\n   int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));\n   #endif\n\n   CHECK(f);\n\n   for (i=0; i < ch; ++i)\n      if (!do_not_decode[i])\n         memset(residue_buffers[i], 0, sizeof(float) * n);\n\n   if (rtype == 2 && ch != 1) {\n      for (j=0; j < ch; ++j)\n         if (!do_not_decode[j])\n            break;\n      if (j == ch)\n         goto done;\n\n      for (pass=0; pass < 8; ++pass) {\n         int pcount = 0, class_set = 0;\n         if (ch == 2) {\n            while (pcount < part_read) {\n               int z = r->begin + pcount*r->part_size;\n               int c_inter = (z & 1), p_inter = z>>1;\n               if (pass == 0) {\n                  Codebook *c = f->codebooks+r->classbook;\n                  int q;\n                  DECODE(q,f,c);\n                  if (q == EOP) goto done;\n                  #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n                  part_classdata[0][class_set] = r->classdata[q];\n                  #else\n                  for (i=classwords-1; i >= 0; --i) {\n                     classifications[0][i+pcount] = q % r->classifications;\n                     q /= r->classifications;\n                  }\n                  #endif\n               }\n               for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {\n                  int z = r->begin + pcount*r->part_size;\n                  #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n                  int c = part_classdata[0][class_set][i];\n                  #else\n                  int c = classifications[0][pcount];\n                  #endif\n                  int b = r->residue_books[c][pass];\n                  if (b >= 0) {\n                     Codebook *book = f->codebooks + b;\n                     #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK\n                     if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))\n                        goto done;\n                     #else\n                     // saves 1%\n                     if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))\n                        goto done;\n                     #endif\n                  } else {\n                     z += r->part_size;\n                     c_inter = z & 1;\n                     p_inter = z >> 1;\n                  }\n               }\n               #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n               ++class_set;\n               #endif\n            }\n         } else if (ch > 2) {\n            while (pcount < part_read) {\n               int z = r->begin + pcount*r->part_size;\n               int c_inter = z % ch, p_inter = z/ch;\n               if (pass == 0) {\n                  Codebook *c = f->codebooks+r->classbook;\n                  int q;\n                  DECODE(q,f,c);\n                  if (q == EOP) goto done;\n                  #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n                  part_classdata[0][class_set] = r->classdata[q];\n                  #else\n                  for (i=classwords-1; i >= 0; --i) {\n                     classifications[0][i+pcount] = q % r->classifications;\n                     q /= r->classifications;\n                  }\n                  #endif\n               }\n               for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {\n                  int z = r->begin + pcount*r->part_size;\n                  #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n                  int c = part_classdata[0][class_set][i];\n                  #else\n                  int c = classifications[0][pcount];\n                  #endif\n                  int b = r->residue_books[c][pass];\n                  if (b >= 0) {\n                     Codebook *book = f->codebooks + b;\n                     if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))\n                        goto done;\n                  } else {\n                     z += r->part_size;\n                     c_inter = z % ch;\n                     p_inter = z / ch;\n                  }\n               }\n               #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n               ++class_set;\n               #endif\n            }\n         }\n      }\n      goto done;\n   }\n   CHECK(f);\n\n   for (pass=0; pass < 8; ++pass) {\n      int pcount = 0, class_set=0;\n      while (pcount < part_read) {\n         if (pass == 0) {\n            for (j=0; j < ch; ++j) {\n               if (!do_not_decode[j]) {\n                  Codebook *c = f->codebooks+r->classbook;\n                  int temp;\n                  DECODE(temp,f,c);\n                  if (temp == EOP) goto done;\n                  #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n                  part_classdata[j][class_set] = r->classdata[temp];\n                  #else\n                  for (i=classwords-1; i >= 0; --i) {\n                     classifications[j][i+pcount] = temp % r->classifications;\n                     temp /= r->classifications;\n                  }\n                  #endif\n               }\n            }\n         }\n         for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {\n            for (j=0; j < ch; ++j) {\n               if (!do_not_decode[j]) {\n                  #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n                  int c = part_classdata[j][class_set][i];\n                  #else\n                  int c = classifications[j][pcount];\n                  #endif\n                  int b = r->residue_books[c][pass];\n                  if (b >= 0) {\n                     float *target = residue_buffers[j];\n                     int offset = r->begin + pcount * r->part_size;\n                     int n = r->part_size;\n                     Codebook *book = f->codebooks + b;\n                     if (!residue_decode(f, book, target, offset, n, rtype))\n                        goto done;\n                  }\n               }\n            }\n         }\n         #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n         ++class_set;\n         #endif\n      }\n   }\n  done:\n   CHECK(f);\n   #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n   temp_free(f,part_classdata);\n   #else\n   temp_free(f,classifications);\n   #endif\n   temp_alloc_restore(f,temp_alloc_point);\n}\n\n\n#if 0\n// slow way for debugging\nvoid inverse_mdct_slow(float *buffer, int n)\n{\n   int i,j;\n   int n2 = n >> 1;\n   float *x = (float *) malloc(sizeof(*x) * n2);\n   memcpy(x, buffer, sizeof(*x) * n2);\n   for (i=0; i < n; ++i) {\n      float acc = 0;\n      for (j=0; j < n2; ++j)\n         // formula from paper:\n         //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));\n         // formula from wikipedia\n         //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));\n         // these are equivalent, except the formula from the paper inverts the multiplier!\n         // however, what actually works is NO MULTIPLIER!?!\n         //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));\n         acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));\n      buffer[i] = acc;\n   }\n   free(x);\n}\n#elif 0\n// same as above, but just barely able to run in real time on modern machines\nvoid inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)\n{\n   float mcos[16384];\n   int i,j;\n   int n2 = n >> 1, nmask = (n << 2) -1;\n   float *x = (float *) malloc(sizeof(*x) * n2);\n   memcpy(x, buffer, sizeof(*x) * n2);\n   for (i=0; i < 4*n; ++i)\n      mcos[i] = (float) cos(M_PI / 2 * i / n);\n\n   for (i=0; i < n; ++i) {\n      float acc = 0;\n      for (j=0; j < n2; ++j)\n         acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];\n      buffer[i] = acc;\n   }\n   free(x);\n}\n#elif 0\n// transform to use a slow dct-iv; this is STILL basically trivial,\n// but only requires half as many ops\nvoid dct_iv_slow(float *buffer, int n)\n{\n   float mcos[16384];\n   float x[2048];\n   int i,j;\n   int n2 = n >> 1, nmask = (n << 3) - 1;\n   memcpy(x, buffer, sizeof(*x) * n);\n   for (i=0; i < 8*n; ++i)\n      mcos[i] = (float) cos(M_PI / 4 * i / n);\n   for (i=0; i < n; ++i) {\n      float acc = 0;\n      for (j=0; j < n; ++j)\n         acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];\n      buffer[i] = acc;\n   }\n}\n\nvoid inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)\n{\n   int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;\n   float temp[4096];\n\n   memcpy(temp, buffer, n2 * sizeof(float));\n   dct_iv_slow(temp, n2);  // returns -c'-d, a-b'\n\n   for (i=0; i < n4  ; ++i) buffer[i] = temp[i+n4];            // a-b'\n   for (   ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1];   // b-a', c+d'\n   for (   ; i < n   ; ++i) buffer[i] = -temp[i - n3_4];       // c'+d\n}\n#endif\n\n#ifndef LIBVORBIS_MDCT\n#define LIBVORBIS_MDCT 0\n#endif\n\n#if LIBVORBIS_MDCT\n// directly call the vorbis MDCT using an interface documented\n// by Jeff Roberts... useful for performance comparison\ntypedef struct\n{\n  int n;\n  int log2n;\n\n  float *trig;\n  int   *bitrev;\n\n  float scale;\n} mdct_lookup;\n\nextern void mdct_init(mdct_lookup *lookup, int n);\nextern void mdct_clear(mdct_lookup *l);\nextern void mdct_backward(mdct_lookup *init, float *in, float *out);\n\nmdct_lookup M1,M2;\n\nvoid inverse_mdct(float *buffer, int n, vorb *f, int blocktype)\n{\n   mdct_lookup *M;\n   if (M1.n == n) M = &M1;\n   else if (M2.n == n) M = &M2;\n   else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }\n   else {\n      if (M2.n) __asm int 3;\n      mdct_init(&M2, n);\n      M = &M2;\n   }\n\n   mdct_backward(M, buffer, buffer);\n}\n#endif\n\n\n// the following were split out into separate functions while optimizing;\n// they could be pushed back up but eh. __forceinline showed no change;\n// they're probably already being inlined.\nstatic void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)\n{\n   float *ee0 = e + i_off;\n   float *ee2 = ee0 + k_off;\n   int i;\n\n   assert((n & 3) == 0);\n   for (i=(n>>2); i > 0; --i) {\n      float k00_20, k01_21;\n      k00_20  = ee0[ 0] - ee2[ 0];\n      k01_21  = ee0[-1] - ee2[-1];\n      ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];\n      ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];\n      ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];\n      ee2[-1] = k01_21 * A[0] + k00_20 * A[1];\n      A += 8;\n\n      k00_20  = ee0[-2] - ee2[-2];\n      k01_21  = ee0[-3] - ee2[-3];\n      ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];\n      ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];\n      ee2[-2] = k00_20 * A[0] - k01_21 * A[1];\n      ee2[-3] = k01_21 * A[0] + k00_20 * A[1];\n      A += 8;\n\n      k00_20  = ee0[-4] - ee2[-4];\n      k01_21  = ee0[-5] - ee2[-5];\n      ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];\n      ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];\n      ee2[-4] = k00_20 * A[0] - k01_21 * A[1];\n      ee2[-5] = k01_21 * A[0] + k00_20 * A[1];\n      A += 8;\n\n      k00_20  = ee0[-6] - ee2[-6];\n      k01_21  = ee0[-7] - ee2[-7];\n      ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];\n      ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];\n      ee2[-6] = k00_20 * A[0] - k01_21 * A[1];\n      ee2[-7] = k01_21 * A[0] + k00_20 * A[1];\n      A += 8;\n      ee0 -= 8;\n      ee2 -= 8;\n   }\n}\n\nstatic void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)\n{\n   int i;\n   float k00_20, k01_21;\n\n   float *e0 = e + d0;\n   float *e2 = e0 + k_off;\n\n   for (i=lim >> 2; i > 0; --i) {\n      k00_20 = e0[-0] - e2[-0];\n      k01_21 = e0[-1] - e2[-1];\n      e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];\n      e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];\n      e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];\n      e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];\n\n      A += k1;\n\n      k00_20 = e0[-2] - e2[-2];\n      k01_21 = e0[-3] - e2[-3];\n      e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];\n      e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];\n      e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];\n      e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];\n\n      A += k1;\n\n      k00_20 = e0[-4] - e2[-4];\n      k01_21 = e0[-5] - e2[-5];\n      e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];\n      e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];\n      e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];\n      e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];\n\n      A += k1;\n\n      k00_20 = e0[-6] - e2[-6];\n      k01_21 = e0[-7] - e2[-7];\n      e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];\n      e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];\n      e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];\n      e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];\n\n      e0 -= 8;\n      e2 -= 8;\n\n      A += k1;\n   }\n}\n\nstatic void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)\n{\n   int i;\n   float A0 = A[0];\n   float A1 = A[0+1];\n   float A2 = A[0+a_off];\n   float A3 = A[0+a_off+1];\n   float A4 = A[0+a_off*2+0];\n   float A5 = A[0+a_off*2+1];\n   float A6 = A[0+a_off*3+0];\n   float A7 = A[0+a_off*3+1];\n\n   float k00,k11;\n\n   float *ee0 = e  +i_off;\n   float *ee2 = ee0+k_off;\n\n   for (i=n; i > 0; --i) {\n      k00     = ee0[ 0] - ee2[ 0];\n      k11     = ee0[-1] - ee2[-1];\n      ee0[ 0] =  ee0[ 0] + ee2[ 0];\n      ee0[-1] =  ee0[-1] + ee2[-1];\n      ee2[ 0] = (k00) * A0 - (k11) * A1;\n      ee2[-1] = (k11) * A0 + (k00) * A1;\n\n      k00     = ee0[-2] - ee2[-2];\n      k11     = ee0[-3] - ee2[-3];\n      ee0[-2] =  ee0[-2] + ee2[-2];\n      ee0[-3] =  ee0[-3] + ee2[-3];\n      ee2[-2] = (k00) * A2 - (k11) * A3;\n      ee2[-3] = (k11) * A2 + (k00) * A3;\n\n      k00     = ee0[-4] - ee2[-4];\n      k11     = ee0[-5] - ee2[-5];\n      ee0[-4] =  ee0[-4] + ee2[-4];\n      ee0[-5] =  ee0[-5] + ee2[-5];\n      ee2[-4] = (k00) * A4 - (k11) * A5;\n      ee2[-5] = (k11) * A4 + (k00) * A5;\n\n      k00     = ee0[-6] - ee2[-6];\n      k11     = ee0[-7] - ee2[-7];\n      ee0[-6] =  ee0[-6] + ee2[-6];\n      ee0[-7] =  ee0[-7] + ee2[-7];\n      ee2[-6] = (k00) * A6 - (k11) * A7;\n      ee2[-7] = (k11) * A6 + (k00) * A7;\n\n      ee0 -= k0;\n      ee2 -= k0;\n   }\n}\n\nstatic __forceinline void iter_54(float *z)\n{\n   float k00,k11,k22,k33;\n   float y0,y1,y2,y3;\n\n   k00  = z[ 0] - z[-4];\n   y0   = z[ 0] + z[-4];\n   y2   = z[-2] + z[-6];\n   k22  = z[-2] - z[-6];\n\n   z[-0] = y0 + y2;      // z0 + z4 + z2 + z6\n   z[-2] = y0 - y2;      // z0 + z4 - z2 - z6\n\n   // done with y0,y2\n\n   k33  = z[-3] - z[-7];\n\n   z[-4] = k00 + k33;    // z0 - z4 + z3 - z7\n   z[-6] = k00 - k33;    // z0 - z4 - z3 + z7\n\n   // done with k33\n\n   k11  = z[-1] - z[-5];\n   y1   = z[-1] + z[-5];\n   y3   = z[-3] + z[-7];\n\n   z[-1] = y1 + y3;      // z1 + z5 + z3 + z7\n   z[-3] = y1 - y3;      // z1 + z5 - z3 - z7\n   z[-5] = k11 - k22;    // z1 - z5 + z2 - z6\n   z[-7] = k11 + k22;    // z1 - z5 - z2 + z6\n}\n\nstatic void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)\n{\n   int a_off = base_n >> 3;\n   float A2 = A[0+a_off];\n   float *z = e + i_off;\n   float *base = z - 16 * n;\n\n   while (z > base) {\n      float k00,k11;\n      float l00,l11;\n\n      k00    = z[-0] - z[ -8];\n      k11    = z[-1] - z[ -9];\n      l00    = z[-2] - z[-10];\n      l11    = z[-3] - z[-11];\n      z[ -0] = z[-0] + z[ -8];\n      z[ -1] = z[-1] + z[ -9];\n      z[ -2] = z[-2] + z[-10];\n      z[ -3] = z[-3] + z[-11];\n      z[ -8] = k00;\n      z[ -9] = k11;\n      z[-10] = (l00+l11) * A2;\n      z[-11] = (l11-l00) * A2;\n\n      k00    = z[ -4] - z[-12];\n      k11    = z[ -5] - z[-13];\n      l00    = z[ -6] - z[-14];\n      l11    = z[ -7] - z[-15];\n      z[ -4] = z[ -4] + z[-12];\n      z[ -5] = z[ -5] + z[-13];\n      z[ -6] = z[ -6] + z[-14];\n      z[ -7] = z[ -7] + z[-15];\n      z[-12] = k11;\n      z[-13] = -k00;\n      z[-14] = (l11-l00) * A2;\n      z[-15] = (l00+l11) * -A2;\n\n      iter_54(z);\n      iter_54(z-8);\n      z -= 16;\n   }\n}\n\nstatic void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)\n{\n   int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;\n   int ld;\n   // @OPTIMIZE: reduce register pressure by using fewer variables?\n   int save_point = temp_alloc_save(f);\n   float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));\n   float *u=NULL,*v=NULL;\n   // twiddle factors\n   float *A = f->A[blocktype];\n\n   // IMDCT algorithm from \"The use of multirate filter banks for coding of high quality digital audio\"\n   // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.\n\n   // kernel from paper\n\n\n   // merged:\n   //   copy and reflect spectral data\n   //   step 0\n\n   // note that it turns out that the items added together during\n   // this step are, in fact, being added to themselves (as reflected\n   // by step 0). inexplicable inefficiency! this became obvious\n   // once I combined the passes.\n\n   // so there's a missing 'times 2' here (for adding X to itself).\n   // this propagates through linearly to the end, where the numbers\n   // are 1/2 too small, and need to be compensated for.\n\n   {\n      float *d,*e, *AA, *e_stop;\n      d = &buf2[n2-2];\n      AA = A;\n      e = &buffer[0];\n      e_stop = &buffer[n2];\n      while (e != e_stop) {\n         d[1] = (e[0] * AA[0] - e[2]*AA[1]);\n         d[0] = (e[0] * AA[1] + e[2]*AA[0]);\n         d -= 2;\n         AA += 2;\n         e += 4;\n      }\n\n      e = &buffer[n2-3];\n      while (d >= buf2) {\n         d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);\n         d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);\n         d -= 2;\n         AA += 2;\n         e -= 4;\n      }\n   }\n\n   // now we use symbolic names for these, so that we can\n   // possibly swap their meaning as we change which operations\n   // are in place\n\n   u = buffer;\n   v = buf2;\n\n   // step 2    (paper output is w, now u)\n   // this could be in place, but the data ends up in the wrong\n   // place... _somebody_'s got to swap it, so this is nominated\n   {\n      float *AA = &A[n2-8];\n      float *d0,*d1, *e0, *e1;\n\n      e0 = &v[n4];\n      e1 = &v[0];\n\n      d0 = &u[n4];\n      d1 = &u[0];\n\n      while (AA >= A) {\n         float v40_20, v41_21;\n\n         v41_21 = e0[1] - e1[1];\n         v40_20 = e0[0] - e1[0];\n         d0[1]  = e0[1] + e1[1];\n         d0[0]  = e0[0] + e1[0];\n         d1[1]  = v41_21*AA[4] - v40_20*AA[5];\n         d1[0]  = v40_20*AA[4] + v41_21*AA[5];\n\n         v41_21 = e0[3] - e1[3];\n         v40_20 = e0[2] - e1[2];\n         d0[3]  = e0[3] + e1[3];\n         d0[2]  = e0[2] + e1[2];\n         d1[3]  = v41_21*AA[0] - v40_20*AA[1];\n         d1[2]  = v40_20*AA[0] + v41_21*AA[1];\n\n         AA -= 8;\n\n         d0 += 4;\n         d1 += 4;\n         e0 += 4;\n         e1 += 4;\n      }\n   }\n\n   // step 3\n   ld = ilog(n) - 1; // ilog is off-by-one from normal definitions\n\n   // optimized step 3:\n\n   // the original step3 loop can be nested r inside s or s inside r;\n   // it's written originally as s inside r, but this is dumb when r\n   // iterates many times, and s few. So I have two copies of it and\n   // switch between them halfway.\n\n   // this is iteration 0 of step 3\n   imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);\n   imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);\n\n   // this is iteration 1 of step 3\n   imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);\n   imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);\n   imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);\n   imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);\n\n   l=2;\n   for (; l < (ld-3)>>1; ++l) {\n      int k0 = n >> (l+2), k0_2 = k0>>1;\n      int lim = 1 << (l+1);\n      int i;\n      for (i=0; i < lim; ++i)\n         imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));\n   }\n\n   for (; l < ld-6; ++l) {\n      int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;\n      int rlim = n >> (l+6), r;\n      int lim = 1 << (l+1);\n      int i_off;\n      float *A0 = A;\n      i_off = n2-1;\n      for (r=rlim; r > 0; --r) {\n         imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);\n         A0 += k1*4;\n         i_off -= 8;\n      }\n   }\n\n   // iterations with count:\n   //   ld-6,-5,-4 all interleaved together\n   //       the big win comes from getting rid of needless flops\n   //         due to the constants on pass 5 & 4 being all 1 and 0;\n   //       combining them to be simultaneous to improve cache made little difference\n   imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);\n\n   // output is u\n\n   // step 4, 5, and 6\n   // cannot be in-place because of step 5\n   {\n      uint16 *bitrev = f->bit_reverse[blocktype];\n      // weirdly, I'd have thought reading sequentially and writing\n      // erratically would have been better than vice-versa, but in\n      // fact that's not what my testing showed. (That is, with\n      // j = bitreverse(i), do you read i and write j, or read j and write i.)\n\n      float *d0 = &v[n4-4];\n      float *d1 = &v[n2-4];\n      while (d0 >= v) {\n         int k4;\n\n         k4 = bitrev[0];\n         d1[3] = u[k4+0];\n         d1[2] = u[k4+1];\n         d0[3] = u[k4+2];\n         d0[2] = u[k4+3];\n\n         k4 = bitrev[1];\n         d1[1] = u[k4+0];\n         d1[0] = u[k4+1];\n         d0[1] = u[k4+2];\n         d0[0] = u[k4+3];\n\n         d0 -= 4;\n         d1 -= 4;\n         bitrev += 2;\n      }\n   }\n   // (paper output is u, now v)\n\n\n   // data must be in buf2\n   assert(v == buf2);\n\n   // step 7   (paper output is v, now v)\n   // this is now in place\n   {\n      float *C = f->C[blocktype];\n      float *d, *e;\n\n      d = v;\n      e = v + n2 - 4;\n\n      while (d < e) {\n         float a02,a11,b0,b1,b2,b3;\n\n         a02 = d[0] - e[2];\n         a11 = d[1] + e[3];\n\n         b0 = C[1]*a02 + C[0]*a11;\n         b1 = C[1]*a11 - C[0]*a02;\n\n         b2 = d[0] + e[ 2];\n         b3 = d[1] - e[ 3];\n\n         d[0] = b2 + b0;\n         d[1] = b3 + b1;\n         e[2] = b2 - b0;\n         e[3] = b1 - b3;\n\n         a02 = d[2] - e[0];\n         a11 = d[3] + e[1];\n\n         b0 = C[3]*a02 + C[2]*a11;\n         b1 = C[3]*a11 - C[2]*a02;\n\n         b2 = d[2] + e[ 0];\n         b3 = d[3] - e[ 1];\n\n         d[2] = b2 + b0;\n         d[3] = b3 + b1;\n         e[0] = b2 - b0;\n         e[1] = b1 - b3;\n\n         C += 4;\n         d += 4;\n         e -= 4;\n      }\n   }\n\n   // data must be in buf2\n\n\n   // step 8+decode   (paper output is X, now buffer)\n   // this generates pairs of data a la 8 and pushes them directly through\n   // the decode kernel (pushing rather than pulling) to avoid having\n   // to make another pass later\n\n   // this cannot POSSIBLY be in place, so we refer to the buffers directly\n\n   {\n      float *d0,*d1,*d2,*d3;\n\n      float *B = f->B[blocktype] + n2 - 8;\n      float *e = buf2 + n2 - 8;\n      d0 = &buffer[0];\n      d1 = &buffer[n2-4];\n      d2 = &buffer[n2];\n      d3 = &buffer[n-4];\n      while (e >= v) {\n         float p0,p1,p2,p3;\n\n         p3 =  e[6]*B[7] - e[7]*B[6];\n         p2 = -e[6]*B[6] - e[7]*B[7];\n\n         d0[0] =   p3;\n         d1[3] = - p3;\n         d2[0] =   p2;\n         d3[3] =   p2;\n\n         p1 =  e[4]*B[5] - e[5]*B[4];\n         p0 = -e[4]*B[4] - e[5]*B[5];\n\n         d0[1] =   p1;\n         d1[2] = - p1;\n         d2[1] =   p0;\n         d3[2] =   p0;\n\n         p3 =  e[2]*B[3] - e[3]*B[2];\n         p2 = -e[2]*B[2] - e[3]*B[3];\n\n         d0[2] =   p3;\n         d1[1] = - p3;\n         d2[2] =   p2;\n         d3[1] =   p2;\n\n         p1 =  e[0]*B[1] - e[1]*B[0];\n         p0 = -e[0]*B[0] - e[1]*B[1];\n\n         d0[3] =   p1;\n         d1[0] = - p1;\n         d2[3] =   p0;\n         d3[0] =   p0;\n\n         B -= 8;\n         e -= 8;\n         d0 += 4;\n         d2 += 4;\n         d1 -= 4;\n         d3 -= 4;\n      }\n   }\n\n   temp_free(f,buf2);\n   temp_alloc_restore(f,save_point);\n}\n\n#if 0\n// this is the original version of the above code, if you want to optimize it from scratch\nvoid inverse_mdct_naive(float *buffer, int n)\n{\n   float s;\n   float A[1 << 12], B[1 << 12], C[1 << 11];\n   int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;\n   int n3_4 = n - n4, ld;\n   // how can they claim this only uses N words?!\n   // oh, because they're only used sparsely, whoops\n   float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];\n   // set up twiddle factors\n\n   for (k=k2=0; k < n4; ++k,k2+=2) {\n      A[k2  ] = (float)  cos(4*k*M_PI/n);\n      A[k2+1] = (float) -sin(4*k*M_PI/n);\n      B[k2  ] = (float)  cos((k2+1)*M_PI/n/2);\n      B[k2+1] = (float)  sin((k2+1)*M_PI/n/2);\n   }\n   for (k=k2=0; k < n8; ++k,k2+=2) {\n      C[k2  ] = (float)  cos(2*(k2+1)*M_PI/n);\n      C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);\n   }\n\n   // IMDCT algorithm from \"The use of multirate filter banks for coding of high quality digital audio\"\n   // Note there are bugs in that pseudocode, presumably due to them attempting\n   // to rename the arrays nicely rather than representing the way their actual\n   // implementation bounces buffers back and forth. As a result, even in the\n   // \"some formulars corrected\" version, a direct implementation fails. These\n   // are noted below as \"paper bug\".\n\n   // copy and reflect spectral data\n   for (k=0; k < n2; ++k) u[k] = buffer[k];\n   for (   ; k < n ; ++k) u[k] = -buffer[n - k - 1];\n   // kernel from paper\n   // step 1\n   for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {\n      v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2]   - (u[k4+2] - u[n-k4-3])*A[k2+1];\n      v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];\n   }\n   // step 2\n   for (k=k4=0; k < n8; k+=1, k4+=4) {\n      w[n2+3+k4] = v[n2+3+k4] + v[k4+3];\n      w[n2+1+k4] = v[n2+1+k4] + v[k4+1];\n      w[k4+3]    = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];\n      w[k4+1]    = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];\n   }\n   // step 3\n   ld = ilog(n) - 1; // ilog is off-by-one from normal definitions\n   for (l=0; l < ld-3; ++l) {\n      int k0 = n >> (l+2), k1 = 1 << (l+3);\n      int rlim = n >> (l+4), r4, r;\n      int s2lim = 1 << (l+2), s2;\n      for (r=r4=0; r < rlim; r4+=4,++r) {\n         for (s2=0; s2 < s2lim; s2+=2) {\n            u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];\n            u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];\n            u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]\n                                - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];\n            u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]\n                                + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];\n         }\n      }\n      if (l+1 < ld-3) {\n         // paper bug: ping-ponging of u&w here is omitted\n         memcpy(w, u, sizeof(u));\n      }\n   }\n\n   // step 4\n   for (i=0; i < n8; ++i) {\n      int j = bit_reverse(i) >> (32-ld+3);\n      assert(j < n8);\n      if (i == j) {\n         // paper bug: original code probably swapped in place; if copying,\n         //            need to directly copy in this case\n         int i8 = i << 3;\n         v[i8+1] = u[i8+1];\n         v[i8+3] = u[i8+3];\n         v[i8+5] = u[i8+5];\n         v[i8+7] = u[i8+7];\n      } else if (i < j) {\n         int i8 = i << 3, j8 = j << 3;\n         v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];\n         v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];\n         v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];\n         v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];\n      }\n   }\n   // step 5\n   for (k=0; k < n2; ++k) {\n      w[k] = v[k*2+1];\n   }\n   // step 6\n   for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {\n      u[n-1-k2] = w[k4];\n      u[n-2-k2] = w[k4+1];\n      u[n3_4 - 1 - k2] = w[k4+2];\n      u[n3_4 - 2 - k2] = w[k4+3];\n   }\n   // step 7\n   for (k=k2=0; k < n8; ++k, k2 += 2) {\n      v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;\n      v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;\n      v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;\n      v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;\n   }\n   // step 8\n   for (k=k2=0; k < n4; ++k,k2 += 2) {\n      X[k]      = v[k2+n2]*B[k2  ] + v[k2+1+n2]*B[k2+1];\n      X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2  ];\n   }\n\n   // decode kernel to output\n   // determined the following value experimentally\n   // (by first figuring out what made inverse_mdct_slow work); then matching that here\n   // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)\n   s = 0.5; // theoretically would be n4\n\n   // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,\n   //     so it needs to use the \"old\" B values to behave correctly, or else\n   //     set s to 1.0 ]]]\n   for (i=0; i < n4  ; ++i) buffer[i] = s * X[i+n4];\n   for (   ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];\n   for (   ; i < n   ; ++i) buffer[i] = -s * X[i - n3_4];\n}\n#endif\n\nstatic float *get_window(vorb *f, int len)\n{\n   len <<= 1;\n   if (len == f->blocksize_0) return f->window[0];\n   if (len == f->blocksize_1) return f->window[1];\n   return NULL;\n}\n\n#ifndef STB_VORBIS_NO_DEFER_FLOOR\ntypedef int16 YTYPE;\n#else\ntypedef int YTYPE;\n#endif\nstatic int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)\n{\n   int n2 = n >> 1;\n   int s = map->chan[i].mux, floor;\n   floor = map->submap_floor[s];\n   if (f->floor_types[floor] == 0) {\n      return error(f, VORBIS_invalid_stream);\n   } else {\n      Floor1 *g = &f->floor_config[floor].floor1;\n      int j,q;\n      int lx = 0, ly = finalY[0] * g->floor1_multiplier;\n      for (q=1; q < g->values; ++q) {\n         j = g->sorted_order[q];\n         #ifndef STB_VORBIS_NO_DEFER_FLOOR\n         STBV_NOTUSED(step2_flag);\n         if (finalY[j] >= 0)\n         #else\n         if (step2_flag[j])\n         #endif\n         {\n            int hy = finalY[j] * g->floor1_multiplier;\n            int hx = g->Xlist[j];\n            if (lx != hx)\n               draw_line(target, lx,ly, hx,hy, n2);\n            CHECK(f);\n            lx = hx, ly = hy;\n         }\n      }\n      if (lx < n2) {\n         // optimization of: draw_line(target, lx,ly, n,ly, n2);\n         for (j=lx; j < n2; ++j)\n            LINE_OP(target[j], inverse_db_table[ly]);\n         CHECK(f);\n      }\n   }\n   return TRUE;\n}\n\n// The meaning of \"left\" and \"right\"\n//\n// For a given frame:\n//     we compute samples from 0..n\n//     window_center is n/2\n//     we'll window and mix the samples from left_start to left_end with data from the previous frame\n//     all of the samples from left_end to right_start can be output without mixing; however,\n//        this interval is 0-length except when transitioning between short and long frames\n//     all of the samples from right_start to right_end need to be mixed with the next frame,\n//        which we don't have, so those get saved in a buffer\n//     frame N's right_end-right_start, the number of samples to mix with the next frame,\n//        has to be the same as frame N+1's left_end-left_start (which they are by\n//        construction)\n\nstatic int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)\n{\n   Mode *m;\n   int i, n, prev, next, window_center;\n   f->channel_buffer_start = f->channel_buffer_end = 0;\n\n  retry:\n   if (f->eof) return FALSE;\n   if (!maybe_start_packet(f))\n      return FALSE;\n   // check packet type\n   if (get_bits(f,1) != 0) {\n      if (IS_PUSH_MODE(f))\n         return error(f,VORBIS_bad_packet_type);\n      while (EOP != get8_packet(f));\n      goto retry;\n   }\n\n   if (f->alloc.alloc_buffer)\n      assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);\n\n   i = get_bits(f, ilog(f->mode_count-1));\n   if (i == EOP) return FALSE;\n   if (i >= f->mode_count) return FALSE;\n   *mode = i;\n   m = f->mode_config + i;\n   if (m->blockflag) {\n      n = f->blocksize_1;\n      prev = get_bits(f,1);\n      next = get_bits(f,1);\n   } else {\n      prev = next = 0;\n      n = f->blocksize_0;\n   }\n\n// WINDOWING\n\n   window_center = n >> 1;\n   if (m->blockflag && !prev) {\n      *p_left_start = (n - f->blocksize_0) >> 2;\n      *p_left_end   = (n + f->blocksize_0) >> 2;\n   } else {\n      *p_left_start = 0;\n      *p_left_end   = window_center;\n   }\n   if (m->blockflag && !next) {\n      *p_right_start = (n*3 - f->blocksize_0) >> 2;\n      *p_right_end   = (n*3 + f->blocksize_0) >> 2;\n   } else {\n      *p_right_start = window_center;\n      *p_right_end   = n;\n   }\n\n   return TRUE;\n}\n\nstatic int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)\n{\n   Mapping *map;\n   int i,j,k,n,n2;\n   int zero_channel[256];\n   int really_zero_channel[256];\n\n// WINDOWING\n\n   STBV_NOTUSED(left_end);\n   n = f->blocksize[m->blockflag];\n   map = &f->mapping[m->mapping];\n\n// FLOORS\n   n2 = n >> 1;\n\n   CHECK(f);\n\n   for (i=0; i < f->channels; ++i) {\n      int s = map->chan[i].mux, floor;\n      zero_channel[i] = FALSE;\n      floor = map->submap_floor[s];\n      if (f->floor_types[floor] == 0) {\n         return error(f, VORBIS_invalid_stream);\n      } else {\n         Floor1 *g = &f->floor_config[floor].floor1;\n         if (get_bits(f, 1)) {\n            short *finalY;\n            uint8 step2_flag[256];\n            static int range_list[4] = { 256, 128, 86, 64 };\n            int range = range_list[g->floor1_multiplier-1];\n            int offset = 2;\n            finalY = f->finalY[i];\n            finalY[0] = get_bits(f, ilog(range)-1);\n            finalY[1] = get_bits(f, ilog(range)-1);\n            for (j=0; j < g->partitions; ++j) {\n               int pclass = g->partition_class_list[j];\n               int cdim = g->class_dimensions[pclass];\n               int cbits = g->class_subclasses[pclass];\n               int csub = (1 << cbits)-1;\n               int cval = 0;\n               if (cbits) {\n                  Codebook *c = f->codebooks + g->class_masterbooks[pclass];\n                  DECODE(cval,f,c);\n               }\n               for (k=0; k < cdim; ++k) {\n                  int book = g->subclass_books[pclass][cval & csub];\n                  cval = cval >> cbits;\n                  if (book >= 0) {\n                     int temp;\n                     Codebook *c = f->codebooks + book;\n                     DECODE(temp,f,c);\n                     finalY[offset++] = temp;\n                  } else\n                     finalY[offset++] = 0;\n               }\n            }\n            if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec\n            step2_flag[0] = step2_flag[1] = 1;\n            for (j=2; j < g->values; ++j) {\n               int low, high, pred, highroom, lowroom, room, val;\n               low = g->neighbors[j][0];\n               high = g->neighbors[j][1];\n               //neighbors(g->Xlist, j, &low, &high);\n               pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);\n               val = finalY[j];\n               highroom = range - pred;\n               lowroom = pred;\n               if (highroom < lowroom)\n                  room = highroom * 2;\n               else\n                  room = lowroom * 2;\n               if (val) {\n                  step2_flag[low] = step2_flag[high] = 1;\n                  step2_flag[j] = 1;\n                  if (val >= room)\n                     if (highroom > lowroom)\n                        finalY[j] = val - lowroom + pred;\n                     else\n                        finalY[j] = pred - val + highroom - 1;\n                  else\n                     if (val & 1)\n                        finalY[j] = pred - ((val+1)>>1);\n                     else\n                        finalY[j] = pred + (val>>1);\n               } else {\n                  step2_flag[j] = 0;\n                  finalY[j] = pred;\n               }\n            }\n\n#ifdef STB_VORBIS_NO_DEFER_FLOOR\n            do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);\n#else\n            // defer final floor computation until _after_ residue\n            for (j=0; j < g->values; ++j) {\n               if (!step2_flag[j])\n                  finalY[j] = -1;\n            }\n#endif\n         } else {\n           error:\n            zero_channel[i] = TRUE;\n         }\n         // So we just defer everything else to later\n\n         // at this point we've decoded the floor into buffer\n      }\n   }\n   CHECK(f);\n   // at this point we've decoded all floors\n\n   if (f->alloc.alloc_buffer)\n      assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);\n\n   // re-enable coupled channels if necessary\n   memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);\n   for (i=0; i < map->coupling_steps; ++i)\n      if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {\n         zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;\n      }\n\n   CHECK(f);\n// RESIDUE DECODE\n   for (i=0; i < map->submaps; ++i) {\n      float *residue_buffers[STB_VORBIS_MAX_CHANNELS];\n      int r;\n      uint8 do_not_decode[256];\n      int ch = 0;\n      for (j=0; j < f->channels; ++j) {\n         if (map->chan[j].mux == i) {\n            if (zero_channel[j]) {\n               do_not_decode[ch] = TRUE;\n               residue_buffers[ch] = NULL;\n            } else {\n               do_not_decode[ch] = FALSE;\n               residue_buffers[ch] = f->channel_buffers[j];\n            }\n            ++ch;\n         }\n      }\n      r = map->submap_residue[i];\n      decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);\n   }\n\n   if (f->alloc.alloc_buffer)\n      assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);\n   CHECK(f);\n\n// INVERSE COUPLING\n   for (i = map->coupling_steps-1; i >= 0; --i) {\n      int n2 = n >> 1;\n      float *m = f->channel_buffers[map->chan[i].magnitude];\n      float *a = f->channel_buffers[map->chan[i].angle    ];\n      for (j=0; j < n2; ++j) {\n         float a2,m2;\n         if (m[j] > 0)\n            if (a[j] > 0)\n               m2 = m[j], a2 = m[j] - a[j];\n            else\n               a2 = m[j], m2 = m[j] + a[j];\n         else\n            if (a[j] > 0)\n               m2 = m[j], a2 = m[j] + a[j];\n            else\n               a2 = m[j], m2 = m[j] - a[j];\n         m[j] = m2;\n         a[j] = a2;\n      }\n   }\n   CHECK(f);\n\n   // finish decoding the floors\n#ifndef STB_VORBIS_NO_DEFER_FLOOR\n   for (i=0; i < f->channels; ++i) {\n      if (really_zero_channel[i]) {\n         memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);\n      } else {\n         do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);\n      }\n   }\n#else\n   for (i=0; i < f->channels; ++i) {\n      if (really_zero_channel[i]) {\n         memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);\n      } else {\n         for (j=0; j < n2; ++j)\n            f->channel_buffers[i][j] *= f->floor_buffers[i][j];\n      }\n   }\n#endif\n\n// INVERSE MDCT\n   CHECK(f);\n   for (i=0; i < f->channels; ++i)\n      inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);\n   CHECK(f);\n\n   // this shouldn't be necessary, unless we exited on an error\n   // and want to flush to get to the next packet\n   flush_packet(f);\n\n   if (f->first_decode) {\n      // assume we start so first non-discarded sample is sample 0\n      // this isn't to spec, but spec would require us to read ahead\n      // and decode the size of all current frames--could be done,\n      // but presumably it's not a commonly used feature\n      f->current_loc = 0u - n2; // start of first frame is positioned for discard (NB this is an intentional unsigned overflow/wrap-around)\n      // we might have to discard samples \"from\" the next frame too,\n      // if we're lapping a large block then a small at the start?\n      f->discard_samples_deferred = n - right_end;\n      f->current_loc_valid = TRUE;\n      f->first_decode = FALSE;\n   } else if (f->discard_samples_deferred) {\n      if (f->discard_samples_deferred >= right_start - left_start) {\n         f->discard_samples_deferred -= (right_start - left_start);\n         left_start = right_start;\n         *p_left = left_start;\n      } else {\n         left_start += f->discard_samples_deferred;\n         *p_left = left_start;\n         f->discard_samples_deferred = 0;\n      }\n   } else if (f->previous_length == 0 && f->current_loc_valid) {\n      // we're recovering from a seek... that means we're going to discard\n      // the samples from this packet even though we know our position from\n      // the last page header, so we need to update the position based on\n      // the discarded samples here\n      // but wait, the code below is going to add this in itself even\n      // on a discard, so we don't need to do it here...\n   }\n\n   // check if we have ogg information about the sample # for this packet\n   if (f->last_seg_which == f->end_seg_with_known_loc) {\n      // if we have a valid current loc, and this is final:\n      if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {\n         uint32 current_end = f->known_loc_for_packet;\n         // then let's infer the size of the (probably) short final frame\n         if (current_end < f->current_loc + (right_end-left_start)) {\n            if (current_end < f->current_loc) {\n               // negative truncation, that's impossible!\n               *len = 0;\n            } else {\n               *len = current_end - f->current_loc;\n            }\n            *len += left_start; // this doesn't seem right, but has no ill effect on my test files\n            if (*len > right_end) *len = right_end; // this should never happen\n            f->current_loc += *len;\n            return TRUE;\n         }\n      }\n      // otherwise, just set our sample loc\n      // guess that the ogg granule pos refers to the _middle_ of the\n      // last frame?\n      // set f->current_loc to the position of left_start\n      f->current_loc = f->known_loc_for_packet - (n2-left_start);\n      f->current_loc_valid = TRUE;\n   }\n   if (f->current_loc_valid)\n      f->current_loc += (right_start - left_start);\n\n   if (f->alloc.alloc_buffer)\n      assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);\n   *len = right_end;  // ignore samples after the window goes to 0\n   CHECK(f);\n\n   return TRUE;\n}\n\nstatic int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)\n{\n   int mode, left_end, right_end;\n   if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;\n   return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);\n}\n\nstatic int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)\n{\n   int prev,i,j;\n   // we use right&left (the start of the right- and left-window sin()-regions)\n   // to determine how much to return, rather than inferring from the rules\n   // (same result, clearer code); 'left' indicates where our sin() window\n   // starts, therefore where the previous window's right edge starts, and\n   // therefore where to start mixing from the previous buffer. 'right'\n   // indicates where our sin() ending-window starts, therefore that's where\n   // we start saving, and where our returned-data ends.\n\n   // mixin from previous window\n   if (f->previous_length) {\n      int i,j, n = f->previous_length;\n      float *w = get_window(f, n);\n      if (w == NULL) return 0;\n      for (i=0; i < f->channels; ++i) {\n         for (j=0; j < n; ++j)\n            f->channel_buffers[i][left+j] =\n               f->channel_buffers[i][left+j]*w[    j] +\n               f->previous_window[i][     j]*w[n-1-j];\n      }\n   }\n\n   prev = f->previous_length;\n\n   // last half of this data becomes previous window\n   f->previous_length = len - right;\n\n   // @OPTIMIZE: could avoid this copy by double-buffering the\n   // output (flipping previous_window with channel_buffers), but\n   // then previous_window would have to be 2x as large, and\n   // channel_buffers couldn't be temp mem (although they're NOT\n   // currently temp mem, they could be (unless we want to level\n   // performance by spreading out the computation))\n   for (i=0; i < f->channels; ++i)\n      for (j=0; right+j < len; ++j)\n         f->previous_window[i][j] = f->channel_buffers[i][right+j];\n\n   if (!prev)\n      // there was no previous packet, so this data isn't valid...\n      // this isn't entirely true, only the would-have-overlapped data\n      // isn't valid, but this seems to be what the spec requires\n      return 0;\n\n   // truncate a short frame\n   if (len < right) right = len;\n\n   f->samples_output += right-left;\n\n   return right - left;\n}\n\nstatic int vorbis_pump_first_frame(stb_vorbis *f)\n{\n   int len, right, left, res;\n   res = vorbis_decode_packet(f, &len, &left, &right);\n   if (res)\n      vorbis_finish_frame(f, len, left, right);\n   return res;\n}\n\n#ifndef STB_VORBIS_NO_PUSHDATA_API\nstatic int is_whole_packet_present(stb_vorbis *f)\n{\n   // make sure that we have the packet available before continuing...\n   // this requires a full ogg parse, but we know we can fetch from f->stream\n\n   // instead of coding this out explicitly, we could save the current read state,\n   // read the next packet with get8() until end-of-packet, check f->eof, then\n   // reset the state? but that would be slower, esp. since we'd have over 256 bytes\n   // of state to restore (primarily the page segment table)\n\n   int s = f->next_seg, first = TRUE;\n   uint8 *p = f->stream;\n\n   if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag\n      for (; s < f->segment_count; ++s) {\n         p += f->segments[s];\n         if (f->segments[s] < 255)               // stop at first short segment\n            break;\n      }\n      // either this continues, or it ends it...\n      if (s == f->segment_count)\n         s = -1; // set 'crosses page' flag\n      if (p > f->stream_end)                     return error(f, VORBIS_need_more_data);\n      first = FALSE;\n   }\n   for (; s == -1;) {\n      uint8 *q;\n      int n;\n\n      // check that we have the page header ready\n      if (p + 26 >= f->stream_end)               return error(f, VORBIS_need_more_data);\n      // validate the page\n      if (memcmp(p, ogg_page_header, 4))         return error(f, VORBIS_invalid_stream);\n      if (p[4] != 0)                             return error(f, VORBIS_invalid_stream);\n      if (first) { // the first segment must NOT have 'continued_packet', later ones MUST\n         if (f->previous_length)\n            if ((p[5] & PAGEFLAG_continued_packet))  return error(f, VORBIS_invalid_stream);\n         // if no previous length, we're resynching, so we can come in on a continued-packet,\n         // which we'll just drop\n      } else {\n         if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);\n      }\n      n = p[26]; // segment counts\n      q = p+27;  // q points to segment table\n      p = q + n; // advance past header\n      // make sure we've read the segment table\n      if (p > f->stream_end)                     return error(f, VORBIS_need_more_data);\n      for (s=0; s < n; ++s) {\n         p += q[s];\n         if (q[s] < 255)\n            break;\n      }\n      if (s == n)\n         s = -1; // set 'crosses page' flag\n      if (p > f->stream_end)                     return error(f, VORBIS_need_more_data);\n      first = FALSE;\n   }\n   return TRUE;\n}\n#endif // !STB_VORBIS_NO_PUSHDATA_API\n\nstatic int start_decoder(vorb *f)\n{\n   uint8 header[6], x,y;\n   int len,i,j,k, max_submaps = 0;\n   int longest_floorlist=0;\n\n   // first page, first packet\n   f->first_decode = TRUE;\n\n   if (!start_page(f))                              return FALSE;\n   // validate page flag\n   if (!(f->page_flag & PAGEFLAG_first_page))       return error(f, VORBIS_invalid_first_page);\n   if (f->page_flag & PAGEFLAG_last_page)           return error(f, VORBIS_invalid_first_page);\n   if (f->page_flag & PAGEFLAG_continued_packet)    return error(f, VORBIS_invalid_first_page);\n   // check for expected packet length\n   if (f->segment_count != 1)                       return error(f, VORBIS_invalid_first_page);\n   if (f->segments[0] != 30) {\n      // check for the Ogg skeleton fishead identifying header to refine our error\n      if (f->segments[0] == 64 &&\n          getn(f, header, 6) &&\n          header[0] == 'f' &&\n          header[1] == 'i' &&\n          header[2] == 's' &&\n          header[3] == 'h' &&\n          header[4] == 'e' &&\n          header[5] == 'a' &&\n          get8(f)   == 'd' &&\n          get8(f)   == '\\0')                        return error(f, VORBIS_ogg_skeleton_not_supported);\n      else\n                                                    return error(f, VORBIS_invalid_first_page);\n   }\n\n   // read packet\n   // check packet header\n   if (get8(f) != VORBIS_packet_id)                 return error(f, VORBIS_invalid_first_page);\n   if (!getn(f, header, 6))                         return error(f, VORBIS_unexpected_eof);\n   if (!vorbis_validate(header))                    return error(f, VORBIS_invalid_first_page);\n   // vorbis_version\n   if (get32(f) != 0)                               return error(f, VORBIS_invalid_first_page);\n   f->channels = get8(f); if (!f->channels)         return error(f, VORBIS_invalid_first_page);\n   if (f->channels > STB_VORBIS_MAX_CHANNELS)       return error(f, VORBIS_too_many_channels);\n   f->sample_rate = get32(f); if (!f->sample_rate)  return error(f, VORBIS_invalid_first_page);\n   get32(f); // bitrate_maximum\n   get32(f); // bitrate_nominal\n   get32(f); // bitrate_minimum\n   x = get8(f);\n   {\n      int log0,log1;\n      log0 = x & 15;\n      log1 = x >> 4;\n      f->blocksize_0 = 1 << log0;\n      f->blocksize_1 = 1 << log1;\n      if (log0 < 6 || log0 > 13)                       return error(f, VORBIS_invalid_setup);\n      if (log1 < 6 || log1 > 13)                       return error(f, VORBIS_invalid_setup);\n      if (log0 > log1)                                 return error(f, VORBIS_invalid_setup);\n   }\n\n   // framing_flag\n   x = get8(f);\n   if (!(x & 1))                                    return error(f, VORBIS_invalid_first_page);\n\n   // second packet!\n   if (!start_page(f))                              return FALSE;\n\n   if (!start_packet(f))                            return FALSE;\n\n   if (!next_segment(f))                            return FALSE;\n\n   if (get8_packet(f) != VORBIS_packet_comment)            return error(f, VORBIS_invalid_setup);\n   for (i=0; i < 6; ++i) header[i] = get8_packet(f);\n   if (!vorbis_validate(header))                    return error(f, VORBIS_invalid_setup);\n   //file vendor\n   len = get32_packet(f);\n   f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1));\n   if (f->vendor == NULL)                           return error(f, VORBIS_outofmem);\n   for(i=0; i < len; ++i) {\n      f->vendor[i] = get8_packet(f);\n   }\n   f->vendor[len] = (char)'\\0';\n   //user comments\n   f->comment_list_length = get32_packet(f);\n   f->comment_list = NULL;\n   if (f->comment_list_length > 0)\n   {\n      f->comment_list = (char**) setup_malloc(f, sizeof(char*) * (f->comment_list_length));\n      if (f->comment_list == NULL)                  return error(f, VORBIS_outofmem);\n   }\n\n   for(i=0; i < f->comment_list_length; ++i) {\n      len = get32_packet(f);\n      f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1));\n      if (f->comment_list[i] == NULL)               return error(f, VORBIS_outofmem);\n\n      for(j=0; j < len; ++j) {\n         f->comment_list[i][j] = get8_packet(f);\n      }\n      f->comment_list[i][len] = (char)'\\0';\n   }\n\n   // framing_flag\n   x = get8_packet(f);\n   if (!(x & 1))                                    return error(f, VORBIS_invalid_setup);\n\n\n   skip(f, f->bytes_in_seg);\n   f->bytes_in_seg = 0;\n\n   do {\n      len = next_segment(f);\n      skip(f, len);\n      f->bytes_in_seg = 0;\n   } while (len);\n\n   // third packet!\n   if (!start_packet(f))                            return FALSE;\n\n   #ifndef STB_VORBIS_NO_PUSHDATA_API\n   if (IS_PUSH_MODE(f)) {\n      if (!is_whole_packet_present(f)) {\n         // convert error in ogg header to write type\n         if (f->error == VORBIS_invalid_stream)\n            f->error = VORBIS_invalid_setup;\n         return FALSE;\n      }\n   }\n   #endif\n\n   crc32_init(); // always init it, to avoid multithread race conditions\n\n   if (get8_packet(f) != VORBIS_packet_setup)       return error(f, VORBIS_invalid_setup);\n   for (i=0; i < 6; ++i) header[i] = get8_packet(f);\n   if (!vorbis_validate(header))                    return error(f, VORBIS_invalid_setup);\n\n   // codebooks\n\n   f->codebook_count = get_bits(f,8) + 1;\n   f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);\n   if (f->codebooks == NULL)                        return error(f, VORBIS_outofmem);\n   memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);\n   for (i=0; i < f->codebook_count; ++i) {\n      uint32 *values;\n      int ordered, sorted_count;\n      int total=0;\n      uint8 *lengths;\n      Codebook *c = f->codebooks+i;\n      CHECK(f);\n      x = get_bits(f, 8); if (x != 0x42)            return error(f, VORBIS_invalid_setup);\n      x = get_bits(f, 8); if (x != 0x43)            return error(f, VORBIS_invalid_setup);\n      x = get_bits(f, 8); if (x != 0x56)            return error(f, VORBIS_invalid_setup);\n      x = get_bits(f, 8);\n      c->dimensions = (get_bits(f, 8)<<8) + x;\n      x = get_bits(f, 8);\n      y = get_bits(f, 8);\n      c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;\n      ordered = get_bits(f,1);\n      c->sparse = ordered ? 0 : get_bits(f,1);\n\n      if (c->dimensions == 0 && c->entries != 0)    return error(f, VORBIS_invalid_setup);\n\n      if (c->sparse)\n         lengths = (uint8 *) setup_temp_malloc(f, c->entries);\n      else\n         lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);\n\n      if (!lengths) return error(f, VORBIS_outofmem);\n\n      if (ordered) {\n         int current_entry = 0;\n         int current_length = get_bits(f,5) + 1;\n         while (current_entry < c->entries) {\n            int limit = c->entries - current_entry;\n            int n = get_bits(f, ilog(limit));\n            if (current_length >= 32) return error(f, VORBIS_invalid_setup);\n            if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }\n            memset(lengths + current_entry, current_length, n);\n            current_entry += n;\n            ++current_length;\n         }\n      } else {\n         for (j=0; j < c->entries; ++j) {\n            int present = c->sparse ? get_bits(f,1) : 1;\n            if (present) {\n               lengths[j] = get_bits(f, 5) + 1;\n               ++total;\n               if (lengths[j] == 32)\n                  return error(f, VORBIS_invalid_setup);\n            } else {\n               lengths[j] = NO_CODE;\n            }\n         }\n      }\n\n      if (c->sparse && total >= c->entries >> 2) {\n         // convert sparse items to non-sparse!\n         if (c->entries > (int) f->setup_temp_memory_required)\n            f->setup_temp_memory_required = c->entries;\n\n         c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);\n         if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);\n         memcpy(c->codeword_lengths, lengths, c->entries);\n         setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!\n         lengths = c->codeword_lengths;\n         c->sparse = 0;\n      }\n\n      // compute the size of the sorted tables\n      if (c->sparse) {\n         sorted_count = total;\n      } else {\n         sorted_count = 0;\n         #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH\n         for (j=0; j < c->entries; ++j)\n            if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)\n               ++sorted_count;\n         #endif\n      }\n\n      c->sorted_entries = sorted_count;\n      values = NULL;\n\n      CHECK(f);\n      if (!c->sparse) {\n         c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);\n         if (!c->codewords)                  return error(f, VORBIS_outofmem);\n      } else {\n         unsigned int size;\n         if (c->sorted_entries) {\n            c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);\n            if (!c->codeword_lengths)           return error(f, VORBIS_outofmem);\n            c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);\n            if (!c->codewords)                  return error(f, VORBIS_outofmem);\n            values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);\n            if (!values)                        return error(f, VORBIS_outofmem);\n         }\n         size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;\n         if (size > f->setup_temp_memory_required)\n            f->setup_temp_memory_required = size;\n      }\n\n      if (!compute_codewords(c, lengths, c->entries, values)) {\n         if (c->sparse) setup_temp_free(f, values, 0);\n         return error(f, VORBIS_invalid_setup);\n      }\n\n      if (c->sorted_entries) {\n         // allocate an extra slot for sentinels\n         c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));\n         if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);\n         // allocate an extra slot at the front so that c->sorted_values[-1] is defined\n         // so that we can catch that case without an extra if\n         c->sorted_values    = ( int   *) setup_malloc(f, sizeof(*c->sorted_values   ) * (c->sorted_entries+1));\n         if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);\n         ++c->sorted_values;\n         c->sorted_values[-1] = -1;\n         compute_sorted_huffman(c, lengths, values);\n      }\n\n      if (c->sparse) {\n         setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);\n         setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);\n         setup_temp_free(f, lengths, c->entries);\n         c->codewords = NULL;\n      }\n\n      compute_accelerated_huffman(c);\n\n      CHECK(f);\n      c->lookup_type = get_bits(f, 4);\n      if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);\n      if (c->lookup_type > 0) {\n         uint16 *mults;\n         c->minimum_value = float32_unpack(get_bits(f, 32));\n         c->delta_value = float32_unpack(get_bits(f, 32));\n         c->value_bits = get_bits(f, 4)+1;\n         c->sequence_p = get_bits(f,1);\n         if (c->lookup_type == 1) {\n            int values = lookup1_values(c->entries, c->dimensions);\n            if (values < 0) return error(f, VORBIS_invalid_setup);\n            c->lookup_values = (uint32) values;\n         } else {\n            c->lookup_values = c->entries * c->dimensions;\n         }\n         if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);\n         mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);\n         if (mults == NULL) return error(f, VORBIS_outofmem);\n         for (j=0; j < (int) c->lookup_values; ++j) {\n            int q = get_bits(f, c->value_bits);\n            if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }\n            mults[j] = q;\n         }\n\n#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK\n         if (c->lookup_type == 1) {\n            int len, sparse = c->sparse;\n            float last=0;\n            // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop\n            if (sparse) {\n               if (c->sorted_entries == 0) goto skip;\n               c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);\n            } else\n               c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries        * c->dimensions);\n            if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }\n            len = sparse ? c->sorted_entries : c->entries;\n            for (j=0; j < len; ++j) {\n               unsigned int z = sparse ? c->sorted_values[j] : j;\n               unsigned int div=1;\n               for (k=0; k < c->dimensions; ++k) {\n                  int off = (z / div) % c->lookup_values;\n                  float val = mults[off]*c->delta_value + c->minimum_value + last;\n                  c->multiplicands[j*c->dimensions + k] = val;\n                  if (c->sequence_p)\n                     last = val;\n                  if (k+1 < c->dimensions) {\n                     if (div > UINT_MAX / (unsigned int) c->lookup_values) {\n                        setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);\n                        return error(f, VORBIS_invalid_setup);\n                     }\n                     div *= c->lookup_values;\n                  }\n               }\n            }\n            c->lookup_type = 2;\n         }\n         else\n#endif\n         {\n            float last=0;\n            CHECK(f);\n            c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);\n            if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }\n            for (j=0; j < (int) c->lookup_values; ++j) {\n               float val = mults[j] * c->delta_value + c->minimum_value + last;\n               c->multiplicands[j] = val;\n               if (c->sequence_p)\n                  last = val;\n            }\n         }\n#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK\n        skip:;\n#endif\n         setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);\n\n         CHECK(f);\n      }\n      CHECK(f);\n   }\n\n   // time domain transfers (notused)\n\n   x = get_bits(f, 6) + 1;\n   for (i=0; i < x; ++i) {\n      uint32 z = get_bits(f, 16);\n      if (z != 0) return error(f, VORBIS_invalid_setup);\n   }\n\n   // Floors\n   f->floor_count = get_bits(f, 6)+1;\n   f->floor_config = (Floor *)  setup_malloc(f, f->floor_count * sizeof(*f->floor_config));\n   if (f->floor_config == NULL) return error(f, VORBIS_outofmem);\n   for (i=0; i < f->floor_count; ++i) {\n      f->floor_types[i] = get_bits(f, 16);\n      if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);\n      if (f->floor_types[i] == 0) {\n         Floor0 *g = &f->floor_config[i].floor0;\n         g->order = get_bits(f,8);\n         g->rate = get_bits(f,16);\n         g->bark_map_size = get_bits(f,16);\n         g->amplitude_bits = get_bits(f,6);\n         g->amplitude_offset = get_bits(f,8);\n         g->number_of_books = get_bits(f,4) + 1;\n         for (j=0; j < g->number_of_books; ++j)\n            g->book_list[j] = get_bits(f,8);\n         return error(f, VORBIS_feature_not_supported);\n      } else {\n         stbv__floor_ordering p[31*8+2];\n         Floor1 *g = &f->floor_config[i].floor1;\n         int max_class = -1;\n         g->partitions = get_bits(f, 5);\n         for (j=0; j < g->partitions; ++j) {\n            g->partition_class_list[j] = get_bits(f, 4);\n            if (g->partition_class_list[j] > max_class)\n               max_class = g->partition_class_list[j];\n         }\n         for (j=0; j <= max_class; ++j) {\n            g->class_dimensions[j] = get_bits(f, 3)+1;\n            g->class_subclasses[j] = get_bits(f, 2);\n            if (g->class_subclasses[j]) {\n               g->class_masterbooks[j] = get_bits(f, 8);\n               if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);\n            }\n            for (k=0; k < 1 << g->class_subclasses[j]; ++k) {\n               g->subclass_books[j][k] = (int16)get_bits(f,8)-1;\n               if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);\n            }\n         }\n         g->floor1_multiplier = get_bits(f,2)+1;\n         g->rangebits = get_bits(f,4);\n         g->Xlist[0] = 0;\n         g->Xlist[1] = 1 << g->rangebits;\n         g->values = 2;\n         for (j=0; j < g->partitions; ++j) {\n            int c = g->partition_class_list[j];\n            for (k=0; k < g->class_dimensions[c]; ++k) {\n               g->Xlist[g->values] = get_bits(f, g->rangebits);\n               ++g->values;\n            }\n         }\n         // precompute the sorting\n         for (j=0; j < g->values; ++j) {\n            p[j].x = g->Xlist[j];\n            p[j].id = j;\n         }\n         qsort(p, g->values, sizeof(p[0]), point_compare);\n         for (j=0; j < g->values-1; ++j)\n            if (p[j].x == p[j+1].x)\n               return error(f, VORBIS_invalid_setup);\n         for (j=0; j < g->values; ++j)\n            g->sorted_order[j] = (uint8) p[j].id;\n         // precompute the neighbors\n         for (j=2; j < g->values; ++j) {\n            int low = 0,hi = 0;\n            neighbors(g->Xlist, j, &low,&hi);\n            g->neighbors[j][0] = low;\n            g->neighbors[j][1] = hi;\n         }\n\n         if (g->values > longest_floorlist)\n            longest_floorlist = g->values;\n      }\n   }\n\n   // Residue\n   f->residue_count = get_bits(f, 6)+1;\n   f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));\n   if (f->residue_config == NULL) return error(f, VORBIS_outofmem);\n   memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));\n   for (i=0; i < f->residue_count; ++i) {\n      uint8 residue_cascade[64];\n      Residue *r = f->residue_config+i;\n      f->residue_types[i] = get_bits(f, 16);\n      if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);\n      r->begin = get_bits(f, 24);\n      r->end = get_bits(f, 24);\n      if (r->end < r->begin) return error(f, VORBIS_invalid_setup);\n      r->part_size = get_bits(f,24)+1;\n      r->classifications = get_bits(f,6)+1;\n      r->classbook = get_bits(f,8);\n      if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);\n      for (j=0; j < r->classifications; ++j) {\n         uint8 high_bits=0;\n         uint8 low_bits=get_bits(f,3);\n         if (get_bits(f,1))\n            high_bits = get_bits(f,5);\n         residue_cascade[j] = high_bits*8 + low_bits;\n      }\n      r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);\n      if (r->residue_books == NULL) return error(f, VORBIS_outofmem);\n      for (j=0; j < r->classifications; ++j) {\n         for (k=0; k < 8; ++k) {\n            if (residue_cascade[j] & (1 << k)) {\n               r->residue_books[j][k] = get_bits(f, 8);\n               if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);\n            } else {\n               r->residue_books[j][k] = -1;\n            }\n         }\n      }\n      // precompute the classifications[] array to avoid inner-loop mod/divide\n      // call it 'classdata' since we already have r->classifications\n      r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);\n      if (!r->classdata) return error(f, VORBIS_outofmem);\n      memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);\n      for (j=0; j < f->codebooks[r->classbook].entries; ++j) {\n         int classwords = f->codebooks[r->classbook].dimensions;\n         int temp = j;\n         r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);\n         if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);\n         for (k=classwords-1; k >= 0; --k) {\n            r->classdata[j][k] = temp % r->classifications;\n            temp /= r->classifications;\n         }\n      }\n   }\n\n   f->mapping_count = get_bits(f,6)+1;\n   f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));\n   if (f->mapping == NULL) return error(f, VORBIS_outofmem);\n   memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));\n   for (i=0; i < f->mapping_count; ++i) {\n      Mapping *m = f->mapping + i;\n      int mapping_type = get_bits(f,16);\n      if (mapping_type != 0) return error(f, VORBIS_invalid_setup);\n      m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));\n      if (m->chan == NULL) return error(f, VORBIS_outofmem);\n      if (get_bits(f,1))\n         m->submaps = get_bits(f,4)+1;\n      else\n         m->submaps = 1;\n      if (m->submaps > max_submaps)\n         max_submaps = m->submaps;\n      if (get_bits(f,1)) {\n         m->coupling_steps = get_bits(f,8)+1;\n         if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);\n         for (k=0; k < m->coupling_steps; ++k) {\n            m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));\n            m->chan[k].angle = get_bits(f, ilog(f->channels-1));\n            if (m->chan[k].magnitude >= f->channels)        return error(f, VORBIS_invalid_setup);\n            if (m->chan[k].angle     >= f->channels)        return error(f, VORBIS_invalid_setup);\n            if (m->chan[k].magnitude == m->chan[k].angle)   return error(f, VORBIS_invalid_setup);\n         }\n      } else\n         m->coupling_steps = 0;\n\n      // reserved field\n      if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);\n      if (m->submaps > 1) {\n         for (j=0; j < f->channels; ++j) {\n            m->chan[j].mux = get_bits(f, 4);\n            if (m->chan[j].mux >= m->submaps)                return error(f, VORBIS_invalid_setup);\n         }\n      } else\n         // @SPECIFICATION: this case is missing from the spec\n         for (j=0; j < f->channels; ++j)\n            m->chan[j].mux = 0;\n\n      for (j=0; j < m->submaps; ++j) {\n         get_bits(f,8); // discard\n         m->submap_floor[j] = get_bits(f,8);\n         m->submap_residue[j] = get_bits(f,8);\n         if (m->submap_floor[j] >= f->floor_count)      return error(f, VORBIS_invalid_setup);\n         if (m->submap_residue[j] >= f->residue_count)  return error(f, VORBIS_invalid_setup);\n      }\n   }\n\n   // Modes\n   f->mode_count = get_bits(f, 6)+1;\n   for (i=0; i < f->mode_count; ++i) {\n      Mode *m = f->mode_config+i;\n      m->blockflag = get_bits(f,1);\n      m->windowtype = get_bits(f,16);\n      m->transformtype = get_bits(f,16);\n      m->mapping = get_bits(f,8);\n      if (m->windowtype != 0)                 return error(f, VORBIS_invalid_setup);\n      if (m->transformtype != 0)              return error(f, VORBIS_invalid_setup);\n      if (m->mapping >= f->mapping_count)     return error(f, VORBIS_invalid_setup);\n   }\n\n   flush_packet(f);\n\n   f->previous_length = 0;\n\n   for (i=0; i < f->channels; ++i) {\n      f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);\n      f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);\n      f->finalY[i]          = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);\n      if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);\n      memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);\n      #ifdef STB_VORBIS_NO_DEFER_FLOOR\n      f->floor_buffers[i]   = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);\n      if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);\n      #endif\n   }\n\n   if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;\n   if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;\n   f->blocksize[0] = f->blocksize_0;\n   f->blocksize[1] = f->blocksize_1;\n\n#ifdef STB_VORBIS_DIVIDE_TABLE\n   if (integer_divide_table[1][1]==0)\n      for (i=0; i < DIVTAB_NUMER; ++i)\n         for (j=1; j < DIVTAB_DENOM; ++j)\n            integer_divide_table[i][j] = i / j;\n#endif\n\n   // compute how much temporary memory is needed\n\n   // 1.\n   {\n      uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);\n      uint32 classify_mem;\n      int i,max_part_read=0;\n      for (i=0; i < f->residue_count; ++i) {\n         Residue *r = f->residue_config + i;\n         unsigned int actual_size = f->blocksize_1 / 2;\n         unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;\n         unsigned int limit_r_end   = r->end   < actual_size ? r->end   : actual_size;\n         int n_read = limit_r_end - limit_r_begin;\n         int part_read = n_read / r->part_size;\n         if (part_read > max_part_read)\n            max_part_read = part_read;\n      }\n      #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE\n      classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));\n      #else\n      classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));\n      #endif\n\n      // maximum reasonable partition size is f->blocksize_1\n\n      f->temp_memory_required = classify_mem;\n      if (imdct_mem > f->temp_memory_required)\n         f->temp_memory_required = imdct_mem;\n   }\n\n\n   if (f->alloc.alloc_buffer) {\n      assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);\n      // check if there's enough temp memory so we don't error later\n      if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)\n         return error(f, VORBIS_outofmem);\n   }\n\n   // @TODO: stb_vorbis_seek_start expects first_audio_page_offset to point to a page\n   // without PAGEFLAG_continued_packet, so this either points to the first page, or\n   // the page after the end of the headers. It might be cleaner to point to a page\n   // in the middle of the headers, when that's the page where the first audio packet\n   // starts, but we'd have to also correctly skip the end of any continued packet in\n   // stb_vorbis_seek_start.\n   if (f->next_seg == -1) {\n      f->first_audio_page_offset = stb_vorbis_get_file_offset(f);\n   } else {\n      f->first_audio_page_offset = 0;\n   }\n\n   return TRUE;\n}\n\nstatic void vorbis_deinit(stb_vorbis *p)\n{\n   int i,j;\n\n   setup_free(p, p->vendor);\n   for (i=0; i < p->comment_list_length; ++i) {\n      setup_free(p, p->comment_list[i]);\n   }\n   setup_free(p, p->comment_list);\n\n   if (p->residue_config) {\n      for (i=0; i < p->residue_count; ++i) {\n         Residue *r = p->residue_config+i;\n         if (r->classdata) {\n            for (j=0; j < p->codebooks[r->classbook].entries; ++j)\n               setup_free(p, r->classdata[j]);\n            setup_free(p, r->classdata);\n         }\n         setup_free(p, r->residue_books);\n      }\n   }\n\n   if (p->codebooks) {\n      CHECK(p);\n      for (i=0; i < p->codebook_count; ++i) {\n         Codebook *c = p->codebooks + i;\n         setup_free(p, c->codeword_lengths);\n         setup_free(p, c->multiplicands);\n         setup_free(p, c->codewords);\n         setup_free(p, c->sorted_codewords);\n         // c->sorted_values[-1] is the first entry in the array\n         setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);\n      }\n      setup_free(p, p->codebooks);\n   }\n   setup_free(p, p->floor_config);\n   setup_free(p, p->residue_config);\n   if (p->mapping) {\n      for (i=0; i < p->mapping_count; ++i)\n         setup_free(p, p->mapping[i].chan);\n      setup_free(p, p->mapping);\n   }\n   CHECK(p);\n   for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {\n      setup_free(p, p->channel_buffers[i]);\n      setup_free(p, p->previous_window[i]);\n      #ifdef STB_VORBIS_NO_DEFER_FLOOR\n      setup_free(p, p->floor_buffers[i]);\n      #endif\n      setup_free(p, p->finalY[i]);\n   }\n   for (i=0; i < 2; ++i) {\n      setup_free(p, p->A[i]);\n      setup_free(p, p->B[i]);\n      setup_free(p, p->C[i]);\n      setup_free(p, p->window[i]);\n      setup_free(p, p->bit_reverse[i]);\n   }\n   #ifndef STB_VORBIS_NO_STDIO\n   if (p->close_on_free) fclose(p->f);\n   #endif\n}\n\nvoid stb_vorbis_close(stb_vorbis *p)\n{\n   if (p == NULL) return;\n   vorbis_deinit(p);\n   setup_free(p,p);\n}\n\nstatic void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)\n{\n   memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start\n   if (z) {\n      p->alloc = *z;\n      p->alloc.alloc_buffer_length_in_bytes &= ~7;\n      p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;\n   }\n   p->eof = 0;\n   p->error = VORBIS__no_error;\n   p->stream = NULL;\n   p->codebooks = NULL;\n   p->page_crc_tests = -1;\n   #ifndef STB_VORBIS_NO_STDIO\n   p->close_on_free = FALSE;\n   p->f = NULL;\n   #endif\n}\n\nint stb_vorbis_get_sample_offset(stb_vorbis *f)\n{\n   if (f->current_loc_valid)\n      return f->current_loc;\n   else\n      return -1;\n}\n\nstb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)\n{\n   stb_vorbis_info d;\n   d.channels = f->channels;\n   d.sample_rate = f->sample_rate;\n   d.setup_memory_required = f->setup_memory_required;\n   d.setup_temp_memory_required = f->setup_temp_memory_required;\n   d.temp_memory_required = f->temp_memory_required;\n   d.max_frame_size = f->blocksize_1 >> 1;\n   return d;\n}\n\nstb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f)\n{\n   stb_vorbis_comment d;\n   d.vendor = f->vendor;\n   d.comment_list_length = f->comment_list_length;\n   d.comment_list = f->comment_list;\n   return d;\n}\n\nint stb_vorbis_get_error(stb_vorbis *f)\n{\n   int e = f->error;\n   f->error = VORBIS__no_error;\n   return e;\n}\n\nstatic stb_vorbis * vorbis_alloc(stb_vorbis *f)\n{\n   stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));\n   return p;\n}\n\n#ifndef STB_VORBIS_NO_PUSHDATA_API\n\nvoid stb_vorbis_flush_pushdata(stb_vorbis *f)\n{\n   f->previous_length = 0;\n   f->page_crc_tests  = 0;\n   f->discard_samples_deferred = 0;\n   f->current_loc_valid = FALSE;\n   f->first_decode = FALSE;\n   f->samples_output = 0;\n   f->channel_buffer_start = 0;\n   f->channel_buffer_end = 0;\n}\n\nstatic int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)\n{\n   int i,n;\n   for (i=0; i < f->page_crc_tests; ++i)\n      f->scan[i].bytes_done = 0;\n\n   // if we have room for more scans, search for them first, because\n   // they may cause us to stop early if their header is incomplete\n   if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {\n      if (data_len < 4) return 0;\n      data_len -= 3; // need to look for 4-byte sequence, so don't miss\n                     // one that straddles a boundary\n      for (i=0; i < data_len; ++i) {\n         if (data[i] == 0x4f) {\n            if (0==memcmp(data+i, ogg_page_header, 4)) {\n               int j,len;\n               uint32 crc;\n               // make sure we have the whole page header\n               if (i+26 >= data_len || i+27+data[i+26] >= data_len) {\n                  // only read up to this page start, so hopefully we'll\n                  // have the whole page header start next time\n                  data_len = i;\n                  break;\n               }\n               // ok, we have it all; compute the length of the page\n               len = 27 + data[i+26];\n               for (j=0; j < data[i+26]; ++j)\n                  len += data[i+27+j];\n               // scan everything up to the embedded crc (which we must 0)\n               crc = 0;\n               for (j=0; j < 22; ++j)\n                  crc = crc32_update(crc, data[i+j]);\n               // now process 4 0-bytes\n               for (   ; j < 26; ++j)\n                  crc = crc32_update(crc, 0);\n               // len is the total number of bytes we need to scan\n               n = f->page_crc_tests++;\n               f->scan[n].bytes_left = len-j;\n               f->scan[n].crc_so_far = crc;\n               f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);\n               // if the last frame on a page is continued to the next, then\n               // we can't recover the sample_loc immediately\n               if (data[i+27+data[i+26]-1] == 255)\n                  f->scan[n].sample_loc = ~0;\n               else\n                  f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);\n               f->scan[n].bytes_done = i+j;\n               if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)\n                  break;\n               // keep going if we still have room for more\n            }\n         }\n      }\n   }\n\n   for (i=0; i < f->page_crc_tests;) {\n      uint32 crc;\n      int j;\n      int n = f->scan[i].bytes_done;\n      int m = f->scan[i].bytes_left;\n      if (m > data_len - n) m = data_len - n;\n      // m is the bytes to scan in the current chunk\n      crc = f->scan[i].crc_so_far;\n      for (j=0; j < m; ++j)\n         crc = crc32_update(crc, data[n+j]);\n      f->scan[i].bytes_left -= m;\n      f->scan[i].crc_so_far = crc;\n      if (f->scan[i].bytes_left == 0) {\n         // does it match?\n         if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {\n            // Houston, we have page\n            data_len = n+m; // consumption amount is wherever that scan ended\n            f->page_crc_tests = -1; // drop out of page scan mode\n            f->previous_length = 0; // decode-but-don't-output one frame\n            f->next_seg = -1;       // start a new page\n            f->current_loc = f->scan[i].sample_loc; // set the current sample location\n                                    // to the amount we'd have decoded had we decoded this page\n            f->current_loc_valid = f->current_loc != ~0U;\n            return data_len;\n         }\n         // delete entry\n         f->scan[i] = f->scan[--f->page_crc_tests];\n      } else {\n         ++i;\n      }\n   }\n\n   return data_len;\n}\n\n// return value: number of bytes we used\nint stb_vorbis_decode_frame_pushdata(\n         stb_vorbis *f,                   // the file we're decoding\n         const uint8 *data, int data_len, // the memory available for decoding\n         int *channels,                   // place to write number of float * buffers\n         float ***output,                 // place to write float ** array of float * buffers\n         int *samples                     // place to write number of output samples\n     )\n{\n   int i;\n   int len,right,left;\n\n   if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);\n\n   if (f->page_crc_tests >= 0) {\n      *samples = 0;\n      return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len);\n   }\n\n   f->stream     = (uint8 *) data;\n   f->stream_end = (uint8 *) data + data_len;\n   f->error      = VORBIS__no_error;\n\n   // check that we have the entire packet in memory\n   if (!is_whole_packet_present(f)) {\n      *samples = 0;\n      return 0;\n   }\n\n   if (!vorbis_decode_packet(f, &len, &left, &right)) {\n      // save the actual error we encountered\n      enum STBVorbisError error = f->error;\n      if (error == VORBIS_bad_packet_type) {\n         // flush and resynch\n         f->error = VORBIS__no_error;\n         while (get8_packet(f) != EOP)\n            if (f->eof) break;\n         *samples = 0;\n         return (int) (f->stream - data);\n      }\n      if (error == VORBIS_continued_packet_flag_invalid) {\n         if (f->previous_length == 0) {\n            // we may be resynching, in which case it's ok to hit one\n            // of these; just discard the packet\n            f->error = VORBIS__no_error;\n            while (get8_packet(f) != EOP)\n               if (f->eof) break;\n            *samples = 0;\n            return (int) (f->stream - data);\n         }\n      }\n      // if we get an error while parsing, what to do?\n      // well, it DEFINITELY won't work to continue from where we are!\n      stb_vorbis_flush_pushdata(f);\n      // restore the error that actually made us bail\n      f->error = error;\n      *samples = 0;\n      return 1;\n   }\n\n   // success!\n   len = vorbis_finish_frame(f, len, left, right);\n   for (i=0; i < f->channels; ++i)\n      f->outputs[i] = f->channel_buffers[i] + left;\n\n   if (channels) *channels = f->channels;\n   *samples = len;\n   *output = f->outputs;\n   return (int) (f->stream - data);\n}\n\nstb_vorbis *stb_vorbis_open_pushdata(\n         const unsigned char *data, int data_len, // the memory available for decoding\n         int *data_used,              // only defined if result is not NULL\n         int *error, const stb_vorbis_alloc *alloc)\n{\n   stb_vorbis *f, p;\n   vorbis_init(&p, alloc);\n   p.stream     = (uint8 *) data;\n   p.stream_end = (uint8 *) data + data_len;\n   p.push_mode  = TRUE;\n   if (!start_decoder(&p)) {\n      if (p.eof)\n         *error = VORBIS_need_more_data;\n      else\n         *error = p.error;\n      vorbis_deinit(&p);\n      return NULL;\n   }\n   f = vorbis_alloc(&p);\n   if (f) {\n      *f = p;\n      *data_used = (int) (f->stream - data);\n      *error = 0;\n      return f;\n   } else {\n      vorbis_deinit(&p);\n      return NULL;\n   }\n}\n#endif // STB_VORBIS_NO_PUSHDATA_API\n\nunsigned int stb_vorbis_get_file_offset(stb_vorbis *f)\n{\n   #ifndef STB_VORBIS_NO_PUSHDATA_API\n   if (f->push_mode) return 0;\n   #endif\n   if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);\n   #ifndef STB_VORBIS_NO_STDIO\n   return (unsigned int) (ftell(f->f) - f->f_start);\n   #endif\n}\n\n#ifndef STB_VORBIS_NO_PULLDATA_API\n//\n// DATA-PULLING API\n//\n\nstatic uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)\n{\n   for(;;) {\n      int n;\n      if (f->eof) return 0;\n      n = get8(f);\n      if (n == 0x4f) { // page header candidate\n         unsigned int retry_loc = stb_vorbis_get_file_offset(f);\n         int i;\n         // check if we're off the end of a file_section stream\n         if (retry_loc - 25 > f->stream_len)\n            return 0;\n         // check the rest of the header\n         for (i=1; i < 4; ++i)\n            if (get8(f) != ogg_page_header[i])\n               break;\n         if (f->eof) return 0;\n         if (i == 4) {\n            uint8 header[27];\n            uint32 i, crc, goal, len;\n            for (i=0; i < 4; ++i)\n               header[i] = ogg_page_header[i];\n            for (; i < 27; ++i)\n               header[i] = get8(f);\n            if (f->eof) return 0;\n            if (header[4] != 0) goto invalid;\n            goal = header[22] + (header[23] << 8) + (header[24]<<16) + ((uint32)header[25]<<24);\n            for (i=22; i < 26; ++i)\n               header[i] = 0;\n            crc = 0;\n            for (i=0; i < 27; ++i)\n               crc = crc32_update(crc, header[i]);\n            len = 0;\n            for (i=0; i < header[26]; ++i) {\n               int s = get8(f);\n               crc = crc32_update(crc, s);\n               len += s;\n            }\n            if (len && f->eof) return 0;\n            for (i=0; i < len; ++i)\n               crc = crc32_update(crc, get8(f));\n            // finished parsing probable page\n            if (crc == goal) {\n               // we could now check that it's either got the last\n               // page flag set, OR it's followed by the capture\n               // pattern, but I guess TECHNICALLY you could have\n               // a file with garbage between each ogg page and recover\n               // from it automatically? So even though that paranoia\n               // might decrease the chance of an invalid decode by\n               // another 2^32, not worth it since it would hose those\n               // invalid-but-useful files?\n               if (end)\n                  *end = stb_vorbis_get_file_offset(f);\n               if (last) {\n                  if (header[5] & 0x04)\n                     *last = 1;\n                  else\n                     *last = 0;\n               }\n               set_file_offset(f, retry_loc-1);\n               return 1;\n            }\n         }\n        invalid:\n         // not a valid page, so rewind and look for next one\n         set_file_offset(f, retry_loc);\n      }\n   }\n}\n\n\n#define SAMPLE_unknown  0xffffffff\n\n// seeking is implemented with a binary search, which narrows down the range to\n// 64K, before using a linear search (because finding the synchronization\n// pattern can be expensive, and the chance we'd find the end page again is\n// relatively high for small ranges)\n//\n// two initial interpolation-style probes are used at the start of the search\n// to try to bound either side of the binary search sensibly, while still\n// working in O(log n) time if they fail.\n\nstatic int get_seek_page_info(stb_vorbis *f, ProbedPage *z)\n{\n   uint8 header[27], lacing[255];\n   int i,len;\n\n   // record where the page starts\n   z->page_start = stb_vorbis_get_file_offset(f);\n\n   // parse the header\n   getn(f, header, 27);\n   if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')\n      return 0;\n   getn(f, lacing, header[26]);\n\n   // determine the length of the payload\n   len = 0;\n   for (i=0; i < header[26]; ++i)\n      len += lacing[i];\n\n   // this implies where the page ends\n   z->page_end = z->page_start + 27 + header[26] + len;\n\n   // read the last-decoded sample out of the data\n   z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);\n\n   // restore file state to where we were\n   set_file_offset(f, z->page_start);\n   return 1;\n}\n\n// rarely used function to seek back to the preceding page while finding the\n// start of a packet\nstatic int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)\n{\n   unsigned int previous_safe, end;\n\n   // now we want to seek back 64K from the limit\n   if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)\n      previous_safe = limit_offset - 65536;\n   else\n      previous_safe = f->first_audio_page_offset;\n\n   set_file_offset(f, previous_safe);\n\n   while (vorbis_find_page(f, &end, NULL)) {\n      if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)\n         return 1;\n      set_file_offset(f, end);\n   }\n\n   return 0;\n}\n\n// implements the search logic for finding a page and starting decoding. if\n// the function succeeds, current_loc_valid will be true and current_loc will\n// be less than or equal to the provided sample number (the closer the\n// better).\nstatic int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)\n{\n   ProbedPage left, right, mid;\n   int i, start_seg_with_known_loc, end_pos, page_start;\n   uint32 delta, stream_length, padding, last_sample_limit;\n   double offset = 0.0, bytes_per_sample = 0.0;\n   int probe = 0;\n\n   // find the last page and validate the target sample\n   stream_length = stb_vorbis_stream_length_in_samples(f);\n   if (stream_length == 0)            return error(f, VORBIS_seek_without_length);\n   if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);\n\n   // this is the maximum difference between the window-center (which is the\n   // actual granule position value), and the right-start (which the spec\n   // indicates should be the granule position (give or take one)).\n   padding = ((f->blocksize_1 - f->blocksize_0) >> 2);\n   if (sample_number < padding)\n      last_sample_limit = 0;\n   else\n      last_sample_limit = sample_number - padding;\n\n   left = f->p_first;\n   while (left.last_decoded_sample == ~0U) {\n      // (untested) the first page does not have a 'last_decoded_sample'\n      set_file_offset(f, left.page_end);\n      if (!get_seek_page_info(f, &left)) goto error;\n   }\n\n   right = f->p_last;\n   assert(right.last_decoded_sample != ~0U);\n\n   // starting from the start is handled differently\n   if (last_sample_limit <= left.last_decoded_sample) {\n      if (stb_vorbis_seek_start(f)) {\n         if (f->current_loc > sample_number)\n            return error(f, VORBIS_seek_failed);\n         return 1;\n      }\n      return 0;\n   }\n\n   while (left.page_end != right.page_start) {\n      assert(left.page_end < right.page_start);\n      // search range in bytes\n      delta = right.page_start - left.page_end;\n      if (delta <= 65536) {\n         // there's only 64K left to search - handle it linearly\n         set_file_offset(f, left.page_end);\n      } else {\n         if (probe < 2) {\n            if (probe == 0) {\n               // first probe (interpolate)\n               double data_bytes = right.page_end - left.page_start;\n               bytes_per_sample = data_bytes / right.last_decoded_sample;\n               offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample);\n            } else {\n               // second probe (try to bound the other side)\n               double error = ((double) last_sample_limit - mid.last_decoded_sample) * bytes_per_sample;\n               if (error >= 0 && error <  8000) error =  8000;\n               if (error <  0 && error > -8000) error = -8000;\n               offset += error * 2;\n            }\n\n            // ensure the offset is valid\n            if (offset < left.page_end)\n               offset = left.page_end;\n            if (offset > right.page_start - 65536)\n               offset = right.page_start - 65536;\n\n            set_file_offset(f, (unsigned int) offset);\n         } else {\n            // binary search for large ranges (offset by 32K to ensure\n            // we don't hit the right page)\n            set_file_offset(f, left.page_end + (delta / 2) - 32768);\n         }\n\n         if (!vorbis_find_page(f, NULL, NULL)) goto error;\n      }\n\n      for (;;) {\n         if (!get_seek_page_info(f, &mid)) goto error;\n         if (mid.last_decoded_sample != ~0U) break;\n         // (untested) no frames end on this page\n         set_file_offset(f, mid.page_end);\n         assert(mid.page_start < right.page_start);\n      }\n\n      // if we've just found the last page again then we're in a tricky file,\n      // and we're close enough (if it wasn't an interpolation probe).\n      if (mid.page_start == right.page_start) {\n         if (probe >= 2 || delta <= 65536)\n            break;\n      } else {\n         if (last_sample_limit < mid.last_decoded_sample)\n            right = mid;\n         else\n            left = mid;\n      }\n\n      ++probe;\n   }\n\n   // seek back to start of the last packet\n   page_start = left.page_start;\n   set_file_offset(f, page_start);\n   if (!start_page(f)) return error(f, VORBIS_seek_failed);\n   end_pos = f->end_seg_with_known_loc;\n   assert(end_pos >= 0);\n\n   for (;;) {\n      for (i = end_pos; i > 0; --i)\n         if (f->segments[i-1] != 255)\n            break;\n\n      start_seg_with_known_loc = i;\n\n      if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))\n         break;\n\n      // (untested) the final packet begins on an earlier page\n      if (!go_to_page_before(f, page_start))\n         goto error;\n\n      page_start = stb_vorbis_get_file_offset(f);\n      if (!start_page(f)) goto error;\n      end_pos = f->segment_count - 1;\n   }\n\n   // prepare to start decoding\n   f->current_loc_valid = FALSE;\n   f->last_seg = FALSE;\n   f->valid_bits = 0;\n   f->packet_bytes = 0;\n   f->bytes_in_seg = 0;\n   f->previous_length = 0;\n   f->next_seg = start_seg_with_known_loc;\n\n   for (i = 0; i < start_seg_with_known_loc; i++)\n      skip(f, f->segments[i]);\n\n   // start decoding (optimizable - this frame is generally discarded)\n   if (!vorbis_pump_first_frame(f))\n      return 0;\n   if (f->current_loc > sample_number)\n      return error(f, VORBIS_seek_failed);\n   return 1;\n\nerror:\n   // try to restore the file to a valid state\n   stb_vorbis_seek_start(f);\n   return error(f, VORBIS_seek_failed);\n}\n\n// the same as vorbis_decode_initial, but without advancing\nstatic int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)\n{\n   int bits_read, bytes_read;\n\n   if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))\n      return 0;\n\n   // either 1 or 2 bytes were read, figure out which so we can rewind\n   bits_read = 1 + ilog(f->mode_count-1);\n   if (f->mode_config[*mode].blockflag)\n      bits_read += 2;\n   bytes_read = (bits_read + 7) / 8;\n\n   f->bytes_in_seg += bytes_read;\n   f->packet_bytes -= bytes_read;\n   skip(f, -bytes_read);\n   if (f->next_seg == -1)\n      f->next_seg = f->segment_count - 1;\n   else\n      f->next_seg--;\n   f->valid_bits = 0;\n\n   return 1;\n}\n\nint stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)\n{\n   uint32 max_frame_samples;\n\n   if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);\n\n   // fast page-level search\n   if (!seek_to_sample_coarse(f, sample_number))\n      return 0;\n\n   assert(f->current_loc_valid);\n   assert(f->current_loc <= sample_number);\n\n   // linear search for the relevant packet\n   max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;\n   while (f->current_loc < sample_number) {\n      int left_start, left_end, right_start, right_end, mode, frame_samples;\n      if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))\n         return error(f, VORBIS_seek_failed);\n      // calculate the number of samples returned by the next frame\n      frame_samples = right_start - left_start;\n      if (f->current_loc + frame_samples > sample_number) {\n         return 1; // the next frame will contain the sample\n      } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {\n         // there's a chance the frame after this could contain the sample\n         vorbis_pump_first_frame(f);\n      } else {\n         // this frame is too early to be relevant\n         f->current_loc += frame_samples;\n         f->previous_length = 0;\n         maybe_start_packet(f);\n         flush_packet(f);\n      }\n   }\n   // the next frame should start with the sample\n   if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed);\n   return 1;\n}\n\nint stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)\n{\n   if (!stb_vorbis_seek_frame(f, sample_number))\n      return 0;\n\n   if (sample_number != f->current_loc) {\n      int n;\n      uint32 frame_start = f->current_loc;\n      stb_vorbis_get_frame_float(f, &n, NULL);\n      assert(sample_number > frame_start);\n      assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);\n      f->channel_buffer_start += (sample_number - frame_start);\n   }\n\n   return 1;\n}\n\nint stb_vorbis_seek_start(stb_vorbis *f)\n{\n   if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); }\n   set_file_offset(f, f->first_audio_page_offset);\n   f->previous_length = 0;\n   f->first_decode = TRUE;\n   f->next_seg = -1;\n   return vorbis_pump_first_frame(f);\n}\n\nunsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)\n{\n   unsigned int restore_offset, previous_safe;\n   unsigned int end, last_page_loc;\n\n   if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);\n   if (!f->total_samples) {\n      unsigned int last;\n      uint32 lo,hi;\n      char header[6];\n\n      // first, store the current decode position so we can restore it\n      restore_offset = stb_vorbis_get_file_offset(f);\n\n      // now we want to seek back 64K from the end (the last page must\n      // be at most a little less than 64K, but let's allow a little slop)\n      if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)\n         previous_safe = f->stream_len - 65536;\n      else\n         previous_safe = f->first_audio_page_offset;\n\n      set_file_offset(f, previous_safe);\n      // previous_safe is now our candidate 'earliest known place that seeking\n      // to will lead to the final page'\n\n      if (!vorbis_find_page(f, &end, &last)) {\n         // if we can't find a page, we're hosed!\n         f->error = VORBIS_cant_find_last_page;\n         f->total_samples = 0xffffffff;\n         goto done;\n      }\n\n      // check if there are more pages\n      last_page_loc = stb_vorbis_get_file_offset(f);\n\n      // stop when the last_page flag is set, not when we reach eof;\n      // this allows us to stop short of a 'file_section' end without\n      // explicitly checking the length of the section\n      while (!last) {\n         set_file_offset(f, end);\n         if (!vorbis_find_page(f, &end, &last)) {\n            // the last page we found didn't have the 'last page' flag\n            // set. whoops!\n            break;\n         }\n         //previous_safe = last_page_loc+1; // NOTE: not used after this point, but note for debugging\n         last_page_loc = stb_vorbis_get_file_offset(f);\n      }\n\n      set_file_offset(f, last_page_loc);\n\n      // parse the header\n      getn(f, (unsigned char *)header, 6);\n      // extract the absolute granule position\n      lo = get32(f);\n      hi = get32(f);\n      if (lo == 0xffffffff && hi == 0xffffffff) {\n         f->error = VORBIS_cant_find_last_page;\n         f->total_samples = SAMPLE_unknown;\n         goto done;\n      }\n      if (hi)\n         lo = 0xfffffffe; // saturate\n      f->total_samples = lo;\n\n      f->p_last.page_start = last_page_loc;\n      f->p_last.page_end   = end;\n      f->p_last.last_decoded_sample = lo;\n\n     done:\n      set_file_offset(f, restore_offset);\n   }\n   return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;\n}\n\nfloat stb_vorbis_stream_length_in_seconds(stb_vorbis *f)\n{\n   return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;\n}\n\n\n\nint stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)\n{\n   int len, right,left,i;\n   if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);\n\n   if (!vorbis_decode_packet(f, &len, &left, &right)) {\n      f->channel_buffer_start = f->channel_buffer_end = 0;\n      return 0;\n   }\n\n   len = vorbis_finish_frame(f, len, left, right);\n   for (i=0; i < f->channels; ++i)\n      f->outputs[i] = f->channel_buffers[i] + left;\n\n   f->channel_buffer_start = left;\n   f->channel_buffer_end   = left+len;\n\n   if (channels) *channels = f->channels;\n   if (output)   *output = f->outputs;\n   return len;\n}\n\n#ifndef STB_VORBIS_NO_STDIO\n\nstb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)\n{\n   stb_vorbis *f, p;\n   vorbis_init(&p, alloc);\n   p.f = file;\n   p.f_start = (uint32) ftell(file);\n   p.stream_len   = length;\n   p.close_on_free = close_on_free;\n   if (start_decoder(&p)) {\n      f = vorbis_alloc(&p);\n      if (f) {\n         *f = p;\n         vorbis_pump_first_frame(f);\n         return f;\n      }\n   }\n   if (error) *error = p.error;\n   vorbis_deinit(&p);\n   return NULL;\n}\n\nstb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)\n{\n   unsigned int len, start;\n   start = (unsigned int) ftell(file);\n   fseek(file, 0, SEEK_END);\n   len = (unsigned int) (ftell(file) - start);\n   fseek(file, start, SEEK_SET);\n   return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);\n}\n\nstb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)\n{\n   FILE *f;\n#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)\n   if (0 != fopen_s(&f, filename, \"rb\"))\n      f = NULL;\n#else\n   f = fopen(filename, \"rb\");\n#endif\n   if (f)\n      return stb_vorbis_open_file(f, TRUE, error, alloc);\n   if (error) *error = VORBIS_file_open_failure;\n   return NULL;\n}\n#endif // STB_VORBIS_NO_STDIO\n\nstb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)\n{\n   stb_vorbis *f, p;\n   if (!data) {\n      if (error) *error = VORBIS_unexpected_eof;\n      return NULL;\n   }\n   vorbis_init(&p, alloc);\n   p.stream = (uint8 *) data;\n   p.stream_end = (uint8 *) data + len;\n   p.stream_start = (uint8 *) p.stream;\n   p.stream_len = len;\n   p.push_mode = FALSE;\n   if (start_decoder(&p)) {\n      f = vorbis_alloc(&p);\n      if (f) {\n         *f = p;\n         vorbis_pump_first_frame(f);\n         if (error) *error = VORBIS__no_error;\n         return f;\n      }\n   }\n   if (error) *error = p.error;\n   vorbis_deinit(&p);\n   return NULL;\n}\n\n#ifndef STB_VORBIS_NO_INTEGER_CONVERSION\n#define PLAYBACK_MONO     1\n#define PLAYBACK_LEFT     2\n#define PLAYBACK_RIGHT    4\n\n#define L  (PLAYBACK_LEFT  | PLAYBACK_MONO)\n#define C  (PLAYBACK_LEFT  | PLAYBACK_RIGHT | PLAYBACK_MONO)\n#define R  (PLAYBACK_RIGHT | PLAYBACK_MONO)\n\nstatic int8 channel_position[7][6] =\n{\n   { 0 },\n   { C },\n   { L, R },\n   { L, C, R },\n   { L, R, L, R },\n   { L, C, R, L, R },\n   { L, C, R, L, R, C },\n};\n\n\n#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT\n   typedef union {\n      float f;\n      int i;\n   } float_conv;\n   typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];\n   #define FASTDEF(x) float_conv x\n   // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round\n   #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))\n   #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))\n   #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))\n   #define check_endianness()\n#else\n   #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))\n   #define check_endianness()\n   #define FASTDEF(x)\n#endif\n\nstatic void copy_samples(short *dest, float *src, int len)\n{\n   int i;\n   check_endianness();\n   for (i=0; i < len; ++i) {\n      FASTDEF(temp);\n      int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);\n      if ((unsigned int) (v + 32768) > 65535)\n         v = v < 0 ? -32768 : 32767;\n      dest[i] = v;\n   }\n}\n\nstatic void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)\n{\n   #define STB_BUFFER_SIZE  32\n   float buffer[STB_BUFFER_SIZE];\n   int i,j,o,n = STB_BUFFER_SIZE;\n   check_endianness();\n   for (o = 0; o < len; o += STB_BUFFER_SIZE) {\n      memset(buffer, 0, sizeof(buffer));\n      if (o + n > len) n = len - o;\n      for (j=0; j < num_c; ++j) {\n         if (channel_position[num_c][j] & mask) {\n            for (i=0; i < n; ++i)\n               buffer[i] += data[j][d_offset+o+i];\n         }\n      }\n      for (i=0; i < n; ++i) {\n         FASTDEF(temp);\n         int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);\n         if ((unsigned int) (v + 32768) > 65535)\n            v = v < 0 ? -32768 : 32767;\n         output[o+i] = v;\n      }\n   }\n   #undef STB_BUFFER_SIZE\n}\n\nstatic void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)\n{\n   #define STB_BUFFER_SIZE  32\n   float buffer[STB_BUFFER_SIZE];\n   int i,j,o,n = STB_BUFFER_SIZE >> 1;\n   // o is the offset in the source data\n   check_endianness();\n   for (o = 0; o < len; o += STB_BUFFER_SIZE >> 1) {\n      // o2 is the offset in the output data\n      int o2 = o << 1;\n      memset(buffer, 0, sizeof(buffer));\n      if (o + n > len) n = len - o;\n      for (j=0; j < num_c; ++j) {\n         int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);\n         if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {\n            for (i=0; i < n; ++i) {\n               buffer[i*2+0] += data[j][d_offset+o+i];\n               buffer[i*2+1] += data[j][d_offset+o+i];\n            }\n         } else if (m == PLAYBACK_LEFT) {\n            for (i=0; i < n; ++i) {\n               buffer[i*2+0] += data[j][d_offset+o+i];\n            }\n         } else if (m == PLAYBACK_RIGHT) {\n            for (i=0; i < n; ++i) {\n               buffer[i*2+1] += data[j][d_offset+o+i];\n            }\n         }\n      }\n      for (i=0; i < (n<<1); ++i) {\n         FASTDEF(temp);\n         int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);\n         if ((unsigned int) (v + 32768) > 65535)\n            v = v < 0 ? -32768 : 32767;\n         output[o2+i] = v;\n      }\n   }\n   #undef STB_BUFFER_SIZE\n}\n\nstatic void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)\n{\n   int i;\n   if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {\n      static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };\n      for (i=0; i < buf_c; ++i)\n         compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);\n   } else {\n      int limit = buf_c < data_c ? buf_c : data_c;\n      for (i=0; i < limit; ++i)\n         copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);\n      for (   ; i < buf_c; ++i)\n         memset(buffer[i]+b_offset, 0, sizeof(short) * samples);\n   }\n}\n\nint stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)\n{\n   float **output = NULL;\n   int len = stb_vorbis_get_frame_float(f, NULL, &output);\n   if (len > num_samples) len = num_samples;\n   if (len)\n      convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);\n   return len;\n}\n\nstatic void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)\n{\n   int i;\n   check_endianness();\n   if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {\n      assert(buf_c == 2);\n      for (i=0; i < buf_c; ++i)\n         compute_stereo_samples(buffer, data_c, data, d_offset, len);\n   } else {\n      int limit = buf_c < data_c ? buf_c : data_c;\n      int j;\n      for (j=0; j < len; ++j) {\n         for (i=0; i < limit; ++i) {\n            FASTDEF(temp);\n            float f = data[i][d_offset+j];\n            int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);\n            if ((unsigned int) (v + 32768) > 65535)\n               v = v < 0 ? -32768 : 32767;\n            *buffer++ = v;\n         }\n         for (   ; i < buf_c; ++i)\n            *buffer++ = 0;\n      }\n   }\n}\n\nint stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)\n{\n   float **output;\n   int len;\n   if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);\n   len = stb_vorbis_get_frame_float(f, NULL, &output);\n   if (len) {\n      if (len*num_c > num_shorts) len = num_shorts / num_c;\n      convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);\n   }\n   return len;\n}\n\nint stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)\n{\n   float **outputs;\n   int len = num_shorts / channels;\n   int n=0;\n   while (n < len) {\n      int k = f->channel_buffer_end - f->channel_buffer_start;\n      if (n+k >= len) k = len - n;\n      if (k)\n         convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);\n      buffer += k*channels;\n      n += k;\n      f->channel_buffer_start += k;\n      if (n == len) break;\n      if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;\n   }\n   return n;\n}\n\nint stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)\n{\n   float **outputs;\n   int n=0;\n   while (n < len) {\n      int k = f->channel_buffer_end - f->channel_buffer_start;\n      if (n+k >= len) k = len - n;\n      if (k)\n         convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);\n      n += k;\n      f->channel_buffer_start += k;\n      if (n == len) break;\n      if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;\n   }\n   return n;\n}\n\n#ifndef STB_VORBIS_NO_STDIO\nint stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)\n{\n   int data_len, offset, total, limit, error;\n   short *data;\n   stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);\n   if (v == NULL) return -1;\n   limit = v->channels * 4096;\n   *channels = v->channels;\n   if (sample_rate)\n      *sample_rate = v->sample_rate;\n   offset = data_len = 0;\n   total = limit;\n   data = (short *) malloc(total * sizeof(*data));\n   if (data == NULL) {\n      stb_vorbis_close(v);\n      return -2;\n   }\n   for (;;) {\n      int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);\n      if (n == 0) break;\n      data_len += n;\n      offset += n * v->channels;\n      if (offset + limit > total) {\n         short *data2;\n         total *= 2;\n         data2 = (short *) realloc(data, total * sizeof(*data));\n         if (data2 == NULL) {\n            free(data);\n            stb_vorbis_close(v);\n            return -2;\n         }\n         data = data2;\n      }\n   }\n   *output = data;\n   stb_vorbis_close(v);\n   return data_len;\n}\n#endif // NO_STDIO\n\nint stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)\n{\n   int data_len, offset, total, limit, error;\n   short *data;\n   stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);\n   if (v == NULL) return -1;\n   limit = v->channels * 4096;\n   *channels = v->channels;\n   if (sample_rate)\n      *sample_rate = v->sample_rate;\n   offset = data_len = 0;\n   total = limit;\n   data = (short *) malloc(total * sizeof(*data));\n   if (data == NULL) {\n      stb_vorbis_close(v);\n      return -2;\n   }\n   for (;;) {\n      int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);\n      if (n == 0) break;\n      data_len += n;\n      offset += n * v->channels;\n      if (offset + limit > total) {\n         short *data2;\n         total *= 2;\n         data2 = (short *) realloc(data, total * sizeof(*data));\n         if (data2 == NULL) {\n            free(data);\n            stb_vorbis_close(v);\n            return -2;\n         }\n         data = data2;\n      }\n   }\n   *output = data;\n   stb_vorbis_close(v);\n   return data_len;\n}\n#endif // STB_VORBIS_NO_INTEGER_CONVERSION\n\nint stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)\n{\n   float **outputs;\n   int len = num_floats / channels;\n   int n=0;\n   int z = f->channels;\n   if (z > channels) z = channels;\n   while (n < len) {\n      int i,j;\n      int k = f->channel_buffer_end - f->channel_buffer_start;\n      if (n+k >= len) k = len - n;\n      for (j=0; j < k; ++j) {\n         for (i=0; i < z; ++i)\n            *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];\n         for (   ; i < channels; ++i)\n            *buffer++ = 0;\n      }\n      n += k;\n      f->channel_buffer_start += k;\n      if (n == len)\n         break;\n      if (!stb_vorbis_get_frame_float(f, NULL, &outputs))\n         break;\n   }\n   return n;\n}\n\nint stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)\n{\n   float **outputs;\n   int n=0;\n   int z = f->channels;\n   if (z > channels) z = channels;\n   while (n < num_samples) {\n      int i;\n      int k = f->channel_buffer_end - f->channel_buffer_start;\n      if (n+k >= num_samples) k = num_samples - n;\n      if (k) {\n         for (i=0; i < z; ++i)\n            memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);\n         for (   ; i < channels; ++i)\n            memset(buffer[i]+n, 0, sizeof(float) * k);\n      }\n      n += k;\n      f->channel_buffer_start += k;\n      if (n == num_samples)\n         break;\n      if (!stb_vorbis_get_frame_float(f, NULL, &outputs))\n         break;\n   }\n   return n;\n}\n#endif // STB_VORBIS_NO_PULLDATA_API\n\n/* Version history\n    1.17    - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223\n                           found with Mayhem by ForAllSecure\n    1.16    - 2019-03-04 - fix warnings\n    1.15    - 2019-02-07 - explicit failure if Ogg Skeleton data is found\n    1.14    - 2018-02-11 - delete bogus dealloca usage\n    1.13    - 2018-01-29 - fix truncation of last frame (hopefully)\n    1.12    - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files\n    1.11    - 2017-07-23 - fix MinGW compilation\n    1.10    - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory\n    1.09    - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version\n    1.08    - 2016-04-02 - fixed multiple warnings; fix setup memory leaks;\n                           avoid discarding last frame of audio data\n    1.07    - 2015-01-16 - fixed some warnings, fix mingw, const-correct API\n                           some more crash fixes when out of memory or with corrupt files\n    1.06    - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)\n                           some crash fixes when out of memory or with corrupt files\n    1.05    - 2015-04-19 - don't define __forceinline if it's redundant\n    1.04    - 2014-08-27 - fix missing const-correct case in API\n    1.03    - 2014-08-07 - Warning fixes\n    1.02    - 2014-07-09 - Declare qsort compare function _cdecl on windows\n    1.01    - 2014-06-18 - fix stb_vorbis_get_samples_float\n    1.0     - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel\n                           (API change) report sample rate for decode-full-file funcs\n    0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila\n    0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem\n    0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence\n    0.99993 - remove assert that fired on legal files with empty tables\n    0.99992 - rewind-to-start\n    0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo\n    0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++\n    0.9998 - add a full-decode function with a memory source\n    0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition\n    0.9996 - query length of vorbis stream in samples/seconds\n    0.9995 - bugfix to another optimization that only happened in certain files\n    0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors\n    0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation\n    0.9992 - performance improvement of IMDCT; now performs close to reference implementation\n    0.9991 - performance improvement of IMDCT\n    0.999 - (should have been 0.9990) performance improvement of IMDCT\n    0.998 - no-CRT support from Casey Muratori\n    0.997 - bugfixes for bugs found by Terje Mathisen\n    0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen\n    0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen\n    0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen\n    0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen\n    0.992 - fixes for MinGW warning\n    0.991 - turn fast-float-conversion on by default\n    0.990 - fix push-mode seek recovery if you seek into the headers\n    0.98b - fix to bad release of 0.98\n    0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode\n    0.97 - builds under c++ (typecasting, don't use 'class' keyword)\n    0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code\n    0.95 - clamping code for 16-bit functions\n    0.94 - not publically released\n    0.93 - fixed all-zero-floor case (was decoding garbage)\n    0.92 - fixed a memory leak\n    0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION\n    0.90 - first public release\n*/\n\n#endif // STB_VORBIS_HEADER_ONLY\n\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "stb_voxel_render.h",
    "content": "// stb_voxel_render.h - v0.89 - Sean Barrett, 2015 - public domain\n//\n// This library helps render large-scale \"voxel\" worlds for games,\n// in this case, one with blocks that can have textures and that\n// can also be a few shapes other than cubes.\n//\n//    Video introduction:\n//       http://www.youtube.com/watch?v=2vnTtiLrV1w\n//\n//    Minecraft-viewer sample app (not very simple though):\n//       http://github.com/nothings/stb/tree/master/tests/caveview\n//\n// It works by creating triangle meshes. The library includes\n//\n//    - converter from dense 3D arrays of block info to vertex mesh\n//    - vertex & fragment shaders for the vertex mesh\n//    - assistance in setting up shader state\n//\n// For portability, none of the library code actually accesses\n// the 3D graphics API. (At the moment, it's not actually portable\n// since the shaders are GLSL only, but patches are welcome.)\n//\n// You have to do all the caching and tracking of vertex buffers\n// yourself. However, you could also try making a game with\n// a small enough world that it's fully loaded rather than\n// streaming. Currently the preferred vertex format is 20 bytes\n// per quad. There are designs to allow much more compact formats\n// with a slight reduction in shader features, but no roadmap\n// for actually implementing them.\n//\n//\n// USAGE\n//\n//   #define the symbol STB_VOXEL_RENDER_IMPLEMENTATION in *one*\n//   C/C++ file before the #include of this file; the implementation\n//   will be generated in that file.\n//\n//   If you define the symbols STB_VOXEL_RENDER_STATIC, then the\n//   implementation will be private to that file.\n//\n//\n// FEATURES\n//\n//   - you can choose textured blocks with the features below,\n//     or colored voxels with 2^24 colors and no textures.\n//\n//   - voxels are mostly just cubes, but there's support for\n//     half-height cubes and diagonal slopes, half-height\n//     diagonals, and even odder shapes especially for doing\n//     more-continuous \"ground\".\n//\n//   - texture coordinates are projections along one of the major\n//     axes, with the per-texture scaling.\n//\n//   - a number of aspects of the shader and the vertex format\n//     are configurable; the library generally takes care of\n//     coordinating the vertex format with the mesh for you.\n//\n//\n// FEATURES (SHADER PERSPECTIVE)\n//\n//   - vertices aligned on integer lattice, z on multiples of 0.5\n//   - per-vertex \"lighting\" or \"ambient occlusion\" value (6 bits)\n//   - per-vertex texture crossfade (3 bits)\n//\n//   - per-face texture #1 id (8-bit index into array texture)\n//   - per-face texture #2 id (8-bit index into second array texture)\n//   - per-face color (6-bit palette index, 2 bits of per-texture boolean enable)\n//   - per-face 5-bit normal for lighting calculations & texture coord computation\n//   - per-face 2-bit texture matrix rotation to rotate faces\n//\n//   - indexed-by-texture-id scale factor (separate for texture #1 and texture #2)\n//   - indexed-by-texture-#2-id blend mode (alpha composite or modulate/multiply);\n//     the first is good for decals, the second for detail textures, \"light maps\",\n//     etc; both modes are controlled by texture #2's alpha, scaled by the\n//     per-vertex texture crossfade and the per-face color (if enabled on texture #2);\n//     modulate/multiply multiplies by an extra factor of 2.0 so that if you\n//     make detail maps whose average brightness is 0.5 everything works nicely.\n//\n//   - ambient lighting: half-lambert directional plus constant, all scaled by vertex ao\n//   - face can be fullbright (emissive), controlled by per-face color\n//   - installable lighting, with default single-point-light\n//   - installable fog, with default hacked smoothstep\n//\n//  Note that all the variations of lighting selection and texture\n//  blending are run-time conditions in the shader, so they can be\n//  intermixed in a single mesh.\n//\n//\n// INTEGRATION ARC\n//\n//   The way to get this library to work from scratch is to do the following:\n//\n//      Step 1. define STBVOX_CONFIG_MODE to 0\n//\n//        This mode uses only vertex attributes and uniforms, and is easiest\n//        to get working. It requires 32 bytes per quad and limits the\n//        size of some tables to avoid hitting uniform limits.\n//\n//      Step 2. define STBVOX_CONFIG_MODE to 1\n//\n//        This requires using a texture buffer to store the quad data,\n//        reducing the size to 20 bytes per quad.\n//\n//      Step 3: define STBVOX_CONFIG_PREFER_TEXBUFFER\n//\n//        This causes some uniforms to be stored as texture buffers\n//        instead. This increases the size of some of those tables,\n//        and avoids a potential slow path (gathering non-uniform\n//        data from uniforms) on some hardware.\n//\n//   In the future I might add additional modes that have significantly\n//   smaller meshes but reduce features, down as small as 6 bytes per quad.\n//   See elsewhere in this file for a table of candidate modes. Switching\n//   to a mode will require changing some of your mesh creation code, but\n//   everything else should be seamless. (And I'd like to change the API\n//   so that mesh creation is data-driven the way the uniforms are, and\n//   then you wouldn't even have to change anything but the mode number.)\n//\n//\n// IMPROVEMENTS FOR SHIP-WORTHY PROGRAMS USING THIS LIBRARY\n//\n//   I currently tolerate a certain level of \"bugginess\" in this library.\n//\n//   I'm referring to things which look a little wrong (as long as they\n//   don't cause holes or cracks in the output meshes), or things which\n//   do not produce as optimal a mesh as possible. Notable examples:\n//\n//        -  incorrect lighting on slopes\n//        -  inefficient meshes for vheight blocks\n//\n//   I am willing to do the work to improve these things if someone is\n//   going to ship a substantial program that would be improved by them.\n//   (It need not be commercial, nor need it be a game.) I just didn't\n//   want to do the work up front if it might never be leveraged. So just\n//   submit a bug report as usual (github is preferred), but add a note\n//   that this is for a thing that is really going to ship. (That means\n//   you need to be far enough into the project that it's clear you're\n//   committed to it; not during early exploratory development.)\n//\n//\n// VOXEL MESH API\n//\n//   Context\n//\n//     To understand the API, make sure you first understand the feature set\n//     listed above.\n//\n//     Because the vertices are compact, they have very limited spatial\n//     precision. Thus a single mesh can only contain the data for a limited\n//     area. To make very large voxel maps, you'll need to build multiple\n//     vertex buffers. (But you want this anyway for frustum culling.)\n//\n//     Each generated mesh has three components:\n//             - vertex data (vertex buffer)\n//             - face data (optional, stored in texture buffer)\n//             - mesh transform (uniforms)\n//\n//     Once you've generated the mesh with this library, it's up to you\n//     to upload it to the GPU, to keep track of the state, and to render\n//     it.\n//\n//   Concept\n//\n//     The basic design is that you pass in one or more 3D arrays; each array\n//     is (typically) one-byte-per-voxel and contains information about one\n//     or more properties of some particular voxel property.\n//\n//     Because there is so much per-vertex and per-face data possible\n//     in the output, and each voxel can have 6 faces and 8 vertices, it\n//     would require an very large data structure to describe all\n//     of the possibilities, and this would cause the mesh-creation\n//     process to be slow. Instead, the API provides multiple ways\n//     to express each property, some more compact, others less so;\n//     each such way has some limitations on what it can express.\n//\n//     Note that there are so many paths and combinations, not all of them\n//     have been tested. Just report bugs and I'll fix 'em.\n//\n//   Details\n//\n//     See the API documentation in the header-file section.\n//\n//\n// CONTRIBUTORS\n//\n//   Features             Porting            Bugfixes & Warnings\n//  Sean Barrett                          github:r-leyh   Jesus Fernandez\n//                                        Miguel Lechon   github:Arbeiterunfallversicherungsgesetz\n//                                        Thomas Frase    James Hofmann\n//                                        Stephen Olsen   github:guitarfreak\n//\n// VERSION HISTORY\n//\n//   0.89   (2020-02-02)  bugfix in sample code\n//   0.88   (2019-03-04)  fix warnings\n//   0.87   (2019-02-25)  fix warning\n//   0.86   (2019-02-07)  fix typos in comments\n//   0.85   (2017-03-03)  add block_selector (by guitarfreak)\n//   0.84   (2016-04-02)  fix GLSL syntax error on glModelView path\n//   0.83   (2015-09-13)  remove non-constant struct initializers to support more compilers\n//   0.82   (2015-08-01)  added input.packed_compact to store rot, vheight & texlerp efficiently\n//                        fix broken tex_overlay2\n//   0.81   (2015-05-28)  fix broken STBVOX_CONFIG_OPTIMIZED_VHEIGHT\n//   0.80   (2015-04-11)  fix broken STBVOX_CONFIG_ROTATION_IN_LIGHTING refactoring\n//                        change STBVOX_MAKE_LIGHTING to STBVOX_MAKE_LIGHTING_EXT so\n//                                    that header defs don't need to see config vars\n//                        add STBVOX_CONFIG_VHEIGHT_IN_LIGHTING and other vheight fixes\n//                        added documentation for vheight (\"weird slopes\")\n//   0.79   (2015-04-01)  fix the missing types from 0.78; fix string constants being const\n//   0.78   (2015-04-02)  bad \"#else\", compile as C++\n//   0.77   (2015-04-01)  documentation tweaks, rename config var to STB_VOXEL_RENDER_STATIC\n//   0.76   (2015-04-01)  typos, signed/unsigned shader issue, more documentation\n//   0.75   (2015-04-01)  initial release\n//\n//\n// HISTORICAL FOUNDATION\n//\n//   stb_voxel_render   20-byte quads   2015/01\n//   zmc engine         32-byte quads   2013/12\n//   zmc engine         96-byte quads   2011/10\n//\n//\n// LICENSE\n//\n//   See end of file for license information.\n\n#ifndef INCLUDE_STB_VOXEL_RENDER_H\n#define INCLUDE_STB_VOXEL_RENDER_H\n\n#include <stdlib.h>\n\ntypedef struct stbvox_mesh_maker stbvox_mesh_maker;\ntypedef struct stbvox_input_description stbvox_input_description;\n\n#ifdef STB_VOXEL_RENDER_STATIC\n#define STBVXDEC static\n#else\n#define STBVXDEC extern\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// CONFIGURATION MACROS\n//\n//  #define STBVOX_CONFIG_MODE <integer>           // REQUIRED\n//     Configures the overall behavior of stb_voxel_render. This\n//     can affect the shaders, the uniform info, and other things.\n//     (If you need more than one mode in the same app, you can\n//     use STB_VOXEL_RENDER_STATIC to create multiple versions\n//     in separate files, and then wrap them.)\n//\n//         Mode value       Meaning\n//             0               Textured blocks, 32-byte quads\n//             1               Textured blocks, 20-byte quads\n//            20               Untextured blocks, 32-byte quads\n//            21               Untextured blocks, 20-byte quads\n//\n//\n//  #define STBVOX_CONFIG_PRECISION_Z  <integer>   // OPTIONAL\n//     Defines the number of bits of fractional position for Z.\n//     Only 0 or 1 are valid. 1 is the default. If 0, then a\n//     single mesh has twice the legal Z range; e.g. in\n//     modes 0,1,20,21, Z in the mesh can extend to 511 instead\n//     of 255. However, half-height blocks cannot be used.\n//\n// All of the following are just #ifdef tested so need no values, and are optional.\n//\n//    STBVOX_CONFIG_BLOCKTYPE_SHORT\n//        use unsigned 16-bit values for 'blocktype' in the input instead of 8-bit values\n//\n//    STBVOX_CONFIG_OPENGL_MODELVIEW\n//        use the gl_ModelView matrix rather than the explicit uniform\n//\n//    STBVOX_CONFIG_HLSL\n//        NOT IMPLEMENTED! Define HLSL shaders instead of GLSL shaders\n//\n//    STBVOX_CONFIG_PREFER_TEXBUFFER\n//        Stores many of the uniform arrays in texture buffers instead,\n//        so they can be larger and may be more efficient on some hardware.\n//\n//    STBVOX_CONFIG_LIGHTING_SIMPLE\n//        Creates a simple lighting engine with a single point light source\n//        in addition to the default half-lambert ambient light.\n//\n//    STBVOX_CONFIG_LIGHTING\n//        Declares a lighting function hook; you must append a lighting function\n//        to the shader before compiling it:\n//            vec3 compute_lighting(vec3 pos, vec3 norm, vec3 albedo, vec3 ambient);\n//        'ambient' is the half-lambert ambient light with vertex ambient-occlusion applied\n//\n//    STBVOX_CONFIG_FOG_SMOOTHSTEP\n//        Defines a simple unrealistic fog system designed to maximize\n//        unobscured view distance while not looking too weird when things\n//        emerge from the fog. Configured using an extra array element\n//        in the STBVOX_UNIFORM_ambient uniform.\n//\n//    STBVOX_CONFIG_FOG\n//        Defines a fog function hook; you must append a fog function to\n//        the shader before compiling it:\n//            vec3 compute_fog(vec3 color, vec3 relative_pos, float fragment_alpha);\n//        \"color\" is the incoming pre-fogged color, fragment_alpha is the alpha value,\n//        and relative_pos is the vector from the point to the camera in worldspace\n//\n//    STBVOX_CONFIG_DISABLE_TEX2\n//        This disables all processing of texture 2 in the shader in case\n//        you don't use it. Eventually this could be replaced with a mode\n//        that omits the unused data entirely.\n//\n//    STBVOX_CONFIG_TEX1_EDGE_CLAMP\n//    STBVOX_CONFIG_TEX2_EDGE_CLAMP\n//        If you want to edge clamp the textures, instead of letting them wrap,\n//        set this flag. By default stb_voxel_render relies on texture wrapping\n//        to simplify texture coordinate generation. This flag forces it to do\n//        it correctly, although there can still be minor artifacts.\n//\n//    STBVOX_CONFIG_ROTATION_IN_LIGHTING\n//        Changes the meaning of the 'lighting' mesher input variable to also\n//        store the rotation; see later discussion.\n//\n//    STBVOX_CONFIG_VHEIGHT_IN_LIGHTING\n//        Changes the meaning of the 'lighting' mesher input variable to also\n//        store the vheight; see later discussion. Cannot use both this and\n//        the previous variable.\n//\n//    STBVOX_CONFIG_PREMULTIPLIED_ALPHA\n//        Adjusts the shader calculations on the assumption that tex1.rgba,\n//        tex2.rgba, and color.rgba all use premultiplied values, and that\n//        the output of the fragment shader should be premultiplied.\n//\n//    STBVOX_CONFIG_UNPREMULTIPLY\n//        Only meaningful if STBVOX_CONFIG_PREMULTIPLIED_ALPHA is defined.\n//        Changes the behavior described above so that the inputs are\n//        still premultiplied alpha, but the output of the fragment\n//        shader is not premultiplied alpha. This is needed when allowing\n//        non-unit alpha values but not doing alpha-blending (for example\n//        when alpha testing).\n//\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// MESHING\n//\n// A mesh represents a (typically) small chunk of a larger world.\n// Meshes encode coordinates using small integers, so those\n// coordinates must be relative to some base location.\n// All of the coordinates in the functions below use\n// these relative coordinates unless explicitly stated\n// otherwise.\n//\n// Input to the meshing step is documented further down\n\nSTBVXDEC void stbvox_init_mesh_maker(stbvox_mesh_maker *mm);\n// Call this function to initialize a mesh-maker context structure\n// used to build meshes. You should have one context per thread\n// that's building meshes.\n\nSTBVXDEC void stbvox_set_buffer(stbvox_mesh_maker *mm, int mesh, int slot, void *buffer, size_t len);\n// Call this to set the buffer into which stbvox will write the mesh\n// it creates. It can build more than one mesh in parallel (distinguished\n// by the 'mesh' parameter), and each mesh can be made up of more than\n// one buffer (distinguished by the 'slot' parameter).\n//\n// Multiple meshes are under your control; use the 'selector' input\n// variable to choose which mesh each voxel's vertices are written to.\n// For example, you can use this to generate separate meshes for opaque\n// and transparent data.\n//\n// You can query the number of slots by calling stbvox_get_buffer_count\n// described below. The meaning of the buffer for each slot depends\n// on STBVOX_CONFIG_MODE.\n//\n//   In mode 0 & mode 20, there is only one slot. The mesh data for that\n//   slot is two interleaved vertex attributes: attr_vertex, a single\n//   32-bit uint, and attr_face, a single 32-bit uint.\n//\n//   In mode 1 & mode 21, there are two slots. The first buffer should\n//   be four times as large as the second buffer. The first buffer\n//   contains a single vertex attribute: 'attr_vertex', a single 32-bit uint.\n//   The second buffer contains texture buffer data (an array of 32-bit uints)\n//   that will be accessed through the sampler identified by STBVOX_UNIFORM_face_data.\n\nSTBVXDEC int stbvox_get_buffer_count(stbvox_mesh_maker *mm);\n// Returns the number of buffers needed per mesh as described above.\n\nSTBVXDEC int stbvox_get_buffer_size_per_quad(stbvox_mesh_maker *mm, int slot);\n// Returns how much of a given buffer will get used per quad. This\n// allows you to choose correct relative sizes for each buffer, although\n// the values are fixed based on the configuration you've selected at\n// compile time, and the details are described in stbvox_set_buffer.\n\nSTBVXDEC void stbvox_set_default_mesh(stbvox_mesh_maker *mm, int mesh);\n// Selects which mesh the mesher will output to (see previous function)\n// if the input doesn't specify a per-voxel selector. (I doubt this is\n// useful, but it's here just in case.)\n\nSTBVXDEC stbvox_input_description *stbvox_get_input_description(stbvox_mesh_maker *mm);\n// This function call returns a pointer to the stbvox_input_description part\n// of stbvox_mesh_maker (which you should otherwise treat as opaque). You\n// zero this structure, then fill out the relevant pointers to the data\n// describing your voxel object/world.\n//\n// See further documentation at the description of stbvox_input_description below.\n\nSTBVXDEC void stbvox_set_input_stride(stbvox_mesh_maker *mm, int x_stride_in_elements, int y_stride_in_elements);\n// This sets the stride between successive elements of the 3D arrays\n// in the stbvox_input_description. Z values are always stored consecutively.\n// (The preferred coordinate system for stbvox is X right, Y forwards, Z up.)\n\nSTBVXDEC void stbvox_set_input_range(stbvox_mesh_maker *mm, int x0, int y0, int z0, int x1, int y1, int z1);\n// This sets the range of values in the 3D array for the voxels that\n// the mesh generator will convert. The lower values are inclusive,\n// the higher values are exclusive, so (0,0,0) to (16,16,16) generates\n// mesh data associated with voxels up to (15,15,15) but no higher.\n//\n// The mesh generate generates faces at the boundary between open space\n// and solid space but associates them with the solid space, so if (15,0,0)\n// is open and (16,0,0) is solid, then the mesh will contain the boundary\n// between them if x0 <= 16 and x1 > 16.\n//\n// Note that the mesh generator will access array elements 1 beyond the\n// limits set in these parameters. For example, if you set the limits\n// to be (0,0,0) and (16,16,16), then the generator will access all of\n// the voxels between (-1,-1,-1) and (16,16,16), including (16,16,16).\n// You may have to do pointer arithmetic to make it work.\n//\n// For example, caveview processes mesh chunks that are 32x32x16, but it\n// does this using input buffers that are 34x34x18.\n//\n// The lower limits are x0 >= 0, y0 >= 0, and z0 >= 0.\n//\n// The upper limits are mode dependent, but all the current methods are\n// limited to x1 < 127, y1 < 127, z1 < 255. Note that these are not\n// powers of two; if you want to use power-of-two chunks (to make\n// it efficient to decide which chunk a coordinate falls in), you're\n// limited to at most x1=64, y1=64, z1=128. For classic Minecraft-style\n// worlds with limited vertical extent, I recommend using a single\n// chunk for the entire height, which limits the height to 255 blocks\n// (one less than Minecraft), and only chunk the map in X & Y.\n\nSTBVXDEC int stbvox_make_mesh(stbvox_mesh_maker *mm);\n// Call this function to create mesh data for the currently configured\n// set of input data. This appends to the currently configured mesh output\n// buffer. Returns 1 on success. If there is not enough room in the buffer,\n// it outputs as much as it can, and returns 0; you need to switch output\n// buffers (either by calling stbvox_set_buffer to set new buffers, or\n// by copying the data out and calling stbvox_reset_buffers), and then\n// call this function again without changing any of the input parameters.\n//\n// Note that this function appends; you can call it multiple times to\n// build a single mesh. For example, caveview uses chunks that are\n// 32x32x255, but builds the mesh for it by processing 32x32x16 at atime\n// (this is faster as it is reuses the same 34x34x18 input buffers rather\n// than needing 34x34x257 input buffers).\n\n// Once you're done creating a mesh into a given buffer,\n// consider the following functions:\n\nSTBVXDEC int stbvox_get_quad_count(stbvox_mesh_maker *mm, int mesh);\n// Returns the number of quads in the mesh currently generated by mm.\n// This is the sum of all consecutive stbvox_make_mesh runs appending\n// to the same buffer. 'mesh' distinguishes between the multiple user\n// meshes available via 'selector' or stbvox_set_default_mesh.\n//\n// Typically you use this function when you're done building the mesh\n// and want to record how to draw it.\n//\n// Note that there are no index buffers; the data stored in the buffers\n// should be drawn as quads (e.g. with GL_QUAD); if your API does not\n// support quads, you can create a single index buffer large enough to\n// draw your largest vertex buffer, and reuse it for every rendering.\n// (Note that if you use 32-bit indices, you'll use 24 bytes of bandwidth\n// per quad, more than the 20 bytes for the vertex/face mesh data.)\n\nSTBVXDEC void stbvox_set_mesh_coordinates(stbvox_mesh_maker *mm, int x, int y, int z);\n// Sets the global coordinates for this chunk, such that (0,0,0) relative\n// coordinates will be at (x,y,z) in global coordinates.\n\nSTBVXDEC void stbvox_get_bounds(stbvox_mesh_maker *mm, float bounds[2][3]);\n// Returns the bounds for the mesh in global coordinates. Use this\n// for e.g. frustum culling the mesh. @BUG: this just uses the\n// values from stbvox_set_input_range(), so if you build by\n// appending multiple values, this will be wrong, and you need to\n// set stbvox_set_input_range() to the full size. Someday this\n// will switch to tracking the actual bounds of the *mesh*, though.\n\nSTBVXDEC void stbvox_get_transform(stbvox_mesh_maker *mm, float transform[3][3]);\n// Returns the 'transform' data for the shader uniforms. It is your\n// job to set this to the shader before drawing the mesh. It is the\n// only uniform that needs to change per-mesh. Note that it is not\n// a 3x3 matrix, but rather a scale to decode fixed point numbers as\n// floats, a translate from relative to global space, and a special\n// translation for texture coordinate generation that avoids\n// floating-point precision issues. @TODO: currently we add the\n// global translation to the vertex, than multiply by modelview,\n// but this means if camera location and vertex are far from the\n// origin, we lose precision. Need to make a special modelview with\n// the translation (or some of it) factored out to avoid this.\n\nSTBVXDEC void stbvox_reset_buffers(stbvox_mesh_maker *mm);\n// Call this function if you're done with the current output buffer\n// but want to reuse it (e.g. you're done appending with\n// stbvox_make_mesh and you've copied the data out to your graphics API\n// so can reuse the buffer).\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// RENDERING\n//\n\nSTBVXDEC char *stbvox_get_vertex_shader(void);\n// Returns the (currently GLSL-only) vertex shader.\n\nSTBVXDEC char *stbvox_get_fragment_shader(void);\n// Returns the (currently GLSL-only) fragment shader.\n// You can override the lighting and fogging calculations\n// by appending data to the end of these; see the #define\n// documentation for more information.\n\nSTBVXDEC char *stbvox_get_fragment_shader_alpha_only(void);\n// Returns a slightly cheaper fragment shader that computes\n// alpha but not color. This is useful for e.g. a depth-only\n// pass when using alpha test.\n\ntypedef struct stbvox_uniform_info stbvox_uniform_info;\n\nSTBVXDEC int stbvox_get_uniform_info(stbvox_uniform_info *info, int uniform);\n// Gets the information about a uniform necessary for you to\n// set up each uniform with a minimal amount of explicit code.\n// See the sample code after the structure definition for stbvox_uniform_info,\n// further down in this header section.\n//\n// \"uniform\" is from the list immediately following. For many\n// of these, default values are provided which you can set.\n// Most values are shared for most draw calls; e.g. for stateful\n// APIs you can set most of the state only once. Only\n// STBVOX_UNIFORM_transform needs to change per draw call.\n//\n// STBVOX_UNIFORM_texscale\n//    64- or 128-long vec4 array. (128 only if STBVOX_CONFIG_PREFER_TEXBUFFER)\n//    x: scale factor to apply to texture #1. must be a power of two. 1.0 means 'face-sized'\n//    y: scale factor to apply to texture #2. must be a power of two. 1.0 means 'face-sized'\n//    z: blend mode indexed by texture #2. 0.0 is alpha compositing; 1.0 is multiplication.\n//    w: unused currently. @TODO use to support texture animation?\n//\n//    Texscale is indexed by the bottom 6 or 7 bits of the texture id; thus for\n//    example the texture at index 0 in the array and the texture in index 128 of\n//    the array must be scaled the same. This means that if you only have 64 or 128\n//    unique textures, they all get distinct values anyway; otherwise you have\n//    to group them in pairs or sets of four.\n//\n// STBVOX_UNIFORM_ambient\n//    4-long vec4 array:\n//      ambient[0].xyz   - negative of direction of a directional light for half-lambert\n//      ambient[1].rgb   - color of light scaled by NdotL (can be negative)\n//      ambient[2].rgb   - constant light added to above calculation;\n//                         effectively light ranges from ambient[2]-ambient[1] to ambient[2]+ambient[1]\n//      ambient[3].rgb   - fog color for STBVOX_CONFIG_FOG_SMOOTHSTEP\n//      ambient[3].a     - reciprocal of squared distance of farthest fog point (viewing distance)\n\n\n                               //  +----- has a default value\n                               //  |  +-- you should always use the default value\nenum                           //  V  V\n{                              //  ------------------------------------------------\n   STBVOX_UNIFORM_face_data,   //  n      the sampler with the face texture buffer\n   STBVOX_UNIFORM_transform,   //  n      the transform data from stbvox_get_transform\n   STBVOX_UNIFORM_tex_array,   //  n      an array of two texture samplers containing the two texture arrays\n   STBVOX_UNIFORM_texscale,    //  Y      a table of texture properties, see above\n   STBVOX_UNIFORM_color_table, //  Y      64 vec4 RGBA values; a default palette is provided; if A > 1.0, fullbright\n   STBVOX_UNIFORM_normals,     //  Y  Y   table of normals, internal-only\n   STBVOX_UNIFORM_texgen,      //  Y  Y   table of texgen vectors, internal-only\n   STBVOX_UNIFORM_ambient,     //  n      lighting & fog info, see above\n   STBVOX_UNIFORM_camera_pos,  //  Y      camera position in global voxel space (for lighting & fog)\n\n   STBVOX_UNIFORM_count,\n};\n\nenum\n{\n   STBVOX_UNIFORM_TYPE_none,\n   STBVOX_UNIFORM_TYPE_sampler,\n   STBVOX_UNIFORM_TYPE_vec2,\n   STBVOX_UNIFORM_TYPE_vec3,\n   STBVOX_UNIFORM_TYPE_vec4,\n};\n\nstruct stbvox_uniform_info\n{\n   int type;                    // which type of uniform\n   int bytes_per_element;       // the size of each uniform array element (e.g. vec3 = 12 bytes)\n   int array_length;            // length of the uniform array\n   char *name;                  // name in the shader @TODO use numeric binding\n   float *default_value;        // if not NULL, you can use this as the uniform pointer\n   int use_tex_buffer;          // if true, then the uniform is a sampler but the data can come from default_value\n};\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Uniform sample code\n//\n\n#if 0\n// Run this once per frame before drawing all the meshes.\n// You still need to separately set the 'transform' uniform for every mesh.\nvoid setup_uniforms(GLuint shader, float camera_pos[4], GLuint tex1, GLuint tex2)\n{\n   int i;\n   glUseProgram(shader); // so uniform binding works\n   for (i=0; i < STBVOX_UNIFORM_count; ++i) {\n      stbvox_uniform_info sui;\n      if (stbvox_get_uniform_info(&sui, i)) {\n         GLint loc = glGetUniformLocation(shader, sui.name);\n         if (loc != -1) {\n            switch (i) {\n               case STBVOX_UNIFORM_camera_pos: // only needed for fog\n                  glUniform4fv(loc, sui.array_length, camera_pos);\n                  break;\n\n               case STBVOX_UNIFORM_tex_array: {\n                  GLuint tex_unit[2] = { 0, 1 }; // your choice of samplers\n                  glUniform1iv(loc, 2, tex_unit);\n\n                  glActiveTexture(GL_TEXTURE0 + tex_unit[0]); glBindTexture(GL_TEXTURE_2D_ARRAY, tex1);\n                  glActiveTexture(GL_TEXTURE0 + tex_unit[1]); glBindTexture(GL_TEXTURE_2D_ARRAY, tex2);\n                  glActiveTexture(GL_TEXTURE0); // reset to default\n                  break;\n               }\n\n               case STBVOX_UNIFORM_face_data:\n                  glUniform1i(loc, SAMPLER_YOU_WILL_BIND_PER_MESH_FACE_DATA_TO);\n                  break;\n\n               case STBVOX_UNIFORM_ambient:     // you definitely want to override this\n               case STBVOX_UNIFORM_color_table: // you might want to override this\n               case STBVOX_UNIFORM_texscale:    // you may want to override this\n                  glUniform4fv(loc, sui.array_length, sui.default_value);\n                  break;\n\n               case STBVOX_UNIFORM_normals:     // you never want to override this\n               case STBVOX_UNIFORM_texgen:      // you never want to override this\n                  glUniform3fv(loc, sui.array_length, sui.default_value);\n                  break;\n            }\n         }\n      }\n   }\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// INPUT TO MESHING\n//\n\n// Shapes of blocks that aren't always cubes\nenum\n{\n   STBVOX_GEOM_empty,\n   STBVOX_GEOM_knockout,  // creates a hole in the mesh\n   STBVOX_GEOM_solid,\n   STBVOX_GEOM_transp,    // solid geometry, but transparent contents so neighbors generate normally, unless same blocktype\n\n   // following 4 can be represented by vheight as well\n   STBVOX_GEOM_slab_upper,\n   STBVOX_GEOM_slab_lower,\n   STBVOX_GEOM_floor_slope_north_is_top,\n   STBVOX_GEOM_ceil_slope_north_is_bottom,\n\n   STBVOX_GEOM_floor_slope_north_is_top_as_wall_UNIMPLEMENTED,   // same as floor_slope above, but uses wall's texture & texture projection\n   STBVOX_GEOM_ceil_slope_north_is_bottom_as_wall_UNIMPLEMENTED,\n   STBVOX_GEOM_crossed_pair,    // corner-to-corner pairs, with normal vector bumped upwards\n   STBVOX_GEOM_force,           // like GEOM_transp, but faces visible even if neighbor is same type, e.g. minecraft fancy leaves\n\n   // these access vheight input\n   STBVOX_GEOM_floor_vheight_03 = 12,  // diagonal is SW-NE\n   STBVOX_GEOM_floor_vheight_12,       // diagonal is SE-NW\n   STBVOX_GEOM_ceil_vheight_03,\n   STBVOX_GEOM_ceil_vheight_12,\n\n   STBVOX_GEOM_count, // number of geom cases\n};\n\nenum\n{\n   STBVOX_FACE_east,\n   STBVOX_FACE_north,\n   STBVOX_FACE_west,\n   STBVOX_FACE_south,\n   STBVOX_FACE_up,\n   STBVOX_FACE_down,\n\n   STBVOX_FACE_count,\n};\n\n#ifdef STBVOX_CONFIG_BLOCKTYPE_SHORT\ntypedef unsigned short stbvox_block_type;\n#else\ntypedef unsigned char stbvox_block_type;\n#endif\n\n// 24-bit color\ntypedef struct\n{\n   unsigned char r,g,b;\n} stbvox_rgb;\n\n#define STBVOX_COLOR_TEX1_ENABLE   64\n#define STBVOX_COLOR_TEX2_ENABLE  128\n\n// This is the data structure you fill out. Most of the arrays can be\n// NULL, except when one is required to get the value to index another.\n//\n// The compass system used in the following descriptions is:\n//     east means increasing x\n//     north means increasing y\n//     up means increasing z\nstruct stbvox_input_description\n{\n   unsigned char lighting_at_vertices;\n   // The default is lighting values (i.e. ambient occlusion) are at block\n   // center, and the vertex light is gathered from those adjacent block\n   // centers that the vertex is facing. This makes smooth lighting\n   // consistent across adjacent faces with the same orientation.\n   //\n   // Setting this flag to non-zero gives you explicit control\n   // of light at each vertex, but now the lighting/ao will be\n   // shared by all vertices at the same point, even if they\n   // have different normals.\n\n   // these are mostly 3D maps you use to define your voxel world, using x_stride and y_stride\n   // note that for cache efficiency, you want to use the block_foo palettes as much as possible instead\n\n   stbvox_rgb *rgb;\n   // Indexed by 3D coordinate.\n   // 24-bit voxel color for STBVOX_CONFIG_MODE = 20 or 21 only\n\n   unsigned char *lighting;\n   // Indexed by 3D coordinate. The lighting value / ambient occlusion\n   // value that is used to define the vertex lighting values.\n   // The raw lighting values are defined at the center of blocks\n   // (or at vertex if 'lighting_at_vertices' is true).\n   //\n   // If the macro STBVOX_CONFIG_ROTATION_IN_LIGHTING is defined,\n   // then an additional 2-bit block rotation value is stored\n   // in this field as well.\n   //\n   // Encode with STBVOX_MAKE_LIGHTING_EXT(lighting,rot)--here\n   // 'lighting' should still be 8 bits, as the macro will\n   // discard the bottom bits automatically. Similarly, if\n   // using STBVOX_CONFIG_VHEIGHT_IN_LIGHTING, encode with\n   // STBVOX_MAKE_LIGHTING_EXT(lighting,vheight).\n   //\n   // (Rationale: rotation needs to be independent of blocktype,\n   // but is only 2 bits so doesn't want to be its own array.\n   // Lighting is the one thing that was likely to already be\n   // in use and that I could easily steal 2 bits from.)\n\n   stbvox_block_type *blocktype;\n   // Indexed by 3D coordinate. This is a core \"block type\" value, which is used\n   // to index into other arrays; essentially a \"palette\". This is much more\n   // memory-efficient and performance-friendly than storing the values explicitly,\n   // but only makes sense if the values are always synchronized.\n   //\n   // If a voxel's blocktype is 0, it is assumed to be empty (STBVOX_GEOM_empty),\n   // and no other blocktypes should be STBVOX_GEOM_empty. (Only if you do not\n   // have blocktypes should STBVOX_GEOM_empty ever used.)\n   //\n   // Normally it is an unsigned byte, but you can override it to be\n   // a short if you have too many blocktypes.\n\n   unsigned char *geometry;\n   // Indexed by 3D coordinate. Contains the geometry type for the block.\n   // Also contains a 2-bit rotation for how the whole block is rotated.\n   // Also includes a 2-bit vheight value when using shared vheight values.\n   // See the separate vheight documentation.\n   // Encode with STBVOX_MAKE_GEOMETRY(geom, rot, vheight)\n\n   unsigned char *block_geometry;\n   // Array indexed by blocktype containing the geometry for this block, plus\n   // a 2-bit \"simple rotation\". Note rotation has limited use since it's not\n   // independent of blocktype.\n   //\n   // Encode with STBVOX_MAKE_GEOMETRY(geom,simple_rot,0)\n\n   unsigned char *block_tex1;\n   // Array indexed by blocktype containing the texture id for texture #1.\n\n   unsigned char (*block_tex1_face)[6];\n   // Array indexed by blocktype and face containing the texture id for texture #1.\n   // The N/E/S/W face choices can be rotated by one of the rotation selectors;\n   // The top & bottom face textures will rotate to match.\n   // Note that it only makes sense to use one of block_tex1 or block_tex1_face;\n   // this pattern repeats throughout and this notice is not repeated.\n\n   unsigned char *tex2;\n   // Indexed by 3D coordinate. Contains the texture id for texture #2\n   // to use on all faces of the block.\n\n   unsigned char *block_tex2;\n   // Array indexed by blocktype containing the texture id for texture #2.\n\n   unsigned char (*block_tex2_face)[6];\n   // Array indexed by blocktype and face containing the texture id for texture #2.\n   // The N/E/S/W face choices can be rotated by one of the rotation selectors;\n   // The top & bottom face textures will rotate to match.\n\n   unsigned char *color;\n   // Indexed by 3D coordinate. Contains the color for all faces of the block.\n   // The core color value is 0..63.\n   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)\n\n   unsigned char *block_color;\n   // Array indexed by blocktype containing the color value to apply to the faces.\n   // The core color value is 0..63.\n   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)\n\n   unsigned char (*block_color_face)[6];\n   // Array indexed by blocktype and face containing the color value to apply to that face.\n   // The core color value is 0..63.\n   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)\n\n   unsigned char *block_texlerp;\n   // Array indexed by blocktype containing 3-bit scalar for texture #2 alpha\n   // (known throughout as 'texlerp'). This is constant over every face even\n   // though the property is potentially per-vertex.\n\n   unsigned char (*block_texlerp_face)[6];\n   // Array indexed by blocktype and face containing 3-bit scalar for texture #2 alpha.\n   // This is constant over the face even though the property is potentially per-vertex.\n\n   unsigned char *block_vheight;\n   // Array indexed by blocktype containing the vheight values for the\n   // top or bottom face of this block. These will rotate properly if the\n   // block is rotated. See discussion of vheight.\n   // Encode with STBVOX_MAKE_VHEIGHT(sw_height, se_height, nw_height, ne_height)\n\n   unsigned char *selector;\n   // Array indexed by 3D coordinates indicating which output mesh to select.\n\n   unsigned char *block_selector;\n   // Array indexed by blocktype indicating which output mesh to select.\n\n   unsigned char *side_texrot;\n   // Array indexed by 3D coordinates encoding 2-bit texture rotations for the\n   // faces on the E/N/W/S sides of the block.\n   // Encode with STBVOX_MAKE_SIDE_TEXROT(rot_e, rot_n, rot_w, rot_s)\n\n   unsigned char *block_side_texrot;\n   // Array indexed by blocktype encoding 2-bit texture rotations for the faces\n   // on the E/N/W/S sides of the block.\n   // Encode with STBVOX_MAKE_SIDE_TEXROT(rot_e, rot_n, rot_w, rot_s)\n\n   unsigned char *overlay;                 // index into palettes listed below\n   // Indexed by 3D coordinate. If 0, there is no overlay. If non-zero,\n   // it indexes into to the below arrays and overrides the values\n   // defined by the blocktype.\n\n   unsigned char (*overlay_tex1)[6];\n   // Array indexed by overlay value and face, containing an override value\n   // for the texture id for texture #1. If 0, the value defined by blocktype\n   // is used.\n\n   unsigned char (*overlay_tex2)[6];\n   // Array indexed by overlay value and face, containing an override value\n   // for the texture id for texture #2. If 0, the value defined by blocktype\n   // is used.\n\n   unsigned char (*overlay_color)[6];\n   // Array indexed by overlay value and face, containing an override value\n   // for the face color. If 0, the value defined by blocktype is used.\n\n   unsigned char *overlay_side_texrot;\n   // Array indexed by overlay value, encoding 2-bit texture rotations for the faces\n   // on the E/N/W/S sides of the block.\n   // Encode with STBVOX_MAKE_SIDE_TEXROT(rot_e, rot_n, rot_w, rot_s)\n\n   unsigned char *rotate;\n   // Indexed by 3D coordinate. Allows independent rotation of several\n   // parts of the voxel, where by rotation I mean swapping textures\n   // and colors between E/N/S/W faces.\n   //    Block: rotates anything indexed by blocktype\n   //    Overlay: rotates anything indexed by overlay\n   //    EColor: rotates faces defined in ecolor_facemask\n   // Encode with STBVOX_MAKE_MATROT(block,overlay,ecolor)\n\n   unsigned char *tex2_for_tex1;\n   // Array indexed by tex1 containing the texture id for texture #2.\n   // You can use this if the two are always/almost-always strictly\n   // correlated (e.g. if tex2 is a detail texture for tex1), as it\n   // will be more efficient (touching fewer cache lines) than using\n   // e.g. block_tex2_face.\n\n   unsigned char *tex2_replace;\n   // Indexed by 3D coordinate. Specifies the texture id for texture #2\n   // to use on a single face of the voxel, which must be E/N/W/S (not U/D).\n   // The texture id is limited to 6 bits unless tex2_facemask is also\n   // defined (see below).\n   // Encode with STBVOX_MAKE_TEX2_REPLACE(tex2, face)\n\n   unsigned char *tex2_facemask;\n   // Indexed by 3D coordinate. Specifies which of the six faces should\n   // have their tex2 replaced by the value of tex2_replace. In this\n   // case, all 8 bits of tex2_replace are used as the texture id.\n   // Encode with STBVOX_MAKE_FACE_MASK(east,north,west,south,up,down)\n\n   unsigned char *extended_color;\n   // Indexed by 3D coordinate. Specifies a value that indexes into\n   // the ecolor arrays below (both of which must be defined).\n\n   unsigned char *ecolor_color;\n   // Indexed by extended_color value, specifies an optional override\n   // for the color value on some faces.\n   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)\n\n   unsigned char *ecolor_facemask;\n   // Indexed by extended_color value, this specifies which faces the\n   // color in ecolor_color should be applied to. The faces can be\n   // independently rotated by the ecolor value of 'rotate', if it exists.\n   // Encode with STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)\n\n   unsigned char *color2;\n   // Indexed by 3D coordinates, specifies an alternative color to apply\n   // to some of the faces of the block.\n   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)\n\n   unsigned char *color2_facemask;\n   // Indexed by 3D coordinates, specifies which faces should use the\n   // color defined in color2. No rotation value is applied.\n   // Encode with STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)\n\n   unsigned char *color3;\n   // Indexed by 3D coordinates, specifies an alternative color to apply\n   // to some of the faces of the block.\n   // Encode with STBVOX_MAKE_COLOR(color_number, tex1_enable, tex2_enable)\n\n   unsigned char *color3_facemask;\n   // Indexed by 3D coordinates, specifies which faces should use the\n   // color defined in color3. No rotation value is applied.\n   // Encode with STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)\n\n   unsigned char *texlerp_simple;\n   // Indexed by 3D coordinates, this is the smallest texlerp encoding\n   // that can do useful work. It consits of three values: baselerp,\n   // vertlerp, and face_vertlerp. Baselerp defines the value\n   // to use on all of the faces but one, from the STBVOX_TEXLERP_BASE\n   // values. face_vertlerp is one of the 6 face values (or STBVOX_FACE_NONE)\n   // which specifies the face should use the vertlerp values.\n   // Vertlerp defines a lerp value at every vertex of the mesh.\n   // Thus, one face can have per-vertex texlerp values, and those\n   // values are encoded in the space so that they will be shared\n   // by adjacent faces that also use vertlerp, allowing continuity\n   // (this is used for the \"texture crossfade\" bit of the release video).\n   // Encode with STBVOX_MAKE_TEXLERP_SIMPLE(baselerp, vertlerp, face_vertlerp)\n\n   // The following texlerp encodings are experimental and maybe not\n   // that useful.\n\n   unsigned char *texlerp;\n   // Indexed by 3D coordinates, this defines four values:\n   //   vertlerp is a lerp value at every vertex of the mesh (using STBVOX_TEXLERP_BASE values).\n   //   ud is the value to use on up and down faces, from STBVOX_TEXLERP_FACE values\n   //   ew is the value to use on east and west faces, from STBVOX_TEXLERP_FACE values\n   //   ns is the value to use on north and south faces, from STBVOX_TEXLERP_FACE values\n   // If any of ud, ew, or ns is STBVOX_TEXLERP_FACE_use_vert, then the\n   // vertlerp values for the vertices are gathered and used for those faces.\n   // Encode with STBVOX_MAKE_TEXLERP(vertlerp,ud,ew,sw)\n\n   unsigned short *texlerp_vert3;\n   // Indexed by 3D coordinates, this works with texlerp and\n   // provides a unique texlerp value for every direction at\n   // every vertex. The same rules of whether faces share values\n   // applies. The STBVOX_TEXLERP_FACE vertlerp value defined in\n   // texlerp is only used for the down direction. The values at\n   // each vertex in other directions are defined in this array,\n   // and each uses the STBVOX_TEXLERP3 values (i.e. full precision\n   // 3-bit texlerp values).\n   // Encode with STBVOX_MAKE_VERT3(vertlerp_e,vertlerp_n,vertlerp_w,vertlerp_s,vertlerp_u)\n\n   unsigned short *texlerp_face3;          // e:3,n:3,w:3,s:3,u:2,d:2\n   // Indexed by 3D coordinates, this provides a compact way to\n   // fully specify the texlerp value indepenendly for every face,\n   // but doesn't allow per-vertex variation. E/N/W/S values are\n   // encoded using STBVOX_TEXLERP3 values, whereas up and down\n   // use STBVOX_TEXLERP_SIMPLE values.\n   // Encode with STBVOX_MAKE_FACE3(face_e,face_n,face_w,face_s,face_u,face_d)\n\n   unsigned char *vheight;                 // STBVOX_MAKE_VHEIGHT   -- sw:2, se:2, nw:2, ne:2, doesn't rotate\n   // Indexed by 3D coordinates, this defines the four\n   // vheight values to use if the geometry is STBVOX_GEOM_vheight*.\n   // See the vheight discussion.\n\n   unsigned char *packed_compact;\n   // Stores block rotation, vheight, and texlerp values:\n   //    block rotation: 2 bits\n   //    vertex vheight: 2 bits\n   //    use_texlerp   : 1 bit\n   //    vertex texlerp: 3 bits\n   // If STBVOX_CONFIG_UP_TEXLERP_PACKED is defined, then 'vertex texlerp' is\n   // used for up faces if use_texlerp is 1. If STBVOX_CONFIG_DOWN_TEXLERP_PACKED\n   // is defined, then 'vertex texlerp' is used for down faces if use_texlerp is 1.\n   // Note if those symbols are defined but packed_compact is NULL, the normal\n   // texlerp default will be used.\n   // Encode with STBVOX_MAKE_PACKED_COMPACT(rot, vheight, texlerp, use_texlerp)\n};\n// @OPTIMIZE allow specializing; build a single struct with all of the\n// 3D-indexed arrays combined so it's AoS instead of SoA for better\n// cache efficiency\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//  VHEIGHT DOCUMENTATION\n//\n//  \"vheight\" is the internal name for the special block types\n//  with sloped tops or bottoms. \"vheight\" stands for \"vertex height\".\n//\n//  Note that these blocks are very flexible (there are 256 of them,\n//  although at least 17 of them should never be used), but they\n//  also have a disadvantage that they generate extra invisible\n//  faces; the generator does not currently detect whether adjacent\n//  vheight blocks hide each others sides, so those side faces are\n//  always generated. For a continuous ground terrain, this means\n//  that you may generate 5x as many quads as needed. See notes\n//  on \"improvements for shipping products\" in the introduction.\n\nenum\n{\n   STBVOX_VERTEX_HEIGHT_0,\n   STBVOX_VERTEX_HEIGHT_half,\n   STBVOX_VERTEX_HEIGHT_1,\n   STBVOX_VERTEX_HEIGHT_one_and_a_half,\n};\n// These are the \"vheight\" values. Vheight stands for \"vertex height\".\n// The idea is that for a \"floor vheight\" block, you take a cube and\n// reposition the top-most vertices at various heights as specified by\n// the vheight values. Similarly, a \"ceiling vheight\" block takes a\n// cube and repositions the bottom-most vertices.\n//\n// A floor block only adjusts the top four vertices; the bottom four vertices\n// remain at the bottom of the block. The height values are 2 bits,\n// measured in halves of a block; so you can specify heights of 0/2,\n// 1/2, 2/2, or 3/2. 0 is the bottom of the block, 1 is halfway\n// up the block, 2 is the top of the block, and 3 is halfway up the\n// next block (and actually outside of the block). The value 3 is\n// actually legal for floor vheight (but not ceiling), and allows you to:\n//\n//     (A) have smoother terrain by having slopes that cross blocks,\n//         e.g. (1,1,3,3) is a regular-seeming slope halfway between blocks\n//     (B) make slopes steeper than 45-degrees, e.g. (0,0,3,3)\n//\n// (Because only z coordinates have half-block precision, and x&y are\n// limited to block corner precision, it's not possible to make these\n// things \"properly\" out of blocks, e.g. a half-slope block on its side\n// or a sloped block halfway between blocks that's made out of two blocks.)\n//\n// If you define STBVOX_CONFIG_OPTIMIZED_VHEIGHT, then the top face\n// (or bottom face for a ceiling vheight block) will be drawn as a\n// single quad even if the four vertex heights aren't planar, and a\n// single normal will be used over the entire quad. If you\n// don't define it, then if the top face is non-planar, it will be\n// split into two triangles, each with their own normal/lighting.\n// (Note that since all output from stb_voxel_render is quad meshes,\n// triangles are actually rendered as degenerate quads.) In this case,\n// the distinction between STBVOX_GEOM_floor_vheight_03 and\n// STBVOX_GEOM_floor_vheight_12 comes into play; the former introduces\n// an edge from the SW to NE corner (i.e. from <0,0,?> to <1,1,?>),\n// while the latter introduces an edge from the NW to SE corner\n// (i.e. from <0,1,?> to <1,0,?>.) For a \"lazy mesh\" look, use\n// exclusively _03 or _12. For a \"classic mesh\" look, alternate\n// _03 and _12 in a checkerboard pattern. For a \"smoothest surface\"\n// look, choose the edge based on actual vertex heights.\n//\n// The four vertex heights can come from several places. The simplest\n// encoding is to just use the 'vheight' parameter which stores four\n// explicit vertex heights for every block. This allows total independence,\n// but at the cost of the largest memory usage, 1 byte per 3D block.\n// Encode this with STBVOX_MAKE_VHEIGHT(vh_sw, vh_se, vh_nw, vh_ne).\n// These coordinates are absolute, not affected by block rotations.\n//\n// An alternative if you just want to encode some very specific block\n// types, not all the possibilities--say you just want half-height slopes,\n// so you want (0,0,1,1) and (1,1,2,2)--then you can use block_vheight\n// to specify them. The geometry rotation will cause block_vheight values\n// to be rotated (because it's as if you're just defining a type of\n// block). This value is also encoded with STBVOX_MAKE_VHEIGHT.\n//\n// If you want to save memory and you're creating a \"continuous ground\"\n// sort of effect, you can make each vertex of the lattice share the\n// vheight value; that is, two adjacent blocks that share a vertex will\n// always get the same vheight value for that vertex. Then you need to\n// store two bits of vheight for every block, which you do by storing it\n// as part another data structure. Store the south-west vertex's vheight\n// with the block. You can either use the \"geometry\" mesh variable (it's\n// a parameter to STBVOX_MAKE_GEOMETRY) or you can store it in the\n// \"lighting\" mesh variable if you defined STBVOX_CONFIG_VHEIGHT_IN_LIGHTING,\n// using STBVOX_MAKE_LIGHTING_EXT(lighting,vheight).\n//\n// Note that if you start with a 2D height map and generate vheight data from\n// it, you don't necessarily store only one value per (x,y) coordinate,\n// as the same value may need to be set up at multiple z heights. For\n// example, if height(8,8) = 13.5, then you want the block at (8,8,13)\n// to store STBVOX_VERTEX_HEIGHT_half, and this will be used by blocks\n// at (7,7,13), (8,7,13), (7,8,13), and (8,8,13). However, if you're\n// allowing steep slopes, it might be the case that you have a block\n// at (7,7,12) which is supposed to stick up to 13.5; that means\n// you also need to store STBVOX_VERTEX_HEIGHT_one_and_a_half at (8,8,12).\n\nenum\n{\n   STBVOX_TEXLERP_FACE_0,\n   STBVOX_TEXLERP_FACE_half,\n   STBVOX_TEXLERP_FACE_1,\n   STBVOX_TEXLERP_FACE_use_vert,\n};\n\nenum\n{\n   STBVOX_TEXLERP_BASE_0,    // 0.0\n   STBVOX_TEXLERP_BASE_2_7,  // 2/7\n   STBVOX_TEXLERP_BASE_5_7,  // 4/7\n   STBVOX_TEXLERP_BASE_1     // 1.0\n};\n\nenum\n{\n   STBVOX_TEXLERP3_0_8,\n   STBVOX_TEXLERP3_1_8,\n   STBVOX_TEXLERP3_2_8,\n   STBVOX_TEXLERP3_3_8,\n   STBVOX_TEXLERP3_4_8,\n   STBVOX_TEXLERP3_5_8,\n   STBVOX_TEXLERP3_6_8,\n   STBVOX_TEXLERP3_7_8,\n};\n\n#define STBVOX_FACE_NONE  7\n\n#define STBVOX_BLOCKTYPE_EMPTY    0\n\n#ifdef STBVOX_BLOCKTYPE_SHORT\n#define STBVOX_BLOCKTYPE_HOLE  65535\n#else\n#define STBVOX_BLOCKTYPE_HOLE    255\n#endif\n\n#define STBVOX_MAKE_GEOMETRY(geom, rotate, vheight) ((geom) + (rotate)*16 + (vheight)*64)\n#define STBVOX_MAKE_VHEIGHT(v_sw, v_se, v_nw, v_ne) ((v_sw) + (v_se)*4 + (v_nw)*16 + (v_ne)*64)\n#define STBVOX_MAKE_MATROT(block, overlay, color)  ((block) + (overlay)*4 + (color)*64)\n#define STBVOX_MAKE_TEX2_REPLACE(tex2, tex2_replace_face) ((tex2) + ((tex2_replace_face) & 3)*64)\n#define STBVOX_MAKE_TEXLERP(ns2, ew2, ud2, vert)  ((ew2) + (ns2)*4 + (ud2)*16 + (vert)*64)\n#define STBVOX_MAKE_TEXLERP_SIMPLE(baselerp,vert,face)   ((vert)*32 + (face)*4 + (baselerp))\n#define STBVOX_MAKE_TEXLERP1(vert,e2,n2,w2,s2,u4,d2) STBVOX_MAKE_TEXLERP(s2, w2, d2, vert)\n#define STBVOX_MAKE_TEXLERP2(vert,e2,n2,w2,s2,u4,d2) ((u2)*16 + (n2)*4 + (s2))\n#define STBVOX_MAKE_FACE_MASK(e,n,w,s,u,d)  ((e)+(n)*2+(w)*4+(s)*8+(u)*16+(d)*32)\n#define STBVOX_MAKE_SIDE_TEXROT(e,n,w,s) ((e)+(n)*4+(w)*16+(s)*64)\n#define STBVOX_MAKE_COLOR(color,t1,t2) ((color)+(t1)*64+(t2)*128)\n#define STBVOX_MAKE_TEXLERP_VERT3(e,n,w,s,u)   ((e)+(n)*8+(w)*64+(s)*512+(u)*4096)\n#define STBVOX_MAKE_TEXLERP_FACE3(e,n,w,s,u,d) ((e)+(n)*8+(w)*64+(s)*512+(u)*4096+(d)*16384)\n#define STBVOX_MAKE_PACKED_COMPACT(rot, vheight, texlerp, def) ((rot)+4*(vheight)+16*(use)+32*(texlerp))\n\n#define STBVOX_MAKE_LIGHTING_EXT(lighting, rot)  (((lighting)&~3)+(rot))\n#define STBVOX_MAKE_LIGHTING(lighting)       (lighting)\n\n#ifndef STBVOX_MAX_MESHES\n#define STBVOX_MAX_MESHES      2           // opaque & transparent\n#endif\n\n#define STBVOX_MAX_MESH_SLOTS  3           // one vertex & two faces, or two vertex and one face\n\n\n// don't mess with this directly, it's just here so you can\n// declare stbvox_mesh_maker on the stack or as a global\nstruct stbvox_mesh_maker\n{\n   stbvox_input_description input;\n   int cur_x, cur_y, cur_z;       // last unprocessed voxel if it splits into multiple buffers\n   int x0,y0,z0,x1,y1,z1;\n   int x_stride_in_bytes;\n   int y_stride_in_bytes;\n   int config_dirty;\n   int default_mesh;\n   unsigned int tags;\n\n   int cube_vertex_offset[6][4]; // this allows access per-vertex data stored block-centered (like texlerp, ambient)\n   int vertex_gather_offset[6][4];\n\n   int pos_x,pos_y,pos_z;\n   int full;\n\n   // computed from user input\n   char *output_cur   [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];\n   char *output_end   [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];\n   char *output_buffer[STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];\n   int   output_len   [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS];\n\n   // computed from config\n   int   output_size  [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS]; // per quad\n   int   output_step  [STBVOX_MAX_MESHES][STBVOX_MAX_MESH_SLOTS]; // per vertex or per face, depending\n   int   num_mesh_slots;\n\n   float default_tex_scale[128][2];\n};\n\n#endif //  INCLUDE_STB_VOXEL_RENDER_H\n\n\n#ifdef STB_VOXEL_RENDER_IMPLEMENTATION\n\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h> // memset\n\n// have to use our own names to avoid the _MSC_VER path having conflicting type names\n#ifndef _MSC_VER\n   #include <stdint.h>\n   typedef uint16_t stbvox_uint16;\n   typedef uint32_t stbvox_uint32;\n#else\n   typedef unsigned short stbvox_uint16;\n   typedef unsigned int   stbvox_uint32;\n#endif\n\n#ifdef _MSC_VER\n   #define STBVOX_NOTUSED(v)  (void)(v)\n#else\n   #define STBVOX_NOTUSED(v)  (void)sizeof(v)\n#endif\n\n\n\n#ifndef STBVOX_CONFIG_MODE\n#error \"Must defined STBVOX_CONFIG_MODE to select the mode\"\n#endif\n\n#if defined(STBVOX_CONFIG_ROTATION_IN_LIGHTING) && defined(STBVOX_CONFIG_VHEIGHT_IN_LIGHTING)\n#error \"Can't store both rotation and vheight in lighting\"\n#endif\n\n\n// The following are candidate voxel modes. Only modes 0, 1, and 20, and 21 are\n// currently implemented. Reducing the storage-per-quad further\n// shouldn't improve performance, although obviously it allow you\n// to create larger worlds without streaming.\n//\n//\n//                      -----------  Two textures -----------       -- One texture --     ---- Color only ----\n//            Mode:     0     1     2     3     4     5     6        10    11    12      20    21    22    23    24\n// ============================================================================================================\n//  uses Tex Buffer     n     Y     Y     Y     Y     Y     Y         Y     Y     Y       n     Y     Y     Y     Y\n//   bytes per quad    32    20    14    12    10     6     6         8     8     4      32    20    10     6     4\n//       non-blocks   all   all   some  some  some slabs stairs     some  some  none    all   all  slabs slabs  none\n//             tex1   256   256   256   256   256   256   256       256   256   256       n     n     n     n     n\n//             tex2   256   256   256   256   256   256   128         n     n     n       n     n     n     n     n\n//           colors    64    64    64    64    64    64    64         8     n     n     2^24  2^24  2^24  2^24  256\n//        vertex ao     Y     Y     Y     Y     Y     n     n         Y     Y     n       Y     Y     Y     n     n\n//   vertex texlerp     Y     Y     Y     n     n     n     n         -     -     -       -     -     -     -     -\n//      x&y extents   127   127   128    64    64   128    64        64   128   128     127   127   128   128   128\n//        z extents   255   255   128    64?   64?   64    64        32    64   128     255   255   128    64   128\n\n// not sure why I only wrote down the above \"result data\" and didn't preserve\n// the vertex formats, but here I've tried to reconstruct the designs...\n//     mode # 3 is wrong, one byte too large, but they may have been an error originally\n\n//            Mode:     0     1     2     3     4     5     6        10    11    12      20    21    22    23    24\n// =============================================================================================================\n//   bytes per quad    32    20    14    12    10     6     6         8     8     4            20    10     6     4\n//\n//    vertex x bits     7     7     0     6     0     0     0         0     0     0             7     0     0     0\n//    vertex y bits     7     7     0     0     0     0     0         0     0     0             7     0     0     0\n//    vertex z bits     9     9     7     4     2     0     0         2     2     0             9     2     0     0\n//   vertex ao bits     6     6     6     6     6     0     0         6     6     0             6     6     0     0\n//  vertex txl bits     3     3     3     0     0     0     0         0     0     0            (3)    0     0     0\n//\n//   face tex1 bits    (8)    8     8     8     8     8     8         8     8     8\n//   face tex2 bits    (8)    8     8     8     8     8     7         -     -     -\n//  face color bits    (8)    8     8     8     8     8     8         3     0     0            24    24    24     8\n// face normal bits    (8)    8     8     8     6     4     7         4     4     3             8     3     4     3\n//      face x bits                 7     0     6     7     6         6     7     7             0     7     7     7\n//      face y bits                 7     6     6     7     6         6     7     7             0     7     7     7\n//      face z bits                 2     2     6     6     6         5     6     7             0     7     6     7\n\n\n#if STBVOX_CONFIG_MODE==0 || STBVOX_CONFIG_MODE==1\n\n   #define STBVOX_ICONFIG_VERTEX_32\n   #define STBVOX_ICONFIG_FACE1_1\n\n#elif STBVOX_CONFIG_MODE==20 || STBVOX_CONFIG_MODE==21\n\n   #define STBVOX_ICONFIG_VERTEX_32\n   #define STBVOX_ICONFIG_FACE1_1\n   #define STBVOX_ICONFIG_UNTEXTURED\n\n#else\n#error \"Selected value of STBVOX_CONFIG_MODE is not supported\"\n#endif\n\n#if STBVOX_CONFIG_MODE==0 || STBVOX_CONFIG_MODE==20\n#define STBVOX_ICONFIG_FACE_ATTRIBUTE\n#endif\n\n#ifndef STBVOX_CONFIG_HLSL\n// the fallback if all others are exhausted is GLSL\n#define STBVOX_ICONFIG_GLSL\n#endif\n\n#ifdef STBVOX_CONFIG_OPENGL_MODELVIEW\n#define STBVOX_ICONFIG_OPENGL_3_1_COMPATIBILITY\n#endif\n\n#if defined(STBVOX_ICONFIG_VERTEX_32)\n   typedef stbvox_uint32 stbvox_mesh_vertex;\n   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \\\n      ((stbvox_uint32) ((x)+((y)<<7)+((z)<<14)+((ao)<<23)+((texlerp)<<29)))\n#elif defined(STBVOX_ICONFIG_VERTEX_16_1)  // mode=2\n   typedef stbvox_uint16 stbvox_mesh_vertex;\n   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \\\n      ((stbvox_uint16) ((z)+((ao)<<7)+((texlerp)<<13)\n#elif defined(STBVOX_ICONFIG_VERTEX_16_2)  // mode=3\n   typedef stbvox_uint16 stbvox_mesh_vertex;\n   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \\\n      ((stbvox_uint16) ((x)+((z)<<6))+((ao)<<10))\n#elif defined(STBVOX_ICONFIG_VERTEX_8)\n   typedef stbvox_uint8 stbvox_mesh_vertex;\n   #define stbvox_vertex_encode(x,y,z,ao,texlerp) \\\n      ((stbvox_uint8) ((z)+((ao)<<6))\n#else\n   #error \"internal error, no vertex type\"\n#endif\n\n#ifdef STBVOX_ICONFIG_FACE1_1\n   typedef struct\n   {\n      unsigned char tex1,tex2,color,face_info;\n   } stbvox_mesh_face;\n#else\n   #error \"internal error, no face type\"\n#endif\n\n\n// 20-byte quad format:\n//\n// per vertex:\n//\n//     x:7\n//     y:7\n//     z:9\n//     ao:6\n//     tex_lerp:3\n//\n// per face:\n//\n//     tex1:8\n//     tex2:8\n//     face:8\n//     color:8\n\n\n// Faces:\n//\n// Faces use the bottom 3 bits to choose the texgen\n// mode, and all the bits to choose the normal.\n// Thus the bottom 3 bits have to be:\n//      e, n, w, s, u, d, u, d\n//\n// These use compact names so tables are readable\n\nenum\n{\n   STBVF_e,\n   STBVF_n,\n   STBVF_w,\n   STBVF_s,\n   STBVF_u,\n   STBVF_d,\n   STBVF_eu,\n   STBVF_ed,\n\n   STBVF_eu_wall,\n   STBVF_nu_wall,\n   STBVF_wu_wall,\n   STBVF_su_wall,\n   STBVF_ne_u,\n   STBVF_ne_d,\n   STBVF_nu,\n   STBVF_nd,\n\n   STBVF_ed_wall,\n   STBVF_nd_wall,\n   STBVF_wd_wall,\n   STBVF_sd_wall,\n   STBVF_nw_u,\n   STBVF_nw_d,\n   STBVF_wu,\n   STBVF_wd,\n\n   STBVF_ne_u_cross,\n   STBVF_nw_u_cross,\n   STBVF_sw_u_cross,\n   STBVF_se_u_cross,\n   STBVF_sw_u,\n   STBVF_sw_d,\n   STBVF_su,\n   STBVF_sd,\n\n   // @TODO we need more than 5 bits to encode the normal to fit the following\n   // so for now we use the right projection but the wrong normal\n   STBVF_se_u = STBVF_su,\n   STBVF_se_d = STBVF_sd,\n\n   STBVF_count,\n};\n\n/////////////////////////////////////////////////////////////////////////////\n//\n//    tables -- i'd prefer if these were at the end of the file, but: C++\n//\n\nstatic float stbvox_default_texgen[2][32][3] =\n{\n   { {  0, 1,0 }, { 0, 0, 1 }, {  0,-1,0 }, { 0, 0,-1 },\n     { -1, 0,0 }, { 0, 0, 1 }, {  1, 0,0 }, { 0, 0,-1 },\n     {  0,-1,0 }, { 0, 0, 1 }, {  0, 1,0 }, { 0, 0,-1 },\n     {  1, 0,0 }, { 0, 0, 1 }, { -1, 0,0 }, { 0, 0,-1 },\n\n     {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 },\n     { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 },\n     {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 },\n     { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 },\n   },\n   { { 0, 0,-1 }, {  0, 1,0 }, { 0, 0, 1 }, {  0,-1,0 },\n     { 0, 0,-1 }, { -1, 0,0 }, { 0, 0, 1 }, {  1, 0,0 },\n     { 0, 0,-1 }, {  0,-1,0 }, { 0, 0, 1 }, {  0, 1,0 },\n     { 0, 0,-1 }, {  1, 0,0 }, { 0, 0, 1 }, { -1, 0,0 },\n\n     { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 },\n     { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 },\n     { 0,-1, 0 }, {  1, 0,0 }, { 0, 1, 0 }, { -1, 0,0 },\n     { 0, 1, 0 }, { -1, 0,0 }, { 0,-1, 0 }, {  1, 0,0 },\n   },\n};\n\n#define STBVOX_RSQRT2   0.7071067811865f\n#define STBVOX_RSQRT3   0.5773502691896f\n\nstatic float stbvox_default_normals[32][3] =\n{\n   { 1,0,0 },  // east\n   { 0,1,0 },  // north\n   { -1,0,0 }, // west\n   { 0,-1,0 }, // south\n   { 0,0,1 },  // up\n   { 0,0,-1 }, // down\n   {  STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // east & up\n   {  STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // east & down\n\n   {  STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // east & up\n   { 0, STBVOX_RSQRT2, STBVOX_RSQRT2 }, // north & up\n   { -STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // west & up\n   { 0,-STBVOX_RSQRT2, STBVOX_RSQRT2 }, // south & up\n   {  STBVOX_RSQRT3, STBVOX_RSQRT3, STBVOX_RSQRT3 }, // ne & up\n   {  STBVOX_RSQRT3, STBVOX_RSQRT3,-STBVOX_RSQRT3 }, // ne & down\n   { 0, STBVOX_RSQRT2, STBVOX_RSQRT2 }, // north & up\n   { 0, STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // north & down\n\n   {  STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // east & down\n   { 0, STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // north & down\n   { -STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // west & down\n   { 0,-STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // south & down\n   { -STBVOX_RSQRT3, STBVOX_RSQRT3, STBVOX_RSQRT3 }, // NW & up\n   { -STBVOX_RSQRT3, STBVOX_RSQRT3,-STBVOX_RSQRT3 }, // NW & down\n   { -STBVOX_RSQRT2,0, STBVOX_RSQRT2 }, // west & up\n   { -STBVOX_RSQRT2,0, -STBVOX_RSQRT2 }, // west & down\n\n   {  STBVOX_RSQRT3, STBVOX_RSQRT3,STBVOX_RSQRT3 }, // NE & up crossed\n   { -STBVOX_RSQRT3, STBVOX_RSQRT3,STBVOX_RSQRT3 }, // NW & up crossed\n   { -STBVOX_RSQRT3,-STBVOX_RSQRT3,STBVOX_RSQRT3 }, // SW & up crossed\n   {  STBVOX_RSQRT3,-STBVOX_RSQRT3,STBVOX_RSQRT3 }, // SE & up crossed\n   { -STBVOX_RSQRT3,-STBVOX_RSQRT3, STBVOX_RSQRT3 }, // SW & up\n   { -STBVOX_RSQRT3,-STBVOX_RSQRT3,-STBVOX_RSQRT3 }, // SW & up\n   { 0,-STBVOX_RSQRT2, STBVOX_RSQRT2 }, // south & up\n   { 0,-STBVOX_RSQRT2, -STBVOX_RSQRT2 }, // south & down\n};\n\nstatic float stbvox_default_texscale[128][4] =\n{\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n   {1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},{1,1,0,0},\n};\n\nstatic unsigned char stbvox_default_palette_compact[64][3] =\n{\n   { 255,255,255 }, { 238,238,238 }, { 221,221,221 }, { 204,204,204 },\n   { 187,187,187 }, { 170,170,170 }, { 153,153,153 }, { 136,136,136 },\n   { 119,119,119 }, { 102,102,102 }, {  85, 85, 85 }, {  68, 68, 68 },\n   {  51, 51, 51 }, {  34, 34, 34 }, {  17, 17, 17 }, {   0,  0,  0 },\n   { 255,240,240 }, { 255,220,220 }, { 255,160,160 }, { 255, 32, 32 },\n   { 200,120,160 }, { 200, 60,150 }, { 220,100,130 }, { 255,  0,128 },\n   { 240,240,255 }, { 220,220,255 }, { 160,160,255 }, {  32, 32,255 },\n   { 120,160,200 }, {  60,150,200 }, { 100,130,220 }, {   0,128,255 },\n   { 240,255,240 }, { 220,255,220 }, { 160,255,160 }, {  32,255, 32 },\n   { 160,200,120 }, { 150,200, 60 }, { 130,220,100 }, { 128,255,  0 },\n   { 255,255,240 }, { 255,255,220 }, { 220,220,180 }, { 255,255, 32 },\n   { 200,160,120 }, { 200,150, 60 }, { 220,130,100 }, { 255,128,  0 },\n   { 255,240,255 }, { 255,220,255 }, { 220,180,220 }, { 255, 32,255 },\n   { 160,120,200 }, { 150, 60,200 }, { 130,100,220 }, { 128,  0,255 },\n   { 240,255,255 }, { 220,255,255 }, { 180,220,220 }, {  32,255,255 },\n   { 120,200,160 }, {  60,200,150 }, { 100,220,130 }, {   0,255,128 },\n};\n\nstatic float stbvox_default_ambient[4][4] =\n{\n   { 0,0,1      ,0 }, // reversed lighting direction\n   { 0.5,0.5,0.5,0 }, // directional color\n   { 0.5,0.5,0.5,0 }, // constant color\n   { 0.5,0.5,0.5,1.0f/1000.0f/1000.0f }, // fog data for simple_fog\n};\n\nstatic float stbvox_default_palette[64][4];\n\nstatic void stbvox_build_default_palette(void)\n{\n   int i;\n   for (i=0; i < 64; ++i) {\n      stbvox_default_palette[i][0] = stbvox_default_palette_compact[i][0] / 255.0f;\n      stbvox_default_palette[i][1] = stbvox_default_palette_compact[i][1] / 255.0f;\n      stbvox_default_palette[i][2] = stbvox_default_palette_compact[i][2] / 255.0f;\n      stbvox_default_palette[i][3] = 1.0f;\n   }\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Shaders\n//\n\n#if defined(STBVOX_ICONFIG_OPENGL_3_1_COMPATIBILITY)\n   #define STBVOX_SHADER_VERSION \"#version 150 compatibility\\n\"\n#elif defined(STBVOX_ICONFIG_OPENGL_3_0)\n   #define STBVOX_SHADER_VERSION \"#version 130\\n\"\n#elif defined(STBVOX_ICONFIG_GLSL)\n   #define STBVOX_SHADER_VERSION \"#version 150\\n\"\n#else\n   #define STBVOX_SHADER_VERSION \"\"\n#endif\n\nstatic const char *stbvox_vertex_program =\n{\n      STBVOX_SHADER_VERSION\n\n   #ifdef STBVOX_ICONFIG_FACE_ATTRIBUTE  // NOT TAG_face_sampled\n      \"in uvec4 attr_face;\\n\"\n   #else\n      \"uniform usamplerBuffer facearray;\\n\"\n   #endif\n\n   #ifdef STBVOX_ICONFIG_FACE_ARRAY_2\n      \"uniform usamplerBuffer facearray2;\\n\"\n   #endif\n\n      // vertex input data\n      \"in uint attr_vertex;\\n\"\n\n      // per-buffer data\n      \"uniform vec3 transform[3];\\n\"\n\n      // per-frame data\n      \"uniform vec4 camera_pos;\\n\"  // 4th value is used for arbitrary hacking\n\n      // to simplify things, we avoid using more than 256 uniform vectors\n      // in fragment shader to avoid possible 1024 component limit, so\n      // we access this table in the fragment shader.\n      \"uniform vec3 normal_table[32];\\n\"\n\n      #ifndef STBVOX_CONFIG_OPENGL_MODELVIEW\n         \"uniform mat4x4 model_view;\\n\"\n      #endif\n\n      // fragment output data\n      \"flat out uvec4  facedata;\\n\"\n      \"     out  vec3  voxelspace_pos;\\n\"\n      \"     out  vec3  vnormal;\\n\"\n      \"     out float  texlerp;\\n\"\n      \"     out float  amb_occ;\\n\"\n\n      // @TODO handle the HLSL way to do this\n      \"void main()\\n\"\n      \"{\\n\"\n      #ifdef STBVOX_ICONFIG_FACE_ATTRIBUTE\n         \"   facedata = attr_face;\\n\"\n      #else\n         \"   int faceID = gl_VertexID >> 2;\\n\"\n         \"   facedata   = texelFetch(facearray, faceID);\\n\"\n      #endif\n\n      // extract data for vertex\n      \"   vec3 offset;\\n\"\n      \"   offset.x = float( (attr_vertex       ) & 127u );\\n\"             // a[0..6]\n      \"   offset.y = float( (attr_vertex >>  7u) & 127u );\\n\"             // a[7..13]\n      \"   offset.z = float( (attr_vertex >> 14u) & 511u );\\n\"             // a[14..22]\n      \"   amb_occ  = float( (attr_vertex >> 23u) &  63u ) / 63.0;\\n\"      // a[23..28]\n      \"   texlerp  = float( (attr_vertex >> 29u)        ) /  7.0;\\n\"      // a[29..31]\n\n      \"   vnormal = normal_table[(facedata.w>>2u) & 31u];\\n\"\n      \"   voxelspace_pos = offset * transform[0];\\n\"  // mesh-to-object scale\n      \"   vec3 position  = voxelspace_pos + transform[1];\\n\"  // mesh-to-object translate\n\n      #ifdef STBVOX_DEBUG_TEST_NORMALS\n         \"   if ((facedata.w & 28u) == 16u || (facedata.w & 28u) == 24u)\\n\"\n         \"      position += vnormal.xyz * camera_pos.w;\\n\"\n      #endif\n\n      #ifndef STBVOX_CONFIG_OPENGL_MODELVIEW\n         \"   gl_Position = model_view * vec4(position,1.0);\\n\"\n      #else\n         \"   gl_Position = gl_ModelViewProjectionMatrix * vec4(position,1.0);\\n\"\n      #endif\n\n      \"}\\n\"\n};\n\n\nstatic const char *stbvox_fragment_program =\n{\n      STBVOX_SHADER_VERSION\n\n      // rlerp is lerp but with t on the left, like god intended\n      #if defined(STBVOX_ICONFIG_GLSL)\n         \"#define rlerp(t,x,y) mix(x,y,t)\\n\"\n      #elif defined(STBVOX_CONFIG_HLSL)\n         \"#define rlerp(t,x,y) lerp(x,y,t)\\n\"\n      #else\n         #error \"need definition of rlerp()\"\n      #endif\n\n\n      // vertex-shader output data\n      \"flat in uvec4  facedata;\\n\"\n      \"     in  vec3  voxelspace_pos;\\n\"\n      \"     in  vec3  vnormal;\\n\"\n      \"     in float  texlerp;\\n\"\n      \"     in float  amb_occ;\\n\"\n\n      // per-buffer data\n      \"uniform vec3 transform[3];\\n\"\n\n      // per-frame data\n      \"uniform vec4 camera_pos;\\n\"  // 4th value is used for arbitrary hacking\n\n      // probably constant data\n      \"uniform vec4 ambient[4];\\n\"\n\n      #ifndef STBVOX_ICONFIG_UNTEXTURED\n         // generally constant data\n         \"uniform sampler2DArray tex_array[2];\\n\"\n\n         #ifdef STBVOX_CONFIG_PREFER_TEXBUFFER\n            \"uniform samplerBuffer color_table;\\n\"\n            \"uniform samplerBuffer texscale;\\n\"\n            \"uniform samplerBuffer texgen;\\n\"\n         #else\n            \"uniform vec4 color_table[64];\\n\"\n            \"uniform vec4 texscale[64];\\n\" // instead of 128, to avoid running out of uniforms\n            \"uniform vec3 texgen[64];\\n\"\n         #endif\n      #endif\n\n      \"out vec4  outcolor;\\n\"\n\n      #if defined(STBVOX_CONFIG_LIGHTING) || defined(STBVOX_CONFIG_LIGHTING_SIMPLE)\n      \"vec3 compute_lighting(vec3 pos, vec3 norm, vec3 albedo, vec3 ambient);\\n\"\n      #endif\n      #if defined(STBVOX_CONFIG_FOG) || defined(STBVOX_CONFIG_FOG_SMOOTHSTEP)\n      \"vec3 compute_fog(vec3 color, vec3 relative_pos, float fragment_alpha);\\n\"\n      #endif\n\n      \"void main()\\n\"\n      \"{\\n\"\n      \"   vec3 albedo;\\n\"\n      \"   float fragment_alpha;\\n\"\n\n      #ifndef STBVOX_ICONFIG_UNTEXTURED\n         // unpack the values\n         \"   uint tex1_id = facedata.x;\\n\"\n         \"   uint tex2_id = facedata.y;\\n\"\n         \"   uint texprojid = facedata.w & 31u;\\n\"\n         \"   uint color_id  = facedata.z;\\n\"\n\n         #ifndef STBVOX_CONFIG_PREFER_TEXBUFFER\n            // load from uniforms / texture buffers\n            \"   vec3 texgen_s = texgen[texprojid];\\n\"\n            \"   vec3 texgen_t = texgen[texprojid+32u];\\n\"\n            \"   float tex1_scale = texscale[tex1_id & 63u].x;\\n\"\n            \"   vec4 color = color_table[color_id & 63u];\\n\"\n            #ifndef STBVOX_CONFIG_DISABLE_TEX2\n            \"   vec4 tex2_props = texscale[tex2_id & 63u];\\n\"\n            #endif\n         #else\n            \"   vec3 texgen_s = texelFetch(texgen, int(texprojid)).xyz;\\n\"\n            \"   vec3 texgen_t = texelFetch(texgen, int(texprojid+32u)).xyz;\\n\"\n            \"   float tex1_scale = texelFetch(texscale, int(tex1_id & 127u)).x;\\n\"\n            \"   vec4 color = texelFetch(color_table, int(color_id & 63u));\\n\"\n            #ifndef STBVOX_CONFIG_DISABLE_TEX2\n            \"   vec4 tex2_props = texelFetch(texscale, int(tex1_id & 127u));\\n\"\n            #endif\n         #endif\n\n         #ifndef STBVOX_CONFIG_DISABLE_TEX2\n         \"   float tex2_scale = tex2_props.y;\\n\"\n         \"   bool texblend_mode = tex2_props.z != 0.0;\\n\"\n         #endif\n         \"   vec2 texcoord;\\n\"\n         \"   vec3 texturespace_pos = voxelspace_pos + transform[2].xyz;\\n\"\n         \"   texcoord.s = dot(texturespace_pos, texgen_s);\\n\"\n         \"   texcoord.t = dot(texturespace_pos, texgen_t);\\n\"\n\n         \"   vec2  texcoord_1 = tex1_scale * texcoord;\\n\"\n         #ifndef STBVOX_CONFIG_DISABLE_TEX2\n         \"   vec2  texcoord_2 = tex2_scale * texcoord;\\n\"\n         #endif\n\n         #ifdef STBVOX_CONFIG_TEX1_EDGE_CLAMP\n         \"   texcoord_1 = texcoord_1 - floor(texcoord_1);\\n\"\n         \"   vec4 tex1 = textureGrad(tex_array[0], vec3(texcoord_1, float(tex1_id)), dFdx(tex1_scale*texcoord), dFdy(tex1_scale*texcoord));\\n\"\n         #else\n         \"   vec4 tex1 = texture(tex_array[0], vec3(texcoord_1, float(tex1_id)));\\n\"\n         #endif\n\n         #ifndef STBVOX_CONFIG_DISABLE_TEX2\n         #ifdef STBVOX_CONFIG_TEX2_EDGE_CLAMP\n         \"   texcoord_2 = texcoord_2 - floor(texcoord_2);\\n\"\n         \"   vec4 tex2 = textureGrad(tex_array[0], vec3(texcoord_2, float(tex2_id)), dFdx(tex2_scale*texcoord), dFdy(tex2_scale*texcoord));\\n\"\n         #else\n         \"   vec4 tex2 = texture(tex_array[1], vec3(texcoord_2, float(tex2_id)));\\n\"\n         #endif\n         #endif\n\n         \"   bool emissive = (color.a > 1.0);\\n\"\n         \"   color.a = min(color.a, 1.0);\\n\"\n\n         // recolor textures\n         \"   if ((color_id &  64u) != 0u) tex1.rgba *= color.rgba;\\n\"\n         \"   fragment_alpha = tex1.a;\\n\"\n         #ifndef STBVOX_CONFIG_DISABLE_TEX2\n            \"   if ((color_id & 128u) != 0u) tex2.rgba *= color.rgba;\\n\"\n\n            #ifdef STBVOX_CONFIG_PREMULTIPLIED_ALPHA\n            \"   tex2.rgba *= texlerp;\\n\"\n            #else\n            \"   tex2.a *= texlerp;\\n\"\n            #endif\n\n            \"   if (texblend_mode)\\n\"\n            \"      albedo = tex1.xyz * rlerp(tex2.a, vec3(1.0,1.0,1.0), 2.0*tex2.xyz);\\n\"\n            \"   else {\\n\"\n            #ifdef STBVOX_CONFIG_PREMULTIPLIED_ALPHA\n            \"      albedo = (1.0-tex2.a)*tex1.xyz + tex2.xyz;\\n\"\n            #else\n            \"      albedo = rlerp(tex2.a, tex1.xyz, tex2.xyz);\\n\"\n            #endif\n            \"      fragment_alpha = tex1.a*(1-tex2.a)+tex2.a;\\n\"\n            \"   }\\n\"\n         #else\n            \"      albedo = tex1.xyz;\\n\"\n         #endif\n\n      #else // UNTEXTURED\n         \"   vec4 color;\"\n         \"   color.xyz = vec3(facedata.xyz) / 255.0;\\n\"\n         \"   bool emissive = false;\\n\"\n         \"   albedo = color.xyz;\\n\"\n         \"   fragment_alpha = 1.0;\\n\"\n      #endif\n\n      #ifdef STBVOX_ICONFIG_VARYING_VERTEX_NORMALS\n         // currently, there are no modes that trigger this path; idea is that there\n         // could be a couple of bits per vertex to perturb the normal to e.g. get curved look\n         \"   vec3 normal = normalize(vnormal);\\n\"\n      #else\n         \"   vec3 normal = vnormal;\\n\"\n      #endif\n\n      \"   vec3 ambient_color = dot(normal, ambient[0].xyz) * ambient[1].xyz + ambient[2].xyz;\\n\"\n\n      \"   ambient_color = clamp(ambient_color, 0.0, 1.0);\"\n      \"   ambient_color *= amb_occ;\\n\"\n\n      \"   vec3 lit_color;\\n\"\n      \"   if (!emissive)\\n\"\n      #if defined(STBVOX_ICONFIG_LIGHTING) || defined(STBVOX_CONFIG_LIGHTING_SIMPLE)\n         \"      lit_color = compute_lighting(voxelspace_pos + transform[1], normal, albedo, ambient_color);\\n\"\n      #else\n         \"      lit_color = albedo * ambient_color ;\\n\"\n      #endif\n      \"   else\\n\"\n      \"      lit_color = albedo;\\n\"\n\n      #if defined(STBVOX_ICONFIG_FOG) || defined(STBVOX_CONFIG_FOG_SMOOTHSTEP)\n         \"   vec3 dist = voxelspace_pos + (transform[1] - camera_pos.xyz);\\n\"\n         \"   lit_color = compute_fog(lit_color, dist, fragment_alpha);\\n\"\n      #endif\n\n      #ifdef STBVOX_CONFIG_UNPREMULTIPLY\n      \"   vec4 final_color = vec4(lit_color/fragment_alpha, fragment_alpha);\\n\"\n      #else\n      \"   vec4 final_color = vec4(lit_color, fragment_alpha);\\n\"\n      #endif\n      \"   outcolor = final_color;\\n\"\n      \"}\\n\"\n\n   #ifdef STBVOX_CONFIG_LIGHTING_SIMPLE\n      \"\\n\"\n      \"uniform vec3 light_source[2];\\n\"\n      \"vec3 compute_lighting(vec3 pos, vec3 norm, vec3 albedo, vec3 ambient)\\n\"\n      \"{\\n\"\n      \"   vec3 light_dir = light_source[0] - pos;\\n\"\n      \"   float lambert = dot(light_dir, norm) / dot(light_dir, light_dir);\\n\"\n      \"   vec3 diffuse = clamp(light_source[1] * clamp(lambert, 0.0, 1.0), 0.0, 1.0);\\n\"\n      \"   return (diffuse + ambient) * albedo;\\n\"\n      \"}\\n\"\n   #endif\n\n   #ifdef STBVOX_CONFIG_FOG_SMOOTHSTEP\n      \"\\n\"\n      \"vec3 compute_fog(vec3 color, vec3 relative_pos, float fragment_alpha)\\n\"\n      \"{\\n\"\n      \"   float f = dot(relative_pos,relative_pos)*ambient[3].w;\\n\"\n      //\"   f = rlerp(f, -2,1);\\n\"\n      \"   f = clamp(f, 0.0, 1.0);\\n\"\n      \"   f = 3.0*f*f - 2.0*f*f*f;\\n\" // smoothstep\n      //\"   f = f*f;\\n\"  // fade in more smoothly\n      #ifdef STBVOX_CONFIG_PREMULTIPLIED_ALPHA\n      \"   return rlerp(f, color.xyz, ambient[3].xyz*fragment_alpha);\\n\"\n      #else\n      \"   return rlerp(f, color.xyz, ambient[3].xyz);\\n\"\n      #endif\n      \"}\\n\"\n   #endif\n};\n\n\n// still requires full alpha lookups, including tex2 if texblend is enabled\nstatic const char *stbvox_fragment_program_alpha_only =\n{\n   STBVOX_SHADER_VERSION\n\n   // vertex-shader output data\n   \"flat in uvec4  facedata;\\n\"\n   \"     in  vec3  voxelspace_pos;\\n\"\n   \"     in float  texlerp;\\n\"\n\n   // per-buffer data\n   \"uniform vec3 transform[3];\\n\"\n\n   #ifndef STBVOX_ICONFIG_UNTEXTURED\n      // generally constant data\n      \"uniform sampler2DArray tex_array[2];\\n\"\n\n      #ifdef STBVOX_CONFIG_PREFER_TEXBUFFER\n         \"uniform samplerBuffer texscale;\\n\"\n         \"uniform samplerBuffer texgen;\\n\"\n      #else\n         \"uniform vec4 texscale[64];\\n\" // instead of 128, to avoid running out of uniforms\n         \"uniform vec3 texgen[64];\\n\"\n      #endif\n   #endif\n\n   \"out vec4  outcolor;\\n\"\n\n   \"void main()\\n\"\n   \"{\\n\"\n   \"   vec3 albedo;\\n\"\n   \"   float fragment_alpha;\\n\"\n\n   #ifndef STBVOX_ICONFIG_UNTEXTURED\n      // unpack the values\n      \"   uint tex1_id = facedata.x;\\n\"\n      \"   uint tex2_id = facedata.y;\\n\"\n      \"   uint texprojid = facedata.w & 31u;\\n\"\n      \"   uint color_id  = facedata.z;\\n\"\n\n      #ifndef STBVOX_CONFIG_PREFER_TEXBUFFER\n         // load from uniforms / texture buffers\n         \"   vec3 texgen_s = texgen[texprojid];\\n\"\n         \"   vec3 texgen_t = texgen[texprojid+32u];\\n\"\n         \"   float tex1_scale = texscale[tex1_id & 63u].x;\\n\"\n         \"   vec4 color = color_table[color_id & 63u];\\n\"\n         \"   vec4 tex2_props = texscale[tex2_id & 63u];\\n\"\n      #else\n         \"   vec3 texgen_s = texelFetch(texgen, int(texprojid)).xyz;\\n\"\n         \"   vec3 texgen_t = texelFetch(texgen, int(texprojid+32u)).xyz;\\n\"\n         \"   float tex1_scale = texelFetch(texscale, int(tex1_id & 127u)).x;\\n\"\n         \"   vec4 color = texelFetch(color_table, int(color_id & 63u));\\n\"\n         \"   vec4 tex2_props = texelFetch(texscale, int(tex2_id & 127u));\\n\"\n      #endif\n\n      #ifndef STBVOX_CONFIG_DISABLE_TEX2\n      \"   float tex2_scale = tex2_props.y;\\n\"\n      \"   bool texblend_mode = tex2_props.z &((facedata.w & 128u) != 0u);\\n\"\n      #endif\n\n      \"   color.a = min(color.a, 1.0);\\n\"\n\n      \"   vec2 texcoord;\\n\"\n      \"   vec3 texturespace_pos = voxelspace_pos + transform[2].xyz;\\n\"\n      \"   texcoord.s = dot(texturespace_pos, texgen_s);\\n\"\n      \"   texcoord.t = dot(texturespace_pos, texgen_t);\\n\"\n\n      \"   vec2  texcoord_1 = tex1_scale * texcoord;\\n\"\n      \"   vec2  texcoord_2 = tex2_scale * texcoord;\\n\"\n\n      #ifdef STBVOX_CONFIG_TEX1_EDGE_CLAMP\n      \"   texcoord_1 = texcoord_1 - floor(texcoord_1);\\n\"\n      \"   vec4 tex1 = textureGrad(tex_array[0], vec3(texcoord_1, float(tex1_id)), dFdx(tex1_scale*texcoord), dFdy(tex1_scale*texcoord));\\n\"\n      #else\n      \"   vec4 tex1 = texture(tex_array[0], vec3(texcoord_1, float(tex1_id)));\\n\"\n      #endif\n\n      \"   if ((color_id &  64u) != 0u) tex1.a *= color.a;\\n\"\n      \"   fragment_alpha = tex1.a;\\n\"\n\n      #ifndef STBVOX_CONFIG_DISABLE_TEX2\n      \"   if (!texblend_mode) {\\n\"\n         #ifdef STBVOX_CONFIG_TEX2_EDGE_CLAMP\n         \"      texcoord_2 = texcoord_2 - floor(texcoord_2);\\n\"\n         \"      vec4 tex2 = textureGrad(tex_array[0], vec3(texcoord_2, float(tex2_id)), dFdx(tex2_scale*texcoord), dFdy(tex2_scale*texcoord));\\n\"\n         #else\n         \"      vec4 tex2 = texture(tex_array[1], vec3(texcoord_2, float(tex2_id)));\\n\"\n         #endif\n\n         \"      tex2.a *= texlerp;\\n\"\n         \"      if ((color_id & 128u) != 0u) tex2.rgba *= color.a;\\n\"\n         \"      fragment_alpha = tex1.a*(1-tex2.a)+tex2.a;\\n\"\n         \"}\\n\"\n      \"\\n\"\n      #endif\n\n   #else // UNTEXTURED\n      \"   fragment_alpha = 1.0;\\n\"\n   #endif\n\n   \"   outcolor = vec4(0.0, 0.0, 0.0, fragment_alpha);\\n\"\n   \"}\\n\"\n};\n\n\nSTBVXDEC char *stbvox_get_vertex_shader(void)\n{\n   return (char *) stbvox_vertex_program;\n}\n\nSTBVXDEC char *stbvox_get_fragment_shader(void)\n{\n   return (char *) stbvox_fragment_program;\n}\n\nSTBVXDEC char *stbvox_get_fragment_shader_alpha_only(void)\n{\n   return (char *) stbvox_fragment_program_alpha_only;\n}\n\nstatic float stbvox_dummy_transform[3][3];\n\n#ifdef STBVOX_CONFIG_PREFER_TEXBUFFER\n#define STBVOX_TEXBUF 1\n#else\n#define STBVOX_TEXBUF 0\n#endif\n\nstatic stbvox_uniform_info stbvox_uniforms[] =\n{\n   { STBVOX_UNIFORM_TYPE_sampler  ,  4,   1, (char*) \"facearray\"    , 0                           },\n   { STBVOX_UNIFORM_TYPE_vec3     , 12,   3, (char*) \"transform\"    , stbvox_dummy_transform[0]   },\n   { STBVOX_UNIFORM_TYPE_sampler  ,  4,   2, (char*) \"tex_array\"    , 0                           },\n   { STBVOX_UNIFORM_TYPE_vec4     , 16, 128, (char*) \"texscale\"     , stbvox_default_texscale[0] , STBVOX_TEXBUF },\n   { STBVOX_UNIFORM_TYPE_vec4     , 16,  64, (char*) \"color_table\"  , stbvox_default_palette[0]  , STBVOX_TEXBUF },\n   { STBVOX_UNIFORM_TYPE_vec3     , 12,  32, (char*) \"normal_table\" , stbvox_default_normals[0]   },\n   { STBVOX_UNIFORM_TYPE_vec3     , 12,  64, (char*) \"texgen\"       , stbvox_default_texgen[0][0], STBVOX_TEXBUF },\n   { STBVOX_UNIFORM_TYPE_vec4     , 16,   4, (char*) \"ambient\"      , stbvox_default_ambient[0]   },\n   { STBVOX_UNIFORM_TYPE_vec4     , 16,   1, (char*) \"camera_pos\"   , stbvox_dummy_transform[0]   },\n};\n\nSTBVXDEC int stbvox_get_uniform_info(stbvox_uniform_info *info, int uniform)\n{\n   if (uniform < 0 || uniform >= STBVOX_UNIFORM_count)\n      return 0;\n\n   *info = stbvox_uniforms[uniform];\n   return 1;\n}\n\n#define STBVOX_GET_GEO(geom_data)  ((geom_data) & 15)\n\ntypedef struct\n{\n   unsigned char block:2;\n   unsigned char overlay:2;\n   unsigned char facerot:2;\n   unsigned char ecolor:2;\n} stbvox_rotate;\n\ntypedef struct\n{\n   unsigned char x,y,z;\n} stbvox_pos;\n\nstatic unsigned char stbvox_rotate_face[6][4] =\n{\n   { 0,1,2,3 },\n   { 1,2,3,0 },\n   { 2,3,0,1 },\n   { 3,0,1,2 },\n   { 4,4,4,4 },\n   { 5,5,5,5 },\n};\n\n#define STBVOX_ROTATE(x,r)   stbvox_rotate_face[x][r] // (((x)+(r))&3)\n\nstbvox_mesh_face stbvox_compute_mesh_face_value(stbvox_mesh_maker *mm, stbvox_rotate rot, int face, int v_off, int normal)\n{\n   stbvox_mesh_face face_data = { 0 };\n   stbvox_block_type bt = mm->input.blocktype[v_off];\n   unsigned char bt_face = STBVOX_ROTATE(face, rot.block);\n   int facerot = rot.facerot;\n\n   #ifdef STBVOX_ICONFIG_UNTEXTURED\n   if (mm->input.rgb) {\n      face_data.tex1  = mm->input.rgb[v_off].r;\n      face_data.tex2  = mm->input.rgb[v_off].g;\n      face_data.color = mm->input.rgb[v_off].b;\n      face_data.face_info = (normal<<2);\n      return face_data;\n   }\n   #else\n   unsigned char color_face;\n\n   if (mm->input.color)\n      face_data.color = mm->input.color[v_off];\n\n   if (mm->input.block_tex1)\n      face_data.tex1 = mm->input.block_tex1[bt];\n   else if (mm->input.block_tex1_face)\n      face_data.tex1 = mm->input.block_tex1_face[bt][bt_face];\n   else\n      face_data.tex1 = bt;\n\n   if (mm->input.block_tex2)\n      face_data.tex2 = mm->input.block_tex2[bt];\n   else if (mm->input.block_tex2_face)\n      face_data.tex2 = mm->input.block_tex2_face[bt][bt_face];\n\n   if (mm->input.block_color) {\n      unsigned char mcol = mm->input.block_color[bt];\n      if (mcol)\n         face_data.color = mcol;\n   } else if (mm->input.block_color_face) {\n      unsigned char mcol = mm->input.block_color_face[bt][bt_face];\n      if (mcol)\n         face_data.color = mcol;\n   }\n\n   if (face <= STBVOX_FACE_south) {\n      if (mm->input.side_texrot)\n         facerot = mm->input.side_texrot[v_off] >> (2 * face);\n      else if (mm->input.block_side_texrot)\n         facerot = mm->input.block_side_texrot[v_off] >> (2 * bt_face);\n   }\n\n   if (mm->input.overlay) {\n      int over_face = STBVOX_ROTATE(face, rot.overlay);\n      unsigned char over = mm->input.overlay[v_off];\n      if (over) {\n         if (mm->input.overlay_tex1) {\n            unsigned char rep1 = mm->input.overlay_tex1[over][over_face];\n            if (rep1)\n               face_data.tex1 = rep1;\n         }\n         if (mm->input.overlay_tex2) {\n            unsigned char rep2 = mm->input.overlay_tex2[over][over_face];\n            if (rep2)\n               face_data.tex2 = rep2;\n         }\n         if (mm->input.overlay_color) {\n            unsigned char rep3 = mm->input.overlay_color[over][over_face];\n            if (rep3)\n               face_data.color = rep3;\n         }\n\n         if (mm->input.overlay_side_texrot && face <= STBVOX_FACE_south)\n            facerot = mm->input.overlay_side_texrot[over] >> (2*over_face);\n      }\n   }\n\n   if (mm->input.tex2_for_tex1)\n      face_data.tex2 = mm->input.tex2_for_tex1[face_data.tex1];\n   if (mm->input.tex2)\n      face_data.tex2 = mm->input.tex2[v_off];\n   if (mm->input.tex2_replace) {\n      if (mm->input.tex2_facemask[v_off] & (1 << face))\n         face_data.tex2 = mm->input.tex2_replace[v_off];\n   }\n\n   color_face = STBVOX_ROTATE(face, rot.ecolor);\n   if (mm->input.extended_color) {\n      unsigned char ec = mm->input.extended_color[v_off];\n      if (mm->input.ecolor_facemask[ec] & (1 << color_face))\n         face_data.color = mm->input.ecolor_color[ec];\n   }\n\n   if (mm->input.color2) {\n      if (mm->input.color2_facemask[v_off] & (1 << color_face))\n         face_data.color = mm->input.color2[v_off];\n      if (mm->input.color3 && (mm->input.color3_facemask[v_off] & (1 << color_face)))\n         face_data.color = mm->input.color3[v_off];\n   }\n   #endif\n\n   face_data.face_info = (normal<<2) + facerot;\n   return face_data;\n}\n\n// these are the types of faces each block can have\nenum\n{\n   STBVOX_FT_none    ,\n   STBVOX_FT_upper   ,\n   STBVOX_FT_lower   ,\n   STBVOX_FT_solid   ,\n   STBVOX_FT_diag_012,\n   STBVOX_FT_diag_023,\n   STBVOX_FT_diag_013,\n   STBVOX_FT_diag_123,\n   STBVOX_FT_force   , // can't be covered up, used for internal faces, also hides nothing\n   STBVOX_FT_partial , // only covered by solid, never covers anything else\n\n   STBVOX_FT_count\n};\n\nstatic unsigned char stbvox_face_lerp[6] = { 0,2,0,2,4,4 };\nstatic unsigned char stbvox_vert3_lerp[5] = { 0,3,6,9,12 };\nstatic unsigned char stbvox_vert_lerp_for_face_lerp[4] = { 0, 4, 7, 7 };\nstatic unsigned char stbvox_face3_lerp[6] = { 0,3,6,9,12,14 };\nstatic unsigned char stbvox_vert_lerp_for_simple[4] = { 0,2,5,7 };\nstatic unsigned char stbvox_face3_updown[8] = { 0,2,5,7,0,2,5,7 }; // ignore top bit\n\n// vertex offsets for face vertices\nstatic unsigned char stbvox_vertex_vector[6][4][3] =\n{\n   { { 1,0,1 }, { 1,1,1 }, { 1,1,0 }, { 1,0,0 } }, // east\n   { { 1,1,1 }, { 0,1,1 }, { 0,1,0 }, { 1,1,0 } }, // north\n   { { 0,1,1 }, { 0,0,1 }, { 0,0,0 }, { 0,1,0 } }, // west\n   { { 0,0,1 }, { 1,0,1 }, { 1,0,0 }, { 0,0,0 } }, // south\n   { { 0,1,1 }, { 1,1,1 }, { 1,0,1 }, { 0,0,1 } }, // up\n   { { 0,0,0 }, { 1,0,0 }, { 1,1,0 }, { 0,1,0 } }, // down\n};\n\n// stbvox_vertex_vector, but read coordinates as binary numbers, zyx\nstatic unsigned char stbvox_vertex_selector[6][4] =\n{\n   { 5,7,3,1 },\n   { 7,6,2,3 },\n   { 6,4,0,2 },\n   { 4,5,1,0 },\n   { 6,7,5,4 },\n   { 0,1,3,2 },\n};\n\nstatic stbvox_mesh_vertex stbvox_vmesh_delta_normal[6][4] =\n{\n   {  stbvox_vertex_encode(1,0,1,0,0) ,\n      stbvox_vertex_encode(1,1,1,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0)  },\n   {  stbvox_vertex_encode(1,1,1,0,0) ,\n      stbvox_vertex_encode(0,1,1,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0)  },\n   {  stbvox_vertex_encode(0,1,1,0,0) ,\n      stbvox_vertex_encode(0,0,1,0,0) ,\n      stbvox_vertex_encode(0,0,0,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0)  },\n   {  stbvox_vertex_encode(0,0,1,0,0) ,\n      stbvox_vertex_encode(1,0,1,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(0,0,0,0,0)  },\n   {  stbvox_vertex_encode(0,1,1,0,0) ,\n      stbvox_vertex_encode(1,1,1,0,0) ,\n      stbvox_vertex_encode(1,0,1,0,0) ,\n      stbvox_vertex_encode(0,0,1,0,0)  },\n   {  stbvox_vertex_encode(0,0,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0)  }\n};\n\nstatic stbvox_mesh_vertex stbvox_vmesh_pre_vheight[6][4] =\n{\n   {  stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0)  },\n   {  stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0)  },\n   {  stbvox_vertex_encode(0,1,0,0,0) ,\n      stbvox_vertex_encode(0,0,0,0,0) ,\n      stbvox_vertex_encode(0,0,0,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0)  },\n   {  stbvox_vertex_encode(0,0,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(0,0,0,0,0)  },\n   {  stbvox_vertex_encode(0,1,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(0,0,0,0,0)  },\n   {  stbvox_vertex_encode(0,0,0,0,0) ,\n      stbvox_vertex_encode(1,0,0,0,0) ,\n      stbvox_vertex_encode(1,1,0,0,0) ,\n      stbvox_vertex_encode(0,1,0,0,0)  }\n};\n\nstatic stbvox_mesh_vertex stbvox_vmesh_delta_half_z[6][4] =\n{\n   { stbvox_vertex_encode(1,0,2,0,0) ,\n     stbvox_vertex_encode(1,1,2,0,0) ,\n     stbvox_vertex_encode(1,1,0,0,0) ,\n     stbvox_vertex_encode(1,0,0,0,0)  },\n   { stbvox_vertex_encode(1,1,2,0,0) ,\n     stbvox_vertex_encode(0,1,2,0,0) ,\n     stbvox_vertex_encode(0,1,0,0,0) ,\n     stbvox_vertex_encode(1,1,0,0,0)  },\n   { stbvox_vertex_encode(0,1,2,0,0) ,\n     stbvox_vertex_encode(0,0,2,0,0) ,\n     stbvox_vertex_encode(0,0,0,0,0) ,\n     stbvox_vertex_encode(0,1,0,0,0)  },\n   { stbvox_vertex_encode(0,0,2,0,0) ,\n     stbvox_vertex_encode(1,0,2,0,0) ,\n     stbvox_vertex_encode(1,0,0,0,0) ,\n     stbvox_vertex_encode(0,0,0,0,0)  },\n   { stbvox_vertex_encode(0,1,2,0,0) ,\n     stbvox_vertex_encode(1,1,2,0,0) ,\n     stbvox_vertex_encode(1,0,2,0,0) ,\n     stbvox_vertex_encode(0,0,2,0,0)  },\n   { stbvox_vertex_encode(0,0,0,0,0) ,\n     stbvox_vertex_encode(1,0,0,0,0) ,\n     stbvox_vertex_encode(1,1,0,0,0) ,\n     stbvox_vertex_encode(0,1,0,0,0)  }\n};\n\nstatic stbvox_mesh_vertex stbvox_vmesh_crossed_pair[6][4] =\n{\n   { stbvox_vertex_encode(1,0,2,0,0) ,\n     stbvox_vertex_encode(0,1,2,0,0) ,\n     stbvox_vertex_encode(0,1,0,0,0) ,\n     stbvox_vertex_encode(1,0,0,0,0)  },\n   { stbvox_vertex_encode(1,1,2,0,0) ,\n     stbvox_vertex_encode(0,0,2,0,0) ,\n     stbvox_vertex_encode(0,0,0,0,0) ,\n     stbvox_vertex_encode(1,1,0,0,0)  },\n   { stbvox_vertex_encode(0,1,2,0,0) ,\n     stbvox_vertex_encode(1,0,2,0,0) ,\n     stbvox_vertex_encode(1,0,0,0,0) ,\n     stbvox_vertex_encode(0,1,0,0,0)  },\n   { stbvox_vertex_encode(0,0,2,0,0) ,\n     stbvox_vertex_encode(1,1,2,0,0) ,\n     stbvox_vertex_encode(1,1,0,0,0) ,\n     stbvox_vertex_encode(0,0,0,0,0)  },\n   // not used, so we leave it non-degenerate to make sure it doesn't get gen'd accidentally\n   { stbvox_vertex_encode(0,1,2,0,0) ,\n     stbvox_vertex_encode(1,1,2,0,0) ,\n     stbvox_vertex_encode(1,0,2,0,0) ,\n     stbvox_vertex_encode(0,0,2,0,0)  },\n   { stbvox_vertex_encode(0,0,0,0,0) ,\n     stbvox_vertex_encode(1,0,0,0,0) ,\n     stbvox_vertex_encode(1,1,0,0,0) ,\n     stbvox_vertex_encode(0,1,0,0,0)  }\n};\n\n#define STBVOX_MAX_GEOM     16\n#define STBVOX_NUM_ROTATION  4\n\n// this is used to determine if a face is ever generated at all\nstatic unsigned char stbvox_hasface[STBVOX_MAX_GEOM][STBVOX_NUM_ROTATION] =\n{\n   { 0,0,0,0 }, // empty\n   { 0,0,0,0 }, // knockout\n   { 63,63,63,63 }, // solid\n   { 63,63,63,63 }, // transp\n   { 63,63,63,63 }, // slab\n   { 63,63,63,63 }, // slab\n   { 1|2|4|48, 8|1|2|48, 4|8|1|48, 2|4|8|48, }, // floor slopes\n   { 1|2|4|48, 8|1|2|48, 4|8|1|48, 2|4|8|48, }, // ceil slopes\n   { 47,47,47,47 }, // wall-projected diagonal with down face\n   { 31,31,31,31 }, // wall-projected diagonal with up face\n   { 63,63,63,63 }, // crossed-pair has special handling, but avoid early-out\n   { 63,63,63,63 }, // force\n   { 63,63,63,63 }, // vheight\n   { 63,63,63,63 }, // vheight\n   { 63,63,63,63 }, // vheight\n   { 63,63,63,63 }, // vheight\n};\n\n// this determines which face type above is visible on each side of the geometry\nstatic unsigned char stbvox_facetype[STBVOX_GEOM_count][6] =\n{\n   { 0, },  // STBVOX_GEOM_empty\n   { STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid }, // knockout\n   { STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid, STBVOX_FT_solid }, // solid\n   { STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force }, // transp\n\n   { STBVOX_FT_upper, STBVOX_FT_upper, STBVOX_FT_upper, STBVOX_FT_upper, STBVOX_FT_solid, STBVOX_FT_force },\n   { STBVOX_FT_lower, STBVOX_FT_lower, STBVOX_FT_lower, STBVOX_FT_lower, STBVOX_FT_force, STBVOX_FT_solid },\n   { STBVOX_FT_diag_123, STBVOX_FT_solid, STBVOX_FT_diag_023, STBVOX_FT_none, STBVOX_FT_force, STBVOX_FT_solid },\n   { STBVOX_FT_diag_012, STBVOX_FT_solid, STBVOX_FT_diag_013, STBVOX_FT_none, STBVOX_FT_solid, STBVOX_FT_force },\n\n   { STBVOX_FT_diag_123, STBVOX_FT_solid, STBVOX_FT_diag_023, STBVOX_FT_force, STBVOX_FT_none, STBVOX_FT_solid },\n   { STBVOX_FT_diag_012, STBVOX_FT_solid, STBVOX_FT_diag_013, STBVOX_FT_force, STBVOX_FT_solid, STBVOX_FT_none },\n   { STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, 0,0 }, // crossed pair\n   { STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force, STBVOX_FT_force }, // GEOM_force\n\n   { STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial, STBVOX_FT_force, STBVOX_FT_solid }, // floor vheight, all neighbors forced\n   { STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial, STBVOX_FT_force, STBVOX_FT_solid }, // floor vheight, all neighbors forced\n   { STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial, STBVOX_FT_solid, STBVOX_FT_force }, // ceil vheight, all neighbors forced\n   { STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial,STBVOX_FT_partial, STBVOX_FT_solid, STBVOX_FT_force }, // ceil vheight, all neighbors forced\n};\n\n// This table indicates what normal to use for the \"up\" face of a sloped geom\n// @TODO this could be done with math given the current arrangement of the enum, but let's not require it\nstatic unsigned char stbvox_floor_slope_for_rot[4] =\n{\n   STBVF_su,\n   STBVF_wu, // @TODO: why is this reversed from what it should be? this is a north-is-up face, so slope should be south&up\n   STBVF_nu,\n   STBVF_eu,\n};\n\nstatic unsigned char stbvox_ceil_slope_for_rot[4] =\n{\n   STBVF_sd,\n   STBVF_ed,\n   STBVF_nd,\n   STBVF_wd,\n};\n\n// this table indicates whether, for each pair of types above, a face is visible.\n// each value indicates whether a given type is visible for all neighbor types\nstatic unsigned short stbvox_face_visible[STBVOX_FT_count] =\n{\n   // we encode the table by listing which cases cause *obscuration*, and bitwise inverting that\n   // table is pre-shifted by 5 to save a shift when it's accessed\n   (unsigned short) ((~0x07ffu                                          )<<5),  // none is completely obscured by everything\n   (unsigned short) ((~((1u<<STBVOX_FT_solid) | (1<<STBVOX_FT_upper)   ))<<5),  // upper\n   (unsigned short) ((~((1u<<STBVOX_FT_solid) | (1<<STBVOX_FT_lower)   ))<<5),  // lower\n   (unsigned short) ((~((1u<<STBVOX_FT_solid)                          ))<<5),  // solid is only completely obscured only by solid\n   (unsigned short) ((~((1u<<STBVOX_FT_solid) | (1<<STBVOX_FT_diag_013)))<<5),  // diag012 matches diag013\n   (unsigned short) ((~((1u<<STBVOX_FT_solid) | (1<<STBVOX_FT_diag_123)))<<5),  // diag023 matches diag123\n   (unsigned short) ((~((1u<<STBVOX_FT_solid) | (1<<STBVOX_FT_diag_012)))<<5),  // diag013 matches diag012\n   (unsigned short) ((~((1u<<STBVOX_FT_solid) | (1<<STBVOX_FT_diag_023)))<<5),  // diag123 matches diag023\n   (unsigned short) ((~0u                                               )<<5),  // force is always rendered regardless, always forces neighbor\n   (unsigned short) ((~((1u<<STBVOX_FT_solid)                          ))<<5),  // partial is only completely obscured only by solid\n};\n\n// the vertex heights of the block types, in binary vertex order (zyx):\n// lower: SW, SE, NW, NE; upper: SW, SE, NW, NE\nstatic stbvox_mesh_vertex stbvox_geometry_vheight[8][8] =\n{\n   #define STBVOX_HEIGHTS(a,b,c,d,e,f,g,h) \\\n     { stbvox_vertex_encode(0,0,a,0,0),  \\\n       stbvox_vertex_encode(0,0,b,0,0),  \\\n       stbvox_vertex_encode(0,0,c,0,0),  \\\n       stbvox_vertex_encode(0,0,d,0,0),  \\\n       stbvox_vertex_encode(0,0,e,0,0),  \\\n       stbvox_vertex_encode(0,0,f,0,0),  \\\n       stbvox_vertex_encode(0,0,g,0,0),  \\\n       stbvox_vertex_encode(0,0,h,0,0) }\n\n   STBVOX_HEIGHTS(0,0,0,0, 2,2,2,2),\n   STBVOX_HEIGHTS(0,0,0,0, 2,2,2,2),\n   STBVOX_HEIGHTS(0,0,0,0, 2,2,2,2),\n   STBVOX_HEIGHTS(0,0,0,0, 2,2,2,2),\n   STBVOX_HEIGHTS(1,1,1,1, 2,2,2,2),\n   STBVOX_HEIGHTS(0,0,0,0, 1,1,1,1),\n   STBVOX_HEIGHTS(0,0,0,0, 0,0,2,2),\n   STBVOX_HEIGHTS(2,2,0,0, 2,2,2,2),\n};\n\n// rotate vertices defined as [z][y][x] coords\nstatic unsigned char stbvox_rotate_vertex[8][4] =\n{\n   { 0,1,3,2 }, // zyx=000\n   { 1,3,2,0 }, // zyx=001\n   { 2,0,1,3 }, // zyx=010\n   { 3,2,0,1 }, // zyx=011\n   { 4,5,7,6 }, // zyx=100\n   { 5,7,6,4 }, // zyx=101\n   { 6,4,5,7 }, // zyx=110\n   { 7,6,4,5 }, // zyx=111\n};\n\n#ifdef STBVOX_CONFIG_OPTIMIZED_VHEIGHT\n// optimized vheight generates a single normal over the entire face, even if it's not planar\nstatic unsigned char stbvox_optimized_face_up_normal[4][4][4][4] =\n{\n   {\n      {\n         { STBVF_u   , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n         { STBVF_nw_u, STBVF_nu  , STBVF_nu  , STBVF_ne_u, },\n         { STBVF_nw_u, STBVF_nu  , STBVF_nu  , STBVF_nu  , },\n         { STBVF_nw_u, STBVF_nw_u, STBVF_nu  , STBVF_nu  , },\n      },{\n         { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n         { STBVF_u   , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n         { STBVF_nw_u, STBVF_nu  , STBVF_nu  , STBVF_ne_u, },\n         { STBVF_nw_u, STBVF_nu  , STBVF_nu  , STBVF_nu  , },\n      },{\n         { STBVF_eu  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n         { STBVF_u   , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n         { STBVF_nw_u, STBVF_nu  , STBVF_nu  , STBVF_ne_u, },\n      },{\n         { STBVF_eu  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_eu  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n         { STBVF_u   , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n      },\n   },{\n      {\n         { STBVF_sw_u, STBVF_u   , STBVF_ne_u, STBVF_ne_u, },\n         { STBVF_wu  , STBVF_nw_u, STBVF_nu  , STBVF_nu  , },\n         { STBVF_wu  , STBVF_nw_u, STBVF_nu  , STBVF_nu  , },\n         { STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, STBVF_nu  , },\n      },{\n         { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_u   , STBVF_ne_u, STBVF_ne_u, },\n         { STBVF_wu  , STBVF_nw_u, STBVF_nu  , STBVF_nu  , },\n         { STBVF_wu  , STBVF_nw_u, STBVF_nu  , STBVF_nu  , },\n      },{\n         { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_u   , STBVF_ne_u, STBVF_ne_u, },\n         { STBVF_wu  , STBVF_nw_u, STBVF_nu  , STBVF_nu  , },\n      },{\n         { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_u   , STBVF_ne_u, STBVF_ne_u, },\n      },\n   },{\n      {\n         { STBVF_sw_u, STBVF_sw_u, STBVF_u   , STBVF_ne_u, },\n         { STBVF_wu  , STBVF_wu  , STBVF_nw_u, STBVF_nu  , },\n         { STBVF_wu  , STBVF_wu  , STBVF_nw_u, STBVF_nu  , },\n         { STBVF_wu  , STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, },\n      },{\n         { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_sw_u, STBVF_u   , STBVF_ne_u, },\n         { STBVF_wu  , STBVF_wu  , STBVF_nw_u, STBVF_nu  , },\n         { STBVF_wu  , STBVF_wu  , STBVF_nw_u, STBVF_nu  , },\n      },{\n         { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_sw_u, STBVF_u   , STBVF_ne_u, },\n         { STBVF_wu  , STBVF_wu  , STBVF_nw_u, STBVF_nu  , },\n      },{\n         { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n         { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_sw_u, STBVF_u   , STBVF_ne_u, },\n      },\n   },{\n      {\n         { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_u   , },\n         { STBVF_sw_u, STBVF_wu  , STBVF_wu  , STBVF_nw_u, },\n         { STBVF_wu  , STBVF_wu  , STBVF_wu  , STBVF_nw_u, },\n         { STBVF_wu  , STBVF_wu  , STBVF_nw_u, STBVF_nw_u, },\n      },{\n         { STBVF_sw_u, STBVF_su  , STBVF_su  , STBVF_su  , },\n         { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_u   , },\n         { STBVF_sw_u, STBVF_wu  , STBVF_wu  , STBVF_nw_u, },\n         { STBVF_wu  , STBVF_wu  , STBVF_wu  , STBVF_nw_u, },\n      },{\n         { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_su  , STBVF_su  , STBVF_su  , },\n         { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_u   , },\n         { STBVF_sw_u, STBVF_wu  , STBVF_wu  , STBVF_nw_u, },\n      },{\n         { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n         { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n         { STBVF_sw_u, STBVF_su  , STBVF_su  , STBVF_su  , },\n         { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_u   , },\n      },\n   },\n};\n#else\n// which normal to use for a given vheight that's planar\n// @TODO: this table was constructed by hand and may have bugs\n//                                 nw se sw\nstatic unsigned char stbvox_planar_face_up_normal[4][4][4] =\n{\n   {                                                      // sw,se,nw,ne;  ne = se+nw-sw\n      { STBVF_u   , 0         , 0         , 0          }, //  0,0,0,0; 1,0,0,-1; 2,0,0,-2; 3,0,0,-3;\n      { STBVF_u   , STBVF_u   , 0         , 0          }, //  0,1,0,1; 1,1,0, 0; 2,1,0,-1; 3,1,0,-2;\n      { STBVF_wu  , STBVF_nw_u, STBVF_nu  , 0          }, //  0,2,0,2; 1,2,0, 1; 2,2,0, 0; 3,2,0,-1;\n      { STBVF_wu  , STBVF_nw_u, STBVF_nw_u, STBVF_nu   }, //  0,3,0,3; 1,3,0, 2; 2,3,0, 1; 3,3,0, 0;\n   },{\n      { STBVF_u   , STBVF_u   , 0         , 0          }, //  0,0,1,1; 1,0,1, 0; 2,0,1,-1; 3,0,1,-2;\n      { STBVF_sw_u, STBVF_u   , STBVF_ne_u, 0          }, //  0,1,1,2; 1,1,1, 1; 2,1,1, 0; 3,1,1,-1;\n      { STBVF_sw_u, STBVF_u   , STBVF_u   , STBVF_ne_u }, //  0,2,1,3; 1,2,1, 2; 2,2,1, 1; 3,2,1, 0;\n      { 0         , STBVF_wu  , STBVF_nw_u, STBVF_nu   }, //  0,3,1,4; 1,3,1, 3; 2,3,1, 2; 3,3,1, 1;\n   },{\n      { STBVF_su  , STBVF_se_u, STBVF_eu  , 0          }, //  0,0,2,2; 1,0,2, 1; 2,0,2, 0; 3,0,2,-1;\n      { STBVF_sw_u, STBVF_u   , STBVF_u   , STBVF_ne_u }, //  0,1,2,3; 1,1,2, 2; 2,1,2, 1; 3,1,2, 0;\n      { 0         , STBVF_sw_u, STBVF_u   , STBVF_ne_u }, //  0,2,2,4; 1,2,2, 3; 2,2,2, 2; 3,2,2, 1;\n      { 0         , 0         , STBVF_u   , STBVF_u    }, //  0,3,2,5; 1,3,2, 4; 2,3,2, 3; 3,3,2, 2;\n   },{\n      { STBVF_su  , STBVF_se_u, STBVF_se_u, STBVF_eu   }, //  0,0,3,3; 1,0,3, 2; 2,0,3, 1; 3,0,3, 0;\n      { 0         , STBVF_su  , STBVF_se_u, STBVF_eu   }, //  0,1,3,4; 1,1,3, 3; 2,1,3, 2; 3,1,3, 1;\n      { 0         , 0         , STBVF_u   , STBVF_u    }, //  0,2,3,5; 1,2,3, 4; 2,2,3, 3; 3,2,3, 2;\n      { 0         , 0         , 0         , STBVF_u    }, //  0,3,3,6; 1,3,3, 5; 2,3,3, 4; 3,3,3, 3;\n   }\n};\n\n// these tables were constructed automatically using a variant of the code\n// below; however, they seem wrong, so who knows\nstatic unsigned char stbvox_face_up_normal_012[4][4][4] =\n{\n   {\n      { STBVF_u   , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_wu  , STBVF_nu  , STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_wu  , STBVF_nw_u, STBVF_nu  , STBVF_ne_u, },\n      { STBVF_wu  , STBVF_nw_u, STBVF_nw_u, STBVF_nu  , },\n   },{\n      { STBVF_su  , STBVF_eu  , STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_sw_u, STBVF_u   , STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_sw_u, STBVF_wu  , STBVF_nu  , STBVF_ne_u, },\n      { STBVF_sw_u, STBVF_wu  , STBVF_nw_u, STBVF_nu  , },\n   },{\n      { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n      { STBVF_sw_u, STBVF_su  , STBVF_eu  , STBVF_ne_u, },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_u   , STBVF_ne_u, },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_wu  , STBVF_nu  , },\n   },{\n      { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n      { STBVF_sw_u, STBVF_su  , STBVF_eu  , STBVF_eu  , },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_su  , STBVF_eu  , },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_u   , },\n   }\n};\n\nstatic unsigned char stbvox_face_up_normal_013[4][4][4] =\n{\n   {\n      { STBVF_u   , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n      { STBVF_nw_u, STBVF_nu  , STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_nw_u, STBVF_nw_u, STBVF_nu  , STBVF_ne_u, },\n      { STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, STBVF_nu  , },\n   },{\n      { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n      { STBVF_wu  , STBVF_u   , STBVF_eu  , STBVF_eu  , },\n      { STBVF_nw_u, STBVF_nw_u, STBVF_nu  , STBVF_ne_u, },\n      { STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, STBVF_nu  , },\n   },{\n      { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n      { STBVF_sw_u, STBVF_su  , STBVF_eu  , STBVF_eu  , },\n      { STBVF_wu  , STBVF_wu  , STBVF_u   , STBVF_eu  , },\n      { STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, STBVF_nu  , },\n   },{\n      { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_eu  , },\n      { STBVF_sw_u, STBVF_su  , STBVF_su  , STBVF_su  , },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_su  , STBVF_eu  , },\n      { STBVF_wu  , STBVF_wu  , STBVF_wu  , STBVF_u   , },\n   }\n};\n\nstatic unsigned char stbvox_face_up_normal_023[4][4][4] =\n{\n   {\n      { STBVF_u   , STBVF_nu  , STBVF_nu  , STBVF_nu  , },\n      { STBVF_eu  , STBVF_eu  , STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n      { STBVF_eu  , STBVF_eu  , STBVF_eu  , STBVF_eu  , },\n   },{\n      { STBVF_wu  , STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, },\n      { STBVF_su  , STBVF_u   , STBVF_nu  , STBVF_nu  , },\n      { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n      { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n   },{\n      { STBVF_wu  , STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, },\n      { STBVF_sw_u, STBVF_wu  , STBVF_nw_u, STBVF_nw_u, },\n      { STBVF_su  , STBVF_su  , STBVF_u   , STBVF_nu  , },\n      { STBVF_su  , STBVF_su  , STBVF_eu  , STBVF_eu  , },\n   },{\n      { STBVF_wu  , STBVF_nw_u, STBVF_nw_u, STBVF_nw_u, },\n      { STBVF_sw_u, STBVF_wu  , STBVF_nw_u, STBVF_nw_u, },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_wu  , STBVF_nw_u, },\n      { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_u   , },\n   }\n};\n\nstatic unsigned char stbvox_face_up_normal_123[4][4][4] =\n{\n   {\n      { STBVF_u   , STBVF_nu  , STBVF_nu  , STBVF_nu  , },\n      { STBVF_eu  , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_eu  , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_eu  , STBVF_ne_u, STBVF_ne_u, STBVF_ne_u, },\n   },{\n      { STBVF_sw_u, STBVF_wu  , STBVF_nw_u, STBVF_nw_u, },\n      { STBVF_su  , STBVF_u   , STBVF_nu  , STBVF_nu  , },\n      { STBVF_eu  , STBVF_eu  , STBVF_ne_u, STBVF_ne_u, },\n      { STBVF_eu  , STBVF_eu  , STBVF_ne_u, STBVF_ne_u, },\n   },{\n      { STBVF_sw_u, STBVF_sw_u, STBVF_wu  , STBVF_nw_u, },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_wu  , STBVF_nw_u, },\n      { STBVF_su  , STBVF_su  , STBVF_u   , STBVF_nu  , },\n      { STBVF_su  , STBVF_eu  , STBVF_eu  , STBVF_ne_u, },\n   },{\n      { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_wu  , },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_wu  , },\n      { STBVF_sw_u, STBVF_sw_u, STBVF_sw_u, STBVF_wu  , },\n      { STBVF_su  , STBVF_su  , STBVF_su  , STBVF_u   , },\n   }\n};\n#endif\n\nvoid stbvox_get_quad_vertex_pointer(stbvox_mesh_maker *mm, int mesh, stbvox_mesh_vertex **vertices, stbvox_mesh_face face)\n{\n   char *p = mm->output_cur[mesh][0];\n   int step = mm->output_step[mesh][0];\n\n   // allocate a new quad from the mesh\n   vertices[0] = (stbvox_mesh_vertex *) p; p += step;\n   vertices[1] = (stbvox_mesh_vertex *) p; p += step;\n   vertices[2] = (stbvox_mesh_vertex *) p; p += step;\n   vertices[3] = (stbvox_mesh_vertex *) p; p += step;\n   mm->output_cur[mesh][0] = p;\n\n   // output the face\n   #ifdef STBVOX_ICONFIG_FACE_ATTRIBUTE\n      // write face as interleaved vertex data\n      *(stbvox_mesh_face *) (vertices[0]+1) = face;\n      *(stbvox_mesh_face *) (vertices[1]+1) = face;\n      *(stbvox_mesh_face *) (vertices[2]+1) = face;\n      *(stbvox_mesh_face *) (vertices[3]+1) = face;\n   #else\n      *(stbvox_mesh_face *) mm->output_cur[mesh][1] = face;\n      mm->output_cur[mesh][1] += 4;\n   #endif\n}\n\nvoid stbvox_make_mesh_for_face(stbvox_mesh_maker *mm, stbvox_rotate rot, int face, int v_off, stbvox_pos pos, stbvox_mesh_vertex vertbase, stbvox_mesh_vertex *face_coord, unsigned char mesh, int normal)\n{\n   stbvox_mesh_face face_data = stbvox_compute_mesh_face_value(mm,rot,face,v_off, normal);\n\n   // still need to compute ao & texlerp for each vertex\n\n   // first compute texlerp into p1\n   stbvox_mesh_vertex p1[4] = { 0 };\n\n   #if defined(STBVOX_CONFIG_DOWN_TEXLERP_PACKED) && defined(STBVOX_CONFIG_UP_TEXLERP_PACKED)\n      #define STBVOX_USE_PACKED(f) ((f) == STBVOX_FACE_up || (f) == STBVOX_FACE_down)\n   #elif defined(STBVOX_CONFIG_UP_TEXLERP_PACKED)\n      #define STBVOX_USE_PACKED(f) ((f) == STBVOX_FACE_up                           )\n   #elif defined(STBVOX_CONFIG_DOWN_TEXLERP_PACKED)\n      #define STBVOX_USE_PACKED(f) (                         (f) == STBVOX_FACE_down)\n   #endif\n\n   #if defined(STBVOX_CONFIG_DOWN_TEXLERP_PACKED) || defined(STBVOX_CONFIG_UP_TEXLERP_PACKED)\n   if (STBVOX_USE_PACKED(face)) {\n      if (!mm->input.packed_compact || 0==(mm->input.packed_compact[v_off]&16))\n         goto set_default;\n      p1[0] = (mm->input.packed_compact[v_off + mm->cube_vertex_offset[face][0]] >> 5);\n      p1[1] = (mm->input.packed_compact[v_off + mm->cube_vertex_offset[face][1]] >> 5);\n      p1[2] = (mm->input.packed_compact[v_off + mm->cube_vertex_offset[face][2]] >> 5);\n      p1[3] = (mm->input.packed_compact[v_off + mm->cube_vertex_offset[face][3]] >> 5);\n      p1[0] = stbvox_vertex_encode(0,0,0,0,p1[0]);\n      p1[1] = stbvox_vertex_encode(0,0,0,0,p1[1]);\n      p1[2] = stbvox_vertex_encode(0,0,0,0,p1[2]);\n      p1[3] = stbvox_vertex_encode(0,0,0,0,p1[3]);\n      goto skip;\n   }\n   #endif\n\n   if (mm->input.block_texlerp) {\n      stbvox_block_type bt = mm->input.blocktype[v_off];\n      unsigned char val = mm->input.block_texlerp[bt];\n      p1[0] = p1[1] = p1[2] = p1[3] = stbvox_vertex_encode(0,0,0,0,val);\n   } else if (mm->input.block_texlerp_face) {\n      stbvox_block_type bt = mm->input.blocktype[v_off];\n      unsigned char bt_face = STBVOX_ROTATE(face, rot.block);\n      unsigned char val = mm->input.block_texlerp_face[bt][bt_face];\n      p1[0] = p1[1] = p1[2] = p1[3] = stbvox_vertex_encode(0,0,0,0,val);\n   } else if (mm->input.texlerp_face3) {\n      unsigned char val = (mm->input.texlerp_face3[v_off] >> stbvox_face3_lerp[face]) & 7;\n      if (face >= STBVOX_FACE_up)\n         val = stbvox_face3_updown[val];\n      p1[0] = p1[1] = p1[2] = p1[3] = stbvox_vertex_encode(0,0,0,0,val);\n   } else if (mm->input.texlerp_simple) {\n      unsigned char val = mm->input.texlerp_simple[v_off];\n      unsigned char lerp_face = (val >> 2) & 7;\n      if (lerp_face == face) {\n         p1[0] = (mm->input.texlerp_simple[v_off + mm->cube_vertex_offset[face][0]] >> 5) & 7;\n         p1[1] = (mm->input.texlerp_simple[v_off + mm->cube_vertex_offset[face][1]] >> 5) & 7;\n         p1[2] = (mm->input.texlerp_simple[v_off + mm->cube_vertex_offset[face][2]] >> 5) & 7;\n         p1[3] = (mm->input.texlerp_simple[v_off + mm->cube_vertex_offset[face][3]] >> 5) & 7;\n         p1[0] = stbvox_vertex_encode(0,0,0,0,p1[0]);\n         p1[1] = stbvox_vertex_encode(0,0,0,0,p1[1]);\n         p1[2] = stbvox_vertex_encode(0,0,0,0,p1[2]);\n         p1[3] = stbvox_vertex_encode(0,0,0,0,p1[3]);\n      } else {\n         unsigned char base = stbvox_vert_lerp_for_simple[val&3];\n         p1[0] = p1[1] = p1[2] = p1[3] = stbvox_vertex_encode(0,0,0,0,base);\n      }\n   } else if (mm->input.texlerp) {\n      unsigned char facelerp = (mm->input.texlerp[v_off] >> stbvox_face_lerp[face]) & 3;\n      if (facelerp == STBVOX_TEXLERP_FACE_use_vert) {\n         if (mm->input.texlerp_vert3 && face != STBVOX_FACE_down) {\n            unsigned char shift = stbvox_vert3_lerp[face];\n            p1[0] = (mm->input.texlerp_vert3[mm->cube_vertex_offset[face][0]] >> shift) & 7;\n            p1[1] = (mm->input.texlerp_vert3[mm->cube_vertex_offset[face][1]] >> shift) & 7;\n            p1[2] = (mm->input.texlerp_vert3[mm->cube_vertex_offset[face][2]] >> shift) & 7;\n            p1[3] = (mm->input.texlerp_vert3[mm->cube_vertex_offset[face][3]] >> shift) & 7;\n         } else {\n            p1[0] = stbvox_vert_lerp_for_simple[mm->input.texlerp[mm->cube_vertex_offset[face][0]]>>6];\n            p1[1] = stbvox_vert_lerp_for_simple[mm->input.texlerp[mm->cube_vertex_offset[face][1]]>>6];\n            p1[2] = stbvox_vert_lerp_for_simple[mm->input.texlerp[mm->cube_vertex_offset[face][2]]>>6];\n            p1[3] = stbvox_vert_lerp_for_simple[mm->input.texlerp[mm->cube_vertex_offset[face][3]]>>6];\n         }\n         p1[0] = stbvox_vertex_encode(0,0,0,0,p1[0]);\n         p1[1] = stbvox_vertex_encode(0,0,0,0,p1[1]);\n         p1[2] = stbvox_vertex_encode(0,0,0,0,p1[2]);\n         p1[3] = stbvox_vertex_encode(0,0,0,0,p1[3]);\n      } else {\n         p1[0] = p1[1] = p1[2] = p1[3] = stbvox_vertex_encode(0,0,0,0,stbvox_vert_lerp_for_face_lerp[facelerp]);\n      }\n   } else {\n      #if defined(STBVOX_CONFIG_UP_TEXLERP_PACKED) || defined(STBVOX_CONFIG_DOWN_TEXLERP_PACKED)\n      set_default:\n      #endif\n      p1[0] = p1[1] = p1[2] = p1[3] = stbvox_vertex_encode(0,0,0,0,7); // @TODO make this configurable\n   }\n\n   #if defined(STBVOX_CONFIG_UP_TEXLERP_PACKED) || defined(STBVOX_CONFIG_DOWN_TEXLERP_PACKED)\n   skip:\n   #endif\n\n   // now compute lighting and store to vertices\n   {\n      stbvox_mesh_vertex *mv[4];\n      stbvox_get_quad_vertex_pointer(mm, mesh, mv, face_data);\n\n      if (mm->input.lighting) {\n         // @TODO: lighting at block centers, but not gathered, instead constant-per-face\n         if (mm->input.lighting_at_vertices) {\n            int i;\n            for (i=0; i < 4; ++i) {\n               *mv[i] = vertbase + face_coord[i]\n                          + stbvox_vertex_encode(0,0,0,mm->input.lighting[v_off + mm->cube_vertex_offset[face][i]] & 63,0)\n                          + p1[i];\n            }\n         } else {\n            unsigned char *amb = &mm->input.lighting[v_off];\n            int i,j;\n            #if defined(STBVOX_CONFIG_ROTATION_IN_LIGHTING) || defined(STBVOX_CONFIG_VHEIGHT_IN_LIGHTING)\n            #define STBVOX_GET_LIGHTING(light) ((light) & ~3)\n            #define STBVOX_LIGHTING_ROUNDOFF   8\n            #else\n            #define STBVOX_GET_LIGHTING(light) (light)\n            #define STBVOX_LIGHTING_ROUNDOFF   2\n            #endif\n\n            for (i=0; i < 4; ++i) {\n               // for each vertex, gather from the four neighbor blocks it's facing\n               unsigned char *vamb = &amb[mm->cube_vertex_offset[face][i]];\n               int total=0;\n               for (j=0; j < 4; ++j)\n                  total += STBVOX_GET_LIGHTING(vamb[mm->vertex_gather_offset[face][j]]);\n               *mv[i] = vertbase + face_coord[i]\n                          + stbvox_vertex_encode(0,0,0,(total+STBVOX_LIGHTING_ROUNDOFF)>>4,0)\n                          + p1[i];\n                          // >> 4 is because:\n                          //   >> 2 to divide by 4 to get average over 4 samples\n                          //   >> 2 because input is 8 bits, output is 6 bits\n            }\n\n            // @TODO: note that gathering baked *lighting*\n            // is different from gathering baked ao; baked ao can count\n            // solid blocks as 0 ao, but baked lighting wants average\n            // of non-blocked--not take average & treat blocked as 0. And\n            // we can't bake the right value into the solid blocks\n            // because they can have different lighting values on\n            // different sides. So we need to actually gather and\n            // then divide by 0..4 (which we can do with a table-driven\n            // multiply, or have an 'if' for the 3 case)\n\n         }\n      } else {\n         vertbase += stbvox_vertex_encode(0,0,0,63,0);\n         *mv[0] = vertbase + face_coord[0] + p1[0];\n         *mv[1] = vertbase + face_coord[1] + p1[1];\n         *mv[2] = vertbase + face_coord[2] + p1[2];\n         *mv[3] = vertbase + face_coord[3] + p1[3];\n      }\n   }\n}\n\n// get opposite-facing normal & texgen for opposite face, used to map up-facing vheight data to down-facing data\nstatic unsigned char stbvox_reverse_face[STBVF_count] =\n{\n   STBVF_w, STBVF_s, STBVF_e, STBVF_n, STBVF_d   , STBVF_u   , STBVF_wd, STBVF_wu,\n         0,       0,       0,       0, STBVF_sw_d, STBVF_sw_u, STBVF_sd, STBVF_su,\n         0,       0,       0,       0, STBVF_se_d, STBVF_se_u, STBVF_ed, STBVF_eu,\n         0,       0,       0,       0, STBVF_ne_d, STBVF_ne_d, STBVF_nd, STBVF_nu\n};\n\n#ifndef STBVOX_CONFIG_OPTIMIZED_VHEIGHT\n// render non-planar quads by splitting into two triangles, rendering each as a degenerate quad\nstatic void stbvox_make_12_split_mesh_for_face(stbvox_mesh_maker *mm, stbvox_rotate rot, int face, int v_off, stbvox_pos pos, stbvox_mesh_vertex vertbase, stbvox_mesh_vertex *face_coord, unsigned char mesh, unsigned char *ht)\n{\n   stbvox_mesh_vertex v[4];\n\n   unsigned char normal1 = stbvox_face_up_normal_012[ht[2]][ht[1]][ht[0]];\n   unsigned char normal2 = stbvox_face_up_normal_123[ht[3]][ht[2]][ht[1]];\n\n   if (face == STBVOX_FACE_down) {\n      normal1 = stbvox_reverse_face[normal1];\n      normal2 = stbvox_reverse_face[normal2];\n   }\n\n   // the floor side face_coord is stored in order NW,NE,SE,SW, but ht[] is stored SW,SE,NW,NE\n   v[0] = face_coord[2];\n   v[1] = face_coord[3];\n   v[2] = face_coord[0];\n   v[3] = face_coord[2];\n   stbvox_make_mesh_for_face(mm, rot, face, v_off, pos, vertbase, v, mesh, normal1);\n   v[1] = face_coord[0];\n   v[2] = face_coord[1];\n   stbvox_make_mesh_for_face(mm, rot, face, v_off, pos, vertbase, v, mesh, normal2);\n}\n\nstatic void stbvox_make_03_split_mesh_for_face(stbvox_mesh_maker *mm, stbvox_rotate rot, int face, int v_off, stbvox_pos pos, stbvox_mesh_vertex vertbase, stbvox_mesh_vertex *face_coord, unsigned char mesh, unsigned char *ht)\n{\n   stbvox_mesh_vertex v[4];\n\n   unsigned char normal1 = stbvox_face_up_normal_013[ht[3]][ht[1]][ht[0]];\n   unsigned char normal2 = stbvox_face_up_normal_023[ht[3]][ht[2]][ht[0]];\n\n   if (face == STBVOX_FACE_down) {\n      normal1 = stbvox_reverse_face[normal1];\n      normal2 = stbvox_reverse_face[normal2];\n   }\n\n   v[0] = face_coord[1];\n   v[1] = face_coord[2];\n   v[2] = face_coord[3];\n   v[3] = face_coord[1];\n   stbvox_make_mesh_for_face(mm, rot, face, v_off, pos, vertbase, v, mesh, normal1);\n   v[1] = face_coord[3];\n   v[2] = face_coord[0];\n   stbvox_make_mesh_for_face(mm, rot, face, v_off, pos, vertbase, v, mesh, normal2);  // this one is correct!\n}\n#endif\n\n#ifndef STBVOX_CONFIG_PRECISION_Z\n#define STBVOX_CONFIG_PRECISION_Z 1\n#endif\n\n// simple case for mesh generation: we have only solid and empty blocks\nstatic void stbvox_make_mesh_for_block(stbvox_mesh_maker *mm, stbvox_pos pos, int v_off, stbvox_mesh_vertex *vmesh)\n{\n   int ns_off = mm->y_stride_in_bytes;\n   int ew_off = mm->x_stride_in_bytes;\n\n   unsigned char *blockptr = &mm->input.blocktype[v_off];\n   stbvox_mesh_vertex basevert = stbvox_vertex_encode(pos.x, pos.y, pos.z << STBVOX_CONFIG_PRECISION_Z , 0,0);\n\n   stbvox_rotate rot = { 0,0,0,0 };\n   unsigned char simple_rot = 0;\n\n   unsigned char mesh = mm->default_mesh;\n\n   if (mm->input.selector)\n      mesh = mm->input.selector[v_off];\n   else if (mm->input.block_selector)\n      mesh = mm->input.block_selector[mm->input.blocktype[v_off]];\n\n   // check if we're going off the end\n   if (mm->output_cur[mesh][0] + mm->output_size[mesh][0]*6 > mm->output_end[mesh][0]) {\n      mm->full = 1;\n      return;\n   }\n\n   #ifdef STBVOX_CONFIG_ROTATION_IN_LIGHTING\n   simple_rot = mm->input.lighting[v_off] & 3;\n   #endif\n\n   if (mm->input.packed_compact)\n      simple_rot = mm->input.packed_compact[v_off] & 3;\n\n   if (blockptr[ 1]==0) {\n      rot.facerot = simple_rot;\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_up  , v_off, pos, basevert, vmesh+4*STBVOX_FACE_up, mesh, STBVOX_FACE_up);\n   }\n   if (blockptr[-1]==0) {\n      rot.facerot = (-simple_rot) & 3;\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_down, v_off, pos, basevert, vmesh+4*STBVOX_FACE_down, mesh, STBVOX_FACE_down);\n   }\n\n   if (mm->input.rotate) {\n      unsigned char val = mm->input.rotate[v_off];\n      rot.block   = (val >> 0) & 3;\n      rot.overlay = (val >> 2) & 3;\n      //rot.tex2    = (val >> 4) & 3;\n      rot.ecolor  = (val >> 6) & 3;\n   } else {\n      rot.block = rot.overlay = rot.ecolor = simple_rot;\n   }\n   rot.facerot = 0;\n\n   if (blockptr[ ns_off]==0)\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_north, v_off, pos, basevert, vmesh+4*STBVOX_FACE_north, mesh, STBVOX_FACE_north);\n   if (blockptr[-ns_off]==0)\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_south, v_off, pos, basevert, vmesh+4*STBVOX_FACE_south, mesh, STBVOX_FACE_south);\n   if (blockptr[ ew_off]==0)\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_east , v_off, pos, basevert, vmesh+4*STBVOX_FACE_east, mesh, STBVOX_FACE_east);\n   if (blockptr[-ew_off]==0)\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_west , v_off, pos, basevert, vmesh+4*STBVOX_FACE_west, mesh, STBVOX_FACE_west);\n}\n\n// complex case for mesh generation: we have lots of different\n// block types, and we don't want to generate faces of blocks\n// if they're hidden by neighbors.\n//\n// we use lots of tables to determine this: we have a table\n// which tells us what face type is generated for each type of\n// geometry, and then a table that tells us whether that type\n// is hidden by a neighbor.\nstatic void stbvox_make_mesh_for_block_with_geo(stbvox_mesh_maker *mm, stbvox_pos pos, int v_off)\n{\n   int ns_off = mm->y_stride_in_bytes;\n   int ew_off = mm->x_stride_in_bytes;\n   int visible_faces, visible_base;\n   unsigned char mesh;\n\n   // first gather the geometry info for this block and all neighbors\n\n   unsigned char bt, nbt[6];\n   unsigned char geo, ngeo[6];\n   unsigned char rot, nrot[6];\n\n   bt = mm->input.blocktype[v_off];\n   nbt[0] = mm->input.blocktype[v_off + ew_off];\n   nbt[1] = mm->input.blocktype[v_off + ns_off];\n   nbt[2] = mm->input.blocktype[v_off - ew_off];\n   nbt[3] = mm->input.blocktype[v_off - ns_off];\n   nbt[4] = mm->input.blocktype[v_off +      1];\n   nbt[5] = mm->input.blocktype[v_off -      1];\n   if (mm->input.geometry) {\n      int i;\n      geo = mm->input.geometry[v_off];\n      ngeo[0] = mm->input.geometry[v_off + ew_off];\n      ngeo[1] = mm->input.geometry[v_off + ns_off];\n      ngeo[2] = mm->input.geometry[v_off - ew_off];\n      ngeo[3] = mm->input.geometry[v_off - ns_off];\n      ngeo[4] = mm->input.geometry[v_off +      1];\n      ngeo[5] = mm->input.geometry[v_off -      1];\n\n      rot = (geo >> 4) & 3;\n      geo &= 15;\n      for (i=0; i < 6; ++i) {\n         nrot[i] = (ngeo[i] >> 4) & 3;\n         ngeo[i] &= 15;\n      }\n   } else {\n      int i;\n      assert(mm->input.block_geometry);\n      geo = mm->input.block_geometry[bt];\n      for (i=0; i < 6; ++i)\n         ngeo[i] = mm->input.block_geometry[nbt[i]];\n      if (mm->input.selector) {\n         #ifndef STBVOX_CONFIG_ROTATION_IN_LIGHTING\n         if (mm->input.packed_compact == NULL) {\n            rot     = (mm->input.selector[v_off         ] >> 4) & 3;\n            nrot[0] = (mm->input.selector[v_off + ew_off] >> 4) & 3;\n            nrot[1] = (mm->input.selector[v_off + ns_off] >> 4) & 3;\n            nrot[2] = (mm->input.selector[v_off - ew_off] >> 4) & 3;\n            nrot[3] = (mm->input.selector[v_off - ns_off] >> 4) & 3;\n            nrot[4] = (mm->input.selector[v_off +      1] >> 4) & 3;\n            nrot[5] = (mm->input.selector[v_off -      1] >> 4) & 3;\n         }\n         #endif\n      } else {\n         #ifndef STBVOX_CONFIG_ROTATION_IN_LIGHTING\n         if (mm->input.packed_compact == NULL) {\n            rot = (geo>>4)&3;\n            geo &= 15;\n            for (i=0; i < 6; ++i) {\n               nrot[i] = (ngeo[i]>>4)&3;\n               ngeo[i] &= 15;\n            }\n         }\n         #endif\n      }\n   }\n\n   #ifndef STBVOX_CONFIG_ROTATION_IN_LIGHTING\n   if (mm->input.packed_compact) {\n      rot = mm->input.packed_compact[rot] & 3;\n      nrot[0] = mm->input.packed_compact[v_off + ew_off] & 3;\n      nrot[1] = mm->input.packed_compact[v_off + ns_off] & 3;\n      nrot[2] = mm->input.packed_compact[v_off - ew_off] & 3;\n      nrot[3] = mm->input.packed_compact[v_off - ns_off] & 3;\n      nrot[4] = mm->input.packed_compact[v_off +      1] & 3;\n      nrot[5] = mm->input.packed_compact[v_off -      1] & 3;\n   }\n   #else\n   rot = mm->input.lighting[v_off] & 3;\n   nrot[0] = (mm->input.lighting[v_off + ew_off]) & 3;\n   nrot[1] = (mm->input.lighting[v_off + ns_off]) & 3;\n   nrot[2] = (mm->input.lighting[v_off - ew_off]) & 3;\n   nrot[3] = (mm->input.lighting[v_off - ns_off]) & 3;\n   nrot[4] = (mm->input.lighting[v_off +      1]) & 3;\n   nrot[5] = (mm->input.lighting[v_off -      1]) & 3;\n   #endif\n\n   if (geo == STBVOX_GEOM_transp) {\n      // transparency has a special rule: if the blocktype is the same,\n      // and the faces are compatible, then can hide them; otherwise,\n      // force them on\n      // Note that this means we don't support any transparentshapes other\n      // than solid blocks, since detecting them is too complicated. If\n      // you wanted to do something like minecraft water, you probably\n      // should just do that with a separate renderer anyway. (We don't\n      // support transparency sorting so you need to use alpha test\n      // anyway)\n      int i;\n      for (i=0; i < 6; ++i)\n         if (nbt[i] != bt) {\n            nbt[i] = 0;\n            ngeo[i] = STBVOX_GEOM_empty;\n         } else\n            ngeo[i] = STBVOX_GEOM_solid;\n      geo = STBVOX_GEOM_solid;\n   }\n\n   // now compute the face visibility\n   visible_base = stbvox_hasface[geo][rot];\n   // @TODO: assert(visible_base != 0); // we should have early-outted earlier in this case\n   visible_faces = 0;\n\n   // now, for every face that might be visible, check if neighbor hides it\n   if (visible_base & (1 << STBVOX_FACE_east)) {\n      int  type = stbvox_facetype[ geo   ][(STBVOX_FACE_east+ rot   )&3];\n      int ntype = stbvox_facetype[ngeo[0]][(STBVOX_FACE_west+nrot[0])&3];\n      visible_faces |= ((stbvox_face_visible[type]) >> (ntype + 5 - STBVOX_FACE_east)) & (1 << STBVOX_FACE_east);\n   }\n   if (visible_base & (1 << STBVOX_FACE_north)) {\n      int  type = stbvox_facetype[ geo   ][(STBVOX_FACE_north+ rot   )&3];\n      int ntype = stbvox_facetype[ngeo[1]][(STBVOX_FACE_south+nrot[1])&3];\n      visible_faces |= ((stbvox_face_visible[type]) >> (ntype + 5 - STBVOX_FACE_north)) & (1 << STBVOX_FACE_north);\n   }\n   if (visible_base & (1 << STBVOX_FACE_west)) {\n      int  type = stbvox_facetype[ geo   ][(STBVOX_FACE_west+ rot   )&3];\n      int ntype = stbvox_facetype[ngeo[2]][(STBVOX_FACE_east+nrot[2])&3];\n      visible_faces |= ((stbvox_face_visible[type]) >> (ntype + 5 - STBVOX_FACE_west)) & (1 << STBVOX_FACE_west);\n   }\n   if (visible_base & (1 << STBVOX_FACE_south)) {\n      int  type = stbvox_facetype[ geo   ][(STBVOX_FACE_south+ rot   )&3];\n      int ntype = stbvox_facetype[ngeo[3]][(STBVOX_FACE_north+nrot[3])&3];\n      visible_faces |= ((stbvox_face_visible[type]) >> (ntype + 5 - STBVOX_FACE_south)) & (1 << STBVOX_FACE_south);\n   }\n   if (visible_base & (1 << STBVOX_FACE_up)) {\n      int  type = stbvox_facetype[ geo   ][STBVOX_FACE_up];\n      int ntype = stbvox_facetype[ngeo[4]][STBVOX_FACE_down];\n      visible_faces |= ((stbvox_face_visible[type]) >> (ntype + 5 - STBVOX_FACE_up)) & (1 << STBVOX_FACE_up);\n   }\n   if (visible_base & (1 << STBVOX_FACE_down)) {\n      int  type = stbvox_facetype[ geo   ][STBVOX_FACE_down];\n      int ntype = stbvox_facetype[ngeo[5]][STBVOX_FACE_up];\n      visible_faces |= ((stbvox_face_visible[type]) >> (ntype + 5 - STBVOX_FACE_down)) & (1 << STBVOX_FACE_down);\n   }\n\n   if (geo == STBVOX_GEOM_force)\n      geo = STBVOX_GEOM_solid;\n\n   assert((geo == STBVOX_GEOM_crossed_pair) ? (visible_faces == 15) : 1);\n\n   // now we finally know for sure which faces are getting generated\n   if (visible_faces == 0)\n      return;\n\n   mesh = mm->default_mesh;\n   if (mm->input.selector)\n      mesh = mm->input.selector[v_off];\n   else if (mm->input.block_selector)\n      mesh = mm->input.block_selector[bt];\n\n   if (geo <= STBVOX_GEOM_ceil_slope_north_is_bottom) {\n      // this is the simple case, we can just use regular block gen with special vmesh calculated with vheight\n      stbvox_mesh_vertex basevert;\n      stbvox_mesh_vertex vmesh[6][4];\n      stbvox_rotate rotate = { 0,0,0,0 };\n      unsigned char simple_rot = rot;\n      int i;\n      // we only need to do this for the displayed faces, but it's easier\n      // to just do it up front; @OPTIMIZE check if it's faster to do it\n      // for visible faces only\n      for (i=0; i < 6*4; ++i) {\n         int vert = stbvox_vertex_selector[0][i];\n         vert = stbvox_rotate_vertex[vert][rot];\n         vmesh[0][i] = stbvox_vmesh_pre_vheight[0][i]\n                     + stbvox_geometry_vheight[geo][vert];\n      }\n\n      basevert = stbvox_vertex_encode(pos.x, pos.y, pos.z << STBVOX_CONFIG_PRECISION_Z, 0,0);\n      if (mm->input.selector) {\n         mesh = mm->input.selector[v_off];\n      } else if (mm->input.block_selector)\n         mesh = mm->input.block_selector[bt];\n\n\n      // check if we're going off the end\n      if (mm->output_cur[mesh][0] + mm->output_size[mesh][0]*6 > mm->output_end[mesh][0]) {\n         mm->full = 1;\n         return;\n      }\n\n      if (geo >= STBVOX_GEOM_floor_slope_north_is_top) {\n         if (visible_faces & (1 << STBVOX_FACE_up)) {\n            int normal = geo == STBVOX_GEOM_floor_slope_north_is_top ? stbvox_floor_slope_for_rot[simple_rot] : STBVOX_FACE_up;\n            rotate.facerot = simple_rot;\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_up  , v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, normal);\n         }\n         if (visible_faces & (1 << STBVOX_FACE_down)) {\n            int normal = geo == STBVOX_GEOM_ceil_slope_north_is_bottom ? stbvox_ceil_slope_for_rot[simple_rot] : STBVOX_FACE_down;\n            rotate.facerot = (-rotate.facerot) & 3;\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, normal);\n         }\n      } else {\n         if (visible_faces & (1 << STBVOX_FACE_up)) {\n            rotate.facerot = simple_rot;\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_up  , v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, STBVOX_FACE_up);\n         }\n         if (visible_faces & (1 << STBVOX_FACE_down)) {\n            rotate.facerot = (-rotate.facerot) & 3;\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, STBVOX_FACE_down);\n         }\n      }\n\n      if (mm->input.rotate) {\n         unsigned char val = mm->input.rotate[v_off];\n         rotate.block   = (val >> 0) & 3;\n         rotate.overlay = (val >> 2) & 3;\n         //rotate.tex2    = (val >> 4) & 3;\n         rotate.ecolor  = (val >> 6) & 3;\n      } else {\n         rotate.block = rotate.overlay = rotate.ecolor = simple_rot;\n      }\n\n      rotate.facerot = 0;\n\n      if (visible_faces & (1 << STBVOX_FACE_north))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_north, v_off, pos, basevert, vmesh[STBVOX_FACE_north], mesh, STBVOX_FACE_north);\n      if (visible_faces & (1 << STBVOX_FACE_south))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_south, v_off, pos, basevert, vmesh[STBVOX_FACE_south], mesh, STBVOX_FACE_south);\n      if (visible_faces & (1 << STBVOX_FACE_east))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_east , v_off, pos, basevert, vmesh[STBVOX_FACE_east ], mesh, STBVOX_FACE_east);\n      if (visible_faces & (1 << STBVOX_FACE_west))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_west , v_off, pos, basevert, vmesh[STBVOX_FACE_west ], mesh, STBVOX_FACE_west);\n   }\n   if (geo >= STBVOX_GEOM_floor_vheight_03) {\n      // this case can also be generated with regular block gen with special vmesh,\n      // except:\n      //     if we want to generate middle diagonal for 'weird' blocks\n      //     it's more complicated to detect neighbor matchups\n      stbvox_mesh_vertex vmesh[6][4];\n      stbvox_mesh_vertex cube[8];\n      stbvox_mesh_vertex basevert;\n      stbvox_rotate rotate = { 0,0,0,0 };\n      unsigned char simple_rot = rot;\n      unsigned char ht[4];\n      int extreme;\n\n      // extract the heights\n      #ifdef STBVOX_CONFIG_VHEIGHT_IN_LIGHTING\n      ht[0] = mm->input.lighting[v_off              ] & 3;\n      ht[1] = mm->input.lighting[v_off+ew_off       ] & 3;\n      ht[2] = mm->input.lighting[v_off       +ns_off] & 3;\n      ht[3] = mm->input.lighting[v_off+ew_off+ns_off] & 3;\n      #else\n      if (mm->input.vheight) {\n         unsigned char v =  mm->input.vheight[v_off];\n         ht[0] = (v >> 0) & 3;\n         ht[1] = (v >> 2) & 3;\n         ht[2] = (v >> 4) & 3;\n         ht[3] = (v >> 6) & 3;\n      } else if (mm->input.block_vheight) {\n         unsigned char v = mm->input.block_vheight[bt];\n         unsigned char raw[4];\n         int i;\n\n         raw[0] = (v >> 0) & 3;\n         raw[1] = (v >> 2) & 3;\n         raw[2] = (v >> 4) & 3;\n         raw[3] = (v >> 6) & 3;\n\n         for (i=0; i < 4; ++i)\n            ht[i] = raw[stbvox_rotate_vertex[i][rot]];\n      } else if (mm->input.packed_compact) {\n         ht[0] = (mm->input.packed_compact[v_off              ] >> 2) & 3;\n         ht[1] = (mm->input.packed_compact[v_off+ew_off       ] >> 2) & 3;\n         ht[2] = (mm->input.packed_compact[v_off       +ns_off] >> 2) & 3;\n         ht[3] = (mm->input.packed_compact[v_off+ew_off+ns_off] >> 2) & 3;\n      } else if (mm->input.geometry) {\n         ht[0] = mm->input.geometry[v_off              ] >> 6;\n         ht[1] = mm->input.geometry[v_off+ew_off       ] >> 6;\n         ht[2] = mm->input.geometry[v_off       +ns_off] >> 6;\n         ht[3] = mm->input.geometry[v_off+ew_off+ns_off] >> 6;\n      } else {\n         assert(0);\n      }\n      #endif\n\n      // flag whether any sides go off the top of the block, which means\n      // our visible_faces test was wrong\n      extreme = (ht[0] == 3 || ht[1] == 3 || ht[2] == 3 || ht[3] == 3);\n\n      if (geo >= STBVOX_GEOM_ceil_vheight_03) {\n         cube[0] = stbvox_vertex_encode(0,0,ht[0],0,0);\n         cube[1] = stbvox_vertex_encode(0,0,ht[1],0,0);\n         cube[2] = stbvox_vertex_encode(0,0,ht[2],0,0);\n         cube[3] = stbvox_vertex_encode(0,0,ht[3],0,0);\n         cube[4] = stbvox_vertex_encode(0,0,2,0,0);\n         cube[5] = stbvox_vertex_encode(0,0,2,0,0);\n         cube[6] = stbvox_vertex_encode(0,0,2,0,0);\n         cube[7] = stbvox_vertex_encode(0,0,2,0,0);\n      } else {\n         cube[0] = stbvox_vertex_encode(0,0,0,0,0);\n         cube[1] = stbvox_vertex_encode(0,0,0,0,0);\n         cube[2] = stbvox_vertex_encode(0,0,0,0,0);\n         cube[3] = stbvox_vertex_encode(0,0,0,0,0);\n         cube[4] = stbvox_vertex_encode(0,0,ht[0],0,0);\n         cube[5] = stbvox_vertex_encode(0,0,ht[1],0,0);\n         cube[6] = stbvox_vertex_encode(0,0,ht[2],0,0);\n         cube[7] = stbvox_vertex_encode(0,0,ht[3],0,0);\n      }\n      if (!mm->input.vheight && mm->input.block_vheight) {\n         // @TODO: support block vheight here, I've forgotten what needs to be done specially\n      }\n\n      // build vertex mesh\n      {\n         int i;\n         for (i=0; i < 6*4; ++i) {\n            int vert = stbvox_vertex_selector[0][i];\n            vmesh[0][i] = stbvox_vmesh_pre_vheight[0][i]\n                        + cube[vert];\n         }\n      }\n\n      basevert = stbvox_vertex_encode(pos.x, pos.y, pos.z << STBVOX_CONFIG_PRECISION_Z, 0,0);\n      // check if we're going off the end\n      if (mm->output_cur[mesh][0] + mm->output_size[mesh][0]*6 > mm->output_end[mesh][0]) {\n         mm->full = 1;\n         return;\n      }\n\n      // @TODO generate split faces\n      if (visible_faces & (1 << STBVOX_FACE_up)) {\n         if (geo >= STBVOX_GEOM_ceil_vheight_03)\n            // flat\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_up  , v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, STBVOX_FACE_up);\n         else {\n         #ifndef STBVOX_CONFIG_OPTIMIZED_VHEIGHT\n            // check if it's non-planar\n            if (cube[5] + cube[6] != cube[4] + cube[7]) {\n               // not planar, split along diagonal and make degenerate quads\n               if (geo == STBVOX_GEOM_floor_vheight_03)\n                  stbvox_make_03_split_mesh_for_face(mm, rotate, STBVOX_FACE_up, v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, ht);\n               else\n                  stbvox_make_12_split_mesh_for_face(mm, rotate, STBVOX_FACE_up, v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, ht);\n            } else\n               stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_up  , v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, stbvox_planar_face_up_normal[ht[2]][ht[1]][ht[0]]);\n         #else\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_up  , v_off, pos, basevert, vmesh[STBVOX_FACE_up], mesh, stbvox_optimized_face_up_normal[ht[3]][ht[2]][ht[1]][ht[0]]);\n         #endif\n         }\n      }\n      if (visible_faces & (1 << STBVOX_FACE_down)) {\n         if (geo < STBVOX_GEOM_ceil_vheight_03)\n            // flat\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, STBVOX_FACE_down);\n         else {\n         #ifndef STBVOX_CONFIG_OPTIMIZED_VHEIGHT\n            // check if it's non-planar\n            if (cube[1] + cube[2] != cube[0] + cube[3]) {\n               // not planar, split along diagonal and make degenerate quads\n               if (geo == STBVOX_GEOM_ceil_vheight_03)\n                  stbvox_make_03_split_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, ht);\n               else\n                  stbvox_make_12_split_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, ht);\n            } else\n               stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, stbvox_reverse_face[stbvox_planar_face_up_normal[ht[2]][ht[1]][ht[0]]]);\n         #else\n            stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_down, v_off, pos, basevert, vmesh[STBVOX_FACE_down], mesh, stbvox_reverse_face[stbvox_optimized_face_up_normal[ht[3]][ht[2]][ht[1]][ht[0]]]);\n         #endif\n         }\n      }\n\n      if (mm->input.rotate) {\n         unsigned char val = mm->input.rotate[v_off];\n         rotate.block   = (val >> 0) & 3;\n         rotate.overlay = (val >> 2) & 3;\n         //rotate.tex2    = (val >> 4) & 3;\n         rotate.ecolor  = (val >> 6) & 3;\n      } else if (mm->input.selector) {\n         rotate.block = rotate.overlay = rotate.ecolor = simple_rot;\n      }\n\n      if ((visible_faces & (1 << STBVOX_FACE_north)) || (extreme && (ht[2] == 3 || ht[3] == 3)))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_north, v_off, pos, basevert, vmesh[STBVOX_FACE_north], mesh, STBVOX_FACE_north);\n      if ((visible_faces & (1 << STBVOX_FACE_south)) || (extreme && (ht[0] == 3 || ht[1] == 3)))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_south, v_off, pos, basevert, vmesh[STBVOX_FACE_south], mesh, STBVOX_FACE_south);\n      if ((visible_faces & (1 << STBVOX_FACE_east)) || (extreme && (ht[1] == 3 || ht[3] == 3)))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_east , v_off, pos, basevert, vmesh[STBVOX_FACE_east ], mesh, STBVOX_FACE_east);\n      if ((visible_faces & (1 << STBVOX_FACE_west)) || (extreme && (ht[0] == 3 || ht[2] == 3)))\n         stbvox_make_mesh_for_face(mm, rotate, STBVOX_FACE_west , v_off, pos, basevert, vmesh[STBVOX_FACE_west ], mesh, STBVOX_FACE_west);\n   }\n\n   if (geo == STBVOX_GEOM_crossed_pair) {\n      // this can be generated with a special vmesh\n      stbvox_mesh_vertex basevert = stbvox_vertex_encode(pos.x, pos.y, pos.z << STBVOX_CONFIG_PRECISION_Z , 0,0);\n      unsigned char simple_rot=0;\n      stbvox_rotate rot = { 0,0,0,0 };\n      unsigned char mesh = mm->default_mesh;\n      if (mm->input.selector) {\n         mesh = mm->input.selector[v_off];\n         simple_rot = mesh >> 4;\n         mesh &= 15;\n      }\n      if (mm->input.block_selector) {\n         mesh = mm->input.block_selector[bt];\n      }\n\n      // check if we're going off the end\n      if (mm->output_cur[mesh][0] + mm->output_size[mesh][0]*4 > mm->output_end[mesh][0]) {\n         mm->full = 1;\n         return;\n      }\n\n      if (mm->input.rotate) {\n         unsigned char val = mm->input.rotate[v_off];\n         rot.block   = (val >> 0) & 3;\n         rot.overlay = (val >> 2) & 3;\n         //rot.tex2    = (val >> 4) & 3;\n         rot.ecolor  = (val >> 6) & 3;\n      } else if (mm->input.selector) {\n         rot.block = rot.overlay = rot.ecolor = simple_rot;\n      }\n      rot.facerot = 0;\n\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_north, v_off, pos, basevert, stbvox_vmesh_crossed_pair[STBVOX_FACE_north], mesh, STBVF_ne_u_cross);\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_south, v_off, pos, basevert, stbvox_vmesh_crossed_pair[STBVOX_FACE_south], mesh, STBVF_sw_u_cross);\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_east , v_off, pos, basevert, stbvox_vmesh_crossed_pair[STBVOX_FACE_east ], mesh, STBVF_se_u_cross);\n      stbvox_make_mesh_for_face(mm, rot, STBVOX_FACE_west , v_off, pos, basevert, stbvox_vmesh_crossed_pair[STBVOX_FACE_west ], mesh, STBVF_nw_u_cross);\n   }\n\n\n   // @TODO\n   // STBVOX_GEOM_floor_slope_north_is_top_as_wall,\n   // STBVOX_GEOM_ceil_slope_north_is_bottom_as_wall,\n}\n\nstatic void stbvox_make_mesh_for_column(stbvox_mesh_maker *mm, int x, int y, int z0)\n{\n   stbvox_pos pos;\n   int v_off = x * mm->x_stride_in_bytes + y * mm->y_stride_in_bytes;\n   int ns_off = mm->y_stride_in_bytes;\n   int ew_off = mm->x_stride_in_bytes;\n   pos.x = x;\n   pos.y = y;\n   pos.z = 0;\n   if (mm->input.geometry) {\n      unsigned char *bt  = mm->input.blocktype + v_off;\n      unsigned char *geo = mm->input.geometry + v_off;\n      int z;\n      for (z=z0; z < mm->z1; ++z) {\n         if (bt[z] && ( !bt[z+ns_off] || !STBVOX_GET_GEO(geo[z+ns_off]) || !bt[z-ns_off] || !STBVOX_GET_GEO(geo[z-ns_off])\n                      || !bt[z+ew_off] || !STBVOX_GET_GEO(geo[z+ew_off]) || !bt[z-ew_off] || !STBVOX_GET_GEO(geo[z-ew_off])\n                      || !bt[z-1] || !STBVOX_GET_GEO(geo[z-1]) || !bt[z+1] || !STBVOX_GET_GEO(geo[z+1])))\n         {  // TODO check up and down\n            pos.z = z;\n            stbvox_make_mesh_for_block_with_geo(mm, pos, v_off+z);\n            if (mm->full) {\n               mm->cur_z = z;\n               return;\n            }\n         }\n      }\n   } else if (mm->input.block_geometry) {\n      int z;\n      unsigned char *bt  = mm->input.blocktype + v_off;\n      unsigned char *geo = mm->input.block_geometry;\n      for (z=z0; z < mm->z1; ++z) {\n         if (bt[z] && (    geo[bt[z+ns_off]] != STBVOX_GEOM_solid\n                        || geo[bt[z-ns_off]] != STBVOX_GEOM_solid\n                        || geo[bt[z+ew_off]] != STBVOX_GEOM_solid\n                        || geo[bt[z-ew_off]] != STBVOX_GEOM_solid\n                        || geo[bt[z-1]] != STBVOX_GEOM_solid\n                        || geo[bt[z+1]] != STBVOX_GEOM_solid))\n         {\n            pos.z = z;\n            stbvox_make_mesh_for_block_with_geo(mm, pos, v_off+z);\n            if (mm->full) {\n               mm->cur_z = z;\n               return;\n            }\n         }\n      }\n   } else {\n      unsigned char *bt = mm->input.blocktype + v_off;\n      int z;\n      #if STBVOX_CONFIG_PRECISION_Z == 1\n      stbvox_mesh_vertex *vmesh = stbvox_vmesh_delta_half_z[0];\n      #else\n      stbvox_mesh_vertex *vmesh = stbvox_vmesh_delta_normal[0];\n      #endif\n      for (z=z0; z < mm->z1; ++z) {\n         // if it's solid and at least one neighbor isn't solid\n         if (bt[z] && (!bt[z+ns_off] || !bt[z-ns_off] || !bt[z+ew_off] || !bt[z-ew_off] || !bt[z-1] || !bt[z+1])) {\n            pos.z = z;\n            stbvox_make_mesh_for_block(mm, pos, v_off+z, vmesh);\n            if (mm->full) {\n               mm->cur_z = z;\n               return;\n            }\n         }\n      }\n   }\n}\n\nstatic void stbvox_bring_up_to_date(stbvox_mesh_maker *mm)\n{\n   if (mm->config_dirty) {\n      int i;\n      #ifdef STBVOX_ICONFIG_FACE_ATTRIBUTE\n         mm->num_mesh_slots = 1;\n         for (i=0; i < STBVOX_MAX_MESHES; ++i) {\n            mm->output_size[i][0] = 32;\n            mm->output_step[i][0] = 8;\n         }\n      #else\n         mm->num_mesh_slots = 2;\n         for (i=0; i < STBVOX_MAX_MESHES; ++i) {\n            mm->output_size[i][0] = 16;\n            mm->output_step[i][0] = 4;\n            mm->output_size[i][1] = 4;\n            mm->output_step[i][1] = 4;\n         }\n      #endif\n\n      mm->config_dirty = 0;\n   }\n}\n\nint stbvox_make_mesh(stbvox_mesh_maker *mm)\n{\n   int x,y;\n   stbvox_bring_up_to_date(mm);\n   mm->full = 0;\n   if (mm->cur_x > mm->x0 || mm->cur_y > mm->y0 || mm->cur_z > mm->z0) {\n      stbvox_make_mesh_for_column(mm, mm->cur_x, mm->cur_y, mm->cur_z);\n      if (mm->full)\n         return 0;\n      ++mm->cur_y;\n      while (mm->cur_y < mm->y1 && !mm->full) {\n         stbvox_make_mesh_for_column(mm, mm->cur_x, mm->cur_y, mm->z0);\n         if (mm->full)\n            return 0;\n         ++mm->cur_y;\n      }\n      ++mm->cur_x;\n   }\n   for (x=mm->cur_x; x < mm->x1; ++x) {\n      for (y=mm->y0; y < mm->y1; ++y) {\n         stbvox_make_mesh_for_column(mm, x, y, mm->z0);\n         if (mm->full) {\n            mm->cur_x = x;\n            mm->cur_y = y;\n            return 0;\n         }\n      }\n   }\n   return 1;\n}\n\nvoid stbvox_init_mesh_maker(stbvox_mesh_maker *mm)\n{\n   memset(mm, 0, sizeof(*mm));\n   stbvox_build_default_palette();\n\n   mm->config_dirty = 1;\n   mm->default_mesh = 0;\n}\n\nint stbvox_get_buffer_count(stbvox_mesh_maker *mm)\n{\n   stbvox_bring_up_to_date(mm);\n   return mm->num_mesh_slots;\n}\n\nint stbvox_get_buffer_size_per_quad(stbvox_mesh_maker *mm, int n)\n{\n   return mm->output_size[0][n];\n}\n\nvoid stbvox_reset_buffers(stbvox_mesh_maker *mm)\n{\n   int i;\n   for (i=0; i < STBVOX_MAX_MESHES*STBVOX_MAX_MESH_SLOTS; ++i) {\n      mm->output_cur[0][i] = 0;\n      mm->output_buffer[0][i] = 0;\n   }\n}\n\nvoid stbvox_set_buffer(stbvox_mesh_maker *mm, int mesh, int slot, void *buffer, size_t len)\n{\n   int i;\n   stbvox_bring_up_to_date(mm);\n   mm->output_buffer[mesh][slot] = (char *) buffer;\n   mm->output_cur   [mesh][slot] = (char *) buffer;\n   mm->output_len   [mesh][slot] = (int) len;\n   mm->output_end   [mesh][slot] = (char *) buffer + len;\n   for (i=0; i < STBVOX_MAX_MESH_SLOTS; ++i) {\n      if (mm->output_buffer[mesh][i]) {\n         assert(mm->output_len[mesh][i] / mm->output_size[mesh][i] == mm->output_len[mesh][slot] / mm->output_size[mesh][slot]);\n      }\n   }\n}\n\nvoid stbvox_set_default_mesh(stbvox_mesh_maker *mm, int mesh)\n{\n   mm->default_mesh = mesh;\n}\n\nint stbvox_get_quad_count(stbvox_mesh_maker *mm, int mesh)\n{\n   return (int) ((mm->output_cur[mesh][0] - mm->output_buffer[mesh][0]) / mm->output_size[mesh][0]);\n}\n\nstbvox_input_description *stbvox_get_input_description(stbvox_mesh_maker *mm)\n{\n   return &mm->input;\n}\n\nvoid stbvox_set_input_range(stbvox_mesh_maker *mm, int x0, int y0, int z0, int x1, int y1, int z1)\n{\n   mm->x0 = x0;\n   mm->y0 = y0;\n   mm->z0 = z0;\n\n   mm->x1 = x1;\n   mm->y1 = y1;\n   mm->z1 = z1;\n\n   mm->cur_x = x0;\n   mm->cur_y = y0;\n   mm->cur_z = z0;\n\n   // @TODO validate that this range is representable in this mode\n}\n\nvoid stbvox_get_transform(stbvox_mesh_maker *mm, float transform[3][3])\n{\n   // scale\n   transform[0][0] = 1.0;\n   transform[0][1] = 1.0;\n   #if STBVOX_CONFIG_PRECISION_Z==1\n   transform[0][2] = 0.5f;\n   #else\n   transform[0][2] = 1.0f;\n   #endif\n   // translation\n   transform[1][0] = (float) (mm->pos_x);\n   transform[1][1] = (float) (mm->pos_y);\n   transform[1][2] = (float) (mm->pos_z);\n   // texture coordinate projection translation\n   transform[2][0] = (float) (mm->pos_x & 255); // @TODO depends on max texture scale\n   transform[2][1] = (float) (mm->pos_y & 255);\n   transform[2][2] = (float) (mm->pos_z & 255);\n}\n\nvoid stbvox_get_bounds(stbvox_mesh_maker *mm, float bounds[2][3])\n{\n   bounds[0][0] = (float) (mm->pos_x + mm->x0);\n   bounds[0][1] = (float) (mm->pos_y + mm->y0);\n   bounds[0][2] = (float) (mm->pos_z + mm->z0);\n   bounds[1][0] = (float) (mm->pos_x + mm->x1);\n   bounds[1][1] = (float) (mm->pos_y + mm->y1);\n   bounds[1][2] = (float) (mm->pos_z + mm->z1);\n}\n\nvoid stbvox_set_mesh_coordinates(stbvox_mesh_maker *mm, int x, int y, int z)\n{\n   mm->pos_x = x;\n   mm->pos_y = y;\n   mm->pos_z = z;\n}\n\nvoid stbvox_set_input_stride(stbvox_mesh_maker *mm, int x_stride_in_bytes, int y_stride_in_bytes)\n{\n   int f,v;\n   mm->x_stride_in_bytes = x_stride_in_bytes;\n   mm->y_stride_in_bytes = y_stride_in_bytes;\n   for (f=0; f < 6; ++f) {\n      for (v=0; v < 4; ++v) {\n         mm->cube_vertex_offset[f][v]   =   stbvox_vertex_vector[f][v][0]    * mm->x_stride_in_bytes\n                                         +  stbvox_vertex_vector[f][v][1]    * mm->y_stride_in_bytes\n                                         +  stbvox_vertex_vector[f][v][2]                           ;\n         mm->vertex_gather_offset[f][v] =  (stbvox_vertex_vector[f][v][0]-1) * mm->x_stride_in_bytes\n                                         + (stbvox_vertex_vector[f][v][1]-1) * mm->y_stride_in_bytes\n                                         + (stbvox_vertex_vector[f][v][2]-1)                        ;\n      }\n   }\n}\n\n/////////////////////////////////////////////////////////////////////////////\n//\n//    offline computation of tables\n//\n\n#if 0\n// compute optimized vheight table\nstatic char *normal_names[32] =\n{\n   0,0,0,0,\"u   \",0, \"eu  \",0,\n   0,0,0,0,\"ne_u\",0, \"nu  \",0,\n   0,0,0,0,\"nw_u\",0, \"wu  \",0,\n   0,0,0,0,\"sw_u\",0, \"su  \",0,\n};\n\nstatic char *find_best_normal(float x, float y, float z)\n{\n   int best_slot = 4;\n   float best_dot = 0;\n   int i;\n   for (i=0; i < 32; ++i) {\n      if (normal_names[i]) {\n         float dot = x * stbvox_default_normals[i][0] + y * stbvox_default_normals[i][1] + z * stbvox_default_normals[i][2];\n         if (dot > best_dot) {\n            best_dot = dot;\n            best_slot = i;\n         }\n      }\n   }\n   return normal_names[best_slot];\n}\n\nint main(int argc, char **argv)\n{\n   int sw,se,nw,ne;\n   for (ne=0; ne < 4; ++ne) {\n      for (nw=0; nw < 4; ++nw) {\n         for (se=0; se < 4; ++se) {\n            printf(\"        { \");\n            for (sw=0; sw < 4; ++sw) {\n               float x = (float) (nw + sw - ne - se);\n               float y = (float) (sw + se - nw - ne);\n               float z = 2;\n               printf(\"STBVF_%s, \", find_best_normal(x,y,z));\n            }\n            printf(\"},\\n\");\n         }\n      }\n   }\n   return 0;\n}\n#endif\n\n// @TODO\n//\n//   - test API for texture rotation on side faces\n//   - API for texture rotation on top & bottom\n//   - better culling of vheight faces with vheight neighbors\n//   - better culling of non-vheight faces with vheight neighbors\n//   - gather vertex lighting from slopes correctly\n//   - better support texture edge_clamp: currently if you fall\n//     exactly on 1.0 you get wrapped incorrectly; this is rare, but\n//     can avoid: compute texcoords in vertex shader, offset towards\n//     center before modding, need 2 bits per vertex to know offset direction)\n//   - other mesh modes (10,6,4-byte quads)\n//\n//\n// With TexBuffer for the fixed vertex data, we can actually do\n// minecrafty non-blocks like stairs -- we still probably only\n// want 256 or so, so we can't do the equivalent of all the vheight\n// combos, but that's ok. The 256 includes baked rotations, but only\n// some of them need it, and lots of block types share some faces.\n//\n// mode 5 (6 bytes):   mode 6 (6 bytes)\n//   x:7                x:6\n//   y:7                y:6\n//   z:6                z:6\n//   tex1:8             tex1:8\n//   tex2:8             tex2:7\n//   color:8            color:8\n//   face:4             face:7\n//\n//\n//  side faces (all x4)        top&bottom faces (2x)    internal faces (1x)\n//     1  regular                1 regular\n//     2  slabs                                             2\n//     8  stairs                 4 stairs                  16\n//     4  diag side                                         8\n//     4  upper diag side                                   8\n//     4  lower diag side                                   8\n//                                                          4 crossed pairs\n//\n//    23*4                   +   5*4                    +  46\n//  == 92 + 20 + 46 = 158\n//\n//   Must drop 30 of them to fit in 7 bits:\n//       ceiling half diagonals: 16+8 = 24\n//   Need to get rid of 6 more.\n//       ceiling diagonals: 8+4 = 12\n//   This brings it to 122, so can add a crossed-pair variant.\n//       (diagonal and non-diagonal, or randomly offset)\n//   Or carpet, which would be 5 more.\n//\n//\n// Mode 4 (10 bytes):\n//  v:  z:2,light:6\n//  f:  x:6,y:6,z:7, t1:8,t2:8,c:8,f:5\n//\n// Mode ? (10 bytes)\n//  v:  xyz:5 (27 values), light:3\n//  f:  x:7,y:7,z:6, t1:8,t2:8,c:8,f:4\n// (v:  x:2,y:2,z:2,light:2)\n\n#endif // STB_VOXEL_RENDER_IMPLEMENTATION\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\nsoftware, either in source code form or as a compiled binary, for any purpose,\ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "tests/Makefile",
    "content": "INCLUDES = -I..\nCFLAGS = -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast -DSTB_DIVIDE_TEST\nCPPFLAGS = -Wno-write-strings -DSTB_DIVIDE_TEST\n\n# Uncomment this line for reproducing OSS-Fuzz bugs with image_fuzzer\n#CFLAGS += -O -fsanitize=address \n\nall:\n\t$(CC) $(INCLUDES) $(CFLAGS) ../stb_vorbis.c test_c_compilation.c test_c_lexer.c test_dxt.c test_easyfont.c test_image.c test_image_write.c test_perlin.c test_sprintf.c test_truetype.c test_voxel.c -lm\n\t$(CC) $(INCLUDES) $(CPPFLAGS) -std=c++0x test_cpp_compilation.cpp -lm -lstdc++\n\t$(CC) $(INCLUDES) $(CFLAGS) -DIWT_TEST image_write_test.c -lm -o image_write_test\n\t$(CC) $(INCLUDES) $(CFLAGS) fuzz_main.c stbi_read_fuzzer.c -lm -o image_fuzzer\n"
  },
  {
    "path": "tests/c_lexer_test.c",
    "content": "#define STB_C_LEX_C_DECIMAL_INTS    Y   //  \"0|[1-9][0-9]*\"                        CLEX_intlit\n#define STB_C_LEX_C_HEX_INTS        Y   //  \"0x[0-9a-fA-F]+\"                       CLEX_intlit\n#define STB_C_LEX_C_OCTAL_INTS      Y   //  \"[0-7]+\"                               CLEX_intlit\n#define STB_C_LEX_C_DECIMAL_FLOATS  Y   //  \"[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?)     CLEX_floatlit\n#define STB_C_LEX_C99_HEX_FLOATS    Y   //  \"0x{hex}+(.{hex}*)?[pP][-+]?{hex}+     CLEX_floatlit\n#define STB_C_LEX_C_IDENTIFIERS     Y   //  \"[_a-zA-Z][_a-zA-Z0-9]*\"               CLEX_id\n#define STB_C_LEX_C_DQ_STRINGS      Y   //  double-quote-delimited strings with escapes  CLEX_dqstring\n#define STB_C_LEX_C_SQ_STRINGS      Y   //  single-quote-delimited strings with escapes  CLEX_ssstring\n#define STB_C_LEX_C_CHARS           Y   //  single-quote-delimited character with escape CLEX_charlits\n#define STB_C_LEX_C_COMMENTS        Y   //  \"/* comment */\"\n#define STB_C_LEX_CPP_COMMENTS      Y   //  \"// comment to end of line\\n\"\n#define STB_C_LEX_C_COMPARISONS     Y   //  \"==\" CLEX_eq  \"!=\" CLEX_noteq   \"<=\" CLEX_lesseq  \">=\" CLEX_greatereq\n#define STB_C_LEX_C_LOGICAL         Y   //  \"&&\"  CLEX_andand   \"||\"  CLEX_oror\n#define STB_C_LEX_C_SHIFTS          Y   //  \"<<\"  CLEX_shl      \">>\"  CLEX_shr\n#define STB_C_LEX_C_INCREMENTS      Y   //  \"++\"  CLEX_plusplus \"--\"  CLEX_minusminus\n#define STB_C_LEX_C_ARROW           Y   //  \"->\"  CLEX_arrow\n#define STB_C_LEX_EQUAL_ARROW       Y   //  \"=>\"  CLEX_eqarrow\n#define STB_C_LEX_C_BITWISEEQ       Y   //  \"&=\"  CLEX_andeq    \"|=\"  CLEX_oreq     \"^=\"  CLEX_xoreq\n#define STB_C_LEX_C_ARITHEQ         Y   //  \"+=\"  CLEX_pluseq   \"-=\"  CLEX_minuseq\n                                        //  \"*=\"  CLEX_muleq    \"/=\"  CLEX_diveq    \"%=\" CLEX_modeq\n                                        //  if both STB_C_LEX_SHIFTS & STB_C_LEX_ARITHEQ:\n                                        //                      \"<<=\" CLEX_shleq    \">>=\" CLEX_shreq\n\n#define STB_C_LEX_PARSE_SUFFIXES    Y   // letters after numbers are parsed as part of those numbers, and must be in suffix list below\n#define STB_C_LEX_DECIMAL_SUFFIXES  \"uUlL\"  // decimal integer suffixes e.g. \"uUlL\" -- these are returned as-is in string storage\n#define STB_C_LEX_HEX_SUFFIXES      \"lL\"  // e.g. \"uUlL\"\n#define STB_C_LEX_OCTAL_SUFFIXES    \"lL\"  // e.g. \"uUlL\"\n#define STB_C_LEX_FLOAT_SUFFIXES    \"uulL\"  //\n\n#define STB_C_LEX_0_IS_EOF             N  // if Y, ends parsing at '\\0'; if N, returns '\\0' as token\n#define STB_C_LEX_INTEGERS_AS_DOUBLES  N  // parses integers as doubles so they can be larger than 'int', but only if STB_C_LEX_STDLIB==N\n#define STB_C_LEX_MULTILINE_DSTRINGS   Y  // allow newlines in double-quoted strings\n#define STB_C_LEX_MULTILINE_SSTRINGS   Y  // allow newlines in single-quoted strings\n#define STB_C_LEX_USE_STDLIB           N  // use strtod,strtol for parsing #s; otherwise inaccurate hack\n#define STB_C_LEX_DOLLAR_IDENTIFIER    Y  // allow $ as an identifier character\n#define STB_C_LEX_FLOAT_NO_DECIMAL     Y  // allow floats that have no decimal point if they have an exponent\n\n#define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES  Y   // if Y, all CLEX_ token names are defined, even if never returned\n                                              // leaving it as N should help you catch config bugs\n\n#define STB_C_LEX_DISCARD_PREPROCESSOR    Y   // discard C-preprocessor directives (e.g. after prepocess\n                                              // still have #line, #pragma, etc)\n\n#define STB_C_LEXER_DEFINITIONS         // This line prevents the header file from replacing your definitions\n\n\n\n#define STB_C_LEXER_IMPLEMENTATION\n#define STB_C_LEXER_SELF_TEST\n#include \"../stb_c_lexer.h\"\n"
  },
  {
    "path": "tests/c_lexer_test.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"c_lexer_test\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=c_lexer_test - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"c_lexer_test.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"c_lexer_test.mak\" CFG=\"c_lexer_test - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"c_lexer_test - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"c_lexer_test - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"c_lexer_test - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"c_lexer_test - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\\c_lexer_test\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"c_lexer_test - Win32 Release\"\n# Name \"c_lexer_test - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\c_lexer_test.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/caveview/README.md",
    "content": "# FAQ\n\n### How to run it?\n\nThere's no GUI. Find a directory with Minecraft Anvil files (.mca).\nCopy a Minecraft \"terrain.png\" into that directory (do a google\nimage search). Run from that directory.\n\n### How accurate is this as a Minecraft viewer?\n\nNot very. Many Minecraft blocks are not handled correctly:\n\n*         No redstone, rails, or other \"flat\" blocks\n*         No signs, doors, fences, carpets, or other complicated geometry\n*         Stairs are turned into ramps\n*         Upper slabs turn into lower slabs\n*         Wood types only for blocks, not stairs, slabs, etc\n*         Colored glass becomes regular glass\n*         Glass panes become glass blocks\n*         Water is opaque\n*         Water level is incorrect\n*         No biome coloration\n*         Cactus is not shrunk, shows holes\n*         Chests are not shrunk\n*         Double-chests draw as two chests\n*         Pumpkins etc. are not rotated properly\n*         Torches are drawn hackily, do not attach to walls\n*         Incorrect textures for blocks that postdate terrain.png\n*         Transparent textures have black fringes due to non-premultiplied-alpha\n*         Skylight and block light are combined in a single value\n*         Only blocks at y=1..255 are shown (not y=0)\n*         If a 32x32x256 \"quad-chunk\" needs more than 800K quads, isn't handled (very unlikely)\n\nSome of these are due to engine limitations, and some of\nthese are because I didn't make the effort since my\ngoal was to make a demo for stb_voxel_render.h, not\nto make a proper Minecraft viewer.\n\n\n### Could this be turned into a proper Minecraft viewer?\n\nYes and no. Yes, you could do it, but no, it wouldn't\nreally resemble this code that much anymore.\n\nYou could certainly use this engine to\nrender the parts of Minecraft it works for, but many\nof the things it doesn't handle it can't handle at all\n(stairs, water, fences, carpets, etc) because it uses\nlow-precision coordinates to store voxel data.\n\nYou would have to render all of the stuff it doesn't\nhandle through another rendering path. In a game (not\na viewer) you would need such a path for movable entities\nlike doors and carts anyway, so possibly handling other\nthings that way wouldn't be so bad.\n\nRails, ladders, and redstone lines could be implemented by\nusing tex2 to overlay those effects, but you can't rotate\ntex1 and tex2 independently, so there may be cases where\nthe underlying texture needs a different rotation from the\noverlaid texture, which would require separate rendering.\nHandling redstone's brightness being different from underlying\nblock's brightness would require separate rendering.\n\nYou can use the face-color effect to do biome coloration,\nbut the change won't be smooth the way it is in Minecraft.\n\n\n### Why isn't building the mesh data faster?\n\nPartly because converting from minecraft data is expensive.\n\nHere is the approximate breakdown of an older version\nof this executable and lib that did the building single-threaded.\n\n*       25%   loading & parsing minecraft files (4/5ths of this is my crappy zlib)\n*       18%   converting from minecraft blockids & lighting to stb blockids & lighting\n*       10%   reordering from data[z][y]\\[x] (minecraft-style) to data[y][x]\\[z] (stb-style)\n*       40%   building mesh data\n*        7%   uploading mesh data to OpenGL\n\nI did do significant optimizations after the above, so the\nfinal breakdown is different, but it should give you some\nsense of the costs.\n\n"
  },
  {
    "path": "tests/caveview/cave_main.c",
    "content": "#define _WIN32_WINNT 0x400\n\n#include <assert.h>\n#include <windows.h>\n\n// stb.h\n#define STB_DEFINE\n#include \"stb.h\"\n\n// stb_gl.h\n#define STB_GL_IMPLEMENTATION\n#define STB_GLEXT_DEFINE \"glext_list.h\"\n#include \"stb_gl.h\"\n\n// SDL\n#include \"sdl.h\"\n#include \"SDL_opengl.h\"\n\n// stb_glprog.h\n#define STB_GLPROG_IMPLEMENTATION\n#define STB_GLPROG_ARB_DEFINE_EXTENSIONS\n#include \"stb_glprog.h\"\n\n// stb_image.h\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n// stb_easy_font.h\n#include \"stb_easy_font.h\" // doesn't require an IMPLEMENTATION\n\n#include \"caveview.h\"\n\nchar *game_name = \"caveview\";\n\n\n#define REVERSE_DEPTH\n\n\n\nstatic void print_string(float x, float y, char *text, float r, float g, float b)\n{\n   static char buffer[99999];\n   int num_quads;\n   \n   num_quads = stb_easy_font_print(x, y, text, NULL, buffer, sizeof(buffer));\n\n   glColor3f(r,g,b);\n   glEnableClientState(GL_VERTEX_ARRAY);\n   glVertexPointer(2, GL_FLOAT, 16, buffer);\n   glDrawArrays(GL_QUADS, 0, num_quads*4);\n   glDisableClientState(GL_VERTEX_ARRAY);\n}\n\nstatic float text_color[3];\nstatic float pos_x = 10;\nstatic float pos_y = 10;\n\nstatic void print(char *text, ...)\n{\n   char buffer[999];\n   va_list va;\n   va_start(va, text);\n   vsprintf(buffer, text, va);\n   va_end(va);\n   print_string(pos_x, pos_y, buffer, text_color[0], text_color[1], text_color[2]);\n   pos_y += 10;\n}\n\nfloat camang[3], camloc[3] = { 60,22,77 };\nfloat player_zoom = 1.0;\nfloat rotate_view = 0.0;\n\n\nvoid camera_to_worldspace(float world[3], float cam_x, float cam_y, float cam_z)\n{\n   float vec[3] = { cam_x, cam_y, cam_z };\n   float t[3];\n   float s,c;\n   s = (float) sin(camang[0]*3.141592/180);\n   c = (float) cos(camang[0]*3.141592/180);\n\n   t[0] = vec[0];\n   t[1] = c*vec[1] - s*vec[2];\n   t[2] = s*vec[1] + c*vec[2];\n\n   s = (float) sin(camang[2]*3.141592/180);\n   c = (float) cos(camang[2]*3.141592/180);\n   world[0] = c*t[0] - s*t[1];\n   world[1] = s*t[0] + c*t[1];\n   world[2] = t[2];\n}\n\n// camera worldspace velocity\nfloat cam_vel[3];\n\nint controls;\n\n#define MAX_VEL  150.0f      // blocks per second\n#define ACCEL      6.0f\n#define DECEL      3.0f\n\n#define STATIC_FRICTION   DECEL\n#define EFFECTIVE_ACCEL   (ACCEL+DECEL)\n\n// dynamic friction:\n//\n//    if going at MAX_VEL, ACCEL and friction must cancel\n//    EFFECTIVE_ACCEL = DECEL + DYNAMIC_FRIC*MAX_VEL\n#define DYNAMIC_FRICTION  (ACCEL/(float)MAX_VEL)\n\nfloat view_x_vel = 0;\nfloat view_z_vel = 0;\nfloat pending_view_x;\nfloat pending_view_z;\nfloat pending_view_x;\nfloat pending_view_z;\n\nvoid process_tick_raw(float dt)\n{\n   int i;\n   float thrust[3] = { 0,0,0 };\n   float world_thrust[3];\n\n   // choose direction to apply thrust\n\n   thrust[0] = (controls &  3)== 1 ? EFFECTIVE_ACCEL : (controls &  3)== 2 ? -EFFECTIVE_ACCEL : 0;\n   thrust[1] = (controls & 12)== 4 ? EFFECTIVE_ACCEL : (controls & 12)== 8 ? -EFFECTIVE_ACCEL : 0;\n   thrust[2] = (controls & 48)==16 ? EFFECTIVE_ACCEL : (controls & 48)==32 ? -EFFECTIVE_ACCEL : 0;\n\n   // @TODO clamp thrust[0] & thrust[1] vector length to EFFECTIVE_ACCEL\n\n   camera_to_worldspace(world_thrust, thrust[0], thrust[1], 0);\n   world_thrust[2] += thrust[2];\n\n   for (i=0; i < 3; ++i) {\n      float acc = world_thrust[i];\n      cam_vel[i] += acc*dt;\n   }\n\n   if (cam_vel[0] || cam_vel[1] || cam_vel[2])\n   {\n      float vel = (float) sqrt(cam_vel[0]*cam_vel[0] + cam_vel[1]*cam_vel[1] + cam_vel[2]*cam_vel[2]);\n      float newvel = vel;\n      float dec = STATIC_FRICTION + DYNAMIC_FRICTION*vel;\n      newvel = vel - dec*dt;\n      if (newvel < 0)\n         newvel = 0;\n      cam_vel[0] *= newvel/vel;\n      cam_vel[1] *= newvel/vel;\n      cam_vel[2] *= newvel/vel;\n   }\n\n   camloc[0] += cam_vel[0] * dt;\n   camloc[1] += cam_vel[1] * dt;\n   camloc[2] += cam_vel[2] * dt;\n\n   view_x_vel *= (float) pow(0.75, dt);\n   view_z_vel *= (float) pow(0.75, dt);\n\n   view_x_vel += (pending_view_x - view_x_vel)*dt*60;\n   view_z_vel += (pending_view_z - view_z_vel)*dt*60;\n\n   pending_view_x -= view_x_vel * dt;\n   pending_view_z -= view_z_vel * dt;\n   camang[0] += view_x_vel * dt;\n   camang[2] += view_z_vel * dt;\n   camang[0] = stb_clamp(camang[0], -90, 90);\n   camang[2] = (float) fmod(camang[2], 360);\n}\n\nvoid process_tick(float dt)\n{\n   while (dt > 1.0f/60) {\n      process_tick_raw(1.0f/60);\n      dt -= 1.0f/60;\n   }\n   process_tick_raw(dt);\n}\n\nvoid update_view(float dx, float dy)\n{\n   // hard-coded mouse sensitivity, not resolution independent?\n   pending_view_z -= dx*300;\n   pending_view_x -= dy*700;\n}\n\nextern int screen_x, screen_y;\nextern int is_synchronous_debug;\nfloat render_time;\n\nextern int chunk_locations, chunks_considered, chunks_in_frustum;\nextern int quads_considered, quads_rendered;\nextern int chunk_storage_rendered, chunk_storage_considered, chunk_storage_total;\nextern int view_dist_in_chunks;\nextern int num_threads_active, num_meshes_started, num_meshes_uploaded;\nextern float chunk_server_activity;\n\nstatic Uint64 start_time, end_time; // render time\n\nfloat chunk_server_status[32];\nint chunk_server_pos;\n\nvoid draw_stats(void)\n{\n   int i;\n\n   static Uint64 last_frame_time;\n   Uint64 cur_time = SDL_GetPerformanceCounter();\n   float chunk_server=0;\n   float frame_time = (cur_time - last_frame_time) / (float) SDL_GetPerformanceFrequency();\n   last_frame_time = cur_time;\n\n   chunk_server_status[chunk_server_pos] = chunk_server_activity;\n   chunk_server_pos = (chunk_server_pos+1) %32;\n\n   for (i=0; i < 32; ++i)\n      chunk_server += chunk_server_status[i] / 32.0f;\n\n   stb_easy_font_spacing(-0.75);\n   pos_y = 10;\n   text_color[0] = text_color[1] = text_color[2] = 1.0f;\n   print(\"Frame time: %6.2fms, CPU frame render time: %5.2fms\", frame_time*1000, render_time*1000);\n   print(\"Tris: %4.1fM drawn of %4.1fM in range\", 2*quads_rendered/1000000.0f, 2*quads_considered/1000000.0f);\n   print(\"Vbuf storage: %dMB in frustum of %dMB in range of %dMB in cache\", chunk_storage_rendered>>20, chunk_storage_considered>>20, chunk_storage_total>>20);\n   print(\"Num mesh builds started this frame: %d; num uploaded this frame: %d\\n\", num_meshes_started, num_meshes_uploaded);\n   print(\"QChunks: %3d in frustum of %3d valid of %3d in range\", chunks_in_frustum, chunks_considered, chunk_locations);\n   print(\"Mesh worker threads active: %d\", num_threads_active);\n   print(\"View distance: %d blocks\", view_dist_in_chunks*16);\n   print(\"%s\", glGetString(GL_RENDERER));\n\n   if (is_synchronous_debug) {\n      text_color[0] = 1.0;\n      text_color[1] = 0.5;\n      text_color[2] = 0.5;\n      print(\"SLOWNESS: Synchronous debug output is enabled!\");\n   }\n}\n\nvoid draw_main(void)\n{\n   glEnable(GL_CULL_FACE);\n   glDisable(GL_TEXTURE_2D);\n   glDisable(GL_LIGHTING);\n   glEnable(GL_DEPTH_TEST);\n   #ifdef REVERSE_DEPTH\n   glDepthFunc(GL_GREATER);\n   glClearDepth(0);\n   #else\n   glDepthFunc(GL_LESS);\n   glClearDepth(1);\n   #endif\n   glDepthMask(GL_TRUE);\n   glDisable(GL_SCISSOR_TEST);\n   glClearColor(0.6f,0.7f,0.9f,0.0f);\n   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n   glColor3f(1,1,1);\n   glFrontFace(GL_CW);\n   glEnable(GL_TEXTURE_2D);\n   glDisable(GL_BLEND);\n\n\n   glMatrixMode(GL_PROJECTION);\n   glLoadIdentity();\n\n   #ifdef REVERSE_DEPTH\n   stbgl_Perspective(player_zoom, 90, 70, 3000, 1.0/16);\n   #else\n   stbgl_Perspective(player_zoom, 90, 70, 1.0/16, 3000);\n   #endif\n\n   // now compute where the camera should be\n   glMatrixMode(GL_MODELVIEW);\n   glLoadIdentity();\n   stbgl_initCamera_zup_facing_y();\n\n   glRotatef(-camang[0],1,0,0);\n   glRotatef(-camang[2],0,0,1);\n   glTranslatef(-camloc[0], -camloc[1], -camloc[2]);\n\n   start_time = SDL_GetPerformanceCounter();\n   render_caves(camloc);\n   end_time = SDL_GetPerformanceCounter();\n\n   render_time = (end_time - start_time) / (float) SDL_GetPerformanceFrequency();\n\n   glMatrixMode(GL_PROJECTION);\n   glLoadIdentity();\n   gluOrtho2D(0,screen_x/2,screen_y/2,0);\n   glMatrixMode(GL_MODELVIEW);\n   glLoadIdentity();\n   glDisable(GL_TEXTURE_2D);\n   glDisable(GL_BLEND);\n   glDisable(GL_CULL_FACE);\n   draw_stats();\n}\n\n\n\n#pragma warning(disable:4244; disable:4305; disable:4018)\n\n#define SCALE   2\n\nvoid error(char *s)\n{\n   SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, \"Error\", s, NULL);\n   exit(0);\n}\n\nvoid ods(char *fmt, ...)\n{\n   char buffer[1000];\n   va_list va;\n   va_start(va, fmt);\n   vsprintf(buffer, fmt, va);\n   va_end(va);\n   SDL_Log(\"%s\", buffer);\n}\n\n#define TICKS_PER_SECOND  60\n\nstatic SDL_Window *window;\n\nextern void draw_main(void);\nextern void process_tick(float dt);\nextern void editor_init(void);\n\nvoid draw(void)\n{\n   draw_main();\n   SDL_GL_SwapWindow(window);\n}\n\n\nstatic int initialized=0;\nstatic float last_dt;\n\nint screen_x,screen_y;\n\nfloat carried_dt = 0;\n#define TICKRATE 60\n\nfloat tex2_alpha = 1.0;\n\nint raw_level_time;\n\nfloat global_timer;\nint global_hack;\n\nint loopmode(float dt, int real, int in_client)\n{\n   if (!initialized) return 0;\n\n   if (!real)\n      return 0;\n\n   // don't allow more than 6 frames to update at a time\n   if (dt > 0.075) dt = 0.075;\n\n   global_timer += dt;\n\n   carried_dt += dt;\n   while (carried_dt > 1.0/TICKRATE) {\n      if (global_hack) {\n         tex2_alpha += global_hack / 60.0f;\n         if (tex2_alpha < 0) tex2_alpha = 0;\n         if (tex2_alpha > 1) tex2_alpha = 1;\n      }\n      //update_input();\n      // if the player is dead, stop the sim\n      carried_dt -= 1.0/TICKRATE;\n   }\n\n   process_tick(dt);\n   draw();\n\n   return 0;\n}\n\nstatic int quit;\n\nextern int controls;\n\nvoid active_control_set(int key)\n{\n   controls |= 1 << key;\n}\n\nvoid active_control_clear(int key)\n{\n   controls &= ~(1 << key);\n}\n\nextern void update_view(float dx, float dy);\n\nvoid  process_sdl_mouse(SDL_Event *e)\n{\n   update_view((float) e->motion.xrel / screen_x, (float) e->motion.yrel / screen_y);\n}\n\nvoid process_event(SDL_Event *e)\n{\n   switch (e->type) {\n      case SDL_MOUSEMOTION:\n         process_sdl_mouse(e);\n         break;\n      case SDL_MOUSEBUTTONDOWN:\n      case SDL_MOUSEBUTTONUP:\n         break;\n\n      case SDL_QUIT:\n         quit = 1;\n         break;\n\n      case SDL_WINDOWEVENT:\n         switch (e->window.event) {\n            case SDL_WINDOWEVENT_SIZE_CHANGED:\n               screen_x = e->window.data1;\n               screen_y = e->window.data2;\n               loopmode(0,1,0);\n               break;\n         }\n         break;\n\n      case SDL_KEYDOWN: {\n         int k = e->key.keysym.sym;\n         int s = e->key.keysym.scancode;\n         SDL_Keymod mod;\n         mod = SDL_GetModState();\n         if (k == SDLK_ESCAPE)\n            quit = 1;\n\n         if (s == SDL_SCANCODE_D)   active_control_set(0);\n         if (s == SDL_SCANCODE_A)   active_control_set(1);\n         if (s == SDL_SCANCODE_W)   active_control_set(2);\n         if (s == SDL_SCANCODE_S)   active_control_set(3);\n         if (k == SDLK_SPACE)       active_control_set(4); \n         if (s == SDL_SCANCODE_LCTRL)   active_control_set(5);\n         if (s == SDL_SCANCODE_S)   active_control_set(6);\n         if (s == SDL_SCANCODE_D)   active_control_set(7);\n         if (k == '1') global_hack = !global_hack;\n         if (k == '2') global_hack = -1;\n\n         #if 0\n         if (game_mode == GAME_editor) {\n            switch (k) {\n               case SDLK_RIGHT: editor_key(STBTE_scroll_right); break;\n               case SDLK_LEFT : editor_key(STBTE_scroll_left ); break;\n               case SDLK_UP   : editor_key(STBTE_scroll_up   ); break;\n               case SDLK_DOWN : editor_key(STBTE_scroll_down ); break;\n            }\n            switch (s) {\n               case SDL_SCANCODE_S: editor_key(STBTE_tool_select); break;\n               case SDL_SCANCODE_B: editor_key(STBTE_tool_brush ); break;\n               case SDL_SCANCODE_E: editor_key(STBTE_tool_erase ); break;\n               case SDL_SCANCODE_R: editor_key(STBTE_tool_rectangle ); break;\n               case SDL_SCANCODE_I: editor_key(STBTE_tool_eyedropper); break;\n               case SDL_SCANCODE_L: editor_key(STBTE_tool_link); break;\n               case SDL_SCANCODE_G: editor_key(STBTE_act_toggle_grid); break;\n            }\n            if ((e->key.keysym.mod & KMOD_CTRL) && !(e->key.keysym.mod & ~KMOD_CTRL)) {\n               switch (s) {\n                  case SDL_SCANCODE_X: editor_key(STBTE_act_cut  ); break;\n                  case SDL_SCANCODE_C: editor_key(STBTE_act_copy ); break;\n                  case SDL_SCANCODE_V: editor_key(STBTE_act_paste); break;\n                  case SDL_SCANCODE_Z: editor_key(STBTE_act_undo ); break;\n                  case SDL_SCANCODE_Y: editor_key(STBTE_act_redo ); break;\n               }\n            }\n         }\n         #endif\n         break;\n      }\n      case SDL_KEYUP: {\n         int k = e->key.keysym.sym;\n         int s = e->key.keysym.scancode;\n         if (s == SDL_SCANCODE_D)   active_control_clear(0);\n         if (s == SDL_SCANCODE_A)   active_control_clear(1);\n         if (s == SDL_SCANCODE_W)   active_control_clear(2);\n         if (s == SDL_SCANCODE_S)   active_control_clear(3);\n         if (k == SDLK_SPACE)       active_control_clear(4); \n         if (s == SDL_SCANCODE_LCTRL)   active_control_clear(5);\n         if (s == SDL_SCANCODE_S)   active_control_clear(6);\n         if (s == SDL_SCANCODE_D)   active_control_clear(7);\n         break;\n      }\n   }\n}\n\nstatic SDL_GLContext *context;\n\nstatic float getTimestep(float minimum_time)\n{\n   float elapsedTime;\n   double thisTime;\n   static double lastTime = -1;\n   \n   if (lastTime == -1)\n      lastTime = SDL_GetTicks() / 1000.0 - minimum_time;\n\n   for(;;) {\n      thisTime = SDL_GetTicks() / 1000.0;\n      elapsedTime = (float) (thisTime - lastTime);\n      if (elapsedTime >= minimum_time) {\n         lastTime = thisTime;         \n         return elapsedTime;\n      }\n      // @TODO: compute correct delay\n      SDL_Delay(1);\n   }\n}\n\nvoid APIENTRY gl_debug(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *param)\n{\n   ods(\"%s\\n\", message);\n}\n\nint is_synchronous_debug;\nvoid enable_synchronous(void)\n{\n   glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);\n   is_synchronous_debug = 1;\n}\n\nvoid prepare_threads(void);\n\n//void stbwingraph_main(void)\nint SDL_main(int argc, char **argv)\n{\n   SDL_Init(SDL_INIT_VIDEO);\n\n   prepare_threads();\n\n   SDL_GL_SetAttribute(SDL_GL_RED_SIZE  , 8);\n   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);\n   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE , 8);\n   SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\n\n   SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);\n   SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n   SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);\n\n   #ifdef GL_DEBUG\n   SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);\n   #endif\n\n   SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);\n\n   screen_x = 1920;\n   screen_y = 1080;\n\n   window = SDL_CreateWindow(\"caveview\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n                                   screen_x, screen_y,\n                                   SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE\n                             );\n   if (!window) error(\"Couldn't create window\");\n\n   context = SDL_GL_CreateContext(window);\n   if (!context) error(\"Couldn't create context\");\n\n   SDL_GL_MakeCurrent(window, context); // is this true by default?\n\n   SDL_SetRelativeMouseMode(SDL_TRUE);\n   #if defined(_MSC_VER) && _MSC_VER < 1300\n   // work around broken behavior in VC6 debugging\n   if (IsDebuggerPresent())\n      SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, \"1\");\n   #endif\n\n   stbgl_initExtensions();\n\n   #ifdef GL_DEBUG\n   if (glDebugMessageCallbackARB) {\n      glDebugMessageCallbackARB(gl_debug, NULL);\n\n      enable_synchronous();\n   }\n   #endif\n\n   SDL_GL_SetSwapInterval(1);\n\n   render_init();\n   mesh_init();\n   world_init();\n\n   initialized = 1;\n\n   while (!quit) {\n      SDL_Event e;\n      while (SDL_PollEvent(&e))\n         process_event(&e);\n\n      loopmode(getTimestep(0.0166f/8), 1, 1);\n   }\n\n   return 0;\n}\n"
  },
  {
    "path": "tests/caveview/cave_mesher.c",
    "content": "// This file takes minecraft chunks (decoded by cave_parse) and\n// uses stb_voxel_render to turn them into vertex buffers.\n\n#define STB_GLEXT_DECLARE \"glext_list.h\"\n#include \"stb_gl.h\"\n#include \"stb_image.h\"\n#include \"stb_glprog.h\"\n\n#include \"caveview.h\"\n#include \"cave_parse.h\"\n#include \"stb.h\"\n#include \"sdl.h\"\n#include \"sdl_thread.h\"\n#include <math.h>\n\n//#define VHEIGHT_TEST\n//#define STBVOX_OPTIMIZED_VHEIGHT\n\n#define STBVOX_CONFIG_MODE  1\n#define STBVOX_CONFIG_OPENGL_MODELVIEW\n#define STBVOX_CONFIG_PREFER_TEXBUFFER\n//#define STBVOX_CONFIG_LIGHTING_SIMPLE\n#define STBVOX_CONFIG_FOG_SMOOTHSTEP\n//#define STBVOX_CONFIG_PREMULTIPLIED_ALPHA  // this doesn't work properly alpha test without next #define\n//#define STBVOX_CONFIG_UNPREMULTIPLY  // slower, fixes alpha test makes windows & fancy leaves look better\n//#define STBVOX_CONFIG_TEX1_EDGE_CLAMP\n#define STBVOX_CONFIG_DISABLE_TEX2\n//#define STBVOX_CONFIG_DOWN_TEXLERP_PACKED\n#define STBVOX_CONFIG_ROTATION_IN_LIGHTING\n\n#define STB_VOXEL_RENDER_IMPLEMENTATION\n#include \"stb_voxel_render.h\"\n\nextern void ods(char *fmt, ...);\n\n//#define FANCY_LEAVES  // nearly 2x the triangles when enabled (if underground is filled)\n#define FAST_CHUNK\n#define IN_PLACE\n\n#define SKIP_TERRAIN   0\n//#define SKIP_TERRAIN   48 // use to avoid building underground stuff\n                          // allows you to see what perf would be like if underground was efficiently culled,\n                          // or if you were making a game without underground\n\nenum\n{\n   C_empty,\n   C_solid,\n   C_trans,\n   C_cross,\n   C_water,\n   C_slab,\n   C_stair,\n   C_force,\n};\n\nunsigned char geom_map[] =\n{\n   STBVOX_GEOM_empty,\n   STBVOX_GEOM_solid,\n   STBVOX_GEOM_transp,\n   STBVOX_GEOM_crossed_pair,\n   STBVOX_GEOM_solid,\n   STBVOX_GEOM_slab_lower,\n   STBVOX_GEOM_floor_slope_north_is_top,\n   STBVOX_GEOM_force,\n};\n\nunsigned char minecraft_info[256][7] =\n{\n   { C_empty, 0,0,0,0,0,0 },\n   { C_solid, 1,1,1,1,1,1 },\n   { C_solid, 3,3,3,3,40,2 },\n   { C_solid, 2,2,2,2,2,2 },\n   { C_solid, 16,16,16,16,16,16 },\n   { C_solid, 4,4,4,4,4,4 },\n   { C_cross, 15,15,15,15 },\n   { C_solid, 17,17,17,17,17,17 },\n\n   // 8\n   { C_water, 223,223,223,223,223,223 },\n   { C_water, 223,223,223,223,223,223 },\n   { C_solid, 255,255,255,255,255,255 },\n   { C_solid, 255,255,255,255,255,255 },\n   { C_solid, 18,18,18,18,18,18 },\n   { C_solid, 19,19,19,19,19,19 },\n   { C_solid, 32,32,32,32,32,32 },\n   { C_solid, 33,33,33,33,33,33 },\n\n   // 16\n   { C_solid, 34,34,34,34,34,34 },\n   { C_solid, 20,20,20,20,21,21 },\n#ifdef FANCY_LEAVES\n   { C_force, 52,52,52,52,52,52 }, // leaves\n#else\n   { C_solid, 53,53,53,53,53,53 }, // leaves\n#endif\n   { C_solid, 24,24,24,24,24,24 },\n   { C_trans, 49,49,49,49,49,49 }, // glass\n   { C_solid, 160,160,160,160,160,160 },\n   { C_solid, 144,144,144,144,144,144 },\n   { C_solid, 46,45,45,45,62,62 },\n\n   // 24\n   { C_solid, 192,192,192,192, 176,176 },\n   { C_solid, 74,74,74,74,74,74 },\n   { C_empty }, // bed\n   { C_empty }, // powered rail\n   { C_empty }, // detector rail\n   { C_solid, 106,108,109,108,108,108 },\n   { C_empty }, // cobweb=11\n   { C_cross, 39,39,39,39 },\n\n   // 32\n   { C_cross, 55,55,55,55,0,0 },\n   { C_solid, 107,108,109,108,108,108 },\n   { C_empty }, // piston head\n   { C_solid, 64,64,64,64,64,64 }, // various colors\n   { C_empty }, // unused\n   { C_cross, 13,13,13,13,0,0 },\n   { C_cross, 12,12,12,12,0,0 },\n   { C_cross, 29,29,29,29,0,0 },\n\n   // 40\n   { C_cross, 28,28,28,28,0,0 },\n   { C_solid, 23,23,23,23,23,23 },\n   { C_solid, 22,22,22,22,22,22 },\n   { C_solid, 5,5,5,5,6,6, },\n   { C_slab , 5,5,5,5,6,6, },\n   { C_solid, 7,7,7,7,7,7, },\n   { C_solid, 8,8,8,8,9,10 },\n   { C_solid, 35,35,35,35,4,4, },\n\n   // 48\n   //{ C_solid, 36,36,36,36,36,36 },\n   { C_force, 36,36,36,36,36,36 },\n   { C_solid, 37,37,37,37,37,37 },\n   { C_cross, 80,80,80,80,80,80 }, // torch\n   { C_empty }, // fire\n   { C_trans, 65,65,65,65,65,65 },\n   { C_stair, 4,4,4,4,4,4 },\n   { C_solid, 26,26,26,27,25,25 },\n   { C_empty }, // redstone\n\n   // 56\n   { C_solid, 50,50,50,50,50,50 },\n   //{ C_force, 50,50,50,50,50,50 },\n   { C_solid, 26,26,26,26,26,26 },\n   { C_solid, 60,59,59,59,43,43 },\n   { C_cross, 95,95,95,95 },\n   { C_solid, 2,2,2,2,86,2 },\n   { C_solid, 44,45,45,45,62,62 },\n   { C_solid, 61,45,45,45,62,62 },\n   { C_empty }, // sign\n\n   // 64\n   { C_empty }, // door\n   { C_empty }, // ladder\n   { C_empty }, // rail\n   { C_stair, 16,16,16,16,16,16 }, // cobblestone stairs\n   { C_empty }, // sign\n   { C_empty }, // lever\n   { C_empty }, // stone pressure plate\n   { C_empty }, // iron door\n\n   // 72\n   { C_empty }, // wooden pressure\n   { C_solid, 51,51,51,51,51,51 },\n   { C_solid, 51,51,51,51,51,51 },\n   { C_empty },\n   { C_empty },\n   { C_empty },\n   { C_empty }, // snow on block below, do as half slab?\n   { C_solid, 67,67,67,67,67,67 },\n\n   // 80\n   { C_solid, 66,66,66,66,66,66 },\n   { C_solid, 70,70,70,70,69,71 },\n   { C_solid, 72,72,72,72,72,72 },\n   { C_cross, 73,73,73,73,73,73 },\n   { C_solid, 74,74,74,74,75,74 },\n   { C_empty }, // fence\n   { C_solid,119,118,118,118,102,102 },\n   { C_solid,103,103,103,103,103,103 },\n\n   // 88\n   { C_solid, 104,104,104,104,104,104 },\n   { C_solid, 105,105,105,105,105,105 },\n   { C_solid, 167,167,167,167,167,167 },\n   { C_solid, 120,118,118,118,102,102 },\n   { C_empty }, // cake\n   { C_empty }, // repeater\n   { C_empty }, // repeater\n   { C_solid, 49,49,49,49,49,49 }, // colored glass\n\n   // 96\n   { C_empty },\n   { C_empty },\n   { C_solid, 54,54,54,54,54,54 },\n   { C_solid, 125,125,125,125,125,125 },\n   { C_solid, 126,126,126,126,126,126 },\n   { C_empty }, // bars\n   { C_trans, 49,49,49,49,49,49 }, // glass pane\n   { C_solid, 136,136,136,136,137,137 }, // melon\n\n   // 104\n   { C_empty }, // pumpkin stem\n   { C_empty }, // melon stem\n   { C_empty }, // vines\n   { C_empty }, // gate\n   { C_stair, 7,7,7,7,7,7, }, // brick stairs\n   { C_stair, 54,54,54,54,54,54 }, // stone brick stairs\n   { C_empty }, // mycelium\n   { C_empty }, // lily pad\n\n   // 112\n   { C_solid, 224,224,224,224,224,224 },\n   { C_empty }, // nether brick fence\n   { C_stair, 224,224,224,224,224,224 }, // nether brick stairs\n   { C_empty }, // nether wart\n   { C_solid, 182,182,182,182,166,183 },\n   { C_empty }, // brewing stand\n   { C_empty }, // cauldron\n   { C_empty }, // end portal\n\n   // 120\n   { C_solid, 159,159,159,159,158,158 },\n   { C_solid, 175,175,175,175,175,175 },\n   { C_empty }, // dragon egg\n   { C_solid, 211,211,211,211,211,211 },\n   { C_solid, 212,212,212,212,212,212 },\n   { C_solid, 4,4,4,4,4,4, }, // wood double-slab\n   { C_slab , 4,4,4,4,4,4, }, // wood slab\n   { C_empty }, // cocoa\n\n   // 128\n   { C_solid, 192,192,192,192,176,176 }, // sandstone stairs\n   { C_solid, 32,32,32,32,32,32 }, // emerald ore\n   { C_solid, 26,26,26,27,25,25 }, // ender chest\n   { C_empty },\n   { C_empty },\n   { C_solid, 23,23,23,23,23,23 }, // emerald block\n   { C_solid, 198,198,198,198,198,198 }, // spruce stairs\n   { C_solid, 214,214,214,214,214,214 }, // birch stairs\n\n   // 136\n   { C_stair, 199,199,199,199,199,199 }, // jungle stairs\n   { C_empty }, // command block\n   { C_empty }, // beacon\n   { C_slab, 16,16,16,16,16,16 }, // cobblestone wall\n   { C_empty }, // flower pot\n   { C_empty }, // carrot\n   { C_empty }, // potatoes\n   { C_empty }, // wooden button\n\n   // 144\n   { C_empty }, // mob head\n   { C_empty }, // anvil\n   { C_solid, 26,26,26,27,25,25 }, // trapped chest\n   { C_empty }, // weighted pressure plate light\n   { C_empty }, // weighted pressure plat eheavy\n   { C_empty }, // comparator inactive\n   { C_empty }, // comparator active\n   { C_empty }, // daylight sensor\n\n   // 152\n   { C_solid, 135,135,135,135,135,135 }, // redstone block\n   { C_solid, 0,0,0,0,0,0, }, // nether quartz ore\n   { C_empty }, // hopper\n   { C_solid, 22,22,22,22,22,22 }, // quartz block\n   { C_stair, 22,22,22,22,22,22 }, // quartz stairs\n   { C_empty }, // activator rail\n   { C_solid, 46,45,45,45,62,62 }, // dropper\n   { C_solid, 72,72,72,72,72,72 }, // stained clay\n\n   // 160\n   { C_trans, 49,49,49,49,49,49 }, // stained glass pane\n   #ifdef FANCY_LEAVES\n   { C_force, 52,52,52,52,52,52 }, // leaves\n   #else\n   { C_solid, 53,53,53,53,53,53 }, // acacia leaves\n   #endif\n   { C_solid, 20,20,20,20,21,21 }, // acacia tree\n   { C_solid, 199,199,199,199,199,199 }, // acacia wood stairs\n   { C_solid, 198,198,198,198,198,198 }, // dark oak stairs\n   { C_solid, 146,146,146,146,146,146 }, // slime block\n\n   { C_solid, 176,176,176,176,176,176 }, // red sandstone\n   { C_solid, 176,176,176,176,176,176 }, // red sandstone\n\n   // 168\n   { C_empty },\n   { C_empty },\n   { C_empty },\n   { C_empty },\n   { C_solid, 72,72,72,72,72,72 }, // hardened clay\n   { C_empty },\n   { C_empty },\n   { C_empty },\n\n   // 176\n   { C_empty },\n   { C_empty },\n   { C_solid, 176,176,176,176,176,176 }, // red sandstone\n};\n\nunsigned char minecraft_tex1_for_blocktype[256][6];\nunsigned char effective_blocktype[256];\nunsigned char minecraft_color_for_blocktype[256][6];\nunsigned char minecraft_geom_for_blocktype[256];\n\nuint8 build_buffer[BUILD_BUFFER_SIZE];\nuint8 face_buffer[FACE_BUFFER_SIZE];\n\n//GLuint vbuf, fbuf, fbuf_tex;\n\n//unsigned char tex1_for_blocktype[256][6];\n\n//unsigned char blocktype[34][34][257];\n//unsigned char lighting[34][34][257];\n\n// a superchunk is 64x64x256, with the border blocks computed as well,\n// which means we need 4x4 chunks plus 16 border chunks plus 4 corner chunks\n\n#define SUPERCHUNK_X   4\n#define SUPERCHUNK_Y   4\n\nunsigned char remap_data[16][16];\nunsigned char remap[256];\nunsigned char rotate_data[4] = { 1,3,2,0 };\n\nvoid convert_fastchunk_inplace(fast_chunk *fc)\n{\n   int i;\n   int num_blocks=0, step=0;\n   unsigned char rot[4096];\n   #ifndef IN_PLACE\n   unsigned char *storage;\n   #endif\n\n   memset(rot, 0, 4096);\n\n   for (i=0; i < 16; ++i)\n      num_blocks += fc->blockdata[i] != NULL;\n\n   #ifndef IN_PLACE\n   storage = malloc(16*16*16*2 * num_blocks);\n   #endif\n\n   for (i=0; i < 16; ++i) {\n      if (fc->blockdata[i]) {\n         int o=0;\n         unsigned char *bd,*dd,*lt,*sky;\n         unsigned char *out, *outb;\n\n         // this ordering allows us to determine which data we can safely overwrite for in-place processing\n         bd = fc->blockdata[i];\n         dd = fc->data[i];\n         lt = fc->light[i];\n         sky = fc->skylight[i];\n\n         #ifdef IN_PLACE\n         out = bd;\n         #else\n         out = storage + 16*16*16*2*step;\n         #endif\n\n         // bd is written in place, but also reads from dd\n         for (o=0; o < 16*16*16/2; o += 1) {\n            unsigned char v1,v2;\n            unsigned char d = dd[o];\n            v1 = bd[o*2+0];\n            v2 = bd[o*2+1];\n\n            if (remap[v1])\n            {\n               //unsigned char d = bd[o] & 15;\n               v1 = remap_data[remap[v1]][d&15];\n               rot[o*2+0] = rotate_data[d&3];\n            } else\n               v1 = effective_blocktype[v1];\n\n            if (remap[v2])\n            {\n               //unsigned char d = bd[o] >> 4;\n               v2 = remap_data[remap[v2]][d>>4];\n               rot[o*2+1] = rotate_data[(d>>4)&3];\n            } else\n               v2 = effective_blocktype[v2];\n\n            out[o*2+0] = v1;\n            out[o*2+1] = v2;\n         }\n\n         // this reads from lt & sky\n         #ifndef IN_PLACE\n         outb = out + 16*16*16;\n         ++step;\n         #endif\n\n         // MC used to write in this order and it makes it possible to compute in-place\n         if (dd < sky && sky < lt) {\n            // @TODO go this path always if !IN_PLACE\n            #ifdef IN_PLACE\n            outb = dd;\n            #endif\n\n            for (o=0; o < 16*16*16/2; ++o) {\n               int bright;\n               bright = (lt[o]&15)*12 + 15 + (sky[o]&15)*16;\n               if (bright > 255) bright = 255;\n               if (bright <  32) bright =  32;\n               outb[o*2+0] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+0]&3));\n\n               bright = (lt[o]>>4)*12 + 15 + (sky[o]>>4)*16;\n               if (bright > 255) bright = 255;\n               if (bright <  32) bright =  32;\n               outb[o*2+1] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+1]&3));\n            }\n         } else {\n            // @TODO: if blocktype is in between others, this breaks; need to find which side has two pointers, and use that\n            // overwrite rot[] array, then copy out\n            #ifdef IN_PLACE\n            outb = (dd < sky) ? dd : sky;\n            if (lt < outb) lt = outb;\n            #endif\n\n            for (o=0; o < 16*16*16/2; ++o) {\n               int bright;\n               bright = (lt[o]&15)*12 + 15 + (sky[o]&15)*16;\n               if (bright > 255) bright = 255;\n               if (bright <  32) bright =  32;\n               rot[o*2+0] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+0]&3));\n\n               bright = (lt[o]>>4)*12 + 15 + (sky[o]>>4)*16;\n               if (bright > 255) bright = 255;\n               if (bright <  32) bright =  32;\n               rot[o*2+1] = STBVOX_MAKE_LIGHTING_EXT((unsigned char) bright, (rot[o*2+1]&3));\n            }\n\n            memcpy(outb, rot, 4096);\n            fc->data[i] = outb;\n         }\n\n         #ifndef IN_PLACE\n         fc->blockdata[i] = out;\n         fc->data[i] = outb;\n         #endif\n      }\n   }\n\n   #ifndef IN_PLACE\n   free(fc->pointer_to_free);\n   fc->pointer_to_free = storage;\n   #endif\n}\n\nvoid make_converted_fastchunk(fast_chunk *fc, int x, int y, int segment, uint8 *sv_blocktype, uint8 *sv_lighting)\n{\n   int z;\n   assert(fc == NULL || (fc->refcount > 0 && fc->refcount < 64));\n   if (fc == NULL || fc->blockdata[segment] == NULL) {\n      for (z=0; z < 16; ++z) {\n         sv_blocktype[z] = C_empty;\n         sv_lighting[z] = 255;\n      }\n   } else {\n      unsigned char *block = fc->blockdata[segment];\n      unsigned char *data  = fc->data[segment];\n      y = 15-y;\n      for (z=0; z < 16; ++z) {\n         sv_blocktype[z] = block[z*256 + y*16 + x];\n         sv_lighting [z] = data [z*256 + y*16 + x];\n      }\n   }\n}\n\n\n#define CHUNK_CACHE   64\ntypedef struct\n{\n   int valid;\n   int chunk_x, chunk_y;\n   fast_chunk *fc;\n} cached_converted_chunk;\n\ncached_converted_chunk chunk_cache[CHUNK_CACHE][CHUNK_CACHE];\nint cache_size = CHUNK_CACHE;\n\nvoid reset_cache_size(int size)\n{\n   int i,j;\n   for (j=size; j < cache_size; ++j) {\n      for (i=size; i < cache_size; ++i) {\n         cached_converted_chunk *ccc = &chunk_cache[j][i];\n         if (ccc->valid) {\n            if (ccc->fc) {\n               free(ccc->fc->pointer_to_free);\n               free(ccc->fc);\n               ccc->fc = NULL;\n            }\n            ccc->valid = 0;\n         }\n      }\n   }\n   cache_size = size;\n}\n\n// this must be called inside mutex\nvoid deref_fastchunk(fast_chunk *fc)\n{\n   if (fc) {\n      assert(fc->refcount > 0);\n      --fc->refcount;\n      if (fc->refcount == 0) {\n         free(fc->pointer_to_free);\n         free(fc);\n      }\n   }\n}\n\nSDL_mutex * chunk_cache_mutex;\nSDL_mutex * chunk_get_mutex;\n\nvoid lock_chunk_get_mutex(void)\n{\n   SDL_LockMutex(chunk_get_mutex);\n}\nvoid unlock_chunk_get_mutex(void)\n{\n   SDL_UnlockMutex(chunk_get_mutex);\n}\n\nfast_chunk *get_converted_fastchunk(int chunk_x, int chunk_y)\n{\n   int slot_x = (chunk_x & (cache_size-1));\n   int slot_y = (chunk_y & (cache_size-1));\n   fast_chunk *fc;\n   cached_converted_chunk *ccc;\n   SDL_LockMutex(chunk_cache_mutex);\n   ccc = &chunk_cache[slot_y][slot_x];\n   if (ccc->valid) {\n      if (ccc->chunk_x == chunk_x && ccc->chunk_y == chunk_y) {\n         fast_chunk *fc = ccc->fc;\n         if (fc)\n            ++fc->refcount;\n         SDL_UnlockMutex(chunk_cache_mutex);\n         return fc;\n      }\n      if (ccc->fc) {\n         deref_fastchunk(ccc->fc);\n         ccc->fc = NULL;\n         ccc->valid = 0;\n      }\n   }\n   SDL_UnlockMutex(chunk_cache_mutex);\n\n   fc = get_decoded_fastchunk_uncached(chunk_x, -chunk_y);\n   if (fc)\n      convert_fastchunk_inplace(fc);\n\n   SDL_LockMutex(chunk_cache_mutex);\n   // another thread might have updated it, so before we overwrite it...\n   if (ccc->fc) {\n      deref_fastchunk(ccc->fc);\n      ccc->fc = NULL;\n   }\n\n   if (fc)\n      fc->refcount = 1; // 1 in the cache\n\n   ccc->chunk_x = chunk_x;\n   ccc->chunk_y = chunk_y;\n   ccc->valid = 1;\n   if (fc)\n      ++fc->refcount;\n   ccc->fc = fc;\n   SDL_UnlockMutex(chunk_cache_mutex);\n   return fc;\n}\n\nvoid make_map_segment_for_superchunk_preconvert(int chunk_x, int chunk_y, int segment, fast_chunk *fc_table[4][4], uint8 sv_blocktype[34][34][18], uint8 sv_lighting[34][34][18])\n{\n   int a,b;\n   assert((chunk_x & 1) == 0);\n   assert((chunk_y & 1) == 0);\n   for (b=-1; b < 3; ++b) {\n      for (a=-1; a < 3; ++a) {\n         int xo = a*16+1;\n         int yo = b*16+1;\n         int x,y;\n         fast_chunk *fc = fc_table[b+1][a+1];\n         for (y=0; y < 16; ++y)\n            for (x=0; x < 16; ++x)\n               if (xo+x >= 0 && xo+x < 34 && yo+y >= 0 && yo+y < 34)\n                  make_converted_fastchunk(fc,x,y, segment, sv_blocktype[xo+x][yo+y], sv_lighting[xo+x][yo+y]);\n      }\n   }\n}\n\n// build 1 mesh covering 2x2 chunks\nvoid build_chunk(int chunk_x, int chunk_y, fast_chunk *fc_table[4][4], raw_mesh *rm)\n{\n   int a,b,z;\n   stbvox_input_description *map;\n\n   #ifdef VHEIGHT_TEST\n   unsigned char vheight[34][34][18];\n   #endif\n\n   #ifndef STBVOX_CONFIG_DISABLE_TEX2\n   unsigned char tex2_choice[34][34][18];\n   #endif\n\n   assert((chunk_x & 1) == 0);\n   assert((chunk_y & 1) == 0);\n\n   rm->cx = chunk_x;\n   rm->cy = chunk_y;\n\n   stbvox_set_input_stride(&rm->mm, 34*18, 18);\n\n   assert(rm->mm.input.geometry == NULL);\n\n   map = stbvox_get_input_description(&rm->mm);\n   map->block_tex1_face = minecraft_tex1_for_blocktype;\n   map->block_color_face = minecraft_color_for_blocktype;\n   map->block_geometry = minecraft_geom_for_blocktype;\n\n   stbvox_reset_buffers(&rm->mm);\n   stbvox_set_buffer(&rm->mm, 0, 0, rm->build_buffer, BUILD_BUFFER_SIZE);\n   stbvox_set_buffer(&rm->mm, 0, 1, rm->face_buffer , FACE_BUFFER_SIZE);\n\n   map->blocktype = &rm->sv_blocktype[1][1][1]; // this is (0,0,0), but we need to be able to query off the edges\n   map->lighting = &rm->sv_lighting[1][1][1];\n\n   // fill in the top two rows of the buffer\n   for (a=0; a < 34; ++a) {\n      for (b=0; b < 34; ++b) {\n         rm->sv_blocktype[a][b][16] = 0;\n         rm->sv_lighting [a][b][16] = 255;\n         rm->sv_blocktype[a][b][17] = 0;\n         rm->sv_lighting [a][b][17] = 255;\n      }\n   }\n\n   #ifndef STBVOX_CONFIG_DISABLE_TEX2\n   for (a=0; a < 34; ++a) {\n      for (b=0; b < 34; ++b) {\n         int px = chunk_x*16 + a - 1;\n         int py = chunk_y*16 + b - 1;\n         float dist = (float) sqrt(px*px + py*py);\n         float s1 = (float) sin(dist / 16), s2, s3;\n         dist = (float) sqrt((px-80)*(px-80) + (py-50)*(py-50));\n         s2 = (float) sin(dist / 11);\n         for (z=0; z < 18; ++z) {\n            s3 = (float) sin(z * 3.141592 / 8);\n\n            s3 = s1*s2*s3;\n            tex2_choice[a][b][z] = 63 & (int) stb_linear_remap(s3,-1,1, -20,83);\n         }\n      }\n   }\n   #endif\n\n   for (z=256-16; z >= SKIP_TERRAIN; z -= 16)\n   {\n      int z0 = z;\n      int z1 = z+16;\n      if (z1 == 256) z1 = 255;\n\n      make_map_segment_for_superchunk_preconvert(chunk_x, chunk_y, z >> 4, fc_table, rm->sv_blocktype, rm->sv_lighting);\n\n      map->blocktype = &rm->sv_blocktype[1][1][1-z]; // specify location of 0,0,0 so that accessing z0..z1 gets right data\n      map->lighting = &rm->sv_lighting[1][1][1-z];\n      #ifndef STBVOX_CONFIG_DISABLE_TEX2\n      map->tex2 = &tex2_choice[1][1][1-z];\n      #endif\n\n      #ifdef VHEIGHT_TEST\n      // hacky test of vheight\n      for (a=0; a < 34; ++a) {\n         for (b=0; b < 34; ++b) {\n            int c;\n            for (c=0; c < 17; ++c) {\n               if (rm->sv_blocktype[a][b][c] != 0 && rm->sv_blocktype[a][b][c+1] == 0) {\n                  // topmost block\n                  vheight[a][b][c] = rand() & 255;\n                  rm->sv_blocktype[a][b][c] = 168;\n               } else if (c > 0 && rm->sv_blocktype[a][b][c] != 0 && rm->sv_blocktype[a][b][c-1] == 0) {\n                  // bottommost block\n                  vheight[a][b][c] = ((rand() % 3) << 6) + ((rand() % 3) << 4) + ((rand() % 3) << 2) + (rand() % 3);\n                  rm->sv_blocktype[a][b][c] = 169;\n               }\n            }\n            vheight[a][b][c] = STBVOX_MAKE_VHEIGHT(2,2,2,2); // flat top\n         }\n      }\n      map->vheight = &vheight[1][1][1-z];\n      #endif\n\n      {\n         stbvox_set_input_range(&rm->mm, 0,0,z0, 32,32,z1);\n         stbvox_set_default_mesh(&rm->mm, 0);\n         stbvox_make_mesh(&rm->mm);\n      }\n\n      // copy the bottom two rows of data up to the top\n      for (a=0; a < 34; ++a) {\n         for (b=0; b < 34; ++b) {\n            rm->sv_blocktype[a][b][16] = rm->sv_blocktype[a][b][0];\n            rm->sv_blocktype[a][b][17] = rm->sv_blocktype[a][b][1];\n            rm->sv_lighting [a][b][16] = rm->sv_lighting [a][b][0];\n            rm->sv_lighting [a][b][17] = rm->sv_lighting [a][b][1];\n         }\n      }\n   }\n\n   stbvox_set_mesh_coordinates(&rm->mm, chunk_x*16, chunk_y*16, 0);\n   stbvox_get_transform(&rm->mm, rm->transform);\n\n   stbvox_set_input_range(&rm->mm, 0,0,0, 32,32,255);\n   stbvox_get_bounds(&rm->mm, rm->bounds);\n\n   rm->num_quads = stbvox_get_quad_count(&rm->mm, 0);\n}\n\nint next_blocktype = 255;\n\nunsigned char mc_rot[4] = { 1,3,2,0 };\n\n// create blocktypes with rotation baked into type...\n// @TODO we no longer need this now that we store rotations\n// in lighting\nvoid build_stair_rotations(int blocktype, unsigned char *map)\n{\n   int i;\n\n   // use the existing block type for floor stairs; allocate a new type for ceil stairs\n   for (i=0; i < 6; ++i) {\n      minecraft_color_for_blocktype[next_blocktype][i] = minecraft_color_for_blocktype[blocktype][i];\n      minecraft_tex1_for_blocktype [next_blocktype][i] = minecraft_tex1_for_blocktype [blocktype][i];\n   }\n   minecraft_geom_for_blocktype[next_blocktype] = (unsigned char) STBVOX_MAKE_GEOMETRY(STBVOX_GEOM_ceil_slope_north_is_bottom, 0, 0);\n   minecraft_geom_for_blocktype[     blocktype] = (unsigned char) STBVOX_MAKE_GEOMETRY(STBVOX_GEOM_floor_slope_north_is_top, 0, 0);\n\n   for (i=0; i < 4; ++i) {\n      map[0+i+8] = map[0+i] =      blocktype;\n      map[4+i+8] = map[4+i] = next_blocktype;\n   }\n   --next_blocktype;\n}\n\nvoid build_wool_variations(int bt, unsigned char *map)\n{\n   int i,k;\n   unsigned char tex[16] = { 64, 210, 194, 178,  162, 146, 130, 114,  225, 209, 193, 177,  161, 145, 129, 113 };\n   for (i=0; i < 16; ++i) {\n      if (i == 0)\n         map[i] = bt;\n      else {\n         map[i] = next_blocktype;\n         for (k=0; k < 6; ++k) {\n            minecraft_tex1_for_blocktype[next_blocktype][k] = tex[i];\n         }\n         minecraft_geom_for_blocktype[next_blocktype] = minecraft_geom_for_blocktype[bt];\n         --next_blocktype;\n      }\n   }\n}\n\nvoid build_wood_variations(int bt, unsigned char *map)\n{\n   int i,k;\n   unsigned char tex[4] = { 5, 198, 214, 199 };\n   for (i=0; i < 4; ++i) {\n      if (i == 0)\n         map[i] = bt;\n      else {\n         map[i] = next_blocktype;\n         for (k=0; k < 6; ++k) {\n            minecraft_tex1_for_blocktype[next_blocktype][k] = tex[i];\n         }\n         minecraft_geom_for_blocktype[next_blocktype] = minecraft_geom_for_blocktype[bt];\n         --next_blocktype;\n      }\n   }\n   map[i] = map[i-1];\n   ++i;\n   for (; i < 16; ++i)\n      map[i] = bt;\n}\n\nvoid remap_in_place(int bt, int rm)\n{\n   int i;\n   remap[bt] = rm;\n   for (i=0; i < 16; ++i)\n      remap_data[rm][i] = bt;\n}\n\n\nvoid mesh_init(void)\n{\n   int i;\n\n   chunk_cache_mutex = SDL_CreateMutex();\n   chunk_get_mutex   = SDL_CreateMutex();\n\n   for (i=0; i < 256; ++i) {\n      memcpy(minecraft_tex1_for_blocktype[i], minecraft_info[i]+1, 6);\n      effective_blocktype[i] = (minecraft_info[i][0] == C_empty ? 0 : i);\n      minecraft_geom_for_blocktype[i] = geom_map[minecraft_info[i][0]];\n   }\n   //effective_blocktype[50] = 0; // delete torches\n\n   for (i=0; i < 6*256; ++i) {\n      if (minecraft_tex1_for_blocktype[0][i] == 40)\n         minecraft_color_for_blocktype[0][i] = 38 | 64; // apply to tex1\n      if (minecraft_tex1_for_blocktype[0][i] == 39)\n         minecraft_color_for_blocktype[0][i] = 39 | 64; // apply to tex1\n      if (minecraft_tex1_for_blocktype[0][i] == 105)\n         minecraft_color_for_blocktype[0][i] = 63; // emissive\n      if (minecraft_tex1_for_blocktype[0][i] == 212)\n         minecraft_color_for_blocktype[0][i] = 63; // emissive\n      if (minecraft_tex1_for_blocktype[0][i] == 80)\n         minecraft_color_for_blocktype[0][i] = 63; // emissive\n   }\n\n   for (i=0; i < 6; ++i) {\n      minecraft_color_for_blocktype[172][i] = 47 | 64; // apply to tex1\n      minecraft_color_for_blocktype[178][i] = 47 | 64; // apply to tex1\n      minecraft_color_for_blocktype[18][i] = 39 | 64; // green\n      minecraft_color_for_blocktype[161][i] = 37 | 64; // green\n      minecraft_color_for_blocktype[10][i] = 63; // emissive lava\n      minecraft_color_for_blocktype[11][i] = 63; // emissive\n      //minecraft_color_for_blocktype[56][i] = 63; // emissive diamond\n      minecraft_color_for_blocktype[48][i] = 63; // emissive dungeon\n   }\n\n   #ifdef VHEIGHT_TEST\n   effective_blocktype[168] = 168;\n   minecraft_tex1_for_blocktype[168][0] = 1;\n   minecraft_tex1_for_blocktype[168][1] = 1;\n   minecraft_tex1_for_blocktype[168][2] = 1;\n   minecraft_tex1_for_blocktype[168][3] = 1;\n   minecraft_tex1_for_blocktype[168][4] = 1;\n   minecraft_tex1_for_blocktype[168][5] = 1;\n   minecraft_geom_for_blocktype[168] = STBVOX_GEOM_floor_vheight_12;\n   effective_blocktype[169] = 169;\n   minecraft_tex1_for_blocktype[169][0] = 1;\n   minecraft_tex1_for_blocktype[169][1] = 1;\n   minecraft_tex1_for_blocktype[169][2] = 1;\n   minecraft_tex1_for_blocktype[169][3] = 1;\n   minecraft_tex1_for_blocktype[169][4] = 1;\n   minecraft_tex1_for_blocktype[169][5] = 1;\n   minecraft_geom_for_blocktype[169] = STBVOX_GEOM_ceil_vheight_03;\n   #endif\n\n   remap[53] = 1;\n   remap[67] = 2;\n   remap[108] = 3;\n   remap[109] = 4;\n   remap[114] = 5;\n   remap[136] = 6;\n   remap[156] = 7;\n   for (i=0; i < 256; ++i)\n      if (remap[i])\n         build_stair_rotations(i, remap_data[remap[i]]);\n   remap[35]  = 8;\n   build_wool_variations(35, remap_data[remap[35]]);\n   remap[5] = 11;\n   build_wood_variations(5, remap_data[remap[5]]);\n\n   // set the remap flags for these so they write the rotation values\n   remap_in_place(54, 9);\n   remap_in_place(146, 10);\n}\n\n// Timing stats while optimizing the single-threaded builder\n\n// 32..-32, 32..-32, SKIP_TERRAIN=0, !FANCY_LEAVES on 'mcrealm' data set\n\n// 6.27s  - reblocked to do 16 z at a time instead of 256 (still using 66x66x258), 4 meshes in parallel\n// 5.96s  - reblocked to use FAST_CHUNK (no intermediate data structure)\n// 5.45s  - unknown change, or previous measurement was wrong\n\n// 6.12s  - use preconverted data, not in-place\n// 5.91s  - use preconverted, in-place\n// 5.34s  - preconvert, in-place, avoid dependency chain (suggested by ryg)\n// 5.34s  - preconvert, in-place, avoid dependency chain, use bit-table instead of byte-table\n// 5.50s  - preconvert, in-place, branchless\n\n// 6.42s  - non-preconvert, avoid dependency chain (not an error)\n// 5.40s  - non-preconvert, w/dependency chain (same as earlier)\n\n// 5.50s  - non-FAST_CHUNK, reblocked outer loop for better cache reuse\n// 4.73s  - FAST_CHUNK non-preconvert, reblocked outer loop\n// 4.25s  - preconvert, in-place, reblocked outer loop\n// 4.18s  - preconvert, in-place, unrolled again\n// 4.10s  - 34x34 1 mesh instead of 66x66 and 4 meshes (will make it easier to do multiple threads)\n\n// 4.83s  - building bitmasks but not using them (2 bits per block, one if empty, one if solid)\n\n// 5.16s  - using empty bitmasks to early out\n// 5.01s  - using solid & empty bitmasks to early out - \"foo\"\n// 4.64s  - empty bitmask only, test 8 at a time, then test geom\n// 4.72s  - empty bitmask only, 8 at a time, then test bits\n// 4.46s  - split bitmask building into three loops (each byte is separate)\n// 4.42s  - further optimize computing bitmask\n\n// 4.58s  - using solid & empty bitmasks to early out, same as \"foo\" but faster bitmask building\n// 4.12s  - using solid & empty bitmasks to efficiently test neighbors\n// 4.04s  - using 16-bit fetches (not endian-independent)\n//        - note this is first place that beats previous best '4.10s - 34x34 1 mesh'\n\n// 4.30s  - current time with bitmasks disabled again (note was 4.10s earlier)\n// 3.95s  - bitmasks enabled again, no other changes\n// 4.00s  - current time with bitmasks disabled again, no other changes -- wide variation that is time dependent?\n//          (note that most of the numbers listed here are median of 3 values already)\n// 3.98s  - bitmasks enabled\n\n// Bitmasks removed from the code as not worth the complexity increase\n\n\n\n// Raw data for Q&A:\n//\n//   26% parsing & loading minecraft files (4/5ths of which is zlib decode)\n//   39% building mesh from stb input format\n//   18% converting from minecraft blocks to stb blocks\n//    9% reordering from minecraft axis order to stb axis order\n//    7% uploading vertex buffer to OpenGL\n"
  },
  {
    "path": "tests/caveview/cave_parse.c",
    "content": "#include <assert.h>\n#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n\n#define FAST_CHUNK   // disabling this enables the old, slower path that deblocks into a regular form\n\n#include \"cave_parse.h\"\n\n#include \"stb_image.h\"\n#include \"stb.h\"\n\n#define NUM_CHUNKS_PER_REGION       32  // only on one axis\n#define NUM_CHUNKS_PER_REGION_LOG2   5\n\n#define NUM_COLUMNS_PER_CHUNK       16\n#define NUM_COLUMNS_PER_CHUNK_LOG2   4\n\nuint32 read_uint32_be(FILE *f)\n{\n   unsigned char data[4];\n   fread(data, 1, 4, f);\n   return (data[0]<<24) + (data[1]<<16) + (data[2]<<8) + data[3];\n}\n\ntypedef struct\n{\n   uint8 *data;\n   size_t len;\n   int x,z; // chunk index\n   int refcount; // for multi-threading\n} compressed_chunk;\n\ntypedef struct\n{\n   int x,z;\n   uint32 sector_data[NUM_CHUNKS_PER_REGION][NUM_CHUNKS_PER_REGION];\n} region;\n\nsize_t cached_compressed=0;\n\nFILE *last_region;\nint last_region_x;\nint last_region_z;\nint opened=0;\n\nstatic void open_file(int reg_x, int reg_z)\n{\n   if (!opened || last_region_x != reg_x || last_region_z != reg_z) {\n      char filename[256];\n      if (last_region != NULL)\n         fclose(last_region);\n      sprintf(filename, \"r.%d.%d.mca\", reg_x, reg_z);\n      last_region = fopen(filename, \"rb\");\n      last_region_x = reg_x;\n      last_region_z = reg_z;\n      opened = 1;\n   }\n}\n\nstatic region *load_region(int reg_x, int reg_z)\n{\n   region *r;\n   int x,z;\n\n   open_file(reg_x, reg_z);\n\n   r = malloc(sizeof(*r));\n\n   if (last_region == NULL) {\n      memset(r, 0, sizeof(*r));\n   } else {\n      fseek(last_region, 0, SEEK_SET);\n      for (z=0; z < NUM_CHUNKS_PER_REGION; ++z)\n         for (x=0; x < NUM_CHUNKS_PER_REGION; ++x)\n            r->sector_data[z][x] = read_uint32_be(last_region);\n   }\n   r->x = reg_x;\n   r->z = reg_z;\n\n   return r;\n}\n\nvoid free_region(region *r)\n{\n   free(r);\n}\n\n#define MAX_MAP_REGIONS   64  // in one axis: 64 regions * 32 chunk/region * 16 columns/chunk = 16384 columns\nregion *regions[MAX_MAP_REGIONS][MAX_MAP_REGIONS];\n\nstatic region *get_region(int reg_x, int reg_z)\n{\n   int slot_x = reg_x & (MAX_MAP_REGIONS-1);\n   int slot_z = reg_z & (MAX_MAP_REGIONS-1);\n   region *r;\n\n   r = regions[slot_z][slot_x];\n\n   if (r) {\n      if (r->x == reg_x && r->z == reg_z)\n         return r;\n      free_region(r);\n   }\n\n   r = load_region(reg_x, reg_z);\n   regions[slot_z][slot_x] = r;\n\n   return r;\n}\n\n// about one region, so size should be ok\n#define NUM_CACHED_X 64\n#define NUM_CACHED_Z 64\n\n// @TODO: is it really worth caching these? we probably can just\n// pull them from the disk cache nearly as efficiently.\n// Can test that by setting to 1x1?\ncompressed_chunk *cached_chunk[NUM_CACHED_Z][NUM_CACHED_X];\n\nstatic void deref_compressed_chunk(compressed_chunk *cc)\n{\n   assert(cc->refcount > 0);\n   --cc->refcount;\n   if (cc->refcount == 0) {\n      if (cc->data)\n         free(cc->data);\n      free(cc);\n   }\n}\n\nstatic compressed_chunk *get_compressed_chunk(int chunk_x, int chunk_z)\n{\n   int slot_x = chunk_x & (NUM_CACHED_X-1);\n   int slot_z = chunk_z & (NUM_CACHED_Z-1);\n   compressed_chunk *cc = cached_chunk[slot_z][slot_x];\n\n   if (cc && cc->x == chunk_x && cc->z == chunk_z)\n      return cc;\n   else {\n      int reg_x = chunk_x >> NUM_CHUNKS_PER_REGION_LOG2;\n      int reg_z = chunk_z >> NUM_CHUNKS_PER_REGION_LOG2;\n      region *r = get_region(reg_x, reg_z);\n      if (cc) {\n         deref_compressed_chunk(cc);\n         cached_chunk[slot_z][slot_x] = NULL;\n      }\n      cc = malloc(sizeof(*cc));\n      cc->x = chunk_x;\n      cc->z = chunk_z;\n      {\n         int subchunk_x = chunk_x & (NUM_CHUNKS_PER_REGION-1);\n         int subchunk_z = chunk_z & (NUM_CHUNKS_PER_REGION-1);\n         uint32 code = r->sector_data[subchunk_z][subchunk_x];\n\n         if (code & 255) {\n            open_file(reg_x, reg_z);\n            fseek(last_region, (code>>8)*4096, SEEK_SET);\n            cc->len = (code&255)*4096;\n            cc->data = malloc(cc->len);\n            fread(cc->data, 1, cc->len, last_region);\n         } else {\n            cc->len = 0;\n            cc->data = 0;\n         }\n      }\n      cc->refcount = 1;\n      cached_chunk[slot_z][slot_x] = cc;\n      return cc;\n   }\n}\n\n\n// NBT parser -- can automatically parse stuff we don't\n// have definitions for, but want to explicitly parse\n// stuff we do have definitions for.\n//\n// option 1: auto-parse everything into data structures,\n// then read those\n//\n// option 2: have a \"parse next object\" which\n// doesn't resolve whether it expands its children\n// yet, and then the user either says \"expand\" or\n// \"skip\" after looking at the name. Anything with\n// \"children\" without names can't go through this\n// interface.\n//\n// Let's try option 2.\n\n\ntypedef struct\n{\n   unsigned char *buffer_start;\n   unsigned char *buffer_end;\n   unsigned char *cur;\n   int nesting;\n   char temp_buffer[256];\n} nbt;\n\nenum { TAG_End=0, TAG_Byte=1, TAG_Short=2, TAG_Int=3, TAG_Long=4,\n       TAG_Float=5, TAG_Double=6, TAG_Byte_Array=7, TAG_String=8,\n       TAG_List=9, TAG_Compound=10, TAG_Int_Array=11 };\n\nstatic void nbt_get_string_data(unsigned char *data, char *buffer, size_t bufsize)\n{\n   int len = data[0]*256 + data[1];\n   int i;\n   for (i=0; i < len && i+1 < (int) bufsize; ++i)\n      buffer[i] = (char) data[i+2];\n   buffer[i] = 0;\n}\n\nstatic char *nbt_peek(nbt *n)\n{\n   unsigned char type = *n->cur;\n   if (type == TAG_End)\n      return NULL;\n   nbt_get_string_data(n->cur+1, n->temp_buffer, sizeof(n->temp_buffer));\n   return n->temp_buffer;\n}\n\nstatic uint32 nbt_parse_uint32(unsigned char *buffer)\n{\n   return (buffer[0] << 24) + (buffer[1]<<16) + (buffer[2]<<8) + buffer[3];\n}\n\nstatic void nbt_skip(nbt *n);\n\n// skip an item that doesn't have an id or name prefix (usable in lists)\nstatic void nbt_skip_raw(nbt *n, unsigned char type)\n{\n   switch (type) {\n      case TAG_Byte  : n->cur += 1; break;\n      case TAG_Short : n->cur += 2; break;\n      case TAG_Int   : n->cur += 4; break;\n      case TAG_Long  : n->cur += 8; break;\n      case TAG_Float : n->cur += 4; break;\n      case TAG_Double: n->cur += 8; break;\n      case TAG_Byte_Array: n->cur += 4 + 1*nbt_parse_uint32(n->cur); break;\n      case TAG_Int_Array : n->cur += 4 + 4*nbt_parse_uint32(n->cur); break;\n      case TAG_String    : n->cur += 2 + (n->cur[0]*256 + n->cur[1]); break;\n      case TAG_List      : {\n         unsigned char list_type = *n->cur++;\n         unsigned int list_len = nbt_parse_uint32(n->cur);\n         unsigned int i;\n         n->cur += 4; // list_len\n         for (i=0; i < list_len; ++i)\n            nbt_skip_raw(n, list_type);\n         break;\n      }\n      case TAG_Compound : {\n         while (*n->cur != TAG_End)\n            nbt_skip(n);\n         nbt_skip(n); // skip the TAG_end\n         break;\n      }\n   }\n   assert(n->cur <= n->buffer_end);\n}\n\nstatic void nbt_skip(nbt *n)\n{\n   unsigned char type = *n->cur++;\n   if (type == TAG_End)\n      return;\n   // skip name\n   n->cur += (n->cur[0]*256 + n->cur[1]) + 2;\n   nbt_skip_raw(n, type);\n}\n\n// byteswap\nstatic void nbt_swap(unsigned char *ptr, int len)\n{\n   int i;\n   for (i=0; i < (len>>1); ++i) {\n      unsigned char t = ptr[i];\n      ptr[i] = ptr[len-1-i];\n      ptr[len-1-i] = t;\n   }\n}\n\n// pass in the expected type, fail if doesn't match\n// returns a pointer to the data, byteswapped if appropriate\nstatic void *nbt_get_fromlist(nbt *n, unsigned char type, int *len)\n{\n   unsigned char *ptr;\n   assert(type != TAG_Compound);\n   assert(type != TAG_List); // we could support getting lists of primitives as if they were arrays, but eh\n   if (len) *len = 1;\n   ptr = n->cur;\n   switch (type) {\n      case TAG_Byte  : break;\n\n      case TAG_Short : nbt_swap(ptr, 2); break;\n      case TAG_Int   : nbt_swap(ptr, 4); break;\n      case TAG_Long  : nbt_swap(ptr, 8); break;\n      case TAG_Float : nbt_swap(ptr, 4); break;\n      case TAG_Double: nbt_swap(ptr, 8); break;\n\n      case TAG_Byte_Array:\n         *len = nbt_parse_uint32(ptr);\n         ptr += 4;\n         break;\n      case TAG_Int_Array: {\n         int i;\n         *len = nbt_parse_uint32(ptr);\n         ptr += 4;\n         for (i=0; i < *len; ++i)\n            nbt_swap(ptr + 4*i, 4);\n         break;\n      }\n\n      default: assert(0); // unhandled case\n   }\n   nbt_skip_raw(n, type);\n   return ptr;\n}\n\nstatic void *nbt_get(nbt *n, unsigned char type, int *len)\n{\n   assert(n->cur[0] == type);\n   n->cur += 3 + (n->cur[1]*256+n->cur[2]);\n   return nbt_get_fromlist(n, type, len);\n}\n\nstatic void nbt_begin_compound(nbt *n) // start a compound\n{\n   assert(*n->cur == TAG_Compound);\n   // skip header\n   n->cur += 3 + (n->cur[1]*256 + n->cur[2]);\n   ++n->nesting;\n}\n\nstatic void nbt_begin_compound_in_list(nbt *n) // start a compound\n{\n   ++n->nesting;\n}\n\nstatic void nbt_end_compound(nbt *n) // end a compound\n{\n   assert(*n->cur == TAG_End);\n   assert(n->nesting != 0);\n   ++n->cur;\n   --n->nesting;   \n}\n\n// @TODO no interface to get lists from lists\nstatic int nbt_begin_list(nbt *n, unsigned char type)\n{\n   uint32 len;\n   unsigned char *ptr;\n\n   ptr = n->cur + 3 + (n->cur[1]*256 + n->cur[2]);\n   if (ptr[0] != type)\n      return -1;\n   n->cur = ptr;\n   len = nbt_parse_uint32(n->cur+1);\n   assert(n->cur[0] == type);\n   // @TODO keep a stack with the count to make sure they do it right\n   ++n->nesting;\n   n->cur += 5;\n   return (int) len;\n}\n\nstatic void nbt_end_list(nbt *n)\n{\n   --n->nesting;\n}\n\n// raw_block chunk is 16x256x16x4 = 2^(4+8+4+2) = 256KB\n//\n// if we want to process 64x64x256 at a time, that will be:\n//    4*4*256KB => 4MB per area in raw_block\n//\n// (plus we maybe need to decode adjacent regions)\n\n\n#ifdef FAST_CHUNK\ntypedef fast_chunk parse_chunk;\n#else\ntypedef chunk parse_chunk;\n#endif\n\nstatic parse_chunk *minecraft_chunk_parse(unsigned char *data, size_t len)\n{\n   char *s;\n   parse_chunk *c = NULL;\n\n   nbt n_store, *n = &n_store;\n   n->buffer_start = data;\n   n->buffer_end   = data + len;\n   n->cur = n->buffer_start;\n   n->nesting = 0;\n\n   nbt_begin_compound(n);\n   while ((s = nbt_peek(n)) != NULL) {\n      if (!strcmp(s, \"Level\")) {\n         int *height;\n         c = malloc(sizeof(*c));\n         #ifdef FAST_CHUNK\n         memset(c, 0, sizeof(*c));\n         c->pointer_to_free = data;\n         #else\n         c->rb[15][15][255].block = 0;\n         #endif\n         c->max_y = 0;\n\n         nbt_begin_compound(n);\n         while ((s = nbt_peek(n)) != NULL) {\n            if (!strcmp(s, \"xPos\"))\n               c->xpos = *(int *) nbt_get(n, TAG_Int, 0);\n            else if (!strcmp(s, \"zPos\"))\n               c->zpos = *(int *) nbt_get(n, TAG_Int, 0);\n            else if (!strcmp(s, \"Sections\")) {\n               int count = nbt_begin_list(n, TAG_Compound), i;\n               if (count == -1) {\n                  // this not-a-list case happens in The End and I'm not sure\n                  // what it means... possibly one of those silly encodings\n                  // where it's not encoded as a list if there's only one?\n                  // not worth figuring out\n                  nbt_skip(n);\n                  count = -1;\n               }\n               for (i=0; i < count; ++i) {\n                  int yi, len;\n                  uint8 *light = NULL, *blocks = NULL, *data = NULL, *skylight = NULL;\n                  nbt_begin_compound_in_list(n);\n                  while ((s = nbt_peek(n)) != NULL) {\n                     if (!strcmp(s, \"Y\"))\n                        yi = * (uint8 *) nbt_get(n, TAG_Byte, 0);\n                     else if (!strcmp(s, \"BlockLight\")) {\n                        light = nbt_get(n, TAG_Byte_Array, &len);\n                        assert(len == 2048);\n                     } else if (!strcmp(s, \"Blocks\")) {\n                        blocks = nbt_get(n, TAG_Byte_Array, &len);\n                        assert(len == 4096);\n                     } else if (!strcmp(s, \"Data\")) {\n                        data = nbt_get(n, TAG_Byte_Array, &len);\n                        assert(len == 2048);\n                     } else if (!strcmp(s, \"SkyLight\")) {\n                        skylight = nbt_get(n, TAG_Byte_Array, &len);\n                        assert(len == 2048);\n                     }\n                  }\n                  nbt_end_compound(n);\n\n                  assert(yi < 16);\n\n                  #ifndef FAST_CHUNK\n\n                  // clear data below current max_y\n                  {\n                     int x,z;\n                     while (c->max_y < yi*16) {\n                        for (x=0; x < 16; ++x)\n                           for (z=0; z < 16; ++z)\n                              c->rb[z][x][c->max_y].block = 0;\n                        ++c->max_y;\n                     }\n                  }\n\n                  // now assemble the data\n                  {\n                     int x,y,z, o2=0,o4=0;\n                     for (y=0; y < 16; ++y) {\n                        for (z=0; z < 16; ++z) {\n                           for (x=0; x < 16; x += 2) {\n                              raw_block *rb = &c->rb[15-z][x][y + yi*16]; // 15-z because switching to z-up will require flipping an axis\n                              rb[0].block = blocks[o4];\n                              rb[0].light = light[o2] & 15;\n                              rb[0].data  = data[o2] & 15;\n                              rb[0].skylight = skylight[o2] & 15;\n\n                              rb[256].block = blocks[o4+1];\n                              rb[256].light = light[o2] >> 4;\n                              rb[256].data  = data[o2] >> 4;\n                              rb[256].skylight = skylight[o2] >> 4;\n\n                              o2 += 1;\n                              o4 += 2;\n                           }\n                        }\n                     }\n                     c->max_y += 16;\n                  }\n                  #else\n                  c->blockdata[yi] = blocks;\n                  c->data     [yi] = data;\n                  c->light    [yi] = light;\n                  c->skylight [yi] = skylight;\n                  #endif\n               }\n               //nbt_end_list(n);\n            } else if (!strcmp(s, \"HeightMap\")) {\n               height = nbt_get(n, TAG_Int_Array, &len);\n               assert(len == 256);\n            } else\n               nbt_skip(n);\n         }\n         nbt_end_compound(n);\n\n      } else\n         nbt_skip(n);\n   }\n   nbt_end_compound(n);\n   assert(n->cur == n->buffer_end);\n   return c;\n}\n\n#define MAX_DECODED_CHUNK_X  64\n#define MAX_DECODED_CHUNK_Z  64\n\ntypedef struct\n{\n   int cx,cz;\n   fast_chunk *fc;\n   int valid;\n} decoded_buffer;\n\nstatic decoded_buffer decoded_buffers[MAX_DECODED_CHUNK_Z][MAX_DECODED_CHUNK_X];\nvoid lock_chunk_get_mutex(void);\nvoid unlock_chunk_get_mutex(void);\n\n#ifdef FAST_CHUNK\nfast_chunk *get_decoded_fastchunk_uncached(int chunk_x, int chunk_z)\n{\n   unsigned char *decoded;\n   compressed_chunk *cc;\n   int inlen;\n   int len;\n   fast_chunk *fc;\n\n   lock_chunk_get_mutex();\n   cc = get_compressed_chunk(chunk_x, chunk_z);\n   if (cc->len != 0)\n      ++cc->refcount;\n   unlock_chunk_get_mutex();\n\n   if (cc->len == 0)\n      return NULL;\n\n   assert(cc != NULL);\n\n   assert(cc->data[4] == 2);\n\n   inlen = nbt_parse_uint32(cc->data);\n   decoded = stbi_zlib_decode_malloc_guesssize(cc->data+5, inlen, inlen*3, &len);\n   assert(decoded != NULL);\n   assert(len != 0);\n\n   lock_chunk_get_mutex();\n   deref_compressed_chunk(cc);\n   unlock_chunk_get_mutex();\n\n   #ifdef FAST_CHUNK\n   fc = minecraft_chunk_parse(decoded, len);\n   #else\n   fc = NULL;\n   #endif\n   if (fc == NULL)\n      free(decoded);\n   return fc;\n}\n\n\ndecoded_buffer *get_decoded_buffer(int chunk_x, int chunk_z)\n{\n   decoded_buffer *db = &decoded_buffers[chunk_z&(MAX_DECODED_CHUNK_Z-1)][chunk_x&(MAX_DECODED_CHUNK_X-1)];\n   if (db->valid) {\n      if (db->cx == chunk_x && db->cz == chunk_z)\n         return db;\n      if (db->fc) {\n         free(db->fc->pointer_to_free);\n         free(db->fc);\n      }\n   }\n\n   db->cx = chunk_x;\n   db->cz = chunk_z;\n   db->valid = 1;\n   db->fc = 0;\n\n   {\n      db->fc = get_decoded_fastchunk_uncached(chunk_x, chunk_z);\n      return db;\n   }\n}\n\nfast_chunk *get_decoded_fastchunk(int chunk_x, int chunk_z)\n{\n   decoded_buffer *db = get_decoded_buffer(chunk_x, chunk_z);\n   return db->fc;\n}\n#endif\n\n#ifndef FAST_CHUNK\nchunk *get_decoded_chunk_raw(int chunk_x, int chunk_z)\n{\n   unsigned char *decoded;\n   compressed_chunk *cc = get_compressed_chunk(chunk_x, chunk_z);\n   assert(cc != NULL);\n   if (cc->len == 0)\n      return NULL;\n   else {\n      chunk *ch;\n      int inlen = nbt_parse_uint32(cc->data);\n      int len;\n      assert(cc->data[4] == 2);\n      decoded = stbi_zlib_decode_malloc_guesssize(cc->data+5, inlen, inlen*3, &len);\n      assert(decoded != NULL);\n      #ifdef FAST_CHUNK\n      ch = NULL;\n      #else\n      ch = minecraft_chunk_parse(decoded, len);\n      #endif\n      free(decoded);\n      return ch;\n   }\n}\n\nstatic chunk *decoded_chunks[MAX_DECODED_CHUNK_Z][MAX_DECODED_CHUNK_X];\nchunk *get_decoded_chunk(int chunk_x, int chunk_z)\n{\n   chunk *c = decoded_chunks[chunk_z&(MAX_DECODED_CHUNK_Z-1)][chunk_x&(MAX_DECODED_CHUNK_X-1)];\n   if (c && c->xpos == chunk_x && c->zpos == chunk_z)\n      return c;\n   if (c) free(c);\n   c = get_decoded_chunk_raw(chunk_x, chunk_z);\n   decoded_chunks[chunk_z&(MAX_DECODED_CHUNK_Z-1)][chunk_x&(MAX_DECODED_CHUNK_X-1)] = c;\n   return c;\n}\n#endif\n"
  },
  {
    "path": "tests/caveview/cave_parse.h",
    "content": "#ifndef INCLUDE_CAVE_PARSE_H\n#define INCLUDE_CAVE_PARSE_H\n\ntypedef struct\n{\n   unsigned char block;\n   unsigned char data;\n   unsigned char light:4;\n   unsigned char skylight:4;\n} raw_block;\n\n// this is the old fully-decoded chunk\ntypedef struct\n{\n   int xpos, zpos, max_y;\n   int height[16][16];\n   raw_block rb[16][16][256]; // [z][x][y] which becomes [y][x][z] in stb\n} chunk;\n\nchunk *get_decoded_chunk(int chunk_x, int chunk_z);\n\n#define NUM_SEGMENTS  16\ntypedef struct\n{\n   int max_y, xpos, zpos;\n\n   unsigned char *blockdata[NUM_SEGMENTS];\n   unsigned char *data[NUM_SEGMENTS];\n   unsigned char *skylight[NUM_SEGMENTS];\n   unsigned char *light[NUM_SEGMENTS];\n   \n   void *pointer_to_free;   \n\n   int refcount; // this allows multi-threaded building without wrapping in ANOTHER struct\n} fast_chunk;\n\nfast_chunk *get_decoded_fastchunk(int chunk_x, int chunk_z); // cache, never call free()\n\nfast_chunk *get_decoded_fastchunk_uncached(int chunk_x, int chunk_z);\n\n#endif\n"
  },
  {
    "path": "tests/caveview/cave_render.c",
    "content": "// This file renders vertex buffers, converts raw meshes\n// to GL meshes, and manages threads that do the raw-mesh\n// building (found in cave_mesher.c)\n\n\n#include \"stb_voxel_render.h\"\n\n#define STB_GLEXT_DECLARE \"glext_list.h\"\n#include \"stb_gl.h\"\n#include \"stb_image.h\"\n#include \"stb_glprog.h\"\n\n#include \"caveview.h\"\n#include \"cave_parse.h\"\n#include \"stb.h\"\n#include \"sdl.h\"\n#include \"sdl_thread.h\"\n#include <math.h>\n#include <assert.h>\n\n//#define STBVOX_CONFIG_TEX1_EDGE_CLAMP\n\n\n// currently no dynamic way to set mesh cache size or view distance\n//#define SHORTVIEW\n\n\nstbvox_mesh_maker g_mesh_maker;\n\nGLuint main_prog;\nGLint uniform_locations[64];\n\n//#define MAX_QUADS_PER_DRAW        (65536 / 4) // assuming 16-bit indices, 4 verts per quad\n//#define FIXED_INDEX_BUFFER_SIZE   (MAX_QUADS_PER_DRAW * 6 * 2)  // 16*1024 * 12 == ~192KB\n\n// while uploading texture data, this holds our each texture\n#define TEX_SIZE  64\nuint32 texture[TEX_SIZE][TEX_SIZE];\n\nGLuint voxel_tex[2];\n\n// chunk state\nenum\n{\n   STATE_invalid,\n   STATE_needed,\n   STATE_requested,\n   STATE_abandoned,\n   STATE_valid,\n};\n\n// mesh is 32x32x255 ... this is hardcoded in that\n// a mesh covers 2x2 minecraft chunks, no #defines for it\ntypedef struct\n{\n   int state;\n   int chunk_x, chunk_y;\n   int num_quads;\n   float priority;\n   int vbuf_size, fbuf_size;\n\n   float transform[3][3];\n   float bounds[2][3];\n\n   GLuint vbuf;// vbuf_tex;\n   GLuint fbuf, fbuf_tex;\n\n} chunk_mesh;\n\nvoid scale_texture(unsigned char *src, int x, int y, int w, int h)\n{\n   int i,j,k;\n   assert(w == 256 && h == 256);\n   for (j=0; j < TEX_SIZE; ++j) {\n      for (i=0; i < TEX_SIZE; ++i) {\n         uint32 val=0;\n         for (k=0; k < 4; ++k) {\n            val >>= 8;\n            val += src[ 4*(x+(i>>2)) + 4*w*(y+(j>>2)) + k]<<24;\n         }\n         texture[j][i] = val;\n      }\n   }\n}\n\nvoid build_base_texture(int n)\n{\n   int x,y;\n   uint32 color = stb_rand() | 0x808080;\n   for (y=0; y<TEX_SIZE; ++y)\n      for (x=0; x<TEX_SIZE; ++x) {\n         texture[y][x] = (color + (stb_rand()&0x1f1f1f))|0xff000000;\n      }\n}\n\nvoid build_overlay_texture(int n)\n{\n   int x,y;\n   uint32 color = stb_rand();\n   if (color & 16)\n      color = 0xff000000;\n   else\n      color = 0xffffffff;\n   for (y=0; y<TEX_SIZE; ++y)\n      for (x=0; x<TEX_SIZE; ++x) {\n         texture[y][x] = 0;\n      }\n\n   for (y=0; y < TEX_SIZE/8; ++y) {\n      for (x=0; x < TEX_SIZE; ++x) {\n         texture[y][x] = color;\n         texture[TEX_SIZE-1-y][x] = color;\n         texture[x][y] = color;\n         texture[x][TEX_SIZE-1-y] = color;\n      }\n   }\n}\n\n// view radius of about 1024 = 2048 columns / 32 columns-per-mesh = 2^11 / 2^5 = 64x64\n// so we need bigger than 64x64 so we can precache, which means we have to be\n// non-power-of-two, or we have to be pretty huge\n#define CACHED_MESH_NUM_X   128\n#define CACHED_MESH_NUM_Y   128\n\n\nchunk_mesh cached_chunk_mesh[CACHED_MESH_NUM_Y][CACHED_MESH_NUM_X];\n\nvoid free_chunk(int slot_x, int slot_y)\n{\n   chunk_mesh *cm = &cached_chunk_mesh[slot_y][slot_x];\n   if (cm->state == STATE_valid) {\n      glDeleteTextures(1, &cm->fbuf_tex);\n      glDeleteBuffersARB(1, &cm->vbuf);\n      glDeleteBuffersARB(1, &cm->fbuf);\n      cached_chunk_mesh[slot_y][slot_x].state = STATE_invalid;\n   }\n}\n\nvoid upload_mesh(chunk_mesh *cm, uint8 *build_buffer, uint8 *face_buffer)\n{\n   glGenBuffersARB(1, &cm->vbuf);\n   glBindBufferARB(GL_ARRAY_BUFFER_ARB, cm->vbuf);\n   glBufferDataARB(GL_ARRAY_BUFFER_ARB, cm->num_quads*4*sizeof(uint32), build_buffer, GL_STATIC_DRAW_ARB);\n   glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n\n   glGenBuffersARB(1, &cm->fbuf);\n   glBindBufferARB(GL_TEXTURE_BUFFER_ARB, cm->fbuf);\n   glBufferDataARB(GL_TEXTURE_BUFFER_ARB, cm->num_quads*sizeof(uint32), face_buffer , GL_STATIC_DRAW_ARB);\n   glBindBufferARB(GL_TEXTURE_BUFFER_ARB, 0);\n\n   glGenTextures(1, &cm->fbuf_tex);\n   glBindTexture(GL_TEXTURE_BUFFER_ARB, cm->fbuf_tex);\n   glTexBufferARB(GL_TEXTURE_BUFFER_ARB, GL_RGBA8UI, cm->fbuf);\n   glBindTexture(GL_TEXTURE_BUFFER_ARB, 0);\n}\n\nstatic void upload_mesh_data(raw_mesh *rm)\n{\n   int cx = rm->cx;\n   int cy = rm->cy;\n   int slot_x = (cx >> 1) & (CACHED_MESH_NUM_X-1);\n   int slot_y = (cy >> 1) & (CACHED_MESH_NUM_Y-1);\n   chunk_mesh *cm;\n\n   free_chunk(slot_x, slot_y);\n\n   cm = &cached_chunk_mesh[slot_y][slot_x];\n   cm->num_quads = rm->num_quads;\n\n   upload_mesh(cm, rm->build_buffer, rm->face_buffer);\n   cm->vbuf_size = rm->num_quads*4*sizeof(uint32);\n   cm->fbuf_size = rm->num_quads*sizeof(uint32);\n   cm->priority = 100000;\n   cm->chunk_x = cx;\n   cm->chunk_y = cy;\n\n   memcpy(cm->bounds, rm->bounds, sizeof(cm->bounds));\n   memcpy(cm->transform, rm->transform, sizeof(cm->transform));\n\n   // write barrier here\n   cm->state = STATE_valid;\n}\n\nGLint uniform_loc[16];\nfloat table3[128][3];\nfloat table4[64][4];\nGLint tablei[2];\n\nfloat step=0;\n\n#ifdef SHORTVIEW\nint view_dist_in_chunks = 50;\n#else\nint view_dist_in_chunks = 80;\n#endif\n\nvoid setup_uniforms(float pos[3])\n{\n   int i,j;\n   step += 1.0f/60.0f;\n   for (i=0; i < STBVOX_UNIFORM_count; ++i) {\n      stbvox_uniform_info raw, *ui=&raw;\n      stbvox_get_uniform_info(&raw, i);\n      uniform_loc[i] = -1;\n\n      if (i == STBVOX_UNIFORM_texscale || i == STBVOX_UNIFORM_texgen || i == STBVOX_UNIFORM_color_table)\n         continue;\n\n      if (ui) {\n         void *data = ui->default_value;\n         uniform_loc[i] = stbgl_find_uniform(main_prog, ui->name);\n        switch (i) {\n            case STBVOX_UNIFORM_face_data:\n               tablei[0] = 2;\n               data = tablei;\n               break;\n\n            case STBVOX_UNIFORM_tex_array:\n               glActiveTextureARB(GL_TEXTURE0_ARB);\n               glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, voxel_tex[0]);\n               glActiveTextureARB(GL_TEXTURE1_ARB);\n               glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, voxel_tex[1]);\n               glActiveTextureARB(GL_TEXTURE0_ARB);\n               tablei[0] = 0;\n               tablei[1] = 1;\n               data = tablei;\n               break;\n\n            case STBVOX_UNIFORM_color_table:\n               data = ui->default_value;\n               ((float *)data)[63*4+3] = 2.0f; // emissive\n               break;\n\n            case STBVOX_UNIFORM_camera_pos:\n               data = table3[0];\n               table3[0][0] = pos[0];\n               table3[0][1] = pos[1];\n               table3[0][2] = pos[2];\n               table3[0][3] = stb_max(0,(float)sin(step*2)*0.125f);\n               break;\n\n            case STBVOX_UNIFORM_ambient: {\n               float bright = 1.0;\n               //float bright = 0.75;\n               float amb[3][3];\n\n               // ambient direction is sky-colored upwards\n               // \"ambient\" lighting is from above\n               table4[0][0] =  0.3f;\n               table4[0][1] = -0.5f;\n               table4[0][2] =  0.9f;\n\n               amb[1][0] = 0.3f; amb[1][1] = 0.3f; amb[1][2] = 0.3f; // dark-grey\n               amb[2][0] = 1.0; amb[2][1] = 1.0; amb[2][2] = 1.0; // white\n\n               // convert so (table[1]*dot+table[2]) gives\n               // above interpolation\n               //     lerp((dot+1)/2, amb[1], amb[2])\n               //     amb[1] + (amb[2] - amb[1]) * (dot+1)/2\n               //     amb[1] + (amb[2] - amb[1]) * dot/2 + (amb[2]-amb[1])/2\n\n               for (j=0; j < 3; ++j) {\n                  table4[1][j] = (amb[2][j] - amb[1][j])/2 * bright;\n                  table4[2][j] = (amb[1][j] + amb[2][j])/2 * bright;\n               }\n\n               // fog color\n               table4[3][0] = 0.6f, table4[3][1] = 0.7f, table4[3][2] = 0.9f;\n               table4[3][3] = 1.0f / (view_dist_in_chunks * 16);\n               table4[3][3] *= table4[3][3];\n\n               data = table4;\n               break;\n            }\n         }\n\n         switch (ui->type) {\n            case STBVOX_UNIFORM_TYPE_sampler: stbglUniform1iv(uniform_loc[i], ui->array_length, data); break;\n            case STBVOX_UNIFORM_TYPE_vec2:    stbglUniform2fv(uniform_loc[i], ui->array_length, data); break;\n            case STBVOX_UNIFORM_TYPE_vec3:    stbglUniform3fv(uniform_loc[i], ui->array_length, data); break;\n            case STBVOX_UNIFORM_TYPE_vec4:    stbglUniform4fv(uniform_loc[i], ui->array_length, data); break;\n         }\n      }\n   }\n}\n\nGLuint unitex[64], unibuf[64];\nvoid make_texture_buffer_for_uniform(int uniform, int slot)\n{\n   GLenum type;\n   stbvox_uniform_info raw, *ui=&raw;\n   GLint uloc;\n   \n   stbvox_get_uniform_info(ui, uniform);\n   uloc = stbgl_find_uniform(main_prog, ui->name);\n\n   if (uniform == STBVOX_UNIFORM_color_table)\n      ((float *)ui->default_value)[63*4+3] = 2.0f; // emissive\n\n   glGenBuffersARB(1, &unibuf[uniform]);\n   glBindBufferARB(GL_ARRAY_BUFFER_ARB, unibuf[uniform]);\n   glBufferDataARB(GL_ARRAY_BUFFER_ARB, ui->array_length * ui->bytes_per_element, ui->default_value, GL_STATIC_DRAW_ARB);\n   glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n\n   glGenTextures(1, &unitex[uniform]);\n   glBindTexture(GL_TEXTURE_BUFFER_ARB, unitex[uniform]);\n   switch (ui->type) {\n      case STBVOX_UNIFORM_TYPE_vec2: type = GL_RG32F; break;\n      case STBVOX_UNIFORM_TYPE_vec3: type = GL_RGB32F; break;\n      case STBVOX_UNIFORM_TYPE_vec4: type = GL_RGBA32F; break;\n      default: assert(0);\n   }\n   glTexBufferARB(GL_TEXTURE_BUFFER_ARB, type, unibuf[uniform]);\n   glBindTexture(GL_TEXTURE_BUFFER_ARB, 0);\n\n   glActiveTextureARB(GL_TEXTURE0 + slot);\n   glBindTexture(GL_TEXTURE_BUFFER_ARB, unitex[uniform]);\n   glActiveTextureARB(GL_TEXTURE0);\n\n   stbglUseProgram(main_prog);\n   stbglUniform1i(uloc, slot);\n}\n\n#define MAX_MESH_WORKERS  8\n#define MAX_CHUNK_LOAD_WORKERS 2\n\nint num_mesh_workers;\nint num_chunk_load_workers;\n\ntypedef struct\n{\n   int state;\n   int request_cx;\n   int request_cy;\n   int padding[13];\n\n   SDL_sem * request_received;\n\n   SDL_sem * chunk_server_done_processing;\n   int chunk_action;\n   int chunk_request_x;\n   int chunk_request_y;\n   fast_chunk *chunks[4][4];\n\n   int padding2[16];\n   raw_mesh rm;\n   int padding3[16];\n\n   uint8 *build_buffer;\n   uint8 *face_buffer ;\n} mesh_worker;\n\nenum\n{\n   WSTATE_idle,\n   WSTATE_requested,\n   WSTATE_running,\n   WSTATE_mesh_ready,\n};\n\nmesh_worker mesh_data[MAX_MESH_WORKERS];\nint num_meshes_started; // stats\n\nint request_chunk(int chunk_x, int chunk_y);\nvoid update_meshes_from_render_thread(void);\n\nunsigned char tex2_data[64][4];\n\nvoid init_tex2_gradient(void)\n{\n   int i;\n   for (i=0; i < 16; ++i) {\n      tex2_data[i+ 0][0] = 64 + 12*i;\n      tex2_data[i+ 0][1] = 32;\n      tex2_data[i+ 0][2] = 64;\n\n      tex2_data[i+16][0] = 255;\n      tex2_data[i+16][1] = 32 + 8*i;\n      tex2_data[i+16][2] = 64;\n\n      tex2_data[i+32][0] = 255;\n      tex2_data[i+32][1] = 160;\n      tex2_data[i+32][2] = 64 + 12*i;\n\n      tex2_data[i+48][0] = 255;\n      tex2_data[i+48][1] = 160 + 6*i;\n      tex2_data[i+48][2] = 255;\n   }\n}\n\nvoid set_tex2_alpha(float fa)\n{\n   int i;\n   int a = (int) stb_lerp(fa, 0, 255);\n   if (a < 0) a = 0; else if (a > 255) a = 255;\n   glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, voxel_tex[1]);\n   for (i=0; i < 64; ++i) {\n      tex2_data[i][3] = a;\n      glTexSubImage3DEXT(GL_TEXTURE_2D_ARRAY_EXT, 0, 0,0,i, 1,1,1, GL_RGBA, GL_UNSIGNED_BYTE, tex2_data[i]);\n   }\n}\n\nvoid render_init(void)\n{\n   int i;\n   char *binds[] = { \"attr_vertex\", \"attr_face\", NULL };\n   char *vertex;\n   char *fragment;\n   int w=0,h=0;\n\n   unsigned char *texdata = stbi_load(\"terrain.png\", &w, &h, NULL, 4);\n\n   stbvox_init_mesh_maker(&g_mesh_maker);\n   for (i=0; i < num_mesh_workers; ++i) {\n      stbvox_init_mesh_maker(&mesh_data[i].rm.mm);\n   }\n\n   vertex = stbvox_get_vertex_shader();\n   fragment = stbvox_get_fragment_shader();\n\n   {\n      char error_buffer[1024];\n      char *main_vertex[] = { vertex, NULL };\n      char *main_fragment[] = { fragment, NULL };\n      main_prog = stbgl_create_program(main_vertex, main_fragment, binds, error_buffer, sizeof(error_buffer));\n      if (main_prog == 0) {\n         ods(\"Compile error for main shader: %s\\n\", error_buffer);\n         assert(0);\n         exit(1);\n      }\n   }\n   //init_index_buffer();\n\n   make_texture_buffer_for_uniform(STBVOX_UNIFORM_texscale     , 3);\n   make_texture_buffer_for_uniform(STBVOX_UNIFORM_texgen       , 4);\n   make_texture_buffer_for_uniform(STBVOX_UNIFORM_color_table  , 5);\n\n   glGenTextures(2, voxel_tex);\n\n   glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, voxel_tex[0]);\n   glTexImage3DEXT(GL_TEXTURE_2D_ARRAY_EXT, 0, GL_RGBA,\n                      TEX_SIZE,TEX_SIZE,256,\n                      0,GL_RGBA,GL_UNSIGNED_BYTE,NULL);\n   for (i=0; i < 256; ++i) {\n      if (texdata)\n         scale_texture(texdata, (i&15)*w/16, (h/16)*(i>>4), w,h);\n      else\n         build_base_texture(i);\n      glTexSubImage3DEXT(GL_TEXTURE_2D_ARRAY_EXT, 0, 0,0,i, TEX_SIZE,TEX_SIZE,1, GL_RGBA, GL_UNSIGNED_BYTE, texture[0]);\n   }\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16);\n   #ifdef STBVOX_CONFIG_TEX1_EDGE_CLAMP\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n   #endif\n\n   glGenerateMipmapEXT(GL_TEXTURE_2D_ARRAY_EXT);\n\n   glBindTexture(GL_TEXTURE_2D_ARRAY_EXT, voxel_tex[1]);\n   glTexImage3DEXT(GL_TEXTURE_2D_ARRAY_EXT, 0, GL_RGBA,\n                      1,1,64,\n                      0,GL_RGBA,GL_UNSIGNED_BYTE,NULL);\n   init_tex2_gradient();\n   set_tex2_alpha(0.0);\n   #if 0\n   for (i=0; i < 128; ++i) {\n      //build_overlay_texture(i);\n      glTexSubImage3DEXT(GL_TEXTURE_2D_ARRAY_EXT, 0, 0,0,i, TEX_SIZE,TEX_SIZE,1, GL_RGBA, GL_UNSIGNED_BYTE, texture[0]);\n   }\n   #endif\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n   glTexParameteri(GL_TEXTURE_2D_ARRAY_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n   glGenerateMipmapEXT(GL_TEXTURE_2D_ARRAY_EXT);\n}\n\nvoid world_init(void)\n{\n   int a,b,x,y;\n\n   Uint64 start_time, end_time;\n   #ifdef NDEBUG\n   int range = 32;\n   #else\n   int range = 12;\n   #endif\n\n   start_time = SDL_GetPerformanceCounter();\n\n   // iterate in 8x8 clusters of qchunks at a time to get better converted-chunk-cache reuse\n   // than a purely row-by-row ordering is (single-threaded this is a bigger win than\n   // any of the above optimizations were, since it halves zlib/mc-conversion costs)\n   for (x=-range; x <= range; x += 16)\n      for (y=-range; y <= range; y += 16)\n         for (b=y; b < y+16 && b <= range; b += 2)\n            for (a=x; a < x+16 && a <= range; a += 2)\n               while (!request_chunk(a, b)) { // if request fails, all threads are busy\n                  update_meshes_from_render_thread();\n                  SDL_Delay(1);\n               }\n\n   // wait until all the workers are done,\n   // (this is only needed if we want to time\n   // when the build finishes, or when we want to reset the\n   // cache size; otherwise we could just go ahead and\n   // start rendering whatever we've got)\n   for(;;) {\n      int i;\n      update_meshes_from_render_thread();\n      for (i=0; i < num_mesh_workers; ++i)\n         if (mesh_data[i].state != WSTATE_idle)\n            break;\n      if (i == num_mesh_workers)\n         break;\n      SDL_Delay(3);\n   }\n\n   end_time = SDL_GetPerformanceCounter();\n   ods(\"Build time: %7.2fs\\n\", (end_time - start_time) / (float) SDL_GetPerformanceFrequency());\n\n   // don't waste lots of storage on chunk caches once it's finished starting-up;\n   // this was only needed to be this large because we worked in large blocks\n   // to maximize sharing\n   reset_cache_size(32);\n}\n\nextern SDL_mutex * chunk_cache_mutex;\n\nint mesh_worker_handler(void *data)\n{\n   mesh_worker *mw = data;\n   mw->face_buffer = malloc(FACE_BUFFER_SIZE);\n   mw->build_buffer = malloc(BUILD_BUFFER_SIZE);\n\n   // this loop only works because the compiler can't\n   // tell that the SDL_calls don't access mw->state;\n   // really we should barrier that stuff\n   for(;;) {\n      int i,j;\n      int cx,cy;\n\n      // wait for a chunk request\n      SDL_SemWait(mw->request_received);\n\n      // analyze the chunk request\n      assert(mw->state == WSTATE_requested);\n      cx = mw->request_cx;\n      cy = mw->request_cy;\n\n      // this is inaccurate as it can block while another thread has the cache locked\n      mw->state = WSTATE_running;\n\n      // get the chunks we need (this takes a lock and caches them)\n      for (j=0; j < 4; ++j)\n         for (i=0; i < 4; ++i)\n            mw->chunks[j][i] = get_converted_fastchunk(cx-1 + i, cy-1 + j);\n\n      // build the mesh based on the chunks\n      mw->rm.build_buffer = mw->build_buffer;\n      mw->rm.face_buffer = mw->face_buffer;\n      build_chunk(cx, cy, mw->chunks, &mw->rm);\n      mw->state = WSTATE_mesh_ready;\n      // don't need to notify of this, because it gets polled\n\n      // when done, free the chunks\n\n      // for efficiency we just take the mutex once around the whole thing,\n      // though this spreads the mutex logic over two files\n      SDL_LockMutex(chunk_cache_mutex);\n      for (j=0; j < 4; ++j)\n         for (i=0; i < 4; ++i) {\n            deref_fastchunk(mw->chunks[j][i]);\n            mw->chunks[j][i] = NULL;\n         }\n      SDL_UnlockMutex(chunk_cache_mutex);\n   }\n   return 0;\n}\n\nint request_chunk(int chunk_x, int chunk_y)\n{\n   int i;\n   for (i=0; i < num_mesh_workers; ++i) {\n      mesh_worker *mw = &mesh_data[i];\n      if (mw->state == WSTATE_idle) {\n         mw->request_cx = chunk_x;\n         mw->request_cy = chunk_y;\n         mw->state = WSTATE_requested;\n         SDL_SemPost(mw->request_received);\n         ++num_meshes_started;\n         return 1;\n      }\n   }\n   return 0;\n}\n\nvoid prepare_threads(void)\n{\n   int i;\n   int num_proc = SDL_GetCPUCount();\n\n   if (num_proc > 6)\n      num_mesh_workers = num_proc/2;\n   else if (num_proc > 4)\n      num_mesh_workers = 4;\n   else \n      num_mesh_workers = num_proc-1;\n\n// @TODO\n//   Thread usage is probably pretty terrible; need to make a\n//   separate queue of needed chunks, instead of just generating\n//   one request per thread per frame, and a separate queue of\n//   results. (E.g. If it takes 1.5 frames to build mesh, thread\n//   is idle for 0.5 frames.) To fake this for now, I've just\n//   doubled the number of threads to let those serve as a 'queue',\n//   but that's dumb.\n\n   num_mesh_workers *= 2; // try to get better thread usage\n\n   if (num_mesh_workers > MAX_MESH_WORKERS)\n      num_mesh_workers = MAX_MESH_WORKERS;\n\n   for (i=0; i < num_mesh_workers; ++i) {\n      mesh_worker *data = &mesh_data[i];\n      data->request_received = SDL_CreateSemaphore(0);\n      data->chunk_server_done_processing = SDL_CreateSemaphore(0);\n      SDL_CreateThread(mesh_worker_handler, \"mesh worker\", data);\n   }\n}\n\n\n// \"better\" buffer uploading\n#if 0\n   if (glBufferStorage) {\n      glDeleteBuffersARB(1, &vb->vbuf);\n      glGenBuffersARB(1, &vb->vbuf);\n\n      glBindBufferARB(GL_ARRAY_BUFFER_ARB, vb->vbuf);\n      glBufferStorage(GL_ARRAY_BUFFER_ARB, sizeof(build_buffer), build_buffer, 0);\n      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n   } else {\n      glBindBufferARB(GL_ARRAY_BUFFER_ARB, vb->vbuf);\n      glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(build_buffer), build_buffer, GL_STATIC_DRAW_ARB);\n      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n   }\n#endif\n\n\ntypedef struct\n{\n   float x,y,z,w;\n} plane;\n\nstatic plane frustum[6];\n\nstatic void matd_mul(double out[4][4], double src1[4][4], double src2[4][4])\n{\n   int i,j,k;\n   for (j=0; j < 4; ++j) {\n      for (i=0; i < 4; ++i) {\n         double t=0;\n         for (k=0; k < 4; ++k)\n            t += src1[k][i] * src2[j][k];\n         out[i][j] = t;\n      }\n   }\n}\n\n// https://fgiesen.wordpress.com/2012/08/31/frustum-planes-from-the-projection-matrix/\nstatic void compute_frustum(void)\n{\n   int i;\n   GLdouble mv[4][4],proj[4][4], mvproj[4][4];\n   glGetDoublev(GL_MODELVIEW_MATRIX , mv[0]);\n   glGetDoublev(GL_PROJECTION_MATRIX, proj[0]);\n   matd_mul(mvproj, proj, mv);\n   for (i=0; i < 4; ++i) {\n      (&frustum[0].x)[i] = (float) (mvproj[3][i] + mvproj[0][i]);\n      (&frustum[1].x)[i] = (float) (mvproj[3][i] - mvproj[0][i]);\n      (&frustum[2].x)[i] = (float) (mvproj[3][i] + mvproj[1][i]);\n      (&frustum[3].x)[i] = (float) (mvproj[3][i] - mvproj[1][i]);\n      (&frustum[4].x)[i] = (float) (mvproj[3][i] + mvproj[2][i]);\n      (&frustum[5].x)[i] = (float) (mvproj[3][i] - mvproj[2][i]);\n   }   \n}\n\nstatic int test_plane(plane *p, float x0, float y0, float z0, float x1, float y1, float z1)\n{\n   // return false if the box is entirely behind the plane\n   float d=0;\n   assert(x0 <= x1 && y0 <= y1 && z0 <= z1);\n   if (p->x > 0) d += x1*p->x; else d += x0*p->x;\n   if (p->y > 0) d += y1*p->y; else d += y0*p->y;\n   if (p->z > 0) d += z1*p->z; else d += z0*p->z;\n   return d + p->w >= 0;\n}\n\nstatic int is_box_in_frustum(float *bmin, float *bmax)\n{\n   int i;\n   for (i=0; i < 6; ++i)\n      if (!test_plane(&frustum[i], bmin[0], bmin[1], bmin[2], bmax[0], bmax[1], bmax[2]))\n         return 0;\n   return 1;\n}\n\nfloat compute_priority(int cx, int cy, float x, float y)\n{\n   float distx, disty, dist2;\n   distx = (cx*16+8) - x;\n   disty = (cy*16+8) - y;\n   dist2 = distx*distx + disty*disty;\n   return view_dist_in_chunks*view_dist_in_chunks * 16 * 16 - dist2;\n}\n\nint chunk_locations, chunks_considered, chunks_in_frustum;\nint quads_considered, quads_rendered;\nint chunk_storage_rendered, chunk_storage_considered, chunk_storage_total;\nint update_frustum = 1;\n\n#ifdef SHORTVIEW\nint max_chunk_storage = 450 << 20;\nint min_chunk_storage = 350 << 20;\n#else\nint max_chunk_storage = 900 << 20;\nint min_chunk_storage = 800 << 20;\n#endif\n\nfloat min_priority = -500; // this really wants to be in unit space, not squared space\n\nint num_meshes_uploaded;\n\nvoid update_meshes_from_render_thread(void)\n{\n   int i;\n   for (i=0; i < num_mesh_workers; ++i) {\n      mesh_worker *mw = &mesh_data[i];\n      if (mw->state == WSTATE_mesh_ready) {\n         upload_mesh_data(&mw->rm);\n         ++num_meshes_uploaded;\n         mw->state = WSTATE_idle;\n      }\n   }\n}\n\nextern float tex2_alpha;\nextern int global_hack;\nint num_threads_active;\nfloat chunk_server_activity;\n\nvoid render_caves(float campos[3])\n{\n   float x = campos[0], y = campos[1];\n   int qchunk_x, qchunk_y;\n   int cam_x, cam_y;\n   int i,j, rad;\n\n   compute_frustum();\n\n   chunk_locations = chunks_considered = chunks_in_frustum = 0;\n   quads_considered = quads_rendered = 0;\n   chunk_storage_total = chunk_storage_considered = chunk_storage_rendered = 0;\n\n   cam_x = (int) floor(x+0.5);\n   cam_y = (int) floor(y+0.5);\n\n   qchunk_x = (((int) floor(x)+16) >> 5) << 1;\n   qchunk_y = (((int) floor(y)+16) >> 5) << 1;\n\n   glEnable(GL_ALPHA_TEST);\n   glAlphaFunc(GL_GREATER, 0.5);\n\n   stbglUseProgram(main_prog);\n   setup_uniforms(campos); // set uniforms to default values inefficiently\n   glActiveTextureARB(GL_TEXTURE2_ARB);\n   stbglEnableVertexAttribArray(0);\n\n   {\n      float lighting[2][3] = { { campos[0],campos[1],campos[2] }, { 0.75,0.75,0.65f } };\n      float bright = 8;\n      lighting[1][0] *= bright;\n      lighting[1][1] *= bright;\n      lighting[1][2] *= bright;\n      stbglUniform3fv(stbgl_find_uniform(main_prog, \"light_source\"), 2, lighting[0]);\n   }\n\n   if (global_hack)\n      set_tex2_alpha(tex2_alpha);\n\n   num_meshes_uploaded = 0;\n   update_meshes_from_render_thread();\n\n   // traverse all in-range chunks and analyze them\n   for (j=-view_dist_in_chunks; j <= view_dist_in_chunks; j += 2) {\n      for (i=-view_dist_in_chunks; i <= view_dist_in_chunks; i += 2) {\n         float priority;\n         int cx = qchunk_x + i;\n         int cy = qchunk_y + j;\n\n         priority = compute_priority(cx, cy, x, y);\n         if (priority >= min_priority) {\n            int slot_x = (cx>>1) & (CACHED_MESH_NUM_X-1);\n            int slot_y = (cy>>1) & (CACHED_MESH_NUM_Y-1);\n            chunk_mesh *cm = &cached_chunk_mesh[slot_y][slot_x];\n            ++chunk_locations;\n            if (cm->state == STATE_valid && priority >= 0) {\n               // check if chunk pos actually matches\n               if (cm->chunk_x != cx || cm->chunk_y != cy) {\n                  // we have a stale chunk we need to recreate\n                  free_chunk(slot_x, slot_y); // it probably will have already gotten freed, but just in case\n               }\n            }\n            if (cm->state == STATE_invalid) {\n               cm->chunk_x = cx;\n               cm->chunk_y = cy;\n               cm->state = STATE_needed;\n            }\n            cm->priority = priority;\n         }\n      }\n   }\n\n   // draw front-to-back\n   for (rad = 0; rad <= view_dist_in_chunks; rad += 2) {\n      for (j=-rad; j <= rad; j += 2) {\n         // if j is +- rad, then iterate i through all values\n         // if j isn't +-rad, then i should be only -rad & rad\n         int step = 2;\n         if (abs(j) != rad)\n            step = 2*rad;\n         for (i=-rad; i <= rad; i += step) {\n            int cx = qchunk_x + i;\n            int cy = qchunk_y + j;\n            int slot_x = (cx>>1) & (CACHED_MESH_NUM_X-1);\n            int slot_y = (cy>>1) & (CACHED_MESH_NUM_Y-1);\n            chunk_mesh *cm = &cached_chunk_mesh[slot_y][slot_x];\n            if (cm->state == STATE_valid && cm->priority >= 0) {\n               ++chunks_considered;\n               quads_considered += cm->num_quads;\n               if (is_box_in_frustum(cm->bounds[0], cm->bounds[1])) {\n                  ++chunks_in_frustum;\n\n                  // @TODO if in range\n                  stbglUniform3fv(uniform_loc[STBVOX_UNIFORM_transform], 3, cm->transform[0]);\n                  glBindBufferARB(GL_ARRAY_BUFFER_ARB, cm->vbuf);\n                  glVertexAttribIPointer(0, 1, GL_UNSIGNED_INT, 4, (void*) 0);\n                  glBindTexture(GL_TEXTURE_BUFFER_ARB, cm->fbuf_tex);\n                  glDrawArrays(GL_QUADS, 0, cm->num_quads*4);\n                  quads_rendered += cm->num_quads;\n\n                  chunk_storage_rendered += cm->vbuf_size + cm->fbuf_size;\n               }\n               chunk_storage_considered += cm->vbuf_size + cm->fbuf_size;\n            }\n         }\n      }\n   }\n\n   stbglDisableVertexAttribArray(0);\n   glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n   glActiveTextureARB(GL_TEXTURE0_ARB);\n\n   stbglUseProgram(0);\n   num_meshes_started = 0;\n\n   {\n      #define MAX_QUEUE  8\n      float highest_priority[MAX_QUEUE];\n      int highest_i[MAX_QUEUE], highest_j[MAX_QUEUE];\n      float lowest_priority = view_dist_in_chunks * view_dist_in_chunks * 16 * 16.0f;\n      int lowest_i = -1, lowest_j = -1;\n\n      for (i=0; i < MAX_QUEUE; ++i) {\n         highest_priority[i] = min_priority;\n         highest_i[i] = -1;\n         highest_j[i] = -1;\n      }\n\n      for (j=0; j < CACHED_MESH_NUM_Y; ++j) {\n         for (i=0; i < CACHED_MESH_NUM_X; ++i) {\n            chunk_mesh *cm = &cached_chunk_mesh[j][i];\n            if (cm->state == STATE_valid) {\n               cm->priority = compute_priority(cm->chunk_x, cm->chunk_y, x, y);\n               chunk_storage_total += cm->vbuf_size + cm->fbuf_size;\n               if (cm->priority < lowest_priority) {\n                  lowest_priority = cm->priority;\n                  lowest_i = i;\n                  lowest_j = j;\n               }\n            }\n            if (cm->state == STATE_needed) {\n               cm->priority = compute_priority(cm->chunk_x, cm->chunk_y, x, y);\n               if (cm->priority < min_priority)\n                  cm->state = STATE_invalid;\n               else if (cm->priority > highest_priority[0]) {\n                  int k;\n                  highest_priority[0] = cm->priority;\n                  highest_i[0] = i;\n                  highest_j[0] = j;\n                  // bubble this up to right place\n                  for (k=0; k < MAX_QUEUE-1; ++k) {\n                     if (highest_priority[k] > highest_priority[k+1]) {\n                        highest_priority[k] = highest_priority[k+1];\n                        highest_priority[k+1] = cm->priority;\n                        highest_i[k] = highest_i[k+1];\n                        highest_i[k+1] = i;\n                        highest_j[k] = highest_j[k+1];\n                        highest_j[k+1] = j;\n                     } else {\n                        break;\n                     }\n                  }\n               }\n            }\n         }\n      }\n\n\n      // I couldn't find any straightforward logic that avoids\n      // the hysteresis problem of continually creating & freeing\n      // a block on the margin, so I just don't free a block until\n      // it's out of range, but this doesn't actually correctly\n      // handle when the cache is too small for the given range\n      if (chunk_storage_total >= min_chunk_storage && lowest_i >= 0) {\n         if (cached_chunk_mesh[lowest_j][lowest_i].priority < -1200) // -1000? 0?\n            free_chunk(lowest_i, lowest_j);\n      }\n\n      if (chunk_storage_total < max_chunk_storage && highest_i[0] >= 0) {\n         for (j=MAX_QUEUE-1; j >= 0; --j) {\n            if (highest_j[0] >= 0) {\n               chunk_mesh *cm = &cached_chunk_mesh[highest_j[j]][highest_i[j]];\n               if (request_chunk(cm->chunk_x, cm->chunk_y)) {\n                  cm->state = STATE_requested;\n               } else {\n                  // if we couldn't queue this one, skip the remainder\n                  break;\n               }\n            }\n         }\n      }\n   }\n\n   update_meshes_from_render_thread();\n\n   num_threads_active = 0;\n   for (i=0; i < num_mesh_workers; ++i) {\n      num_threads_active += (mesh_data[i].state == WSTATE_running);\n   }\n}\n"
  },
  {
    "path": "tests/caveview/caveview.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"caveview\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Application\" 0x0101\n\nCFG=caveview - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"caveview.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"caveview.mak\" CFG=\"caveview - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"caveview - Win32 Release\" (based on \"Win32 (x86) Application\")\n!MESSAGE \"caveview - Win32 Debug\" (based on \"Win32 (x86) Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nMTL=midl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"caveview - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /MD /W3 /WX /GX /Zd /O2 /I \"../..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /FD /c\n# SUBTRACT CPP /YX\n# ADD BASE MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\n# ADD MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib sdl2.lib opengl32.lib glu32.lib winmm.lib sdl2_mixer.lib advapi32.lib /nologo /subsystem:windows /debug /machine:I386\n# SUBTRACT LINK32 /map\n\n!ELSEIF  \"$(CFG)\" == \"caveview - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /MDd /W3 /WX /Gm /GX /Zi /Od /I \"../..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /FD /GZ /c\n# ADD BASE MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\n# ADD MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib advapi32.lib winspool.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib sdl2.lib opengl32.lib glu32.lib winmm.lib sdl2_mixer.lib /nologo /subsystem:windows /incremental:no /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"caveview - Win32 Release\"\n# Name \"caveview - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\cave_main.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\cave_mesher.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\cave_parse.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\cave_parse.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\cave_render.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\caveview.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\glext.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\glext_list.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\README.md\n# End Source File\n# Begin Source File\n\nSOURCE=.\\win32\\SDL_windows_main.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\..\\stb.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\..\\stb_easy_font.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\stb_gl.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\stb_glprog.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\..\\stb_image.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\..\\stb_voxel_render.h\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/caveview/caveview.dsw",
    "content": "Microsoft Developer Studio Workspace File, Format Version 6.00\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\n\n###############################################################################\n\nProject: \"caveview\"=.\\caveview.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nGlobal:\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<3>\n{{{\n}}}\n\n###############################################################################\n\n"
  },
  {
    "path": "tests/caveview/caveview.h",
    "content": "#ifndef INCLUDE_CAVEVIEW_H\n#define INCLUDE_CAVEVIEW_H\n\n#include \"stb.h\"\n\n#include \"stb_voxel_render.h\"\n\ntypedef struct\n{\n   int cx,cy;\n\n   stbvox_mesh_maker mm;\n\n   uint8 *build_buffer;\n   uint8 *face_buffer;\n\n   int num_quads;\n   float transform[3][3];\n   float bounds[2][3];\n\n   uint8 sv_blocktype[34][34][18];\n   uint8 sv_lighting [34][34][18];\n} raw_mesh;\n\n// a 3D checkerboard of empty,solid would be: 32x32x255x6/2 ~= 800000\n// an all-leaf qchunk would be: 32 x 32 x 255 x 6 ~= 1,600,000\n\n#define BUILD_QUAD_MAX     400000\n#define BUILD_BUFFER_SIZE  (4*4*BUILD_QUAD_MAX) // 4 bytes per vertex, 4 vertices per quad\n#define FACE_BUFFER_SIZE   (  4*BUILD_QUAD_MAX) // 4 bytes per quad\n\n\nextern void mesh_init(void);\nextern void render_init(void);\nextern void world_init(void);\nextern void ods(char *fmt, ...); // output debug string\nextern void reset_cache_size(int size);\n\n\nextern void render_caves(float pos[3]);\n\n\n#include \"cave_parse.h\"  // fast_chunk\n\nextern fast_chunk *get_converted_fastchunk(int chunk_x, int chunk_y);\nextern void build_chunk(int chunk_x, int chunk_y, fast_chunk *fc_table[4][4], raw_mesh *rm);\nextern void reset_cache_size(int size);\nextern void deref_fastchunk(fast_chunk *fc);\n\n#endif"
  },
  {
    "path": "tests/caveview/glext.h",
    "content": "#ifndef __glext_h_\n#define __glext_h_ 1\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n** Copyright (c) 2013 The Khronos Group Inc.\n**\n** Permission is hereby granted, free of charge, to any person obtaining a\n** copy of this software and/or associated documentation files (the\n** \"Materials\"), to deal in the Materials without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and/or sell copies of the Materials, and to\n** permit persons to whom the Materials are furnished to do so, subject to\n** the following conditions:\n**\n** The above copyright notice and this permission notice shall be included\n** in all copies or substantial portions of the Materials.\n**\n** THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n*/\n/*\n** This header is generated from the Khronos OpenGL / OpenGL ES XML\n** API Registry. The current version of the Registry, generator scripts\n** used to make the header, and the header can be found at\n**   http://www.opengl.org/registry/\n**\n** Khronos $Revision: 24756 $ on $Date: 2014-01-14 03:42:29 -0800 (Tue, 14 Jan 2014) $\n*/\n\n#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN 1\n#endif\n#include <windows.h>\n#endif\n\n#ifndef APIENTRY\n#define APIENTRY\n#endif\n#ifndef APIENTRYP\n#define APIENTRYP APIENTRY *\n#endif\n#ifndef GLAPI\n#define GLAPI extern\n#endif\n\n#define GL_GLEXT_VERSION 20140114\n\n/* Generated C header for:\n * API: gl\n * Profile: compatibility\n * Versions considered: .*\n * Versions emitted: 1\\.[2-9]|[234]\\.[0-9]\n * Default extensions included: gl\n * Additional extensions included: _nomatch_^\n * Extensions removed: _nomatch_^\n */\n\n#ifndef GL_VERSION_1_2\n#define GL_VERSION_1_2 1\n#define GL_UNSIGNED_BYTE_3_3_2            0x8032\n#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033\n#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034\n#define GL_UNSIGNED_INT_8_8_8_8           0x8035\n#define GL_UNSIGNED_INT_10_10_10_2        0x8036\n#define GL_TEXTURE_BINDING_3D             0x806A\n#define GL_PACK_SKIP_IMAGES               0x806B\n#define GL_PACK_IMAGE_HEIGHT              0x806C\n#define GL_UNPACK_SKIP_IMAGES             0x806D\n#define GL_UNPACK_IMAGE_HEIGHT            0x806E\n#define GL_TEXTURE_3D                     0x806F\n#define GL_PROXY_TEXTURE_3D               0x8070\n#define GL_TEXTURE_DEPTH                  0x8071\n#define GL_TEXTURE_WRAP_R                 0x8072\n#define GL_MAX_3D_TEXTURE_SIZE            0x8073\n#define GL_UNSIGNED_BYTE_2_3_3_REV        0x8362\n#define GL_UNSIGNED_SHORT_5_6_5           0x8363\n#define GL_UNSIGNED_SHORT_5_6_5_REV       0x8364\n#define GL_UNSIGNED_SHORT_4_4_4_4_REV     0x8365\n#define GL_UNSIGNED_SHORT_1_5_5_5_REV     0x8366\n#define GL_UNSIGNED_INT_8_8_8_8_REV       0x8367\n#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368\n#define GL_BGR                            0x80E0\n#define GL_BGRA                           0x80E1\n#define GL_MAX_ELEMENTS_VERTICES          0x80E8\n#define GL_MAX_ELEMENTS_INDICES           0x80E9\n#define GL_CLAMP_TO_EDGE                  0x812F\n#define GL_TEXTURE_MIN_LOD                0x813A\n#define GL_TEXTURE_MAX_LOD                0x813B\n#define GL_TEXTURE_BASE_LEVEL             0x813C\n#define GL_TEXTURE_MAX_LEVEL              0x813D\n#define GL_SMOOTH_POINT_SIZE_RANGE        0x0B12\n#define GL_SMOOTH_POINT_SIZE_GRANULARITY  0x0B13\n#define GL_SMOOTH_LINE_WIDTH_RANGE        0x0B22\n#define GL_SMOOTH_LINE_WIDTH_GRANULARITY  0x0B23\n#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E\n#define GL_RESCALE_NORMAL                 0x803A\n#define GL_LIGHT_MODEL_COLOR_CONTROL      0x81F8\n#define GL_SINGLE_COLOR                   0x81F9\n#define GL_SEPARATE_SPECULAR_COLOR        0x81FA\n#define GL_ALIASED_POINT_SIZE_RANGE       0x846D\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);\ntypedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef 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);\ntypedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);\nGLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\n#endif\n#endif /* GL_VERSION_1_2 */\n\n#ifndef GL_VERSION_1_3\n#define GL_VERSION_1_3 1\n#define GL_TEXTURE0                       0x84C0\n#define GL_TEXTURE1                       0x84C1\n#define GL_TEXTURE2                       0x84C2\n#define GL_TEXTURE3                       0x84C3\n#define GL_TEXTURE4                       0x84C4\n#define GL_TEXTURE5                       0x84C5\n#define GL_TEXTURE6                       0x84C6\n#define GL_TEXTURE7                       0x84C7\n#define GL_TEXTURE8                       0x84C8\n#define GL_TEXTURE9                       0x84C9\n#define GL_TEXTURE10                      0x84CA\n#define GL_TEXTURE11                      0x84CB\n#define GL_TEXTURE12                      0x84CC\n#define GL_TEXTURE13                      0x84CD\n#define GL_TEXTURE14                      0x84CE\n#define GL_TEXTURE15                      0x84CF\n#define GL_TEXTURE16                      0x84D0\n#define GL_TEXTURE17                      0x84D1\n#define GL_TEXTURE18                      0x84D2\n#define GL_TEXTURE19                      0x84D3\n#define GL_TEXTURE20                      0x84D4\n#define GL_TEXTURE21                      0x84D5\n#define GL_TEXTURE22                      0x84D6\n#define GL_TEXTURE23                      0x84D7\n#define GL_TEXTURE24                      0x84D8\n#define GL_TEXTURE25                      0x84D9\n#define GL_TEXTURE26                      0x84DA\n#define GL_TEXTURE27                      0x84DB\n#define GL_TEXTURE28                      0x84DC\n#define GL_TEXTURE29                      0x84DD\n#define GL_TEXTURE30                      0x84DE\n#define GL_TEXTURE31                      0x84DF\n#define GL_ACTIVE_TEXTURE                 0x84E0\n#define GL_MULTISAMPLE                    0x809D\n#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E\n#define GL_SAMPLE_ALPHA_TO_ONE            0x809F\n#define GL_SAMPLE_COVERAGE                0x80A0\n#define GL_SAMPLE_BUFFERS                 0x80A8\n#define GL_SAMPLES                        0x80A9\n#define GL_SAMPLE_COVERAGE_VALUE          0x80AA\n#define GL_SAMPLE_COVERAGE_INVERT         0x80AB\n#define GL_TEXTURE_CUBE_MAP               0x8513\n#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A\n#define GL_PROXY_TEXTURE_CUBE_MAP         0x851B\n#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C\n#define GL_COMPRESSED_RGB                 0x84ED\n#define GL_COMPRESSED_RGBA                0x84EE\n#define GL_TEXTURE_COMPRESSION_HINT       0x84EF\n#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE  0x86A0\n#define GL_TEXTURE_COMPRESSED             0x86A1\n#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2\n#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3\n#define GL_CLAMP_TO_BORDER                0x812D\n#define GL_CLIENT_ACTIVE_TEXTURE          0x84E1\n#define GL_MAX_TEXTURE_UNITS              0x84E2\n#define GL_TRANSPOSE_MODELVIEW_MATRIX     0x84E3\n#define GL_TRANSPOSE_PROJECTION_MATRIX    0x84E4\n#define GL_TRANSPOSE_TEXTURE_MATRIX       0x84E5\n#define GL_TRANSPOSE_COLOR_MATRIX         0x84E6\n#define GL_MULTISAMPLE_BIT                0x20000000\n#define GL_NORMAL_MAP                     0x8511\n#define GL_REFLECTION_MAP                 0x8512\n#define GL_COMPRESSED_ALPHA               0x84E9\n#define GL_COMPRESSED_LUMINANCE           0x84EA\n#define GL_COMPRESSED_LUMINANCE_ALPHA     0x84EB\n#define GL_COMPRESSED_INTENSITY           0x84EC\n#define GL_COMBINE                        0x8570\n#define GL_COMBINE_RGB                    0x8571\n#define GL_COMBINE_ALPHA                  0x8572\n#define GL_SOURCE0_RGB                    0x8580\n#define GL_SOURCE1_RGB                    0x8581\n#define GL_SOURCE2_RGB                    0x8582\n#define GL_SOURCE0_ALPHA                  0x8588\n#define GL_SOURCE1_ALPHA                  0x8589\n#define GL_SOURCE2_ALPHA                  0x858A\n#define GL_OPERAND0_RGB                   0x8590\n#define GL_OPERAND1_RGB                   0x8591\n#define GL_OPERAND2_RGB                   0x8592\n#define GL_OPERAND0_ALPHA                 0x8598\n#define GL_OPERAND1_ALPHA                 0x8599\n#define GL_OPERAND2_ALPHA                 0x859A\n#define GL_RGB_SCALE                      0x8573\n#define GL_ADD_SIGNED                     0x8574\n#define GL_INTERPOLATE                    0x8575\n#define GL_SUBTRACT                       0x84E7\n#define GL_CONSTANT                       0x8576\n#define GL_PRIMARY_COLOR                  0x8577\n#define GL_PREVIOUS                       0x8578\n#define GL_DOT3_RGB                       0x86AE\n#define GL_DOT3_RGBA                      0x86AF\ntypedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);\ntypedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data);\ntypedef 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);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, void *img);\ntypedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m);\ntypedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m);\ntypedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m);\ntypedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glActiveTexture (GLenum texture);\nGLAPI void APIENTRY glSampleCoverage (GLfloat value, GLboolean invert);\nGLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, void *img);\nGLAPI void APIENTRY glClientActiveTexture (GLenum texture);\nGLAPI void APIENTRY glMultiTexCoord1d (GLenum target, GLdouble s);\nGLAPI void APIENTRY glMultiTexCoord1dv (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord1f (GLenum target, GLfloat s);\nGLAPI void APIENTRY glMultiTexCoord1fv (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord1i (GLenum target, GLint s);\nGLAPI void APIENTRY glMultiTexCoord1iv (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord1s (GLenum target, GLshort s);\nGLAPI void APIENTRY glMultiTexCoord1sv (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glMultiTexCoord2d (GLenum target, GLdouble s, GLdouble t);\nGLAPI void APIENTRY glMultiTexCoord2dv (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord2f (GLenum target, GLfloat s, GLfloat t);\nGLAPI void APIENTRY glMultiTexCoord2fv (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord2i (GLenum target, GLint s, GLint t);\nGLAPI void APIENTRY glMultiTexCoord2iv (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord2s (GLenum target, GLshort s, GLshort t);\nGLAPI void APIENTRY glMultiTexCoord2sv (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glMultiTexCoord3d (GLenum target, GLdouble s, GLdouble t, GLdouble r);\nGLAPI void APIENTRY glMultiTexCoord3dv (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord3f (GLenum target, GLfloat s, GLfloat t, GLfloat r);\nGLAPI void APIENTRY glMultiTexCoord3fv (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord3i (GLenum target, GLint s, GLint t, GLint r);\nGLAPI void APIENTRY glMultiTexCoord3iv (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord3s (GLenum target, GLshort s, GLshort t, GLshort r);\nGLAPI void APIENTRY glMultiTexCoord3sv (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glMultiTexCoord4d (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);\nGLAPI void APIENTRY glMultiTexCoord4dv (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);\nGLAPI void APIENTRY glMultiTexCoord4fv (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord4i (GLenum target, GLint s, GLint t, GLint r, GLint q);\nGLAPI void APIENTRY glMultiTexCoord4iv (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord4s (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);\nGLAPI void APIENTRY glMultiTexCoord4sv (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *m);\nGLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *m);\nGLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *m);\nGLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *m);\n#endif\n#endif /* GL_VERSION_1_3 */\n\n#ifndef GL_VERSION_1_4\n#define GL_VERSION_1_4 1\n#define GL_BLEND_DST_RGB                  0x80C8\n#define GL_BLEND_SRC_RGB                  0x80C9\n#define GL_BLEND_DST_ALPHA                0x80CA\n#define GL_BLEND_SRC_ALPHA                0x80CB\n#define GL_POINT_FADE_THRESHOLD_SIZE      0x8128\n#define GL_DEPTH_COMPONENT16              0x81A5\n#define GL_DEPTH_COMPONENT24              0x81A6\n#define GL_DEPTH_COMPONENT32              0x81A7\n#define GL_MIRRORED_REPEAT                0x8370\n#define GL_MAX_TEXTURE_LOD_BIAS           0x84FD\n#define GL_TEXTURE_LOD_BIAS               0x8501\n#define GL_INCR_WRAP                      0x8507\n#define GL_DECR_WRAP                      0x8508\n#define GL_TEXTURE_DEPTH_SIZE             0x884A\n#define GL_TEXTURE_COMPARE_MODE           0x884C\n#define GL_TEXTURE_COMPARE_FUNC           0x884D\n#define GL_POINT_SIZE_MIN                 0x8126\n#define GL_POINT_SIZE_MAX                 0x8127\n#define GL_POINT_DISTANCE_ATTENUATION     0x8129\n#define GL_GENERATE_MIPMAP                0x8191\n#define GL_GENERATE_MIPMAP_HINT           0x8192\n#define GL_FOG_COORDINATE_SOURCE          0x8450\n#define GL_FOG_COORDINATE                 0x8451\n#define GL_FRAGMENT_DEPTH                 0x8452\n#define GL_CURRENT_FOG_COORDINATE         0x8453\n#define GL_FOG_COORDINATE_ARRAY_TYPE      0x8454\n#define GL_FOG_COORDINATE_ARRAY_STRIDE    0x8455\n#define GL_FOG_COORDINATE_ARRAY_POINTER   0x8456\n#define GL_FOG_COORDINATE_ARRAY           0x8457\n#define GL_COLOR_SUM                      0x8458\n#define GL_CURRENT_SECONDARY_COLOR        0x8459\n#define GL_SECONDARY_COLOR_ARRAY_SIZE     0x845A\n#define GL_SECONDARY_COLOR_ARRAY_TYPE     0x845B\n#define GL_SECONDARY_COLOR_ARRAY_STRIDE   0x845C\n#define GL_SECONDARY_COLOR_ARRAY_POINTER  0x845D\n#define GL_SECONDARY_COLOR_ARRAY          0x845E\n#define GL_TEXTURE_FILTER_CONTROL         0x8500\n#define GL_DEPTH_TEXTURE_MODE             0x884B\n#define GL_COMPARE_R_TO_TEXTURE           0x884E\n#define GL_FUNC_ADD                       0x8006\n#define GL_FUNC_SUBTRACT                  0x800A\n#define GL_FUNC_REVERSE_SUBTRACT          0x800B\n#define GL_MIN                            0x8007\n#define GL_MAX                            0x8008\n#define GL_CONSTANT_COLOR                 0x8001\n#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002\n#define GL_CONSTANT_ALPHA                 0x8003\n#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\nGLAPI void APIENTRY glMultiDrawArrays (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount);\nGLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount);\nGLAPI void APIENTRY glPointParameterf (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glPointParameteri (GLenum pname, GLint param);\nGLAPI void APIENTRY glPointParameteriv (GLenum pname, const GLint *params);\nGLAPI void APIENTRY glFogCoordf (GLfloat coord);\nGLAPI void APIENTRY glFogCoordfv (const GLfloat *coord);\nGLAPI void APIENTRY glFogCoordd (GLdouble coord);\nGLAPI void APIENTRY glFogCoorddv (const GLdouble *coord);\nGLAPI void APIENTRY glFogCoordPointer (GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glSecondaryColor3b (GLbyte red, GLbyte green, GLbyte blue);\nGLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *v);\nGLAPI void APIENTRY glSecondaryColor3d (GLdouble red, GLdouble green, GLdouble blue);\nGLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *v);\nGLAPI void APIENTRY glSecondaryColor3f (GLfloat red, GLfloat green, GLfloat blue);\nGLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *v);\nGLAPI void APIENTRY glSecondaryColor3i (GLint red, GLint green, GLint blue);\nGLAPI void APIENTRY glSecondaryColor3iv (const GLint *v);\nGLAPI void APIENTRY glSecondaryColor3s (GLshort red, GLshort green, GLshort blue);\nGLAPI void APIENTRY glSecondaryColor3sv (const GLshort *v);\nGLAPI void APIENTRY glSecondaryColor3ub (GLubyte red, GLubyte green, GLubyte blue);\nGLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *v);\nGLAPI void APIENTRY glSecondaryColor3ui (GLuint red, GLuint green, GLuint blue);\nGLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *v);\nGLAPI void APIENTRY glSecondaryColor3us (GLushort red, GLushort green, GLushort blue);\nGLAPI void APIENTRY glSecondaryColor3usv (const GLushort *v);\nGLAPI void APIENTRY glSecondaryColorPointer (GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glWindowPos2d (GLdouble x, GLdouble y);\nGLAPI void APIENTRY glWindowPos2dv (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos2f (GLfloat x, GLfloat y);\nGLAPI void APIENTRY glWindowPos2fv (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos2i (GLint x, GLint y);\nGLAPI void APIENTRY glWindowPos2iv (const GLint *v);\nGLAPI void APIENTRY glWindowPos2s (GLshort x, GLshort y);\nGLAPI void APIENTRY glWindowPos2sv (const GLshort *v);\nGLAPI void APIENTRY glWindowPos3d (GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glWindowPos3dv (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos3f (GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glWindowPos3fv (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos3i (GLint x, GLint y, GLint z);\nGLAPI void APIENTRY glWindowPos3iv (const GLint *v);\nGLAPI void APIENTRY glWindowPos3s (GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glWindowPos3sv (const GLshort *v);\nGLAPI void APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);\nGLAPI void APIENTRY glBlendEquation (GLenum mode);\n#endif\n#endif /* GL_VERSION_1_4 */\n\n#ifndef GL_VERSION_1_5\n#define GL_VERSION_1_5 1\n#include <stddef.h>\ntypedef ptrdiff_t GLsizeiptr;\ntypedef ptrdiff_t GLintptr;\n#define GL_BUFFER_SIZE                    0x8764\n#define GL_BUFFER_USAGE                   0x8765\n#define GL_QUERY_COUNTER_BITS             0x8864\n#define GL_CURRENT_QUERY                  0x8865\n#define GL_QUERY_RESULT                   0x8866\n#define GL_QUERY_RESULT_AVAILABLE         0x8867\n#define GL_ARRAY_BUFFER                   0x8892\n#define GL_ELEMENT_ARRAY_BUFFER           0x8893\n#define GL_ARRAY_BUFFER_BINDING           0x8894\n#define GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895\n#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F\n#define GL_READ_ONLY                      0x88B8\n#define GL_WRITE_ONLY                     0x88B9\n#define GL_READ_WRITE                     0x88BA\n#define GL_BUFFER_ACCESS                  0x88BB\n#define GL_BUFFER_MAPPED                  0x88BC\n#define GL_BUFFER_MAP_POINTER             0x88BD\n#define GL_STREAM_DRAW                    0x88E0\n#define GL_STREAM_READ                    0x88E1\n#define GL_STREAM_COPY                    0x88E2\n#define GL_STATIC_DRAW                    0x88E4\n#define GL_STATIC_READ                    0x88E5\n#define GL_STATIC_COPY                    0x88E6\n#define GL_DYNAMIC_DRAW                   0x88E8\n#define GL_DYNAMIC_READ                   0x88E9\n#define GL_DYNAMIC_COPY                   0x88EA\n#define GL_SAMPLES_PASSED                 0x8914\n#define GL_SRC1_ALPHA                     0x8589\n#define GL_VERTEX_ARRAY_BUFFER_BINDING    0x8896\n#define GL_NORMAL_ARRAY_BUFFER_BINDING    0x8897\n#define GL_COLOR_ARRAY_BUFFER_BINDING     0x8898\n#define GL_INDEX_ARRAY_BUFFER_BINDING     0x8899\n#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A\n#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B\n#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C\n#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D\n#define GL_WEIGHT_ARRAY_BUFFER_BINDING    0x889E\n#define GL_FOG_COORD_SRC                  0x8450\n#define GL_FOG_COORD                      0x8451\n#define GL_CURRENT_FOG_COORD              0x8453\n#define GL_FOG_COORD_ARRAY_TYPE           0x8454\n#define GL_FOG_COORD_ARRAY_STRIDE         0x8455\n#define GL_FOG_COORD_ARRAY_POINTER        0x8456\n#define GL_FOG_COORD_ARRAY                0x8457\n#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D\n#define GL_SRC0_RGB                       0x8580\n#define GL_SRC1_RGB                       0x8581\n#define GL_SRC2_RGB                       0x8582\n#define GL_SRC0_ALPHA                     0x8588\n#define GL_SRC2_ALPHA                     0x858A\ntypedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids);\ntypedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids);\ntypedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id);\ntypedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);\ntypedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);\ntypedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);\ntypedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);\ntypedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);\ntypedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, void *data);\ntypedef void *(APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);\ntypedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenQueries (GLsizei n, GLuint *ids);\nGLAPI void APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids);\nGLAPI GLboolean APIENTRY glIsQuery (GLuint id);\nGLAPI void APIENTRY glBeginQuery (GLenum target, GLuint id);\nGLAPI void APIENTRY glEndQuery (GLenum target);\nGLAPI void APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetQueryObjectiv (GLuint id, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);\nGLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);\nGLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);\nGLAPI GLboolean APIENTRY glIsBuffer (GLuint buffer);\nGLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);\nGLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);\nGLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, void *data);\nGLAPI void *APIENTRY glMapBuffer (GLenum target, GLenum access);\nGLAPI GLboolean APIENTRY glUnmapBuffer (GLenum target);\nGLAPI void APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params);\n#endif\n#endif /* GL_VERSION_1_5 */\n\n#ifndef GL_VERSION_2_0\n#define GL_VERSION_2_0 1\ntypedef char GLchar;\n#define GL_BLEND_EQUATION_RGB             0x8009\n#define GL_VERTEX_ATTRIB_ARRAY_ENABLED    0x8622\n#define GL_VERTEX_ATTRIB_ARRAY_SIZE       0x8623\n#define GL_VERTEX_ATTRIB_ARRAY_STRIDE     0x8624\n#define GL_VERTEX_ATTRIB_ARRAY_TYPE       0x8625\n#define GL_CURRENT_VERTEX_ATTRIB          0x8626\n#define GL_VERTEX_PROGRAM_POINT_SIZE      0x8642\n#define GL_VERTEX_ATTRIB_ARRAY_POINTER    0x8645\n#define GL_STENCIL_BACK_FUNC              0x8800\n#define GL_STENCIL_BACK_FAIL              0x8801\n#define GL_STENCIL_BACK_PASS_DEPTH_FAIL   0x8802\n#define GL_STENCIL_BACK_PASS_DEPTH_PASS   0x8803\n#define GL_MAX_DRAW_BUFFERS               0x8824\n#define GL_DRAW_BUFFER0                   0x8825\n#define GL_DRAW_BUFFER1                   0x8826\n#define GL_DRAW_BUFFER2                   0x8827\n#define GL_DRAW_BUFFER3                   0x8828\n#define GL_DRAW_BUFFER4                   0x8829\n#define GL_DRAW_BUFFER5                   0x882A\n#define GL_DRAW_BUFFER6                   0x882B\n#define GL_DRAW_BUFFER7                   0x882C\n#define GL_DRAW_BUFFER8                   0x882D\n#define GL_DRAW_BUFFER9                   0x882E\n#define GL_DRAW_BUFFER10                  0x882F\n#define GL_DRAW_BUFFER11                  0x8830\n#define GL_DRAW_BUFFER12                  0x8831\n#define GL_DRAW_BUFFER13                  0x8832\n#define GL_DRAW_BUFFER14                  0x8833\n#define GL_DRAW_BUFFER15                  0x8834\n#define GL_BLEND_EQUATION_ALPHA           0x883D\n#define GL_MAX_VERTEX_ATTRIBS             0x8869\n#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A\n#define GL_MAX_TEXTURE_IMAGE_UNITS        0x8872\n#define GL_FRAGMENT_SHADER                0x8B30\n#define GL_VERTEX_SHADER                  0x8B31\n#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49\n#define GL_MAX_VERTEX_UNIFORM_COMPONENTS  0x8B4A\n#define GL_MAX_VARYING_FLOATS             0x8B4B\n#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C\n#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D\n#define GL_SHADER_TYPE                    0x8B4F\n#define GL_FLOAT_VEC2                     0x8B50\n#define GL_FLOAT_VEC3                     0x8B51\n#define GL_FLOAT_VEC4                     0x8B52\n#define GL_INT_VEC2                       0x8B53\n#define GL_INT_VEC3                       0x8B54\n#define GL_INT_VEC4                       0x8B55\n#define GL_BOOL                           0x8B56\n#define GL_BOOL_VEC2                      0x8B57\n#define GL_BOOL_VEC3                      0x8B58\n#define GL_BOOL_VEC4                      0x8B59\n#define GL_FLOAT_MAT2                     0x8B5A\n#define GL_FLOAT_MAT3                     0x8B5B\n#define GL_FLOAT_MAT4                     0x8B5C\n#define GL_SAMPLER_1D                     0x8B5D\n#define GL_SAMPLER_2D                     0x8B5E\n#define GL_SAMPLER_3D                     0x8B5F\n#define GL_SAMPLER_CUBE                   0x8B60\n#define GL_SAMPLER_1D_SHADOW              0x8B61\n#define GL_SAMPLER_2D_SHADOW              0x8B62\n#define GL_DELETE_STATUS                  0x8B80\n#define GL_COMPILE_STATUS                 0x8B81\n#define GL_LINK_STATUS                    0x8B82\n#define GL_VALIDATE_STATUS                0x8B83\n#define GL_INFO_LOG_LENGTH                0x8B84\n#define GL_ATTACHED_SHADERS               0x8B85\n#define GL_ACTIVE_UNIFORMS                0x8B86\n#define GL_ACTIVE_UNIFORM_MAX_LENGTH      0x8B87\n#define GL_SHADER_SOURCE_LENGTH           0x8B88\n#define GL_ACTIVE_ATTRIBUTES              0x8B89\n#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH    0x8B8A\n#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B\n#define GL_SHADING_LANGUAGE_VERSION       0x8B8C\n#define GL_CURRENT_PROGRAM                0x8B8D\n#define GL_POINT_SPRITE_COORD_ORIGIN      0x8CA0\n#define GL_LOWER_LEFT                     0x8CA1\n#define GL_UPPER_LEFT                     0x8CA2\n#define GL_STENCIL_BACK_REF               0x8CA3\n#define GL_STENCIL_BACK_VALUE_MASK        0x8CA4\n#define GL_STENCIL_BACK_WRITEMASK         0x8CA5\n#define GL_VERTEX_PROGRAM_TWO_SIDE        0x8643\n#define GL_POINT_SPRITE                   0x8861\n#define GL_COORD_REPLACE                  0x8862\n#define GL_MAX_TEXTURE_COORDS             0x8871\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);\ntypedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs);\ntypedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);\ntypedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask);\ntypedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);\ntypedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);\ntypedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);\ntypedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);\ntypedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);\ntypedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);\ntypedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);\ntypedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);\ntypedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);\ntypedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);\ntypedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);\ntypedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders);\ntypedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);\ntypedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);\ntypedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);\ntypedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);\ntypedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);\ntypedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader);\ntypedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);\ntypedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);\ntypedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);\ntypedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);\ntypedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);\ntypedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\ntypedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\ntypedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);\ntypedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);\ntypedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);\ntypedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\ntypedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);\nGLAPI void APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs);\nGLAPI void APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);\nGLAPI void APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);\nGLAPI void APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);\nGLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);\nGLAPI void APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name);\nGLAPI void APIENTRY glCompileShader (GLuint shader);\nGLAPI GLuint APIENTRY glCreateProgram (void);\nGLAPI GLuint APIENTRY glCreateShader (GLenum type);\nGLAPI void APIENTRY glDeleteProgram (GLuint program);\nGLAPI void APIENTRY glDeleteShader (GLuint shader);\nGLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);\nGLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);\nGLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);\nGLAPI void APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);\nGLAPI void APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);\nGLAPI void APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders);\nGLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);\nGLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);\nGLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);\nGLAPI void APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);\nGLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);\nGLAPI void APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params);\nGLAPI void APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribdv (GLuint index, GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);\nGLAPI GLboolean APIENTRY glIsProgram (GLuint program);\nGLAPI GLboolean APIENTRY glIsShader (GLuint shader);\nGLAPI void APIENTRY glLinkProgram (GLuint program);\nGLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);\nGLAPI void APIENTRY glUseProgram (GLuint program);\nGLAPI void APIENTRY glUniform1f (GLint location, GLfloat v0);\nGLAPI void APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1);\nGLAPI void APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\nGLAPI void APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\nGLAPI void APIENTRY glUniform1i (GLint location, GLint v0);\nGLAPI void APIENTRY glUniform2i (GLint location, GLint v0, GLint v1);\nGLAPI void APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2);\nGLAPI void APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\nGLAPI void APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glValidateProgram (GLuint program);\nGLAPI void APIENTRY glVertexAttrib1d (GLuint index, GLdouble x);\nGLAPI void APIENTRY glVertexAttrib1dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib1f (GLuint index, GLfloat x);\nGLAPI void APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib1s (GLuint index, GLshort x);\nGLAPI void APIENTRY glVertexAttrib1sv (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib2d (GLuint index, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glVertexAttrib2dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y);\nGLAPI void APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib2s (GLuint index, GLshort x, GLshort y);\nGLAPI void APIENTRY glVertexAttrib2sv (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib3d (GLuint index, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glVertexAttrib3dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib3s (GLuint index, GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glVertexAttrib3sv (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4Nbv (GLuint index, const GLbyte *v);\nGLAPI void APIENTRY glVertexAttrib4Niv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttrib4Nsv (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4Nub (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);\nGLAPI void APIENTRY glVertexAttrib4Nubv (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttrib4Nusv (GLuint index, const GLushort *v);\nGLAPI void APIENTRY glVertexAttrib4bv (GLuint index, const GLbyte *v);\nGLAPI void APIENTRY glVertexAttrib4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glVertexAttrib4dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib4iv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttrib4s (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);\nGLAPI void APIENTRY glVertexAttrib4sv (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4ubv (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttrib4uiv (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttrib4usv (GLuint index, const GLushort *v);\nGLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);\n#endif\n#endif /* GL_VERSION_2_0 */\n\n#ifndef GL_VERSION_2_1\n#define GL_VERSION_2_1 1\n#define GL_PIXEL_PACK_BUFFER              0x88EB\n#define GL_PIXEL_UNPACK_BUFFER            0x88EC\n#define GL_PIXEL_PACK_BUFFER_BINDING      0x88ED\n#define GL_PIXEL_UNPACK_BUFFER_BINDING    0x88EF\n#define GL_FLOAT_MAT2x3                   0x8B65\n#define GL_FLOAT_MAT2x4                   0x8B66\n#define GL_FLOAT_MAT3x2                   0x8B67\n#define GL_FLOAT_MAT3x4                   0x8B68\n#define GL_FLOAT_MAT4x2                   0x8B69\n#define GL_FLOAT_MAT4x3                   0x8B6A\n#define GL_SRGB                           0x8C40\n#define GL_SRGB8                          0x8C41\n#define GL_SRGB_ALPHA                     0x8C42\n#define GL_SRGB8_ALPHA8                   0x8C43\n#define GL_COMPRESSED_SRGB                0x8C48\n#define GL_COMPRESSED_SRGB_ALPHA          0x8C49\n#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F\n#define GL_SLUMINANCE_ALPHA               0x8C44\n#define GL_SLUMINANCE8_ALPHA8             0x8C45\n#define GL_SLUMINANCE                     0x8C46\n#define GL_SLUMINANCE8                    0x8C47\n#define GL_COMPRESSED_SLUMINANCE          0x8C4A\n#define GL_COMPRESSED_SLUMINANCE_ALPHA    0x8C4B\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\n#endif\n#endif /* GL_VERSION_2_1 */\n\n#ifndef GL_VERSION_3_0\n#define GL_VERSION_3_0 1\ntypedef unsigned short GLhalf;\n#define GL_COMPARE_REF_TO_TEXTURE         0x884E\n#define GL_CLIP_DISTANCE0                 0x3000\n#define GL_CLIP_DISTANCE1                 0x3001\n#define GL_CLIP_DISTANCE2                 0x3002\n#define GL_CLIP_DISTANCE3                 0x3003\n#define GL_CLIP_DISTANCE4                 0x3004\n#define GL_CLIP_DISTANCE5                 0x3005\n#define GL_CLIP_DISTANCE6                 0x3006\n#define GL_CLIP_DISTANCE7                 0x3007\n#define GL_MAX_CLIP_DISTANCES             0x0D32\n#define GL_MAJOR_VERSION                  0x821B\n#define GL_MINOR_VERSION                  0x821C\n#define GL_NUM_EXTENSIONS                 0x821D\n#define GL_CONTEXT_FLAGS                  0x821E\n#define GL_COMPRESSED_RED                 0x8225\n#define GL_COMPRESSED_RG                  0x8226\n#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001\n#define GL_RGBA32F                        0x8814\n#define GL_RGB32F                         0x8815\n#define GL_RGBA16F                        0x881A\n#define GL_RGB16F                         0x881B\n#define GL_VERTEX_ATTRIB_ARRAY_INTEGER    0x88FD\n#define GL_MAX_ARRAY_TEXTURE_LAYERS       0x88FF\n#define GL_MIN_PROGRAM_TEXEL_OFFSET       0x8904\n#define GL_MAX_PROGRAM_TEXEL_OFFSET       0x8905\n#define GL_CLAMP_READ_COLOR               0x891C\n#define GL_FIXED_ONLY                     0x891D\n#define GL_MAX_VARYING_COMPONENTS         0x8B4B\n#define GL_TEXTURE_1D_ARRAY               0x8C18\n#define GL_PROXY_TEXTURE_1D_ARRAY         0x8C19\n#define GL_TEXTURE_2D_ARRAY               0x8C1A\n#define GL_PROXY_TEXTURE_2D_ARRAY         0x8C1B\n#define GL_TEXTURE_BINDING_1D_ARRAY       0x8C1C\n#define GL_TEXTURE_BINDING_2D_ARRAY       0x8C1D\n#define GL_R11F_G11F_B10F                 0x8C3A\n#define GL_UNSIGNED_INT_10F_11F_11F_REV   0x8C3B\n#define GL_RGB9_E5                        0x8C3D\n#define GL_UNSIGNED_INT_5_9_9_9_REV       0x8C3E\n#define GL_TEXTURE_SHARED_SIZE            0x8C3F\n#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76\n#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F\n#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80\n#define GL_TRANSFORM_FEEDBACK_VARYINGS    0x8C83\n#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84\n#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85\n#define GL_PRIMITIVES_GENERATED           0x8C87\n#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88\n#define GL_RASTERIZER_DISCARD             0x8C89\n#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A\n#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B\n#define GL_INTERLEAVED_ATTRIBS            0x8C8C\n#define GL_SEPARATE_ATTRIBS               0x8C8D\n#define GL_TRANSFORM_FEEDBACK_BUFFER      0x8C8E\n#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F\n#define GL_RGBA32UI                       0x8D70\n#define GL_RGB32UI                        0x8D71\n#define GL_RGBA16UI                       0x8D76\n#define GL_RGB16UI                        0x8D77\n#define GL_RGBA8UI                        0x8D7C\n#define GL_RGB8UI                         0x8D7D\n#define GL_RGBA32I                        0x8D82\n#define GL_RGB32I                         0x8D83\n#define GL_RGBA16I                        0x8D88\n#define GL_RGB16I                         0x8D89\n#define GL_RGBA8I                         0x8D8E\n#define GL_RGB8I                          0x8D8F\n#define GL_RED_INTEGER                    0x8D94\n#define GL_GREEN_INTEGER                  0x8D95\n#define GL_BLUE_INTEGER                   0x8D96\n#define GL_RGB_INTEGER                    0x8D98\n#define GL_RGBA_INTEGER                   0x8D99\n#define GL_BGR_INTEGER                    0x8D9A\n#define GL_BGRA_INTEGER                   0x8D9B\n#define GL_SAMPLER_1D_ARRAY               0x8DC0\n#define GL_SAMPLER_2D_ARRAY               0x8DC1\n#define GL_SAMPLER_1D_ARRAY_SHADOW        0x8DC3\n#define GL_SAMPLER_2D_ARRAY_SHADOW        0x8DC4\n#define GL_SAMPLER_CUBE_SHADOW            0x8DC5\n#define GL_UNSIGNED_INT_VEC2              0x8DC6\n#define GL_UNSIGNED_INT_VEC3              0x8DC7\n#define GL_UNSIGNED_INT_VEC4              0x8DC8\n#define GL_INT_SAMPLER_1D                 0x8DC9\n#define GL_INT_SAMPLER_2D                 0x8DCA\n#define GL_INT_SAMPLER_3D                 0x8DCB\n#define GL_INT_SAMPLER_CUBE               0x8DCC\n#define GL_INT_SAMPLER_1D_ARRAY           0x8DCE\n#define GL_INT_SAMPLER_2D_ARRAY           0x8DCF\n#define GL_UNSIGNED_INT_SAMPLER_1D        0x8DD1\n#define GL_UNSIGNED_INT_SAMPLER_2D        0x8DD2\n#define GL_UNSIGNED_INT_SAMPLER_3D        0x8DD3\n#define GL_UNSIGNED_INT_SAMPLER_CUBE      0x8DD4\n#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY  0x8DD6\n#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY  0x8DD7\n#define GL_QUERY_WAIT                     0x8E13\n#define GL_QUERY_NO_WAIT                  0x8E14\n#define GL_QUERY_BY_REGION_WAIT           0x8E15\n#define GL_QUERY_BY_REGION_NO_WAIT        0x8E16\n#define GL_BUFFER_ACCESS_FLAGS            0x911F\n#define GL_BUFFER_MAP_LENGTH              0x9120\n#define GL_BUFFER_MAP_OFFSET              0x9121\n#define GL_DEPTH_COMPONENT32F             0x8CAC\n#define GL_DEPTH32F_STENCIL8              0x8CAD\n#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD\n#define GL_INVALID_FRAMEBUFFER_OPERATION  0x0506\n#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210\n#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211\n#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212\n#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213\n#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214\n#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215\n#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216\n#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217\n#define GL_FRAMEBUFFER_DEFAULT            0x8218\n#define GL_FRAMEBUFFER_UNDEFINED          0x8219\n#define GL_DEPTH_STENCIL_ATTACHMENT       0x821A\n#define GL_MAX_RENDERBUFFER_SIZE          0x84E8\n#define GL_DEPTH_STENCIL                  0x84F9\n#define GL_UNSIGNED_INT_24_8              0x84FA\n#define GL_DEPTH24_STENCIL8               0x88F0\n#define GL_TEXTURE_STENCIL_SIZE           0x88F1\n#define GL_TEXTURE_RED_TYPE               0x8C10\n#define GL_TEXTURE_GREEN_TYPE             0x8C11\n#define GL_TEXTURE_BLUE_TYPE              0x8C12\n#define GL_TEXTURE_ALPHA_TYPE             0x8C13\n#define GL_TEXTURE_DEPTH_TYPE             0x8C16\n#define GL_UNSIGNED_NORMALIZED            0x8C17\n#define GL_FRAMEBUFFER_BINDING            0x8CA6\n#define GL_DRAW_FRAMEBUFFER_BINDING       0x8CA6\n#define GL_RENDERBUFFER_BINDING           0x8CA7\n#define GL_READ_FRAMEBUFFER               0x8CA8\n#define GL_DRAW_FRAMEBUFFER               0x8CA9\n#define GL_READ_FRAMEBUFFER_BINDING       0x8CAA\n#define GL_RENDERBUFFER_SAMPLES           0x8CAB\n#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0\n#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4\n#define GL_FRAMEBUFFER_COMPLETE           0x8CD5\n#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6\n#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7\n#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB\n#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC\n#define GL_FRAMEBUFFER_UNSUPPORTED        0x8CDD\n#define GL_MAX_COLOR_ATTACHMENTS          0x8CDF\n#define GL_COLOR_ATTACHMENT0              0x8CE0\n#define GL_COLOR_ATTACHMENT1              0x8CE1\n#define GL_COLOR_ATTACHMENT2              0x8CE2\n#define GL_COLOR_ATTACHMENT3              0x8CE3\n#define GL_COLOR_ATTACHMENT4              0x8CE4\n#define GL_COLOR_ATTACHMENT5              0x8CE5\n#define GL_COLOR_ATTACHMENT6              0x8CE6\n#define GL_COLOR_ATTACHMENT7              0x8CE7\n#define GL_COLOR_ATTACHMENT8              0x8CE8\n#define GL_COLOR_ATTACHMENT9              0x8CE9\n#define GL_COLOR_ATTACHMENT10             0x8CEA\n#define GL_COLOR_ATTACHMENT11             0x8CEB\n#define GL_COLOR_ATTACHMENT12             0x8CEC\n#define GL_COLOR_ATTACHMENT13             0x8CED\n#define GL_COLOR_ATTACHMENT14             0x8CEE\n#define GL_COLOR_ATTACHMENT15             0x8CEF\n#define GL_DEPTH_ATTACHMENT               0x8D00\n#define GL_STENCIL_ATTACHMENT             0x8D20\n#define GL_FRAMEBUFFER                    0x8D40\n#define GL_RENDERBUFFER                   0x8D41\n#define GL_RENDERBUFFER_WIDTH             0x8D42\n#define GL_RENDERBUFFER_HEIGHT            0x8D43\n#define GL_RENDERBUFFER_INTERNAL_FORMAT   0x8D44\n#define GL_STENCIL_INDEX1                 0x8D46\n#define GL_STENCIL_INDEX4                 0x8D47\n#define GL_STENCIL_INDEX8                 0x8D48\n#define GL_STENCIL_INDEX16                0x8D49\n#define GL_RENDERBUFFER_RED_SIZE          0x8D50\n#define GL_RENDERBUFFER_GREEN_SIZE        0x8D51\n#define GL_RENDERBUFFER_BLUE_SIZE         0x8D52\n#define GL_RENDERBUFFER_ALPHA_SIZE        0x8D53\n#define GL_RENDERBUFFER_DEPTH_SIZE        0x8D54\n#define GL_RENDERBUFFER_STENCIL_SIZE      0x8D55\n#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56\n#define GL_MAX_SAMPLES                    0x8D57\n#define GL_INDEX                          0x8222\n#define GL_TEXTURE_LUMINANCE_TYPE         0x8C14\n#define GL_TEXTURE_INTENSITY_TYPE         0x8C15\n#define GL_FRAMEBUFFER_SRGB               0x8DB9\n#define GL_HALF_FLOAT                     0x140B\n#define GL_MAP_READ_BIT                   0x0001\n#define GL_MAP_WRITE_BIT                  0x0002\n#define GL_MAP_INVALIDATE_RANGE_BIT       0x0004\n#define GL_MAP_INVALIDATE_BUFFER_BIT      0x0008\n#define GL_MAP_FLUSH_EXPLICIT_BIT         0x0010\n#define GL_MAP_UNSYNCHRONIZED_BIT         0x0020\n#define GL_COMPRESSED_RED_RGTC1           0x8DBB\n#define GL_COMPRESSED_SIGNED_RED_RGTC1    0x8DBC\n#define GL_COMPRESSED_RG_RGTC2            0x8DBD\n#define GL_COMPRESSED_SIGNED_RG_RGTC2     0x8DBE\n#define GL_RG                             0x8227\n#define GL_RG_INTEGER                     0x8228\n#define GL_R8                             0x8229\n#define GL_R16                            0x822A\n#define GL_RG8                            0x822B\n#define GL_RG16                           0x822C\n#define GL_R16F                           0x822D\n#define GL_R32F                           0x822E\n#define GL_RG16F                          0x822F\n#define GL_RG32F                          0x8230\n#define GL_R8I                            0x8231\n#define GL_R8UI                           0x8232\n#define GL_R16I                           0x8233\n#define GL_R16UI                          0x8234\n#define GL_R32I                           0x8235\n#define GL_R32UI                          0x8236\n#define GL_RG8I                           0x8237\n#define GL_RG8UI                          0x8238\n#define GL_RG16I                          0x8239\n#define GL_RG16UI                         0x823A\n#define GL_RG32I                          0x823B\n#define GL_RG32UI                         0x823C\n#define GL_VERTEX_ARRAY_BINDING           0x85B5\n#define GL_CLAMP_VERTEX_COLOR             0x891A\n#define GL_CLAMP_FRAGMENT_COLOR           0x891B\n#define GL_ALPHA_INTEGER                  0x8D97\ntypedef void (APIENTRYP PFNGLCOLORMASKIPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);\ntypedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);\ntypedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);\ntypedef void (APIENTRYP PFNGLENABLEIPROC) (GLenum target, GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLEIPROC) (GLenum target, GLuint index);\ntypedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC) (GLenum target, GLuint index);\ntypedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode);\ntypedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void);\ntypedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer);\ntypedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);\ntypedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);\ntypedef void (APIENTRYP PFNGLCLAMPCOLORPROC) (GLenum target, GLenum clamp);\ntypedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC) (GLuint id, GLenum mode);\ntypedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC) (void);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC) (GLuint index, GLint x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC) (GLuint index, GLint x, GLint y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC) (GLuint index, GLint x, GLint y, GLint z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC) (GLuint index, GLuint x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC) (GLuint index, GLuint x, GLuint y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC) (GLuint index, const GLbyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC) (GLuint index, const GLushort *v);\ntypedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params);\ntypedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name);\ntypedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name);\ntypedef void (APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0);\ntypedef void (APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1);\ntypedef void (APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2);\ntypedef void (APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\ntypedef void (APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value);\ntypedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value);\ntypedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);\ntypedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);\ntypedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers);\ntypedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers);\ntypedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer);\ntypedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer);\ntypedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers);\ntypedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers);\ntypedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);\ntypedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);\ntypedef void *(APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);\ntypedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length);\ntypedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);\ntypedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);\ntypedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);\ntypedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorMaski (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);\nGLAPI void APIENTRY glGetBooleani_v (GLenum target, GLuint index, GLboolean *data);\nGLAPI void APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data);\nGLAPI void APIENTRY glEnablei (GLenum target, GLuint index);\nGLAPI void APIENTRY glDisablei (GLenum target, GLuint index);\nGLAPI GLboolean APIENTRY glIsEnabledi (GLenum target, GLuint index);\nGLAPI void APIENTRY glBeginTransformFeedback (GLenum primitiveMode);\nGLAPI void APIENTRY glEndTransformFeedback (void);\nGLAPI void APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);\nGLAPI void APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer);\nGLAPI void APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);\nGLAPI void APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);\nGLAPI void APIENTRY glClampColor (GLenum target, GLenum clamp);\nGLAPI void APIENTRY glBeginConditionalRender (GLuint id, GLenum mode);\nGLAPI void APIENTRY glEndConditionalRender (void);\nGLAPI void APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glVertexAttribI1i (GLuint index, GLint x);\nGLAPI void APIENTRY glVertexAttribI2i (GLuint index, GLint x, GLint y);\nGLAPI void APIENTRY glVertexAttribI3i (GLuint index, GLint x, GLint y, GLint z);\nGLAPI void APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glVertexAttribI1ui (GLuint index, GLuint x);\nGLAPI void APIENTRY glVertexAttribI2ui (GLuint index, GLuint x, GLuint y);\nGLAPI void APIENTRY glVertexAttribI3ui (GLuint index, GLuint x, GLuint y, GLuint z);\nGLAPI void APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\nGLAPI void APIENTRY glVertexAttribI1iv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI2iv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI3iv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI1uiv (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI2uiv (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI3uiv (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI4bv (GLuint index, const GLbyte *v);\nGLAPI void APIENTRY glVertexAttribI4sv (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttribI4ubv (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttribI4usv (GLuint index, const GLushort *v);\nGLAPI void APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params);\nGLAPI void APIENTRY glBindFragDataLocation (GLuint program, GLuint color, const GLchar *name);\nGLAPI GLint APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name);\nGLAPI void APIENTRY glUniform1ui (GLint location, GLuint v0);\nGLAPI void APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1);\nGLAPI void APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2);\nGLAPI void APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\nGLAPI void APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glTexParameterIiv (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glTexParameterIuiv (GLenum target, GLenum pname, const GLuint *params);\nGLAPI void APIENTRY glGetTexParameterIiv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetTexParameterIuiv (GLenum target, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value);\nGLAPI void APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value);\nGLAPI void APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value);\nGLAPI void APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);\nGLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);\nGLAPI GLboolean APIENTRY glIsRenderbuffer (GLuint renderbuffer);\nGLAPI void APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);\nGLAPI void APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers);\nGLAPI void APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers);\nGLAPI void APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI GLboolean APIENTRY glIsFramebuffer (GLuint framebuffer);\nGLAPI void APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);\nGLAPI void APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers);\nGLAPI void APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers);\nGLAPI GLenum APIENTRY glCheckFramebufferStatus (GLenum target);\nGLAPI void APIENTRY glFramebufferTexture1D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\nGLAPI void APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\nGLAPI void APIENTRY glFramebufferTexture3D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);\nGLAPI void APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);\nGLAPI void APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGenerateMipmap (GLenum target);\nGLAPI void APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);\nGLAPI void APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);\nGLAPI void *APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);\nGLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length);\nGLAPI void APIENTRY glBindVertexArray (GLuint array);\nGLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);\nGLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);\nGLAPI GLboolean APIENTRY glIsVertexArray (GLuint array);\n#endif\n#endif /* GL_VERSION_3_0 */\n\n#ifndef GL_VERSION_3_1\n#define GL_VERSION_3_1 1\n#define GL_SAMPLER_2D_RECT                0x8B63\n#define GL_SAMPLER_2D_RECT_SHADOW         0x8B64\n#define GL_SAMPLER_BUFFER                 0x8DC2\n#define GL_INT_SAMPLER_2D_RECT            0x8DCD\n#define GL_INT_SAMPLER_BUFFER             0x8DD0\n#define GL_UNSIGNED_INT_SAMPLER_2D_RECT   0x8DD5\n#define GL_UNSIGNED_INT_SAMPLER_BUFFER    0x8DD8\n#define GL_TEXTURE_BUFFER                 0x8C2A\n#define GL_MAX_TEXTURE_BUFFER_SIZE        0x8C2B\n#define GL_TEXTURE_BINDING_BUFFER         0x8C2C\n#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D\n#define GL_TEXTURE_RECTANGLE              0x84F5\n#define GL_TEXTURE_BINDING_RECTANGLE      0x84F6\n#define GL_PROXY_TEXTURE_RECTANGLE        0x84F7\n#define GL_MAX_RECTANGLE_TEXTURE_SIZE     0x84F8\n#define GL_R8_SNORM                       0x8F94\n#define GL_RG8_SNORM                      0x8F95\n#define GL_RGB8_SNORM                     0x8F96\n#define GL_RGBA8_SNORM                    0x8F97\n#define GL_R16_SNORM                      0x8F98\n#define GL_RG16_SNORM                     0x8F99\n#define GL_RGB16_SNORM                    0x8F9A\n#define GL_RGBA16_SNORM                   0x8F9B\n#define GL_SIGNED_NORMALIZED              0x8F9C\n#define GL_PRIMITIVE_RESTART              0x8F9D\n#define GL_PRIMITIVE_RESTART_INDEX        0x8F9E\n#define GL_COPY_READ_BUFFER               0x8F36\n#define GL_COPY_WRITE_BUFFER              0x8F37\n#define GL_UNIFORM_BUFFER                 0x8A11\n#define GL_UNIFORM_BUFFER_BINDING         0x8A28\n#define GL_UNIFORM_BUFFER_START           0x8A29\n#define GL_UNIFORM_BUFFER_SIZE            0x8A2A\n#define GL_MAX_VERTEX_UNIFORM_BLOCKS      0x8A2B\n#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS    0x8A2D\n#define GL_MAX_COMBINED_UNIFORM_BLOCKS    0x8A2E\n#define GL_MAX_UNIFORM_BUFFER_BINDINGS    0x8A2F\n#define GL_MAX_UNIFORM_BLOCK_SIZE         0x8A30\n#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31\n#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33\n#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34\n#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35\n#define GL_ACTIVE_UNIFORM_BLOCKS          0x8A36\n#define GL_UNIFORM_TYPE                   0x8A37\n#define GL_UNIFORM_SIZE                   0x8A38\n#define GL_UNIFORM_NAME_LENGTH            0x8A39\n#define GL_UNIFORM_BLOCK_INDEX            0x8A3A\n#define GL_UNIFORM_OFFSET                 0x8A3B\n#define GL_UNIFORM_ARRAY_STRIDE           0x8A3C\n#define GL_UNIFORM_MATRIX_STRIDE          0x8A3D\n#define GL_UNIFORM_IS_ROW_MAJOR           0x8A3E\n#define GL_UNIFORM_BLOCK_BINDING          0x8A3F\n#define GL_UNIFORM_BLOCK_DATA_SIZE        0x8A40\n#define GL_UNIFORM_BLOCK_NAME_LENGTH      0x8A41\n#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS  0x8A42\n#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43\n#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44\n#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46\n#define GL_INVALID_INDEX                  0xFFFFFFFFu\ntypedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount);\ntypedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer);\ntypedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices);\ntypedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName);\ntypedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName);\ntypedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);\ntypedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount);\nGLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount);\nGLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer);\nGLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index);\nGLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);\nGLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices);\nGLAPI void APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetActiveUniformName (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName);\nGLAPI GLuint APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName);\nGLAPI void APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);\nGLAPI void APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);\n#endif\n#endif /* GL_VERSION_3_1 */\n\n#ifndef GL_VERSION_3_2\n#define GL_VERSION_3_2 1\ntypedef struct __GLsync *GLsync;\n#ifndef GLEXT_64_TYPES_DEFINED\n/* This code block is duplicated in glxext.h, so must be protected */\n#define GLEXT_64_TYPES_DEFINED\n/* Define int32_t, int64_t, and uint64_t types for UST/MSC */\n/* (as used in the GL_EXT_timer_query extension). */\n#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L\n#include <inttypes.h>\n#elif defined(__sun__) || defined(__digital__)\n#include <inttypes.h>\n#if defined(__STDC__)\n#if defined(__arch64__) || defined(_LP64)\ntypedef long int int64_t;\ntypedef unsigned long int uint64_t;\n#else\ntypedef long long int int64_t;\ntypedef unsigned long long int uint64_t;\n#endif /* __arch64__ */\n#endif /* __STDC__ */\n#elif defined( __VMS ) || defined(__sgi)\n#include <inttypes.h>\n#elif defined(__SCO__) || defined(__USLC__)\n#include <stdint.h>\n#elif defined(__UNIXOS2__) || defined(__SOL64__)\ntypedef long int int32_t;\ntypedef long long int int64_t;\ntypedef unsigned long long int uint64_t;\n#elif defined(_WIN32) && defined(__GNUC__)\n#include <stdint.h>\n#elif defined(_WIN32)\ntypedef __int32 int32_t;\ntypedef __int64 int64_t;\ntypedef unsigned __int64 uint64_t;\n#else\n/* Fallback if nothing above works */\n#include <inttypes.h>\n#endif\n#endif\ntypedef uint64_t GLuint64;\ntypedef int64_t GLint64;\n#define GL_CONTEXT_CORE_PROFILE_BIT       0x00000001\n#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002\n#define GL_LINES_ADJACENCY                0x000A\n#define GL_LINE_STRIP_ADJACENCY           0x000B\n#define GL_TRIANGLES_ADJACENCY            0x000C\n#define GL_TRIANGLE_STRIP_ADJACENCY       0x000D\n#define GL_PROGRAM_POINT_SIZE             0x8642\n#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29\n#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7\n#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8\n#define GL_GEOMETRY_SHADER                0x8DD9\n#define GL_GEOMETRY_VERTICES_OUT          0x8916\n#define GL_GEOMETRY_INPUT_TYPE            0x8917\n#define GL_GEOMETRY_OUTPUT_TYPE           0x8918\n#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF\n#define GL_MAX_GEOMETRY_OUTPUT_VERTICES   0x8DE0\n#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1\n#define GL_MAX_VERTEX_OUTPUT_COMPONENTS   0x9122\n#define GL_MAX_GEOMETRY_INPUT_COMPONENTS  0x9123\n#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124\n#define GL_MAX_FRAGMENT_INPUT_COMPONENTS  0x9125\n#define GL_CONTEXT_PROFILE_MASK           0x9126\n#define GL_DEPTH_CLAMP                    0x864F\n#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C\n#define GL_FIRST_VERTEX_CONVENTION        0x8E4D\n#define GL_LAST_VERTEX_CONVENTION         0x8E4E\n#define GL_PROVOKING_VERTEX               0x8E4F\n#define GL_TEXTURE_CUBE_MAP_SEAMLESS      0x884F\n#define GL_MAX_SERVER_WAIT_TIMEOUT        0x9111\n#define GL_OBJECT_TYPE                    0x9112\n#define GL_SYNC_CONDITION                 0x9113\n#define GL_SYNC_STATUS                    0x9114\n#define GL_SYNC_FLAGS                     0x9115\n#define GL_SYNC_FENCE                     0x9116\n#define GL_SYNC_GPU_COMMANDS_COMPLETE     0x9117\n#define GL_UNSIGNALED                     0x9118\n#define GL_SIGNALED                       0x9119\n#define GL_ALREADY_SIGNALED               0x911A\n#define GL_TIMEOUT_EXPIRED                0x911B\n#define GL_CONDITION_SATISFIED            0x911C\n#define GL_WAIT_FAILED                    0x911D\n#define GL_TIMEOUT_IGNORED                0xFFFFFFFFFFFFFFFFull\n#define GL_SYNC_FLUSH_COMMANDS_BIT        0x00000001\n#define GL_SAMPLE_POSITION                0x8E50\n#define GL_SAMPLE_MASK                    0x8E51\n#define GL_SAMPLE_MASK_VALUE              0x8E52\n#define GL_MAX_SAMPLE_MASK_WORDS          0x8E59\n#define GL_TEXTURE_2D_MULTISAMPLE         0x9100\n#define GL_PROXY_TEXTURE_2D_MULTISAMPLE   0x9101\n#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY   0x9102\n#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103\n#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104\n#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105\n#define GL_TEXTURE_SAMPLES                0x9106\n#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107\n#define GL_SAMPLER_2D_MULTISAMPLE         0x9108\n#define GL_INT_SAMPLER_2D_MULTISAMPLE     0x9109\n#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A\n#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY   0x910B\n#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C\n#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D\n#define GL_MAX_COLOR_TEXTURE_SAMPLES      0x910E\n#define GL_MAX_DEPTH_TEXTURE_SAMPLES      0x910F\n#define GL_MAX_INTEGER_SAMPLES            0x9110\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex);\ntypedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode);\ntypedef GLsync (APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags);\ntypedef GLboolean (APIENTRYP PFNGLISSYNCPROC) (GLsync sync);\ntypedef void (APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync);\ntypedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout);\ntypedef void (APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout);\ntypedef void (APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data);\ntypedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);\ntypedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);\ntypedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);\ntypedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);\ntypedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val);\ntypedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint maskNumber, GLbitfield mask);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);\nGLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);\nGLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex);\nGLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex);\nGLAPI void APIENTRY glProvokingVertex (GLenum mode);\nGLAPI GLsync APIENTRY glFenceSync (GLenum condition, GLbitfield flags);\nGLAPI GLboolean APIENTRY glIsSync (GLsync sync);\nGLAPI void APIENTRY glDeleteSync (GLsync sync);\nGLAPI GLenum APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout);\nGLAPI void APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout);\nGLAPI void APIENTRY glGetInteger64v (GLenum pname, GLint64 *data);\nGLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);\nGLAPI void APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data);\nGLAPI void APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params);\nGLAPI void APIENTRY glFramebufferTexture (GLenum target, GLenum attachment, GLuint texture, GLint level);\nGLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);\nGLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);\nGLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val);\nGLAPI void APIENTRY glSampleMaski (GLuint maskNumber, GLbitfield mask);\n#endif\n#endif /* GL_VERSION_3_2 */\n\n#ifndef GL_VERSION_3_3\n#define GL_VERSION_3_3 1\n#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR    0x88FE\n#define GL_SRC1_COLOR                     0x88F9\n#define GL_ONE_MINUS_SRC1_COLOR           0x88FA\n#define GL_ONE_MINUS_SRC1_ALPHA           0x88FB\n#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS   0x88FC\n#define GL_ANY_SAMPLES_PASSED             0x8C2F\n#define GL_SAMPLER_BINDING                0x8919\n#define GL_RGB10_A2UI                     0x906F\n#define GL_TEXTURE_SWIZZLE_R              0x8E42\n#define GL_TEXTURE_SWIZZLE_G              0x8E43\n#define GL_TEXTURE_SWIZZLE_B              0x8E44\n#define GL_TEXTURE_SWIZZLE_A              0x8E45\n#define GL_TEXTURE_SWIZZLE_RGBA           0x8E46\n#define GL_TIME_ELAPSED                   0x88BF\n#define GL_TIMESTAMP                      0x8E28\n#define GL_INT_2_10_10_10_REV             0x8D9F\ntypedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name);\ntypedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers);\ntypedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers);\ntypedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler);\ntypedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);\ntypedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param);\ntypedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param);\ntypedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint *param);\ntypedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint *param);\ntypedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64 *params);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64 *params);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\ntypedef void (APIENTRYP PFNGLVERTEXP2UIPROC) (GLenum type, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXP2UIVPROC) (GLenum type, const GLuint *value);\ntypedef void (APIENTRYP PFNGLVERTEXP3UIPROC) (GLenum type, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXP3UIVPROC) (GLenum type, const GLuint *value);\ntypedef void (APIENTRYP PFNGLVERTEXP4UIPROC) (GLenum type, GLuint value);\ntypedef void (APIENTRYP PFNGLVERTEXP4UIVPROC) (GLenum type, const GLuint *value);\ntypedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC) (GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC) (GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC) (GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC) (GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC) (GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC) (GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC) (GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC) (GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC) (GLenum texture, GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC) (GLenum texture, GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC) (GLenum texture, GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC) (GLenum texture, GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLNORMALP3UIPROC) (GLenum type, GLuint coords);\ntypedef void (APIENTRYP PFNGLNORMALP3UIVPROC) (GLenum type, const GLuint *coords);\ntypedef void (APIENTRYP PFNGLCOLORP3UIPROC) (GLenum type, GLuint color);\ntypedef void (APIENTRYP PFNGLCOLORP3UIVPROC) (GLenum type, const GLuint *color);\ntypedef void (APIENTRYP PFNGLCOLORP4UIPROC) (GLenum type, GLuint color);\ntypedef void (APIENTRYP PFNGLCOLORP4UIVPROC) (GLenum type, const GLuint *color);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC) (GLenum type, GLuint color);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC) (GLenum type, const GLuint *color);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindFragDataLocationIndexed (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name);\nGLAPI GLint APIENTRY glGetFragDataIndex (GLuint program, const GLchar *name);\nGLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers);\nGLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers);\nGLAPI GLboolean APIENTRY glIsSampler (GLuint sampler);\nGLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);\nGLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param);\nGLAPI void APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param);\nGLAPI void APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param);\nGLAPI void APIENTRY glSamplerParameterIiv (GLuint sampler, GLenum pname, const GLint *param);\nGLAPI void APIENTRY glSamplerParameterIuiv (GLuint sampler, GLenum pname, const GLuint *param);\nGLAPI void APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetSamplerParameterIiv (GLuint sampler, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetSamplerParameterIuiv (GLuint sampler, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glQueryCounter (GLuint id, GLenum target);\nGLAPI void APIENTRY glGetQueryObjecti64v (GLuint id, GLenum pname, GLint64 *params);\nGLAPI void APIENTRY glGetQueryObjectui64v (GLuint id, GLenum pname, GLuint64 *params);\nGLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor);\nGLAPI void APIENTRY glVertexAttribP1ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);\nGLAPI void APIENTRY glVertexAttribP1uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\nGLAPI void APIENTRY glVertexAttribP2ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);\nGLAPI void APIENTRY glVertexAttribP2uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\nGLAPI void APIENTRY glVertexAttribP3ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);\nGLAPI void APIENTRY glVertexAttribP3uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\nGLAPI void APIENTRY glVertexAttribP4ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);\nGLAPI void APIENTRY glVertexAttribP4uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);\nGLAPI void APIENTRY glVertexP2ui (GLenum type, GLuint value);\nGLAPI void APIENTRY glVertexP2uiv (GLenum type, const GLuint *value);\nGLAPI void APIENTRY glVertexP3ui (GLenum type, GLuint value);\nGLAPI void APIENTRY glVertexP3uiv (GLenum type, const GLuint *value);\nGLAPI void APIENTRY glVertexP4ui (GLenum type, GLuint value);\nGLAPI void APIENTRY glVertexP4uiv (GLenum type, const GLuint *value);\nGLAPI void APIENTRY glTexCoordP1ui (GLenum type, GLuint coords);\nGLAPI void APIENTRY glTexCoordP1uiv (GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glTexCoordP2ui (GLenum type, GLuint coords);\nGLAPI void APIENTRY glTexCoordP2uiv (GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glTexCoordP3ui (GLenum type, GLuint coords);\nGLAPI void APIENTRY glTexCoordP3uiv (GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glTexCoordP4ui (GLenum type, GLuint coords);\nGLAPI void APIENTRY glTexCoordP4uiv (GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glMultiTexCoordP1ui (GLenum texture, GLenum type, GLuint coords);\nGLAPI void APIENTRY glMultiTexCoordP1uiv (GLenum texture, GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glMultiTexCoordP2ui (GLenum texture, GLenum type, GLuint coords);\nGLAPI void APIENTRY glMultiTexCoordP2uiv (GLenum texture, GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glMultiTexCoordP3ui (GLenum texture, GLenum type, GLuint coords);\nGLAPI void APIENTRY glMultiTexCoordP3uiv (GLenum texture, GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glMultiTexCoordP4ui (GLenum texture, GLenum type, GLuint coords);\nGLAPI void APIENTRY glMultiTexCoordP4uiv (GLenum texture, GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glNormalP3ui (GLenum type, GLuint coords);\nGLAPI void APIENTRY glNormalP3uiv (GLenum type, const GLuint *coords);\nGLAPI void APIENTRY glColorP3ui (GLenum type, GLuint color);\nGLAPI void APIENTRY glColorP3uiv (GLenum type, const GLuint *color);\nGLAPI void APIENTRY glColorP4ui (GLenum type, GLuint color);\nGLAPI void APIENTRY glColorP4uiv (GLenum type, const GLuint *color);\nGLAPI void APIENTRY glSecondaryColorP3ui (GLenum type, GLuint color);\nGLAPI void APIENTRY glSecondaryColorP3uiv (GLenum type, const GLuint *color);\n#endif\n#endif /* GL_VERSION_3_3 */\n\n#ifndef GL_VERSION_4_0\n#define GL_VERSION_4_0 1\n#define GL_SAMPLE_SHADING                 0x8C36\n#define GL_MIN_SAMPLE_SHADING_VALUE       0x8C37\n#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E\n#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F\n#define GL_TEXTURE_CUBE_MAP_ARRAY         0x9009\n#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A\n#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY   0x900B\n#define GL_SAMPLER_CUBE_MAP_ARRAY         0x900C\n#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW  0x900D\n#define GL_INT_SAMPLER_CUBE_MAP_ARRAY     0x900E\n#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F\n#define GL_DRAW_INDIRECT_BUFFER           0x8F3F\n#define GL_DRAW_INDIRECT_BUFFER_BINDING   0x8F43\n#define GL_GEOMETRY_SHADER_INVOCATIONS    0x887F\n#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A\n#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B\n#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C\n#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D\n#define GL_MAX_VERTEX_STREAMS             0x8E71\n#define GL_DOUBLE_VEC2                    0x8FFC\n#define GL_DOUBLE_VEC3                    0x8FFD\n#define GL_DOUBLE_VEC4                    0x8FFE\n#define GL_DOUBLE_MAT2                    0x8F46\n#define GL_DOUBLE_MAT3                    0x8F47\n#define GL_DOUBLE_MAT4                    0x8F48\n#define GL_DOUBLE_MAT2x3                  0x8F49\n#define GL_DOUBLE_MAT2x4                  0x8F4A\n#define GL_DOUBLE_MAT3x2                  0x8F4B\n#define GL_DOUBLE_MAT3x4                  0x8F4C\n#define GL_DOUBLE_MAT4x2                  0x8F4D\n#define GL_DOUBLE_MAT4x3                  0x8F4E\n#define GL_ACTIVE_SUBROUTINES             0x8DE5\n#define GL_ACTIVE_SUBROUTINE_UNIFORMS     0x8DE6\n#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47\n#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH   0x8E48\n#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49\n#define GL_MAX_SUBROUTINES                0x8DE7\n#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8\n#define GL_NUM_COMPATIBLE_SUBROUTINES     0x8E4A\n#define GL_COMPATIBLE_SUBROUTINES         0x8E4B\n#define GL_PATCHES                        0x000E\n#define GL_PATCH_VERTICES                 0x8E72\n#define GL_PATCH_DEFAULT_INNER_LEVEL      0x8E73\n#define GL_PATCH_DEFAULT_OUTER_LEVEL      0x8E74\n#define GL_TESS_CONTROL_OUTPUT_VERTICES   0x8E75\n#define GL_TESS_GEN_MODE                  0x8E76\n#define GL_TESS_GEN_SPACING               0x8E77\n#define GL_TESS_GEN_VERTEX_ORDER          0x8E78\n#define GL_TESS_GEN_POINT_MODE            0x8E79\n#define GL_ISOLINES                       0x8E7A\n#define GL_FRACTIONAL_ODD                 0x8E7B\n#define GL_FRACTIONAL_EVEN                0x8E7C\n#define GL_MAX_PATCH_VERTICES             0x8E7D\n#define GL_MAX_TESS_GEN_LEVEL             0x8E7E\n#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F\n#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80\n#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81\n#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82\n#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83\n#define GL_MAX_TESS_PATCH_COMPONENTS      0x8E84\n#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85\n#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86\n#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89\n#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A\n#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C\n#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D\n#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E\n#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F\n#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0\n#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1\n#define GL_TESS_EVALUATION_SHADER         0x8E87\n#define GL_TESS_CONTROL_SHADER            0x8E88\n#define GL_TRANSFORM_FEEDBACK             0x8E22\n#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23\n#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24\n#define GL_TRANSFORM_FEEDBACK_BINDING     0x8E25\n#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70\ntypedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLfloat value);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);\ntypedef void (APIENTRYP PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst);\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);\ntypedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect);\ntypedef void (APIENTRYP PFNGLUNIFORM1DPROC) (GLint location, GLdouble x);\ntypedef void (APIENTRYP PFNGLUNIFORM2DPROC) (GLint location, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLUNIFORM3DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLUNIFORM4DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLUNIFORM1DVPROC) (GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2DVPROC) (GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3DVPROC) (GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4DVPROC) (GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLGETUNIFORMDVPROC) (GLuint program, GLint location, GLdouble *params);\ntypedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const GLchar *name);\ntypedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values);\ntypedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);\ntypedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);\ntypedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint *indices);\ntypedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint *values);\ntypedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value);\ntypedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values);\ntypedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id);\ntypedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids);\ntypedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids);\ntypedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void);\ntypedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void);\ntypedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id);\ntypedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream);\ntypedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id);\ntypedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index);\ntypedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMinSampleShading (GLfloat value);\nGLAPI void APIENTRY glBlendEquationi (GLuint buf, GLenum mode);\nGLAPI void APIENTRY glBlendEquationSeparatei (GLuint buf, GLenum modeRGB, GLenum modeAlpha);\nGLAPI void APIENTRY glBlendFunci (GLuint buf, GLenum src, GLenum dst);\nGLAPI void APIENTRY glBlendFuncSeparatei (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);\nGLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const void *indirect);\nGLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect);\nGLAPI void APIENTRY glUniform1d (GLint location, GLdouble x);\nGLAPI void APIENTRY glUniform2d (GLint location, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glUniform3d (GLint location, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glUniform4d (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glUniform1dv (GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glUniform2dv (GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glUniform3dv (GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glUniform4dv (GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix2x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix2x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix3x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix3x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix4x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glUniformMatrix4x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glGetUniformdv (GLuint program, GLint location, GLdouble *params);\nGLAPI GLint APIENTRY glGetSubroutineUniformLocation (GLuint program, GLenum shadertype, const GLchar *name);\nGLAPI GLuint APIENTRY glGetSubroutineIndex (GLuint program, GLenum shadertype, const GLchar *name);\nGLAPI void APIENTRY glGetActiveSubroutineUniformiv (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values);\nGLAPI void APIENTRY glGetActiveSubroutineUniformName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);\nGLAPI void APIENTRY glGetActiveSubroutineName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);\nGLAPI void APIENTRY glUniformSubroutinesuiv (GLenum shadertype, GLsizei count, const GLuint *indices);\nGLAPI void APIENTRY glGetUniformSubroutineuiv (GLenum shadertype, GLint location, GLuint *params);\nGLAPI void APIENTRY glGetProgramStageiv (GLuint program, GLenum shadertype, GLenum pname, GLint *values);\nGLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value);\nGLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values);\nGLAPI void APIENTRY glBindTransformFeedback (GLenum target, GLuint id);\nGLAPI void APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids);\nGLAPI void APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids);\nGLAPI GLboolean APIENTRY glIsTransformFeedback (GLuint id);\nGLAPI void APIENTRY glPauseTransformFeedback (void);\nGLAPI void APIENTRY glResumeTransformFeedback (void);\nGLAPI void APIENTRY glDrawTransformFeedback (GLenum mode, GLuint id);\nGLAPI void APIENTRY glDrawTransformFeedbackStream (GLenum mode, GLuint id, GLuint stream);\nGLAPI void APIENTRY glBeginQueryIndexed (GLenum target, GLuint index, GLuint id);\nGLAPI void APIENTRY glEndQueryIndexed (GLenum target, GLuint index);\nGLAPI void APIENTRY glGetQueryIndexediv (GLenum target, GLuint index, GLenum pname, GLint *params);\n#endif\n#endif /* GL_VERSION_4_0 */\n\n#ifndef GL_VERSION_4_1\n#define GL_VERSION_4_1 1\n#define GL_FIXED                          0x140C\n#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A\n#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B\n#define GL_LOW_FLOAT                      0x8DF0\n#define GL_MEDIUM_FLOAT                   0x8DF1\n#define GL_HIGH_FLOAT                     0x8DF2\n#define GL_LOW_INT                        0x8DF3\n#define GL_MEDIUM_INT                     0x8DF4\n#define GL_HIGH_INT                       0x8DF5\n#define GL_SHADER_COMPILER                0x8DFA\n#define GL_SHADER_BINARY_FORMATS          0x8DF8\n#define GL_NUM_SHADER_BINARY_FORMATS      0x8DF9\n#define GL_MAX_VERTEX_UNIFORM_VECTORS     0x8DFB\n#define GL_MAX_VARYING_VECTORS            0x8DFC\n#define GL_MAX_FRAGMENT_UNIFORM_VECTORS   0x8DFD\n#define GL_RGB565                         0x8D62\n#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257\n#define GL_PROGRAM_BINARY_LENGTH          0x8741\n#define GL_NUM_PROGRAM_BINARY_FORMATS     0x87FE\n#define GL_PROGRAM_BINARY_FORMATS         0x87FF\n#define GL_VERTEX_SHADER_BIT              0x00000001\n#define GL_FRAGMENT_SHADER_BIT            0x00000002\n#define GL_GEOMETRY_SHADER_BIT            0x00000004\n#define GL_TESS_CONTROL_SHADER_BIT        0x00000008\n#define GL_TESS_EVALUATION_SHADER_BIT     0x00000010\n#define GL_ALL_SHADER_BITS                0xFFFFFFFF\n#define GL_PROGRAM_SEPARABLE              0x8258\n#define GL_ACTIVE_PROGRAM                 0x8259\n#define GL_PROGRAM_PIPELINE_BINDING       0x825A\n#define GL_MAX_VIEWPORTS                  0x825B\n#define GL_VIEWPORT_SUBPIXEL_BITS         0x825C\n#define GL_VIEWPORT_BOUNDS_RANGE          0x825D\n#define GL_LAYER_PROVOKING_VERTEX         0x825E\n#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F\n#define GL_UNDEFINED_VERTEX               0x8260\ntypedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void);\ntypedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length);\ntypedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);\ntypedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f);\ntypedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d);\ntypedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);\ntypedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value);\ntypedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) (GLuint pipeline, GLbitfield stages, GLuint program);\ntypedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC) (GLuint pipeline, GLuint program);\ntypedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) (GLenum type, GLsizei count, const GLchar *const*strings);\ntypedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC) (GLuint pipeline);\ntypedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC) (GLsizei n, const GLuint *pipelines);\ntypedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines);\ntypedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC) (GLuint pipeline);\ntypedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) (GLuint pipeline, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) (GLuint program, GLint location, GLint v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) (GLuint program, GLint location, GLfloat v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC) (GLuint program, GLint location, GLdouble v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) (GLuint program, GLint location, GLuint v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) (GLuint program, GLint location, GLint v0, GLint v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC) (GLuint pipeline);\ntypedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC) (GLuint index, GLdouble x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC) (GLuint index, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC) (GLuint first, GLsizei count, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);\ntypedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLSCISSORARRAYVPROC) (GLuint first, GLsizei count, const GLint *v);\ntypedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC) (GLuint first, GLsizei count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLdouble n, GLdouble f);\ntypedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);\ntypedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glReleaseShaderCompiler (void);\nGLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length);\nGLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);\nGLAPI void APIENTRY glDepthRangef (GLfloat n, GLfloat f);\nGLAPI void APIENTRY glClearDepthf (GLfloat d);\nGLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);\nGLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length);\nGLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value);\nGLAPI void APIENTRY glUseProgramStages (GLuint pipeline, GLbitfield stages, GLuint program);\nGLAPI void APIENTRY glActiveShaderProgram (GLuint pipeline, GLuint program);\nGLAPI GLuint APIENTRY glCreateShaderProgramv (GLenum type, GLsizei count, const GLchar *const*strings);\nGLAPI void APIENTRY glBindProgramPipeline (GLuint pipeline);\nGLAPI void APIENTRY glDeleteProgramPipelines (GLsizei n, const GLuint *pipelines);\nGLAPI void APIENTRY glGenProgramPipelines (GLsizei n, GLuint *pipelines);\nGLAPI GLboolean APIENTRY glIsProgramPipeline (GLuint pipeline);\nGLAPI void APIENTRY glGetProgramPipelineiv (GLuint pipeline, GLenum pname, GLint *params);\nGLAPI void APIENTRY glProgramUniform1i (GLuint program, GLint location, GLint v0);\nGLAPI void APIENTRY glProgramUniform1iv (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform1f (GLuint program, GLint location, GLfloat v0);\nGLAPI void APIENTRY glProgramUniform1fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform1d (GLuint program, GLint location, GLdouble v0);\nGLAPI void APIENTRY glProgramUniform1dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform1ui (GLuint program, GLint location, GLuint v0);\nGLAPI void APIENTRY glProgramUniform1uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniform2i (GLuint program, GLint location, GLint v0, GLint v1);\nGLAPI void APIENTRY glProgramUniform2iv (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform2f (GLuint program, GLint location, GLfloat v0, GLfloat v1);\nGLAPI void APIENTRY glProgramUniform2fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform2d (GLuint program, GLint location, GLdouble v0, GLdouble v1);\nGLAPI void APIENTRY glProgramUniform2dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform2ui (GLuint program, GLint location, GLuint v0, GLuint v1);\nGLAPI void APIENTRY glProgramUniform2uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniform3i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);\nGLAPI void APIENTRY glProgramUniform3iv (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform3f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\nGLAPI void APIENTRY glProgramUniform3fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform3d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2);\nGLAPI void APIENTRY glProgramUniform3dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform3ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);\nGLAPI void APIENTRY glProgramUniform3uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniform4i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\nGLAPI void APIENTRY glProgramUniform4iv (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform4f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\nGLAPI void APIENTRY glProgramUniform4fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform4d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);\nGLAPI void APIENTRY glProgramUniform4dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform4ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\nGLAPI void APIENTRY glProgramUniform4uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniformMatrix2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glValidateProgramPipeline (GLuint pipeline);\nGLAPI void APIENTRY glGetProgramPipelineInfoLog (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);\nGLAPI void APIENTRY glVertexAttribL1d (GLuint index, GLdouble x);\nGLAPI void APIENTRY glVertexAttribL2d (GLuint index, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glVertexAttribL3d (GLuint index, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glVertexAttribL4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glVertexAttribL1dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribL2dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribL3dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribL4dv (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribLPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glViewportArrayv (GLuint first, GLsizei count, const GLfloat *v);\nGLAPI void APIENTRY glViewportIndexedf (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);\nGLAPI void APIENTRY glViewportIndexedfv (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glScissorArrayv (GLuint first, GLsizei count, const GLint *v);\nGLAPI void APIENTRY glScissorIndexed (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glScissorIndexedv (GLuint index, const GLint *v);\nGLAPI void APIENTRY glDepthRangeArrayv (GLuint first, GLsizei count, const GLdouble *v);\nGLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLdouble n, GLdouble f);\nGLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data);\nGLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data);\n#endif\n#endif /* GL_VERSION_4_1 */\n\n#ifndef GL_VERSION_4_2\n#define GL_VERSION_4_2 1\n#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH  0x9127\n#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128\n#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH  0x9129\n#define GL_UNPACK_COMPRESSED_BLOCK_SIZE   0x912A\n#define GL_PACK_COMPRESSED_BLOCK_WIDTH    0x912B\n#define GL_PACK_COMPRESSED_BLOCK_HEIGHT   0x912C\n#define GL_PACK_COMPRESSED_BLOCK_DEPTH    0x912D\n#define GL_PACK_COMPRESSED_BLOCK_SIZE     0x912E\n#define GL_NUM_SAMPLE_COUNTS              0x9380\n#define GL_MIN_MAP_BUFFER_ALIGNMENT       0x90BC\n#define GL_ATOMIC_COUNTER_BUFFER          0x92C0\n#define GL_ATOMIC_COUNTER_BUFFER_BINDING  0x92C1\n#define GL_ATOMIC_COUNTER_BUFFER_START    0x92C2\n#define GL_ATOMIC_COUNTER_BUFFER_SIZE     0x92C3\n#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4\n#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5\n#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6\n#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7\n#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8\n#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9\n#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA\n#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB\n#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC\n#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD\n#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE\n#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF\n#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0\n#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1\n#define GL_MAX_VERTEX_ATOMIC_COUNTERS     0x92D2\n#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3\n#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4\n#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS   0x92D5\n#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS   0x92D6\n#define GL_MAX_COMBINED_ATOMIC_COUNTERS   0x92D7\n#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8\n#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC\n#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS  0x92D9\n#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA\n#define GL_UNSIGNED_INT_ATOMIC_COUNTER    0x92DB\n#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001\n#define GL_ELEMENT_ARRAY_BARRIER_BIT      0x00000002\n#define GL_UNIFORM_BARRIER_BIT            0x00000004\n#define GL_TEXTURE_FETCH_BARRIER_BIT      0x00000008\n#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020\n#define GL_COMMAND_BARRIER_BIT            0x00000040\n#define GL_PIXEL_BUFFER_BARRIER_BIT       0x00000080\n#define GL_TEXTURE_UPDATE_BARRIER_BIT     0x00000100\n#define GL_BUFFER_UPDATE_BARRIER_BIT      0x00000200\n#define GL_FRAMEBUFFER_BARRIER_BIT        0x00000400\n#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800\n#define GL_ATOMIC_COUNTER_BARRIER_BIT     0x00001000\n#define GL_ALL_BARRIER_BITS               0xFFFFFFFF\n#define GL_MAX_IMAGE_UNITS                0x8F38\n#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39\n#define GL_IMAGE_BINDING_NAME             0x8F3A\n#define GL_IMAGE_BINDING_LEVEL            0x8F3B\n#define GL_IMAGE_BINDING_LAYERED          0x8F3C\n#define GL_IMAGE_BINDING_LAYER            0x8F3D\n#define GL_IMAGE_BINDING_ACCESS           0x8F3E\n#define GL_IMAGE_1D                       0x904C\n#define GL_IMAGE_2D                       0x904D\n#define GL_IMAGE_3D                       0x904E\n#define GL_IMAGE_2D_RECT                  0x904F\n#define GL_IMAGE_CUBE                     0x9050\n#define GL_IMAGE_BUFFER                   0x9051\n#define GL_IMAGE_1D_ARRAY                 0x9052\n#define GL_IMAGE_2D_ARRAY                 0x9053\n#define GL_IMAGE_CUBE_MAP_ARRAY           0x9054\n#define GL_IMAGE_2D_MULTISAMPLE           0x9055\n#define GL_IMAGE_2D_MULTISAMPLE_ARRAY     0x9056\n#define GL_INT_IMAGE_1D                   0x9057\n#define GL_INT_IMAGE_2D                   0x9058\n#define GL_INT_IMAGE_3D                   0x9059\n#define GL_INT_IMAGE_2D_RECT              0x905A\n#define GL_INT_IMAGE_CUBE                 0x905B\n#define GL_INT_IMAGE_BUFFER               0x905C\n#define GL_INT_IMAGE_1D_ARRAY             0x905D\n#define GL_INT_IMAGE_2D_ARRAY             0x905E\n#define GL_INT_IMAGE_CUBE_MAP_ARRAY       0x905F\n#define GL_INT_IMAGE_2D_MULTISAMPLE       0x9060\n#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061\n#define GL_UNSIGNED_INT_IMAGE_1D          0x9062\n#define GL_UNSIGNED_INT_IMAGE_2D          0x9063\n#define GL_UNSIGNED_INT_IMAGE_3D          0x9064\n#define GL_UNSIGNED_INT_IMAGE_2D_RECT     0x9065\n#define GL_UNSIGNED_INT_IMAGE_CUBE        0x9066\n#define GL_UNSIGNED_INT_IMAGE_BUFFER      0x9067\n#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY    0x9068\n#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY    0x9069\n#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A\n#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B\n#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C\n#define GL_MAX_IMAGE_SAMPLES              0x906D\n#define GL_IMAGE_BINDING_FORMAT           0x906E\n#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7\n#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8\n#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9\n#define GL_MAX_VERTEX_IMAGE_UNIFORMS      0x90CA\n#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB\n#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC\n#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS    0x90CD\n#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS    0x90CE\n#define GL_MAX_COMBINED_IMAGE_UNIFORMS    0x90CF\n#define GL_COMPRESSED_RGBA_BPTC_UNORM     0x8E8C\n#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D\n#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E\n#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F\n#define GL_TEXTURE_IMMUTABLE_FORMAT       0x912F\ntypedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance);\ntypedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);\ntypedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);\ntypedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers);\ntypedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);\ntypedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);\ntypedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei instancecount);\ntypedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);\nGLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance);\nGLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance);\nGLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);\nGLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params);\nGLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);\nGLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers);\nGLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);\nGLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);\nGLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei instancecount);\nGLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount);\n#endif\n#endif /* GL_VERSION_4_2 */\n\n#ifndef GL_VERSION_4_3\n#define GL_VERSION_4_3 1\ntypedef void (APIENTRY  *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);\n#define GL_NUM_SHADING_LANGUAGE_VERSIONS  0x82E9\n#define GL_VERTEX_ATTRIB_ARRAY_LONG       0x874E\n#define GL_COMPRESSED_RGB8_ETC2           0x9274\n#define GL_COMPRESSED_SRGB8_ETC2          0x9275\n#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276\n#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277\n#define GL_COMPRESSED_RGBA8_ETC2_EAC      0x9278\n#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279\n#define GL_COMPRESSED_R11_EAC             0x9270\n#define GL_COMPRESSED_SIGNED_R11_EAC      0x9271\n#define GL_COMPRESSED_RG11_EAC            0x9272\n#define GL_COMPRESSED_SIGNED_RG11_EAC     0x9273\n#define GL_PRIMITIVE_RESTART_FIXED_INDEX  0x8D69\n#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A\n#define GL_MAX_ELEMENT_INDEX              0x8D6B\n#define GL_COMPUTE_SHADER                 0x91B9\n#define GL_MAX_COMPUTE_UNIFORM_BLOCKS     0x91BB\n#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC\n#define GL_MAX_COMPUTE_IMAGE_UNIFORMS     0x91BD\n#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262\n#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263\n#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264\n#define GL_MAX_COMPUTE_ATOMIC_COUNTERS    0x8265\n#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266\n#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB\n#define GL_MAX_COMPUTE_WORK_GROUP_COUNT   0x91BE\n#define GL_MAX_COMPUTE_WORK_GROUP_SIZE    0x91BF\n#define GL_COMPUTE_WORK_GROUP_SIZE        0x8267\n#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC\n#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED\n#define GL_DISPATCH_INDIRECT_BUFFER       0x90EE\n#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF\n#define GL_DEBUG_OUTPUT_SYNCHRONOUS       0x8242\n#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243\n#define GL_DEBUG_CALLBACK_FUNCTION        0x8244\n#define GL_DEBUG_CALLBACK_USER_PARAM      0x8245\n#define GL_DEBUG_SOURCE_API               0x8246\n#define GL_DEBUG_SOURCE_WINDOW_SYSTEM     0x8247\n#define GL_DEBUG_SOURCE_SHADER_COMPILER   0x8248\n#define GL_DEBUG_SOURCE_THIRD_PARTY       0x8249\n#define GL_DEBUG_SOURCE_APPLICATION       0x824A\n#define GL_DEBUG_SOURCE_OTHER             0x824B\n#define GL_DEBUG_TYPE_ERROR               0x824C\n#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D\n#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR  0x824E\n#define GL_DEBUG_TYPE_PORTABILITY         0x824F\n#define GL_DEBUG_TYPE_PERFORMANCE         0x8250\n#define GL_DEBUG_TYPE_OTHER               0x8251\n#define GL_MAX_DEBUG_MESSAGE_LENGTH       0x9143\n#define GL_MAX_DEBUG_LOGGED_MESSAGES      0x9144\n#define GL_DEBUG_LOGGED_MESSAGES          0x9145\n#define GL_DEBUG_SEVERITY_HIGH            0x9146\n#define GL_DEBUG_SEVERITY_MEDIUM          0x9147\n#define GL_DEBUG_SEVERITY_LOW             0x9148\n#define GL_DEBUG_TYPE_MARKER              0x8268\n#define GL_DEBUG_TYPE_PUSH_GROUP          0x8269\n#define GL_DEBUG_TYPE_POP_GROUP           0x826A\n#define GL_DEBUG_SEVERITY_NOTIFICATION    0x826B\n#define GL_MAX_DEBUG_GROUP_STACK_DEPTH    0x826C\n#define GL_DEBUG_GROUP_STACK_DEPTH        0x826D\n#define GL_BUFFER                         0x82E0\n#define GL_SHADER                         0x82E1\n#define GL_PROGRAM                        0x82E2\n#define GL_QUERY                          0x82E3\n#define GL_PROGRAM_PIPELINE               0x82E4\n#define GL_SAMPLER                        0x82E6\n#define GL_MAX_LABEL_LENGTH               0x82E8\n#define GL_DEBUG_OUTPUT                   0x92E0\n#define GL_CONTEXT_FLAG_DEBUG_BIT         0x00000002\n#define GL_MAX_UNIFORM_LOCATIONS          0x826E\n#define GL_FRAMEBUFFER_DEFAULT_WIDTH      0x9310\n#define GL_FRAMEBUFFER_DEFAULT_HEIGHT     0x9311\n#define GL_FRAMEBUFFER_DEFAULT_LAYERS     0x9312\n#define GL_FRAMEBUFFER_DEFAULT_SAMPLES    0x9313\n#define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314\n#define GL_MAX_FRAMEBUFFER_WIDTH          0x9315\n#define GL_MAX_FRAMEBUFFER_HEIGHT         0x9316\n#define GL_MAX_FRAMEBUFFER_LAYERS         0x9317\n#define GL_MAX_FRAMEBUFFER_SAMPLES        0x9318\n#define GL_INTERNALFORMAT_SUPPORTED       0x826F\n#define GL_INTERNALFORMAT_PREFERRED       0x8270\n#define GL_INTERNALFORMAT_RED_SIZE        0x8271\n#define GL_INTERNALFORMAT_GREEN_SIZE      0x8272\n#define GL_INTERNALFORMAT_BLUE_SIZE       0x8273\n#define GL_INTERNALFORMAT_ALPHA_SIZE      0x8274\n#define GL_INTERNALFORMAT_DEPTH_SIZE      0x8275\n#define GL_INTERNALFORMAT_STENCIL_SIZE    0x8276\n#define GL_INTERNALFORMAT_SHARED_SIZE     0x8277\n#define GL_INTERNALFORMAT_RED_TYPE        0x8278\n#define GL_INTERNALFORMAT_GREEN_TYPE      0x8279\n#define GL_INTERNALFORMAT_BLUE_TYPE       0x827A\n#define GL_INTERNALFORMAT_ALPHA_TYPE      0x827B\n#define GL_INTERNALFORMAT_DEPTH_TYPE      0x827C\n#define GL_INTERNALFORMAT_STENCIL_TYPE    0x827D\n#define GL_MAX_WIDTH                      0x827E\n#define GL_MAX_HEIGHT                     0x827F\n#define GL_MAX_DEPTH                      0x8280\n#define GL_MAX_LAYERS                     0x8281\n#define GL_MAX_COMBINED_DIMENSIONS        0x8282\n#define GL_COLOR_COMPONENTS               0x8283\n#define GL_DEPTH_COMPONENTS               0x8284\n#define GL_STENCIL_COMPONENTS             0x8285\n#define GL_COLOR_RENDERABLE               0x8286\n#define GL_DEPTH_RENDERABLE               0x8287\n#define GL_STENCIL_RENDERABLE             0x8288\n#define GL_FRAMEBUFFER_RENDERABLE         0x8289\n#define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A\n#define GL_FRAMEBUFFER_BLEND              0x828B\n#define GL_READ_PIXELS                    0x828C\n#define GL_READ_PIXELS_FORMAT             0x828D\n#define GL_READ_PIXELS_TYPE               0x828E\n#define GL_TEXTURE_IMAGE_FORMAT           0x828F\n#define GL_TEXTURE_IMAGE_TYPE             0x8290\n#define GL_GET_TEXTURE_IMAGE_FORMAT       0x8291\n#define GL_GET_TEXTURE_IMAGE_TYPE         0x8292\n#define GL_MIPMAP                         0x8293\n#define GL_MANUAL_GENERATE_MIPMAP         0x8294\n#define GL_AUTO_GENERATE_MIPMAP           0x8295\n#define GL_COLOR_ENCODING                 0x8296\n#define GL_SRGB_READ                      0x8297\n#define GL_SRGB_WRITE                     0x8298\n#define GL_FILTER                         0x829A\n#define GL_VERTEX_TEXTURE                 0x829B\n#define GL_TESS_CONTROL_TEXTURE           0x829C\n#define GL_TESS_EVALUATION_TEXTURE        0x829D\n#define GL_GEOMETRY_TEXTURE               0x829E\n#define GL_FRAGMENT_TEXTURE               0x829F\n#define GL_COMPUTE_TEXTURE                0x82A0\n#define GL_TEXTURE_SHADOW                 0x82A1\n#define GL_TEXTURE_GATHER                 0x82A2\n#define GL_TEXTURE_GATHER_SHADOW          0x82A3\n#define GL_SHADER_IMAGE_LOAD              0x82A4\n#define GL_SHADER_IMAGE_STORE             0x82A5\n#define GL_SHADER_IMAGE_ATOMIC            0x82A6\n#define GL_IMAGE_TEXEL_SIZE               0x82A7\n#define GL_IMAGE_COMPATIBILITY_CLASS      0x82A8\n#define GL_IMAGE_PIXEL_FORMAT             0x82A9\n#define GL_IMAGE_PIXEL_TYPE               0x82AA\n#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC\n#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD\n#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE\n#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF\n#define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1\n#define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2\n#define GL_TEXTURE_COMPRESSED_BLOCK_SIZE  0x82B3\n#define GL_CLEAR_BUFFER                   0x82B4\n#define GL_TEXTURE_VIEW                   0x82B5\n#define GL_VIEW_COMPATIBILITY_CLASS       0x82B6\n#define GL_FULL_SUPPORT                   0x82B7\n#define GL_CAVEAT_SUPPORT                 0x82B8\n#define GL_IMAGE_CLASS_4_X_32             0x82B9\n#define GL_IMAGE_CLASS_2_X_32             0x82BA\n#define GL_IMAGE_CLASS_1_X_32             0x82BB\n#define GL_IMAGE_CLASS_4_X_16             0x82BC\n#define GL_IMAGE_CLASS_2_X_16             0x82BD\n#define GL_IMAGE_CLASS_1_X_16             0x82BE\n#define GL_IMAGE_CLASS_4_X_8              0x82BF\n#define GL_IMAGE_CLASS_2_X_8              0x82C0\n#define GL_IMAGE_CLASS_1_X_8              0x82C1\n#define GL_IMAGE_CLASS_11_11_10           0x82C2\n#define GL_IMAGE_CLASS_10_10_10_2         0x82C3\n#define GL_VIEW_CLASS_128_BITS            0x82C4\n#define GL_VIEW_CLASS_96_BITS             0x82C5\n#define GL_VIEW_CLASS_64_BITS             0x82C6\n#define GL_VIEW_CLASS_48_BITS             0x82C7\n#define GL_VIEW_CLASS_32_BITS             0x82C8\n#define GL_VIEW_CLASS_24_BITS             0x82C9\n#define GL_VIEW_CLASS_16_BITS             0x82CA\n#define GL_VIEW_CLASS_8_BITS              0x82CB\n#define GL_VIEW_CLASS_S3TC_DXT1_RGB       0x82CC\n#define GL_VIEW_CLASS_S3TC_DXT1_RGBA      0x82CD\n#define GL_VIEW_CLASS_S3TC_DXT3_RGBA      0x82CE\n#define GL_VIEW_CLASS_S3TC_DXT5_RGBA      0x82CF\n#define GL_VIEW_CLASS_RGTC1_RED           0x82D0\n#define GL_VIEW_CLASS_RGTC2_RG            0x82D1\n#define GL_VIEW_CLASS_BPTC_UNORM          0x82D2\n#define GL_VIEW_CLASS_BPTC_FLOAT          0x82D3\n#define GL_UNIFORM                        0x92E1\n#define GL_UNIFORM_BLOCK                  0x92E2\n#define GL_PROGRAM_INPUT                  0x92E3\n#define GL_PROGRAM_OUTPUT                 0x92E4\n#define GL_BUFFER_VARIABLE                0x92E5\n#define GL_SHADER_STORAGE_BLOCK           0x92E6\n#define GL_VERTEX_SUBROUTINE              0x92E8\n#define GL_TESS_CONTROL_SUBROUTINE        0x92E9\n#define GL_TESS_EVALUATION_SUBROUTINE     0x92EA\n#define GL_GEOMETRY_SUBROUTINE            0x92EB\n#define GL_FRAGMENT_SUBROUTINE            0x92EC\n#define GL_COMPUTE_SUBROUTINE             0x92ED\n#define GL_VERTEX_SUBROUTINE_UNIFORM      0x92EE\n#define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF\n#define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0\n#define GL_GEOMETRY_SUBROUTINE_UNIFORM    0x92F1\n#define GL_FRAGMENT_SUBROUTINE_UNIFORM    0x92F2\n#define GL_COMPUTE_SUBROUTINE_UNIFORM     0x92F3\n#define GL_TRANSFORM_FEEDBACK_VARYING     0x92F4\n#define GL_ACTIVE_RESOURCES               0x92F5\n#define GL_MAX_NAME_LENGTH                0x92F6\n#define GL_MAX_NUM_ACTIVE_VARIABLES       0x92F7\n#define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8\n#define GL_NAME_LENGTH                    0x92F9\n#define GL_TYPE                           0x92FA\n#define GL_ARRAY_SIZE                     0x92FB\n#define GL_OFFSET                         0x92FC\n#define GL_BLOCK_INDEX                    0x92FD\n#define GL_ARRAY_STRIDE                   0x92FE\n#define GL_MATRIX_STRIDE                  0x92FF\n#define GL_IS_ROW_MAJOR                   0x9300\n#define GL_ATOMIC_COUNTER_BUFFER_INDEX    0x9301\n#define GL_BUFFER_BINDING                 0x9302\n#define GL_BUFFER_DATA_SIZE               0x9303\n#define GL_NUM_ACTIVE_VARIABLES           0x9304\n#define GL_ACTIVE_VARIABLES               0x9305\n#define GL_REFERENCED_BY_VERTEX_SHADER    0x9306\n#define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307\n#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308\n#define GL_REFERENCED_BY_GEOMETRY_SHADER  0x9309\n#define GL_REFERENCED_BY_FRAGMENT_SHADER  0x930A\n#define GL_REFERENCED_BY_COMPUTE_SHADER   0x930B\n#define GL_TOP_LEVEL_ARRAY_SIZE           0x930C\n#define GL_TOP_LEVEL_ARRAY_STRIDE         0x930D\n#define GL_LOCATION                       0x930E\n#define GL_LOCATION_INDEX                 0x930F\n#define GL_IS_PER_PATCH                   0x92E7\n#define GL_SHADER_STORAGE_BUFFER          0x90D2\n#define GL_SHADER_STORAGE_BUFFER_BINDING  0x90D3\n#define GL_SHADER_STORAGE_BUFFER_START    0x90D4\n#define GL_SHADER_STORAGE_BUFFER_SIZE     0x90D5\n#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6\n#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7\n#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8\n#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9\n#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA\n#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB\n#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC\n#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD\n#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE  0x90DE\n#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF\n#define GL_SHADER_STORAGE_BARRIER_BIT     0x00002000\n#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39\n#define GL_DEPTH_STENCIL_TEXTURE_MODE     0x90EA\n#define GL_TEXTURE_BUFFER_OFFSET          0x919D\n#define GL_TEXTURE_BUFFER_SIZE            0x919E\n#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F\n#define GL_TEXTURE_VIEW_MIN_LEVEL         0x82DB\n#define GL_TEXTURE_VIEW_NUM_LEVELS        0x82DC\n#define GL_TEXTURE_VIEW_MIN_LAYER         0x82DD\n#define GL_TEXTURE_VIEW_NUM_LAYERS        0x82DE\n#define GL_TEXTURE_IMMUTABLE_LEVELS       0x82DF\n#define GL_VERTEX_ATTRIB_BINDING          0x82D4\n#define GL_VERTEX_ATTRIB_RELATIVE_OFFSET  0x82D5\n#define GL_VERTEX_BINDING_DIVISOR         0x82D6\n#define GL_VERTEX_BINDING_OFFSET          0x82D7\n#define GL_VERTEX_BINDING_STRIDE          0x82D8\n#define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9\n#define GL_MAX_VERTEX_ATTRIB_BINDINGS     0x82DA\n#define GL_DISPLAY_LIST                   0x82E7\ntypedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC) (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data);\ntypedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC) (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data);\ntypedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);\ntypedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC) (GLintptr indirect);\ntypedef 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);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params);\ntypedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth);\ntypedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC) (GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length);\ntypedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);\ntypedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride);\ntypedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC) (GLuint program, GLenum programInterface, GLenum pname, GLint *params);\ntypedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name);\ntypedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params);\ntypedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC) (GLuint program, GLenum programInterface, const GLchar *name);\ntypedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name);\ntypedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding);\ntypedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);\ntypedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);\ntypedef void (APIENTRYP PFNGLTEXTUREVIEWPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);\ntypedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC) (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC) (GLuint attribindex, GLuint bindingindex);\ntypedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC) (GLuint bindingindex, GLuint divisor);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void *userParam);\ntypedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);\ntypedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message);\ntypedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC) (void);\ntypedef void (APIENTRYP PFNGLOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label);\ntypedef void (APIENTRYP PFNGLGETOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label);\ntypedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC) (const void *ptr, GLsizei length, const GLchar *label);\ntypedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glClearBufferData (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glClearBufferSubData (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glDispatchCompute (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);\nGLAPI void APIENTRY glDispatchComputeIndirect (GLintptr indirect);\nGLAPI void APIENTRY glCopyImageSubData (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);\nGLAPI void APIENTRY glFramebufferParameteri (GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glGetFramebufferParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetInternalformati64v (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params);\nGLAPI void APIENTRY glInvalidateTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth);\nGLAPI void APIENTRY glInvalidateTexImage (GLuint texture, GLint level);\nGLAPI void APIENTRY glInvalidateBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr length);\nGLAPI void APIENTRY glInvalidateBufferData (GLuint buffer);\nGLAPI void APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments);\nGLAPI void APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glMultiDrawArraysIndirect (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride);\nGLAPI void APIENTRY glMultiDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride);\nGLAPI void APIENTRY glGetProgramInterfaceiv (GLuint program, GLenum programInterface, GLenum pname, GLint *params);\nGLAPI GLuint APIENTRY glGetProgramResourceIndex (GLuint program, GLenum programInterface, const GLchar *name);\nGLAPI void APIENTRY glGetProgramResourceName (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name);\nGLAPI void APIENTRY glGetProgramResourceiv (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params);\nGLAPI GLint APIENTRY glGetProgramResourceLocation (GLuint program, GLenum programInterface, const GLchar *name);\nGLAPI GLint APIENTRY glGetProgramResourceLocationIndex (GLuint program, GLenum programInterface, const GLchar *name);\nGLAPI void APIENTRY glShaderStorageBlockBinding (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding);\nGLAPI void APIENTRY glTexBufferRange (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);\nGLAPI void APIENTRY glTexStorage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);\nGLAPI void APIENTRY glTexStorage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);\nGLAPI void APIENTRY glTextureView (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);\nGLAPI void APIENTRY glBindVertexBuffer (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);\nGLAPI void APIENTRY glVertexAttribFormat (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);\nGLAPI void APIENTRY glVertexAttribIFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\nGLAPI void APIENTRY glVertexAttribLFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\nGLAPI void APIENTRY glVertexAttribBinding (GLuint attribindex, GLuint bindingindex);\nGLAPI void APIENTRY glVertexBindingDivisor (GLuint bindingindex, GLuint divisor);\nGLAPI void APIENTRY glDebugMessageControl (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);\nGLAPI void APIENTRY glDebugMessageInsert (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);\nGLAPI void APIENTRY glDebugMessageCallback (GLDEBUGPROC callback, const void *userParam);\nGLAPI GLuint APIENTRY glGetDebugMessageLog (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);\nGLAPI void APIENTRY glPushDebugGroup (GLenum source, GLuint id, GLsizei length, const GLchar *message);\nGLAPI void APIENTRY glPopDebugGroup (void);\nGLAPI void APIENTRY glObjectLabel (GLenum identifier, GLuint name, GLsizei length, const GLchar *label);\nGLAPI void APIENTRY glGetObjectLabel (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label);\nGLAPI void APIENTRY glObjectPtrLabel (const void *ptr, GLsizei length, const GLchar *label);\nGLAPI void APIENTRY glGetObjectPtrLabel (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label);\n#endif\n#endif /* GL_VERSION_4_3 */\n\n#ifndef GL_VERSION_4_4\n#define GL_VERSION_4_4 1\n#define GL_MAX_VERTEX_ATTRIB_STRIDE       0x82E5\n#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221\n#define GL_TEXTURE_BUFFER_BINDING         0x8C2A\n#define GL_MAP_PERSISTENT_BIT             0x0040\n#define GL_MAP_COHERENT_BIT               0x0080\n#define GL_DYNAMIC_STORAGE_BIT            0x0100\n#define GL_CLIENT_STORAGE_BIT             0x0200\n#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000\n#define GL_BUFFER_IMMUTABLE_STORAGE       0x821F\n#define GL_BUFFER_STORAGE_FLAGS           0x8220\n#define GL_CLEAR_TEXTURE                  0x9365\n#define GL_LOCATION_COMPONENT             0x934A\n#define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B\n#define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C\n#define GL_QUERY_BUFFER                   0x9192\n#define GL_QUERY_BUFFER_BARRIER_BIT       0x00008000\n#define GL_QUERY_BUFFER_BINDING           0x9193\n#define GL_QUERY_RESULT_NO_WAIT           0x9194\n#define GL_MIRROR_CLAMP_TO_EDGE           0x8743\ntypedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags);\ntypedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data);\ntypedef 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);\ntypedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers);\ntypedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes);\ntypedef void (APIENTRYP PFNGLBINDTEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures);\ntypedef void (APIENTRYP PFNGLBINDSAMPLERSPROC) (GLuint first, GLsizei count, const GLuint *samplers);\ntypedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures);\ntypedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC) (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBufferStorage (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags);\nGLAPI void APIENTRY glClearTexImage (GLuint texture, GLint level, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glClearTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glBindBuffersBase (GLenum target, GLuint first, GLsizei count, const GLuint *buffers);\nGLAPI void APIENTRY glBindBuffersRange (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes);\nGLAPI void APIENTRY glBindTextures (GLuint first, GLsizei count, const GLuint *textures);\nGLAPI void APIENTRY glBindSamplers (GLuint first, GLsizei count, const GLuint *samplers);\nGLAPI void APIENTRY glBindImageTextures (GLuint first, GLsizei count, const GLuint *textures);\nGLAPI void APIENTRY glBindVertexBuffers (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides);\n#endif\n#endif /* GL_VERSION_4_4 */\n\n#ifndef GL_ARB_ES2_compatibility\n#define GL_ARB_ES2_compatibility 1\n#endif /* GL_ARB_ES2_compatibility */\n\n#ifndef GL_ARB_ES3_compatibility\n#define GL_ARB_ES3_compatibility 1\n#endif /* GL_ARB_ES3_compatibility */\n\n#ifndef GL_ARB_arrays_of_arrays\n#define GL_ARB_arrays_of_arrays 1\n#endif /* GL_ARB_arrays_of_arrays */\n\n#ifndef GL_ARB_base_instance\n#define GL_ARB_base_instance 1\n#endif /* GL_ARB_base_instance */\n\n#ifndef GL_ARB_bindless_texture\n#define GL_ARB_bindless_texture 1\ntypedef uint64_t GLuint64EXT;\n#define GL_UNSIGNED_INT64_ARB             0x140F\ntypedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLEARBPROC) (GLuint texture);\ntypedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEARBPROC) (GLuint texture, GLuint sampler);\ntypedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle);\ntypedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC) (GLuint64 handle);\ntypedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLEARBPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);\ntypedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle, GLenum access);\ntypedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC) (GLuint64 handle);\ntypedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64ARBPROC) (GLint location, GLuint64 value);\ntypedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC) (GLuint program, GLint location, GLuint64 value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values);\ntypedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle);\ntypedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64ARBPROC) (GLuint index, GLuint64EXT x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VARBPROC) (GLuint index, const GLuint64EXT *v);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VARBPROC) (GLuint index, GLenum pname, GLuint64EXT *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint64 APIENTRY glGetTextureHandleARB (GLuint texture);\nGLAPI GLuint64 APIENTRY glGetTextureSamplerHandleARB (GLuint texture, GLuint sampler);\nGLAPI void APIENTRY glMakeTextureHandleResidentARB (GLuint64 handle);\nGLAPI void APIENTRY glMakeTextureHandleNonResidentARB (GLuint64 handle);\nGLAPI GLuint64 APIENTRY glGetImageHandleARB (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);\nGLAPI void APIENTRY glMakeImageHandleResidentARB (GLuint64 handle, GLenum access);\nGLAPI void APIENTRY glMakeImageHandleNonResidentARB (GLuint64 handle);\nGLAPI void APIENTRY glUniformHandleui64ARB (GLint location, GLuint64 value);\nGLAPI void APIENTRY glUniformHandleui64vARB (GLint location, GLsizei count, const GLuint64 *value);\nGLAPI void APIENTRY glProgramUniformHandleui64ARB (GLuint program, GLint location, GLuint64 value);\nGLAPI void APIENTRY glProgramUniformHandleui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *values);\nGLAPI GLboolean APIENTRY glIsTextureHandleResidentARB (GLuint64 handle);\nGLAPI GLboolean APIENTRY glIsImageHandleResidentARB (GLuint64 handle);\nGLAPI void APIENTRY glVertexAttribL1ui64ARB (GLuint index, GLuint64EXT x);\nGLAPI void APIENTRY glVertexAttribL1ui64vARB (GLuint index, const GLuint64EXT *v);\nGLAPI void APIENTRY glGetVertexAttribLui64vARB (GLuint index, GLenum pname, GLuint64EXT *params);\n#endif\n#endif /* GL_ARB_bindless_texture */\n\n#ifndef GL_ARB_blend_func_extended\n#define GL_ARB_blend_func_extended 1\n#endif /* GL_ARB_blend_func_extended */\n\n#ifndef GL_ARB_buffer_storage\n#define GL_ARB_buffer_storage 1\n#endif /* GL_ARB_buffer_storage */\n\n#ifndef GL_ARB_cl_event\n#define GL_ARB_cl_event 1\nstruct _cl_context;\nstruct _cl_event;\n#define GL_SYNC_CL_EVENT_ARB              0x8240\n#define GL_SYNC_CL_EVENT_COMPLETE_ARB     0x8241\ntypedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context *context, struct _cl_event *event, GLbitfield flags);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context *context, struct _cl_event *event, GLbitfield flags);\n#endif\n#endif /* GL_ARB_cl_event */\n\n#ifndef GL_ARB_clear_buffer_object\n#define GL_ARB_clear_buffer_object 1\n#endif /* GL_ARB_clear_buffer_object */\n\n#ifndef GL_ARB_clear_texture\n#define GL_ARB_clear_texture 1\n#endif /* GL_ARB_clear_texture */\n\n#ifndef GL_ARB_color_buffer_float\n#define GL_ARB_color_buffer_float 1\n#define GL_RGBA_FLOAT_MODE_ARB            0x8820\n#define GL_CLAMP_VERTEX_COLOR_ARB         0x891A\n#define GL_CLAMP_FRAGMENT_COLOR_ARB       0x891B\n#define GL_CLAMP_READ_COLOR_ARB           0x891C\n#define GL_FIXED_ONLY_ARB                 0x891D\ntypedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glClampColorARB (GLenum target, GLenum clamp);\n#endif\n#endif /* GL_ARB_color_buffer_float */\n\n#ifndef GL_ARB_compatibility\n#define GL_ARB_compatibility 1\n#endif /* GL_ARB_compatibility */\n\n#ifndef GL_ARB_compressed_texture_pixel_storage\n#define GL_ARB_compressed_texture_pixel_storage 1\n#endif /* GL_ARB_compressed_texture_pixel_storage */\n\n#ifndef GL_ARB_compute_shader\n#define GL_ARB_compute_shader 1\n#define GL_COMPUTE_SHADER_BIT             0x00000020\n#endif /* GL_ARB_compute_shader */\n\n#ifndef GL_ARB_compute_variable_group_size\n#define GL_ARB_compute_variable_group_size 1\n#define GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB 0x9344\n#define GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB 0x90EB\n#define GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB 0x9345\n#define GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB 0x91BF\ntypedef void (APIENTRYP PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDispatchComputeGroupSizeARB (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z);\n#endif\n#endif /* GL_ARB_compute_variable_group_size */\n\n#ifndef GL_ARB_conservative_depth\n#define GL_ARB_conservative_depth 1\n#endif /* GL_ARB_conservative_depth */\n\n#ifndef GL_ARB_copy_buffer\n#define GL_ARB_copy_buffer 1\n#define GL_COPY_READ_BUFFER_BINDING       0x8F36\n#define GL_COPY_WRITE_BUFFER_BINDING      0x8F37\n#endif /* GL_ARB_copy_buffer */\n\n#ifndef GL_ARB_copy_image\n#define GL_ARB_copy_image 1\n#endif /* GL_ARB_copy_image */\n\n#ifndef GL_ARB_debug_output\n#define GL_ARB_debug_output 1\ntypedef void (APIENTRY  *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);\n#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB   0x8242\n#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243\n#define GL_DEBUG_CALLBACK_FUNCTION_ARB    0x8244\n#define GL_DEBUG_CALLBACK_USER_PARAM_ARB  0x8245\n#define GL_DEBUG_SOURCE_API_ARB           0x8246\n#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247\n#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248\n#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB   0x8249\n#define GL_DEBUG_SOURCE_APPLICATION_ARB   0x824A\n#define GL_DEBUG_SOURCE_OTHER_ARB         0x824B\n#define GL_DEBUG_TYPE_ERROR_ARB           0x824C\n#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D\n#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E\n#define GL_DEBUG_TYPE_PORTABILITY_ARB     0x824F\n#define GL_DEBUG_TYPE_PERFORMANCE_ARB     0x8250\n#define GL_DEBUG_TYPE_OTHER_ARB           0x8251\n#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB   0x9143\n#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB  0x9144\n#define GL_DEBUG_LOGGED_MESSAGES_ARB      0x9145\n#define GL_DEBUG_SEVERITY_HIGH_ARB        0x9146\n#define GL_DEBUG_SEVERITY_MEDIUM_ARB      0x9147\n#define GL_DEBUG_SEVERITY_LOW_ARB         0x9148\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC) (GLDEBUGPROCARB callback, const void *userParam);\ntypedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDebugMessageControlARB (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);\nGLAPI void APIENTRY glDebugMessageInsertARB (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);\nGLAPI void APIENTRY glDebugMessageCallbackARB (GLDEBUGPROCARB callback, const void *userParam);\nGLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);\n#endif\n#endif /* GL_ARB_debug_output */\n\n#ifndef GL_ARB_depth_buffer_float\n#define GL_ARB_depth_buffer_float 1\n#endif /* GL_ARB_depth_buffer_float */\n\n#ifndef GL_ARB_depth_clamp\n#define GL_ARB_depth_clamp 1\n#endif /* GL_ARB_depth_clamp */\n\n#ifndef GL_ARB_depth_texture\n#define GL_ARB_depth_texture 1\n#define GL_DEPTH_COMPONENT16_ARB          0x81A5\n#define GL_DEPTH_COMPONENT24_ARB          0x81A6\n#define GL_DEPTH_COMPONENT32_ARB          0x81A7\n#define GL_TEXTURE_DEPTH_SIZE_ARB         0x884A\n#define GL_DEPTH_TEXTURE_MODE_ARB         0x884B\n#endif /* GL_ARB_depth_texture */\n\n#ifndef GL_ARB_draw_buffers\n#define GL_ARB_draw_buffers 1\n#define GL_MAX_DRAW_BUFFERS_ARB           0x8824\n#define GL_DRAW_BUFFER0_ARB               0x8825\n#define GL_DRAW_BUFFER1_ARB               0x8826\n#define GL_DRAW_BUFFER2_ARB               0x8827\n#define GL_DRAW_BUFFER3_ARB               0x8828\n#define GL_DRAW_BUFFER4_ARB               0x8829\n#define GL_DRAW_BUFFER5_ARB               0x882A\n#define GL_DRAW_BUFFER6_ARB               0x882B\n#define GL_DRAW_BUFFER7_ARB               0x882C\n#define GL_DRAW_BUFFER8_ARB               0x882D\n#define GL_DRAW_BUFFER9_ARB               0x882E\n#define GL_DRAW_BUFFER10_ARB              0x882F\n#define GL_DRAW_BUFFER11_ARB              0x8830\n#define GL_DRAW_BUFFER12_ARB              0x8831\n#define GL_DRAW_BUFFER13_ARB              0x8832\n#define GL_DRAW_BUFFER14_ARB              0x8833\n#define GL_DRAW_BUFFER15_ARB              0x8834\ntypedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawBuffersARB (GLsizei n, const GLenum *bufs);\n#endif\n#endif /* GL_ARB_draw_buffers */\n\n#ifndef GL_ARB_draw_buffers_blend\n#define GL_ARB_draw_buffers_blend 1\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);\ntypedef void (APIENTRYP PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst);\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationiARB (GLuint buf, GLenum mode);\nGLAPI void APIENTRY glBlendEquationSeparateiARB (GLuint buf, GLenum modeRGB, GLenum modeAlpha);\nGLAPI void APIENTRY glBlendFunciARB (GLuint buf, GLenum src, GLenum dst);\nGLAPI void APIENTRY glBlendFuncSeparateiARB (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);\n#endif\n#endif /* GL_ARB_draw_buffers_blend */\n\n#ifndef GL_ARB_draw_elements_base_vertex\n#define GL_ARB_draw_elements_base_vertex 1\n#endif /* GL_ARB_draw_elements_base_vertex */\n\n#ifndef GL_ARB_draw_indirect\n#define GL_ARB_draw_indirect 1\n#endif /* GL_ARB_draw_indirect */\n\n#ifndef GL_ARB_draw_instanced\n#define GL_ARB_draw_instanced 1\ntypedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawArraysInstancedARB (GLenum mode, GLint first, GLsizei count, GLsizei primcount);\nGLAPI void APIENTRY glDrawElementsInstancedARB (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);\n#endif\n#endif /* GL_ARB_draw_instanced */\n\n#ifndef GL_ARB_enhanced_layouts\n#define GL_ARB_enhanced_layouts 1\n#endif /* GL_ARB_enhanced_layouts */\n\n#ifndef GL_ARB_explicit_attrib_location\n#define GL_ARB_explicit_attrib_location 1\n#endif /* GL_ARB_explicit_attrib_location */\n\n#ifndef GL_ARB_explicit_uniform_location\n#define GL_ARB_explicit_uniform_location 1\n#endif /* GL_ARB_explicit_uniform_location */\n\n#ifndef GL_ARB_fragment_coord_conventions\n#define GL_ARB_fragment_coord_conventions 1\n#endif /* GL_ARB_fragment_coord_conventions */\n\n#ifndef GL_ARB_fragment_layer_viewport\n#define GL_ARB_fragment_layer_viewport 1\n#endif /* GL_ARB_fragment_layer_viewport */\n\n#ifndef GL_ARB_fragment_program\n#define GL_ARB_fragment_program 1\n#define GL_FRAGMENT_PROGRAM_ARB           0x8804\n#define GL_PROGRAM_FORMAT_ASCII_ARB       0x8875\n#define GL_PROGRAM_LENGTH_ARB             0x8627\n#define GL_PROGRAM_FORMAT_ARB             0x8876\n#define GL_PROGRAM_BINDING_ARB            0x8677\n#define GL_PROGRAM_INSTRUCTIONS_ARB       0x88A0\n#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB   0x88A1\n#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2\n#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3\n#define GL_PROGRAM_TEMPORARIES_ARB        0x88A4\n#define GL_MAX_PROGRAM_TEMPORARIES_ARB    0x88A5\n#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6\n#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7\n#define GL_PROGRAM_PARAMETERS_ARB         0x88A8\n#define GL_MAX_PROGRAM_PARAMETERS_ARB     0x88A9\n#define GL_PROGRAM_NATIVE_PARAMETERS_ARB  0x88AA\n#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB\n#define GL_PROGRAM_ATTRIBS_ARB            0x88AC\n#define GL_MAX_PROGRAM_ATTRIBS_ARB        0x88AD\n#define GL_PROGRAM_NATIVE_ATTRIBS_ARB     0x88AE\n#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF\n#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4\n#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5\n#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6\n#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB   0x8805\n#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB   0x8806\n#define GL_PROGRAM_TEX_INDIRECTIONS_ARB   0x8807\n#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808\n#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809\n#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A\n#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B\n#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C\n#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D\n#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E\n#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F\n#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810\n#define GL_PROGRAM_STRING_ARB             0x8628\n#define GL_PROGRAM_ERROR_POSITION_ARB     0x864B\n#define GL_CURRENT_MATRIX_ARB             0x8641\n#define GL_TRANSPOSE_CURRENT_MATRIX_ARB   0x88B7\n#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640\n#define GL_MAX_PROGRAM_MATRICES_ARB       0x862F\n#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E\n#define GL_MAX_TEXTURE_COORDS_ARB         0x8871\n#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB    0x8872\n#define GL_PROGRAM_ERROR_STRING_ARB       0x8874\n#define GL_MATRIX0_ARB                    0x88C0\n#define GL_MATRIX1_ARB                    0x88C1\n#define GL_MATRIX2_ARB                    0x88C2\n#define GL_MATRIX3_ARB                    0x88C3\n#define GL_MATRIX4_ARB                    0x88C4\n#define GL_MATRIX5_ARB                    0x88C5\n#define GL_MATRIX6_ARB                    0x88C6\n#define GL_MATRIX7_ARB                    0x88C7\n#define GL_MATRIX8_ARB                    0x88C8\n#define GL_MATRIX9_ARB                    0x88C9\n#define GL_MATRIX10_ARB                   0x88CA\n#define GL_MATRIX11_ARB                   0x88CB\n#define GL_MATRIX12_ARB                   0x88CC\n#define GL_MATRIX13_ARB                   0x88CD\n#define GL_MATRIX14_ARB                   0x88CE\n#define GL_MATRIX15_ARB                   0x88CF\n#define GL_MATRIX16_ARB                   0x88D0\n#define GL_MATRIX17_ARB                   0x88D1\n#define GL_MATRIX18_ARB                   0x88D2\n#define GL_MATRIX19_ARB                   0x88D3\n#define GL_MATRIX20_ARB                   0x88D4\n#define GL_MATRIX21_ARB                   0x88D5\n#define GL_MATRIX22_ARB                   0x88D6\n#define GL_MATRIX23_ARB                   0x88D7\n#define GL_MATRIX24_ARB                   0x88D8\n#define GL_MATRIX25_ARB                   0x88D9\n#define GL_MATRIX26_ARB                   0x88DA\n#define GL_MATRIX27_ARB                   0x88DB\n#define GL_MATRIX28_ARB                   0x88DC\n#define GL_MATRIX29_ARB                   0x88DD\n#define GL_MATRIX30_ARB                   0x88DE\n#define GL_MATRIX31_ARB                   0x88DF\ntypedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const void *string);\ntypedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program);\ntypedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs);\ntypedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, void *string);\ntypedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramStringARB (GLenum target, GLenum format, GLsizei len, const void *string);\nGLAPI void APIENTRY glBindProgramARB (GLenum target, GLuint program);\nGLAPI void APIENTRY glDeleteProgramsARB (GLsizei n, const GLuint *programs);\nGLAPI void APIENTRY glGenProgramsARB (GLsizei n, GLuint *programs);\nGLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum target, GLuint index, const GLdouble *params);\nGLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum target, GLuint index, const GLfloat *params);\nGLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum target, GLuint index, const GLdouble *params);\nGLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum target, GLuint index, const GLfloat *params);\nGLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum target, GLuint index, GLdouble *params);\nGLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum target, GLuint index, GLfloat *params);\nGLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum target, GLuint index, GLdouble *params);\nGLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum target, GLuint index, GLfloat *params);\nGLAPI void APIENTRY glGetProgramivARB (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetProgramStringARB (GLenum target, GLenum pname, void *string);\nGLAPI GLboolean APIENTRY glIsProgramARB (GLuint program);\n#endif\n#endif /* GL_ARB_fragment_program */\n\n#ifndef GL_ARB_fragment_program_shadow\n#define GL_ARB_fragment_program_shadow 1\n#endif /* GL_ARB_fragment_program_shadow */\n\n#ifndef GL_ARB_fragment_shader\n#define GL_ARB_fragment_shader 1\n#define GL_FRAGMENT_SHADER_ARB            0x8B30\n#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49\n#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B\n#endif /* GL_ARB_fragment_shader */\n\n#ifndef GL_ARB_framebuffer_no_attachments\n#define GL_ARB_framebuffer_no_attachments 1\n#endif /* GL_ARB_framebuffer_no_attachments */\n\n#ifndef GL_ARB_framebuffer_object\n#define GL_ARB_framebuffer_object 1\n#endif /* GL_ARB_framebuffer_object */\n\n#ifndef GL_ARB_framebuffer_sRGB\n#define GL_ARB_framebuffer_sRGB 1\n#endif /* GL_ARB_framebuffer_sRGB */\n\n#ifndef GL_ARB_geometry_shader4\n#define GL_ARB_geometry_shader4 1\n#define GL_LINES_ADJACENCY_ARB            0x000A\n#define GL_LINE_STRIP_ADJACENCY_ARB       0x000B\n#define GL_TRIANGLES_ADJACENCY_ARB        0x000C\n#define GL_TRIANGLE_STRIP_ADJACENCY_ARB   0x000D\n#define GL_PROGRAM_POINT_SIZE_ARB         0x8642\n#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB 0x8C29\n#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB 0x8DA7\n#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB 0x8DA8\n#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB 0x8DA9\n#define GL_GEOMETRY_SHADER_ARB            0x8DD9\n#define GL_GEOMETRY_VERTICES_OUT_ARB      0x8DDA\n#define GL_GEOMETRY_INPUT_TYPE_ARB        0x8DDB\n#define GL_GEOMETRY_OUTPUT_TYPE_ARB       0x8DDC\n#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB 0x8DDD\n#define GL_MAX_VERTEX_VARYING_COMPONENTS_ARB 0x8DDE\n#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF\n#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0\n#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramParameteriARB (GLuint program, GLenum pname, GLint value);\nGLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, GLuint texture, GLint level);\nGLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);\nGLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);\n#endif\n#endif /* GL_ARB_geometry_shader4 */\n\n#ifndef GL_ARB_get_program_binary\n#define GL_ARB_get_program_binary 1\n#endif /* GL_ARB_get_program_binary */\n\n#ifndef GL_ARB_gpu_shader5\n#define GL_ARB_gpu_shader5 1\n#endif /* GL_ARB_gpu_shader5 */\n\n#ifndef GL_ARB_gpu_shader_fp64\n#define GL_ARB_gpu_shader_fp64 1\n#endif /* GL_ARB_gpu_shader_fp64 */\n\n#ifndef GL_ARB_half_float_pixel\n#define GL_ARB_half_float_pixel 1\ntypedef unsigned short GLhalfARB;\n#define GL_HALF_FLOAT_ARB                 0x140B\n#endif /* GL_ARB_half_float_pixel */\n\n#ifndef GL_ARB_half_float_vertex\n#define GL_ARB_half_float_vertex 1\n#endif /* GL_ARB_half_float_vertex */\n\n#ifndef GL_ARB_imaging\n#define GL_ARB_imaging 1\n#define GL_BLEND_COLOR                    0x8005\n#define GL_BLEND_EQUATION                 0x8009\n#define GL_CONVOLUTION_1D                 0x8010\n#define GL_CONVOLUTION_2D                 0x8011\n#define GL_SEPARABLE_2D                   0x8012\n#define GL_CONVOLUTION_BORDER_MODE        0x8013\n#define GL_CONVOLUTION_FILTER_SCALE       0x8014\n#define GL_CONVOLUTION_FILTER_BIAS        0x8015\n#define GL_REDUCE                         0x8016\n#define GL_CONVOLUTION_FORMAT             0x8017\n#define GL_CONVOLUTION_WIDTH              0x8018\n#define GL_CONVOLUTION_HEIGHT             0x8019\n#define GL_MAX_CONVOLUTION_WIDTH          0x801A\n#define GL_MAX_CONVOLUTION_HEIGHT         0x801B\n#define GL_POST_CONVOLUTION_RED_SCALE     0x801C\n#define GL_POST_CONVOLUTION_GREEN_SCALE   0x801D\n#define GL_POST_CONVOLUTION_BLUE_SCALE    0x801E\n#define GL_POST_CONVOLUTION_ALPHA_SCALE   0x801F\n#define GL_POST_CONVOLUTION_RED_BIAS      0x8020\n#define GL_POST_CONVOLUTION_GREEN_BIAS    0x8021\n#define GL_POST_CONVOLUTION_BLUE_BIAS     0x8022\n#define GL_POST_CONVOLUTION_ALPHA_BIAS    0x8023\n#define GL_HISTOGRAM                      0x8024\n#define GL_PROXY_HISTOGRAM                0x8025\n#define GL_HISTOGRAM_WIDTH                0x8026\n#define GL_HISTOGRAM_FORMAT               0x8027\n#define GL_HISTOGRAM_RED_SIZE             0x8028\n#define GL_HISTOGRAM_GREEN_SIZE           0x8029\n#define GL_HISTOGRAM_BLUE_SIZE            0x802A\n#define GL_HISTOGRAM_ALPHA_SIZE           0x802B\n#define GL_HISTOGRAM_LUMINANCE_SIZE       0x802C\n#define GL_HISTOGRAM_SINK                 0x802D\n#define GL_MINMAX                         0x802E\n#define GL_MINMAX_FORMAT                  0x802F\n#define GL_MINMAX_SINK                    0x8030\n#define GL_TABLE_TOO_LARGE                0x8031\n#define GL_COLOR_MATRIX                   0x80B1\n#define GL_COLOR_MATRIX_STACK_DEPTH       0x80B2\n#define GL_MAX_COLOR_MATRIX_STACK_DEPTH   0x80B3\n#define GL_POST_COLOR_MATRIX_RED_SCALE    0x80B4\n#define GL_POST_COLOR_MATRIX_GREEN_SCALE  0x80B5\n#define GL_POST_COLOR_MATRIX_BLUE_SCALE   0x80B6\n#define GL_POST_COLOR_MATRIX_ALPHA_SCALE  0x80B7\n#define GL_POST_COLOR_MATRIX_RED_BIAS     0x80B8\n#define GL_POST_COLOR_MATRIX_GREEN_BIAS   0x80B9\n#define GL_POST_COLOR_MATRIX_BLUE_BIAS    0x80BA\n#define GL_POST_COLOR_MATRIX_ALPHA_BIAS   0x80BB\n#define GL_COLOR_TABLE                    0x80D0\n#define GL_POST_CONVOLUTION_COLOR_TABLE   0x80D1\n#define GL_POST_COLOR_MATRIX_COLOR_TABLE  0x80D2\n#define GL_PROXY_COLOR_TABLE              0x80D3\n#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4\n#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5\n#define GL_COLOR_TABLE_SCALE              0x80D6\n#define GL_COLOR_TABLE_BIAS               0x80D7\n#define GL_COLOR_TABLE_FORMAT             0x80D8\n#define GL_COLOR_TABLE_WIDTH              0x80D9\n#define GL_COLOR_TABLE_RED_SIZE           0x80DA\n#define GL_COLOR_TABLE_GREEN_SIZE         0x80DB\n#define GL_COLOR_TABLE_BLUE_SIZE          0x80DC\n#define GL_COLOR_TABLE_ALPHA_SIZE         0x80DD\n#define GL_COLOR_TABLE_LUMINANCE_SIZE     0x80DE\n#define GL_COLOR_TABLE_INTENSITY_SIZE     0x80DF\n#define GL_CONSTANT_BORDER                0x8151\n#define GL_REPLICATE_BORDER               0x8153\n#define GL_CONVOLUTION_BORDER_COLOR       0x8154\ntypedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table);\ntypedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, void *table);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data);\ntypedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, void *image);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span);\ntypedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\ntypedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);\ntypedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink);\ntypedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table);\nGLAPI void APIENTRY glColorTableParameterfv (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glColorTableParameteriv (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glCopyColorTable (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glGetColorTable (GLenum target, GLenum format, GLenum type, void *table);\nGLAPI void APIENTRY glGetColorTableParameterfv (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetColorTableParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glColorSubTable (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glCopyColorSubTable (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glConvolutionFilter1D (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image);\nGLAPI void APIENTRY glConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image);\nGLAPI void APIENTRY glConvolutionParameterf (GLenum target, GLenum pname, GLfloat params);\nGLAPI void APIENTRY glConvolutionParameterfv (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glConvolutionParameteri (GLenum target, GLenum pname, GLint params);\nGLAPI void APIENTRY glConvolutionParameteriv (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetConvolutionFilter (GLenum target, GLenum format, GLenum type, void *image);\nGLAPI void APIENTRY glGetConvolutionParameterfv (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetConvolutionParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetSeparableFilter (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span);\nGLAPI void APIENTRY glSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column);\nGLAPI void APIENTRY glGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\nGLAPI void APIENTRY glGetHistogramParameterfv (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetHistogramParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\nGLAPI void APIENTRY glGetMinmaxParameterfv (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMinmaxParameteriv (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glHistogram (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);\nGLAPI void APIENTRY glMinmax (GLenum target, GLenum internalformat, GLboolean sink);\nGLAPI void APIENTRY glResetHistogram (GLenum target);\nGLAPI void APIENTRY glResetMinmax (GLenum target);\n#endif\n#endif /* GL_ARB_imaging */\n\n#ifndef GL_ARB_indirect_parameters\n#define GL_ARB_indirect_parameters 1\n#define GL_PARAMETER_BUFFER_ARB           0x80EE\n#define GL_PARAMETER_BUFFER_BINDING_ARB   0x80EF\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC) (GLenum mode, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC) (GLenum mode, GLenum type, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiDrawArraysIndirectCountARB (GLenum mode, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);\nGLAPI void APIENTRY glMultiDrawElementsIndirectCountARB (GLenum mode, GLenum type, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride);\n#endif\n#endif /* GL_ARB_indirect_parameters */\n\n#ifndef GL_ARB_instanced_arrays\n#define GL_ARB_instanced_arrays 1\n#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor);\n#endif\n#endif /* GL_ARB_instanced_arrays */\n\n#ifndef GL_ARB_internalformat_query\n#define GL_ARB_internalformat_query 1\n#endif /* GL_ARB_internalformat_query */\n\n#ifndef GL_ARB_internalformat_query2\n#define GL_ARB_internalformat_query2 1\n#define GL_SRGB_DECODE_ARB                0x8299\n#endif /* GL_ARB_internalformat_query2 */\n\n#ifndef GL_ARB_invalidate_subdata\n#define GL_ARB_invalidate_subdata 1\n#endif /* GL_ARB_invalidate_subdata */\n\n#ifndef GL_ARB_map_buffer_alignment\n#define GL_ARB_map_buffer_alignment 1\n#endif /* GL_ARB_map_buffer_alignment */\n\n#ifndef GL_ARB_map_buffer_range\n#define GL_ARB_map_buffer_range 1\n#endif /* GL_ARB_map_buffer_range */\n\n#ifndef GL_ARB_matrix_palette\n#define GL_ARB_matrix_palette 1\n#define GL_MATRIX_PALETTE_ARB             0x8840\n#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841\n#define GL_MAX_PALETTE_MATRICES_ARB       0x8842\n#define GL_CURRENT_PALETTE_MATRIX_ARB     0x8843\n#define GL_MATRIX_INDEX_ARRAY_ARB         0x8844\n#define GL_CURRENT_MATRIX_INDEX_ARB       0x8845\n#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB    0x8846\n#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB    0x8847\n#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB  0x8848\n#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849\ntypedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index);\ntypedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices);\ntypedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices);\ntypedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices);\ntypedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint index);\nGLAPI void APIENTRY glMatrixIndexubvARB (GLint size, const GLubyte *indices);\nGLAPI void APIENTRY glMatrixIndexusvARB (GLint size, const GLushort *indices);\nGLAPI void APIENTRY glMatrixIndexuivARB (GLint size, const GLuint *indices);\nGLAPI void APIENTRY glMatrixIndexPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer);\n#endif\n#endif /* GL_ARB_matrix_palette */\n\n#ifndef GL_ARB_multi_bind\n#define GL_ARB_multi_bind 1\n#endif /* GL_ARB_multi_bind */\n\n#ifndef GL_ARB_multi_draw_indirect\n#define GL_ARB_multi_draw_indirect 1\n#endif /* GL_ARB_multi_draw_indirect */\n\n#ifndef GL_ARB_multisample\n#define GL_ARB_multisample 1\n#define GL_MULTISAMPLE_ARB                0x809D\n#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB   0x809E\n#define GL_SAMPLE_ALPHA_TO_ONE_ARB        0x809F\n#define GL_SAMPLE_COVERAGE_ARB            0x80A0\n#define GL_SAMPLE_BUFFERS_ARB             0x80A8\n#define GL_SAMPLES_ARB                    0x80A9\n#define GL_SAMPLE_COVERAGE_VALUE_ARB      0x80AA\n#define GL_SAMPLE_COVERAGE_INVERT_ARB     0x80AB\n#define GL_MULTISAMPLE_BIT_ARB            0x20000000\ntypedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLfloat value, GLboolean invert);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSampleCoverageARB (GLfloat value, GLboolean invert);\n#endif\n#endif /* GL_ARB_multisample */\n\n#ifndef GL_ARB_multitexture\n#define GL_ARB_multitexture 1\n#define GL_TEXTURE0_ARB                   0x84C0\n#define GL_TEXTURE1_ARB                   0x84C1\n#define GL_TEXTURE2_ARB                   0x84C2\n#define GL_TEXTURE3_ARB                   0x84C3\n#define GL_TEXTURE4_ARB                   0x84C4\n#define GL_TEXTURE5_ARB                   0x84C5\n#define GL_TEXTURE6_ARB                   0x84C6\n#define GL_TEXTURE7_ARB                   0x84C7\n#define GL_TEXTURE8_ARB                   0x84C8\n#define GL_TEXTURE9_ARB                   0x84C9\n#define GL_TEXTURE10_ARB                  0x84CA\n#define GL_TEXTURE11_ARB                  0x84CB\n#define GL_TEXTURE12_ARB                  0x84CC\n#define GL_TEXTURE13_ARB                  0x84CD\n#define GL_TEXTURE14_ARB                  0x84CE\n#define GL_TEXTURE15_ARB                  0x84CF\n#define GL_TEXTURE16_ARB                  0x84D0\n#define GL_TEXTURE17_ARB                  0x84D1\n#define GL_TEXTURE18_ARB                  0x84D2\n#define GL_TEXTURE19_ARB                  0x84D3\n#define GL_TEXTURE20_ARB                  0x84D4\n#define GL_TEXTURE21_ARB                  0x84D5\n#define GL_TEXTURE22_ARB                  0x84D6\n#define GL_TEXTURE23_ARB                  0x84D7\n#define GL_TEXTURE24_ARB                  0x84D8\n#define GL_TEXTURE25_ARB                  0x84D9\n#define GL_TEXTURE26_ARB                  0x84DA\n#define GL_TEXTURE27_ARB                  0x84DB\n#define GL_TEXTURE28_ARB                  0x84DC\n#define GL_TEXTURE29_ARB                  0x84DD\n#define GL_TEXTURE30_ARB                  0x84DE\n#define GL_TEXTURE31_ARB                  0x84DF\n#define GL_ACTIVE_TEXTURE_ARB             0x84E0\n#define GL_CLIENT_ACTIVE_TEXTURE_ARB      0x84E1\n#define GL_MAX_TEXTURE_UNITS_ARB          0x84E2\ntypedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture);\ntypedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glActiveTextureARB (GLenum texture);\nGLAPI void APIENTRY glClientActiveTextureARB (GLenum texture);\nGLAPI void APIENTRY glMultiTexCoord1dARB (GLenum target, GLdouble s);\nGLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord1fARB (GLenum target, GLfloat s);\nGLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord1iARB (GLenum target, GLint s);\nGLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord1sARB (GLenum target, GLshort s);\nGLAPI void APIENTRY glMultiTexCoord1svARB (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glMultiTexCoord2dARB (GLenum target, GLdouble s, GLdouble t);\nGLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord2fARB (GLenum target, GLfloat s, GLfloat t);\nGLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord2iARB (GLenum target, GLint s, GLint t);\nGLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord2sARB (GLenum target, GLshort s, GLshort t);\nGLAPI void APIENTRY glMultiTexCoord2svARB (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glMultiTexCoord3dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r);\nGLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord3fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r);\nGLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord3iARB (GLenum target, GLint s, GLint t, GLint r);\nGLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord3sARB (GLenum target, GLshort s, GLshort t, GLshort r);\nGLAPI void APIENTRY glMultiTexCoord3svARB (GLenum target, const GLshort *v);\nGLAPI void APIENTRY glMultiTexCoord4dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);\nGLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum target, const GLdouble *v);\nGLAPI void APIENTRY glMultiTexCoord4fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);\nGLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum target, const GLfloat *v);\nGLAPI void APIENTRY glMultiTexCoord4iARB (GLenum target, GLint s, GLint t, GLint r, GLint q);\nGLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum target, const GLint *v);\nGLAPI void APIENTRY glMultiTexCoord4sARB (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);\nGLAPI void APIENTRY glMultiTexCoord4svARB (GLenum target, const GLshort *v);\n#endif\n#endif /* GL_ARB_multitexture */\n\n#ifndef GL_ARB_occlusion_query\n#define GL_ARB_occlusion_query 1\n#define GL_QUERY_COUNTER_BITS_ARB         0x8864\n#define GL_CURRENT_QUERY_ARB              0x8865\n#define GL_QUERY_RESULT_ARB               0x8866\n#define GL_QUERY_RESULT_AVAILABLE_ARB     0x8867\n#define GL_SAMPLES_PASSED_ARB             0x8914\ntypedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids);\ntypedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids);\ntypedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id);\ntypedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenQueriesARB (GLsizei n, GLuint *ids);\nGLAPI void APIENTRY glDeleteQueriesARB (GLsizei n, const GLuint *ids);\nGLAPI GLboolean APIENTRY glIsQueryARB (GLuint id);\nGLAPI void APIENTRY glBeginQueryARB (GLenum target, GLuint id);\nGLAPI void APIENTRY glEndQueryARB (GLenum target);\nGLAPI void APIENTRY glGetQueryivARB (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetQueryObjectivARB (GLuint id, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetQueryObjectuivARB (GLuint id, GLenum pname, GLuint *params);\n#endif\n#endif /* GL_ARB_occlusion_query */\n\n#ifndef GL_ARB_occlusion_query2\n#define GL_ARB_occlusion_query2 1\n#endif /* GL_ARB_occlusion_query2 */\n\n#ifndef GL_ARB_pixel_buffer_object\n#define GL_ARB_pixel_buffer_object 1\n#define GL_PIXEL_PACK_BUFFER_ARB          0x88EB\n#define GL_PIXEL_UNPACK_BUFFER_ARB        0x88EC\n#define GL_PIXEL_PACK_BUFFER_BINDING_ARB  0x88ED\n#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF\n#endif /* GL_ARB_pixel_buffer_object */\n\n#ifndef GL_ARB_point_parameters\n#define GL_ARB_point_parameters 1\n#define GL_POINT_SIZE_MIN_ARB             0x8126\n#define GL_POINT_SIZE_MAX_ARB             0x8127\n#define GL_POINT_FADE_THRESHOLD_SIZE_ARB  0x8128\n#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameterfARB (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glPointParameterfvARB (GLenum pname, const GLfloat *params);\n#endif\n#endif /* GL_ARB_point_parameters */\n\n#ifndef GL_ARB_point_sprite\n#define GL_ARB_point_sprite 1\n#define GL_POINT_SPRITE_ARB               0x8861\n#define GL_COORD_REPLACE_ARB              0x8862\n#endif /* GL_ARB_point_sprite */\n\n#ifndef GL_ARB_program_interface_query\n#define GL_ARB_program_interface_query 1\n#endif /* GL_ARB_program_interface_query */\n\n#ifndef GL_ARB_provoking_vertex\n#define GL_ARB_provoking_vertex 1\n#endif /* GL_ARB_provoking_vertex */\n\n#ifndef GL_ARB_query_buffer_object\n#define GL_ARB_query_buffer_object 1\n#endif /* GL_ARB_query_buffer_object */\n\n#ifndef GL_ARB_robust_buffer_access_behavior\n#define GL_ARB_robust_buffer_access_behavior 1\n#endif /* GL_ARB_robust_buffer_access_behavior */\n\n#ifndef GL_ARB_robustness\n#define GL_ARB_robustness 1\n#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004\n#define GL_LOSE_CONTEXT_ON_RESET_ARB      0x8252\n#define GL_GUILTY_CONTEXT_RESET_ARB       0x8253\n#define GL_INNOCENT_CONTEXT_RESET_ARB     0x8254\n#define GL_UNKNOWN_CONTEXT_RESET_ARB      0x8255\n#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256\n#define GL_NO_RESET_NOTIFICATION_ARB      0x8261\ntypedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void);\ntypedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img);\ntypedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);\ntypedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, void *img);\ntypedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);\ntypedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params);\ntypedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETNMAPDVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v);\ntypedef void (APIENTRYP PFNGLGETNMAPFVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v);\ntypedef void (APIENTRYP PFNGLGETNMAPIVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v);\ntypedef void (APIENTRYP PFNGLGETNPIXELMAPFVARBPROC) (GLenum map, GLsizei bufSize, GLfloat *values);\ntypedef void (APIENTRYP PFNGLGETNPIXELMAPUIVARBPROC) (GLenum map, GLsizei bufSize, GLuint *values);\ntypedef void (APIENTRYP PFNGLGETNPIXELMAPUSVARBPROC) (GLenum map, GLsizei bufSize, GLushort *values);\ntypedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEARBPROC) (GLsizei bufSize, GLubyte *pattern);\ntypedef void (APIENTRYP PFNGLGETNCOLORTABLEARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table);\ntypedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image);\ntypedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span);\ntypedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values);\ntypedef void (APIENTRYP PFNGLGETNMINMAXARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void);\nGLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img);\nGLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);\nGLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, void *img);\nGLAPI void APIENTRY glGetnUniformfvARB (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);\nGLAPI void APIENTRY glGetnUniformivARB (GLuint program, GLint location, GLsizei bufSize, GLint *params);\nGLAPI void APIENTRY glGetnUniformuivARB (GLuint program, GLint location, GLsizei bufSize, GLuint *params);\nGLAPI void APIENTRY glGetnUniformdvARB (GLuint program, GLint location, GLsizei bufSize, GLdouble *params);\nGLAPI void APIENTRY glGetnMapdvARB (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v);\nGLAPI void APIENTRY glGetnMapfvARB (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v);\nGLAPI void APIENTRY glGetnMapivARB (GLenum target, GLenum query, GLsizei bufSize, GLint *v);\nGLAPI void APIENTRY glGetnPixelMapfvARB (GLenum map, GLsizei bufSize, GLfloat *values);\nGLAPI void APIENTRY glGetnPixelMapuivARB (GLenum map, GLsizei bufSize, GLuint *values);\nGLAPI void APIENTRY glGetnPixelMapusvARB (GLenum map, GLsizei bufSize, GLushort *values);\nGLAPI void APIENTRY glGetnPolygonStippleARB (GLsizei bufSize, GLubyte *pattern);\nGLAPI void APIENTRY glGetnColorTableARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table);\nGLAPI void APIENTRY glGetnConvolutionFilterARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image);\nGLAPI void APIENTRY glGetnSeparableFilterARB (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span);\nGLAPI void APIENTRY glGetnHistogramARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values);\nGLAPI void APIENTRY glGetnMinmaxARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values);\n#endif\n#endif /* GL_ARB_robustness */\n\n#ifndef GL_ARB_robustness_isolation\n#define GL_ARB_robustness_isolation 1\n#endif /* GL_ARB_robustness_isolation */\n\n#ifndef GL_ARB_sample_shading\n#define GL_ARB_sample_shading 1\n#define GL_SAMPLE_SHADING_ARB             0x8C36\n#define GL_MIN_SAMPLE_SHADING_VALUE_ARB   0x8C37\ntypedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLfloat value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMinSampleShadingARB (GLfloat value);\n#endif\n#endif /* GL_ARB_sample_shading */\n\n#ifndef GL_ARB_sampler_objects\n#define GL_ARB_sampler_objects 1\n#endif /* GL_ARB_sampler_objects */\n\n#ifndef GL_ARB_seamless_cube_map\n#define GL_ARB_seamless_cube_map 1\n#endif /* GL_ARB_seamless_cube_map */\n\n#ifndef GL_ARB_seamless_cubemap_per_texture\n#define GL_ARB_seamless_cubemap_per_texture 1\n#endif /* GL_ARB_seamless_cubemap_per_texture */\n\n#ifndef GL_ARB_separate_shader_objects\n#define GL_ARB_separate_shader_objects 1\n#endif /* GL_ARB_separate_shader_objects */\n\n#ifndef GL_ARB_shader_atomic_counters\n#define GL_ARB_shader_atomic_counters 1\n#endif /* GL_ARB_shader_atomic_counters */\n\n#ifndef GL_ARB_shader_bit_encoding\n#define GL_ARB_shader_bit_encoding 1\n#endif /* GL_ARB_shader_bit_encoding */\n\n#ifndef GL_ARB_shader_draw_parameters\n#define GL_ARB_shader_draw_parameters 1\n#endif /* GL_ARB_shader_draw_parameters */\n\n#ifndef GL_ARB_shader_group_vote\n#define GL_ARB_shader_group_vote 1\n#endif /* GL_ARB_shader_group_vote */\n\n#ifndef GL_ARB_shader_image_load_store\n#define GL_ARB_shader_image_load_store 1\n#endif /* GL_ARB_shader_image_load_store */\n\n#ifndef GL_ARB_shader_image_size\n#define GL_ARB_shader_image_size 1\n#endif /* GL_ARB_shader_image_size */\n\n#ifndef GL_ARB_shader_objects\n#define GL_ARB_shader_objects 1\n#ifdef __APPLE__\ntypedef void *GLhandleARB;\n#else\ntypedef unsigned int GLhandleARB;\n#endif\ntypedef char GLcharARB;\n#define GL_PROGRAM_OBJECT_ARB             0x8B40\n#define GL_SHADER_OBJECT_ARB              0x8B48\n#define GL_OBJECT_TYPE_ARB                0x8B4E\n#define GL_OBJECT_SUBTYPE_ARB             0x8B4F\n#define GL_FLOAT_VEC2_ARB                 0x8B50\n#define GL_FLOAT_VEC3_ARB                 0x8B51\n#define GL_FLOAT_VEC4_ARB                 0x8B52\n#define GL_INT_VEC2_ARB                   0x8B53\n#define GL_INT_VEC3_ARB                   0x8B54\n#define GL_INT_VEC4_ARB                   0x8B55\n#define GL_BOOL_ARB                       0x8B56\n#define GL_BOOL_VEC2_ARB                  0x8B57\n#define GL_BOOL_VEC3_ARB                  0x8B58\n#define GL_BOOL_VEC4_ARB                  0x8B59\n#define GL_FLOAT_MAT2_ARB                 0x8B5A\n#define GL_FLOAT_MAT3_ARB                 0x8B5B\n#define GL_FLOAT_MAT4_ARB                 0x8B5C\n#define GL_SAMPLER_1D_ARB                 0x8B5D\n#define GL_SAMPLER_2D_ARB                 0x8B5E\n#define GL_SAMPLER_3D_ARB                 0x8B5F\n#define GL_SAMPLER_CUBE_ARB               0x8B60\n#define GL_SAMPLER_1D_SHADOW_ARB          0x8B61\n#define GL_SAMPLER_2D_SHADOW_ARB          0x8B62\n#define GL_SAMPLER_2D_RECT_ARB            0x8B63\n#define GL_SAMPLER_2D_RECT_SHADOW_ARB     0x8B64\n#define GL_OBJECT_DELETE_STATUS_ARB       0x8B80\n#define GL_OBJECT_COMPILE_STATUS_ARB      0x8B81\n#define GL_OBJECT_LINK_STATUS_ARB         0x8B82\n#define GL_OBJECT_VALIDATE_STATUS_ARB     0x8B83\n#define GL_OBJECT_INFO_LOG_LENGTH_ARB     0x8B84\n#define GL_OBJECT_ATTACHED_OBJECTS_ARB    0x8B85\n#define GL_OBJECT_ACTIVE_UNIFORMS_ARB     0x8B86\n#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87\n#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88\ntypedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);\ntypedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname);\ntypedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj);\ntypedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);\ntypedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length);\ntypedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);\ntypedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);\ntypedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);\ntypedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);\ntypedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);\ntypedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj);\ntypedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0);\ntypedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1);\ntypedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\ntypedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\ntypedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0);\ntypedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1);\ntypedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2);\ntypedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\ntypedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);\ntypedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);\ntypedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);\ntypedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);\ntypedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params);\ntypedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDeleteObjectARB (GLhandleARB obj);\nGLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum pname);\nGLAPI void APIENTRY glDetachObjectARB (GLhandleARB containerObj, GLhandleARB attachedObj);\nGLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum shaderType);\nGLAPI void APIENTRY glShaderSourceARB (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length);\nGLAPI void APIENTRY glCompileShaderARB (GLhandleARB shaderObj);\nGLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);\nGLAPI void APIENTRY glAttachObjectARB (GLhandleARB containerObj, GLhandleARB obj);\nGLAPI void APIENTRY glLinkProgramARB (GLhandleARB programObj);\nGLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB programObj);\nGLAPI void APIENTRY glValidateProgramARB (GLhandleARB programObj);\nGLAPI void APIENTRY glUniform1fARB (GLint location, GLfloat v0);\nGLAPI void APIENTRY glUniform2fARB (GLint location, GLfloat v0, GLfloat v1);\nGLAPI void APIENTRY glUniform3fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\nGLAPI void APIENTRY glUniform4fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\nGLAPI void APIENTRY glUniform1iARB (GLint location, GLint v0);\nGLAPI void APIENTRY glUniform2iARB (GLint location, GLint v0, GLint v1);\nGLAPI void APIENTRY glUniform3iARB (GLint location, GLint v0, GLint v1, GLint v2);\nGLAPI void APIENTRY glUniform4iARB (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\nGLAPI void APIENTRY glUniform1fvARB (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform2fvARB (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform3fvARB (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform4fvARB (GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glUniform1ivARB (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniform2ivARB (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniform3ivARB (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniform4ivARB (GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glUniformMatrix2fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix3fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glUniformMatrix4fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB obj, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB obj, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetInfoLogARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);\nGLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);\nGLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB programObj, const GLcharARB *name);\nGLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);\nGLAPI void APIENTRY glGetUniformfvARB (GLhandleARB programObj, GLint location, GLfloat *params);\nGLAPI void APIENTRY glGetUniformivARB (GLhandleARB programObj, GLint location, GLint *params);\nGLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);\n#endif\n#endif /* GL_ARB_shader_objects */\n\n#ifndef GL_ARB_shader_precision\n#define GL_ARB_shader_precision 1\n#endif /* GL_ARB_shader_precision */\n\n#ifndef GL_ARB_shader_stencil_export\n#define GL_ARB_shader_stencil_export 1\n#endif /* GL_ARB_shader_stencil_export */\n\n#ifndef GL_ARB_shader_storage_buffer_object\n#define GL_ARB_shader_storage_buffer_object 1\n#endif /* GL_ARB_shader_storage_buffer_object */\n\n#ifndef GL_ARB_shader_subroutine\n#define GL_ARB_shader_subroutine 1\n#endif /* GL_ARB_shader_subroutine */\n\n#ifndef GL_ARB_shader_texture_lod\n#define GL_ARB_shader_texture_lod 1\n#endif /* GL_ARB_shader_texture_lod */\n\n#ifndef GL_ARB_shading_language_100\n#define GL_ARB_shading_language_100 1\n#define GL_SHADING_LANGUAGE_VERSION_ARB   0x8B8C\n#endif /* GL_ARB_shading_language_100 */\n\n#ifndef GL_ARB_shading_language_420pack\n#define GL_ARB_shading_language_420pack 1\n#endif /* GL_ARB_shading_language_420pack */\n\n#ifndef GL_ARB_shading_language_include\n#define GL_ARB_shading_language_include 1\n#define GL_SHADER_INCLUDE_ARB             0x8DAE\n#define GL_NAMED_STRING_LENGTH_ARB        0x8DE9\n#define GL_NAMED_STRING_TYPE_ARB          0x8DEA\ntypedef void (APIENTRYP PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string);\ntypedef void (APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name);\ntypedef void (APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length);\ntypedef GLboolean (APIENTRYP PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string);\ntypedef void (APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const GLchar *name, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glNamedStringARB (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string);\nGLAPI void APIENTRY glDeleteNamedStringARB (GLint namelen, const GLchar *name);\nGLAPI void APIENTRY glCompileShaderIncludeARB (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length);\nGLAPI GLboolean APIENTRY glIsNamedStringARB (GLint namelen, const GLchar *name);\nGLAPI void APIENTRY glGetNamedStringARB (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string);\nGLAPI void APIENTRY glGetNamedStringivARB (GLint namelen, const GLchar *name, GLenum pname, GLint *params);\n#endif\n#endif /* GL_ARB_shading_language_include */\n\n#ifndef GL_ARB_shading_language_packing\n#define GL_ARB_shading_language_packing 1\n#endif /* GL_ARB_shading_language_packing */\n\n#ifndef GL_ARB_shadow\n#define GL_ARB_shadow 1\n#define GL_TEXTURE_COMPARE_MODE_ARB       0x884C\n#define GL_TEXTURE_COMPARE_FUNC_ARB       0x884D\n#define GL_COMPARE_R_TO_TEXTURE_ARB       0x884E\n#endif /* GL_ARB_shadow */\n\n#ifndef GL_ARB_shadow_ambient\n#define GL_ARB_shadow_ambient 1\n#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF\n#endif /* GL_ARB_shadow_ambient */\n\n#ifndef GL_ARB_sparse_texture\n#define GL_ARB_sparse_texture 1\n#define GL_TEXTURE_SPARSE_ARB             0x91A6\n#define GL_VIRTUAL_PAGE_SIZE_INDEX_ARB    0x91A7\n#define GL_MIN_SPARSE_LEVEL_ARB           0x919B\n#define GL_NUM_VIRTUAL_PAGE_SIZES_ARB     0x91A8\n#define GL_VIRTUAL_PAGE_SIZE_X_ARB        0x9195\n#define GL_VIRTUAL_PAGE_SIZE_Y_ARB        0x9196\n#define GL_VIRTUAL_PAGE_SIZE_Z_ARB        0x9197\n#define GL_MAX_SPARSE_TEXTURE_SIZE_ARB    0x9198\n#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB 0x9199\n#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB 0x919A\n#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB 0x91A9\ntypedef void (APIENTRYP PFNGLTEXPAGECOMMITMENTARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexPageCommitmentARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident);\n#endif\n#endif /* GL_ARB_sparse_texture */\n\n#ifndef GL_ARB_stencil_texturing\n#define GL_ARB_stencil_texturing 1\n#endif /* GL_ARB_stencil_texturing */\n\n#ifndef GL_ARB_sync\n#define GL_ARB_sync 1\n#endif /* GL_ARB_sync */\n\n#ifndef GL_ARB_tessellation_shader\n#define GL_ARB_tessellation_shader 1\n#endif /* GL_ARB_tessellation_shader */\n\n#ifndef GL_ARB_texture_border_clamp\n#define GL_ARB_texture_border_clamp 1\n#define GL_CLAMP_TO_BORDER_ARB            0x812D\n#endif /* GL_ARB_texture_border_clamp */\n\n#ifndef GL_ARB_texture_buffer_object\n#define GL_ARB_texture_buffer_object 1\n#define GL_TEXTURE_BUFFER_ARB             0x8C2A\n#define GL_MAX_TEXTURE_BUFFER_SIZE_ARB    0x8C2B\n#define GL_TEXTURE_BINDING_BUFFER_ARB     0x8C2C\n#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D\n#define GL_TEXTURE_BUFFER_FORMAT_ARB      0x8C2E\ntypedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer);\n#endif\n#endif /* GL_ARB_texture_buffer_object */\n\n#ifndef GL_ARB_texture_buffer_object_rgb32\n#define GL_ARB_texture_buffer_object_rgb32 1\n#endif /* GL_ARB_texture_buffer_object_rgb32 */\n\n#ifndef GL_ARB_texture_buffer_range\n#define GL_ARB_texture_buffer_range 1\n#endif /* GL_ARB_texture_buffer_range */\n\n#ifndef GL_ARB_texture_compression\n#define GL_ARB_texture_compression 1\n#define GL_COMPRESSED_ALPHA_ARB           0x84E9\n#define GL_COMPRESSED_LUMINANCE_ARB       0x84EA\n#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB\n#define GL_COMPRESSED_INTENSITY_ARB       0x84EC\n#define GL_COMPRESSED_RGB_ARB             0x84ED\n#define GL_COMPRESSED_RGBA_ARB            0x84EE\n#define GL_TEXTURE_COMPRESSION_HINT_ARB   0x84EF\n#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0\n#define GL_TEXTURE_COMPRESSED_ARB         0x86A1\n#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2\n#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data);\ntypedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, void *img);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data);\nGLAPI void APIENTRY glGetCompressedTexImageARB (GLenum target, GLint level, void *img);\n#endif\n#endif /* GL_ARB_texture_compression */\n\n#ifndef GL_ARB_texture_compression_bptc\n#define GL_ARB_texture_compression_bptc 1\n#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C\n#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D\n#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E\n#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F\n#endif /* GL_ARB_texture_compression_bptc */\n\n#ifndef GL_ARB_texture_compression_rgtc\n#define GL_ARB_texture_compression_rgtc 1\n#endif /* GL_ARB_texture_compression_rgtc */\n\n#ifndef GL_ARB_texture_cube_map\n#define GL_ARB_texture_cube_map 1\n#define GL_NORMAL_MAP_ARB                 0x8511\n#define GL_REFLECTION_MAP_ARB             0x8512\n#define GL_TEXTURE_CUBE_MAP_ARB           0x8513\n#define GL_TEXTURE_BINDING_CUBE_MAP_ARB   0x8514\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A\n#define GL_PROXY_TEXTURE_CUBE_MAP_ARB     0x851B\n#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB  0x851C\n#endif /* GL_ARB_texture_cube_map */\n\n#ifndef GL_ARB_texture_cube_map_array\n#define GL_ARB_texture_cube_map_array 1\n#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB     0x9009\n#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A\n#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B\n#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB     0x900C\n#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D\n#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E\n#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F\n#endif /* GL_ARB_texture_cube_map_array */\n\n#ifndef GL_ARB_texture_env_add\n#define GL_ARB_texture_env_add 1\n#endif /* GL_ARB_texture_env_add */\n\n#ifndef GL_ARB_texture_env_combine\n#define GL_ARB_texture_env_combine 1\n#define GL_COMBINE_ARB                    0x8570\n#define GL_COMBINE_RGB_ARB                0x8571\n#define GL_COMBINE_ALPHA_ARB              0x8572\n#define GL_SOURCE0_RGB_ARB                0x8580\n#define GL_SOURCE1_RGB_ARB                0x8581\n#define GL_SOURCE2_RGB_ARB                0x8582\n#define GL_SOURCE0_ALPHA_ARB              0x8588\n#define GL_SOURCE1_ALPHA_ARB              0x8589\n#define GL_SOURCE2_ALPHA_ARB              0x858A\n#define GL_OPERAND0_RGB_ARB               0x8590\n#define GL_OPERAND1_RGB_ARB               0x8591\n#define GL_OPERAND2_RGB_ARB               0x8592\n#define GL_OPERAND0_ALPHA_ARB             0x8598\n#define GL_OPERAND1_ALPHA_ARB             0x8599\n#define GL_OPERAND2_ALPHA_ARB             0x859A\n#define GL_RGB_SCALE_ARB                  0x8573\n#define GL_ADD_SIGNED_ARB                 0x8574\n#define GL_INTERPOLATE_ARB                0x8575\n#define GL_SUBTRACT_ARB                   0x84E7\n#define GL_CONSTANT_ARB                   0x8576\n#define GL_PRIMARY_COLOR_ARB              0x8577\n#define GL_PREVIOUS_ARB                   0x8578\n#endif /* GL_ARB_texture_env_combine */\n\n#ifndef GL_ARB_texture_env_crossbar\n#define GL_ARB_texture_env_crossbar 1\n#endif /* GL_ARB_texture_env_crossbar */\n\n#ifndef GL_ARB_texture_env_dot3\n#define GL_ARB_texture_env_dot3 1\n#define GL_DOT3_RGB_ARB                   0x86AE\n#define GL_DOT3_RGBA_ARB                  0x86AF\n#endif /* GL_ARB_texture_env_dot3 */\n\n#ifndef GL_ARB_texture_float\n#define GL_ARB_texture_float 1\n#define GL_TEXTURE_RED_TYPE_ARB           0x8C10\n#define GL_TEXTURE_GREEN_TYPE_ARB         0x8C11\n#define GL_TEXTURE_BLUE_TYPE_ARB          0x8C12\n#define GL_TEXTURE_ALPHA_TYPE_ARB         0x8C13\n#define GL_TEXTURE_LUMINANCE_TYPE_ARB     0x8C14\n#define GL_TEXTURE_INTENSITY_TYPE_ARB     0x8C15\n#define GL_TEXTURE_DEPTH_TYPE_ARB         0x8C16\n#define GL_UNSIGNED_NORMALIZED_ARB        0x8C17\n#define GL_RGBA32F_ARB                    0x8814\n#define GL_RGB32F_ARB                     0x8815\n#define GL_ALPHA32F_ARB                   0x8816\n#define GL_INTENSITY32F_ARB               0x8817\n#define GL_LUMINANCE32F_ARB               0x8818\n#define GL_LUMINANCE_ALPHA32F_ARB         0x8819\n#define GL_RGBA16F_ARB                    0x881A\n#define GL_RGB16F_ARB                     0x881B\n#define GL_ALPHA16F_ARB                   0x881C\n#define GL_INTENSITY16F_ARB               0x881D\n#define GL_LUMINANCE16F_ARB               0x881E\n#define GL_LUMINANCE_ALPHA16F_ARB         0x881F\n#endif /* GL_ARB_texture_float */\n\n#ifndef GL_ARB_texture_gather\n#define GL_ARB_texture_gather 1\n#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E\n#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F\n#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F\n#endif /* GL_ARB_texture_gather */\n\n#ifndef GL_ARB_texture_mirror_clamp_to_edge\n#define GL_ARB_texture_mirror_clamp_to_edge 1\n#endif /* GL_ARB_texture_mirror_clamp_to_edge */\n\n#ifndef GL_ARB_texture_mirrored_repeat\n#define GL_ARB_texture_mirrored_repeat 1\n#define GL_MIRRORED_REPEAT_ARB            0x8370\n#endif /* GL_ARB_texture_mirrored_repeat */\n\n#ifndef GL_ARB_texture_multisample\n#define GL_ARB_texture_multisample 1\n#endif /* GL_ARB_texture_multisample */\n\n#ifndef GL_ARB_texture_non_power_of_two\n#define GL_ARB_texture_non_power_of_two 1\n#endif /* GL_ARB_texture_non_power_of_two */\n\n#ifndef GL_ARB_texture_query_levels\n#define GL_ARB_texture_query_levels 1\n#endif /* GL_ARB_texture_query_levels */\n\n#ifndef GL_ARB_texture_query_lod\n#define GL_ARB_texture_query_lod 1\n#endif /* GL_ARB_texture_query_lod */\n\n#ifndef GL_ARB_texture_rectangle\n#define GL_ARB_texture_rectangle 1\n#define GL_TEXTURE_RECTANGLE_ARB          0x84F5\n#define GL_TEXTURE_BINDING_RECTANGLE_ARB  0x84F6\n#define GL_PROXY_TEXTURE_RECTANGLE_ARB    0x84F7\n#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8\n#endif /* GL_ARB_texture_rectangle */\n\n#ifndef GL_ARB_texture_rg\n#define GL_ARB_texture_rg 1\n#endif /* GL_ARB_texture_rg */\n\n#ifndef GL_ARB_texture_rgb10_a2ui\n#define GL_ARB_texture_rgb10_a2ui 1\n#endif /* GL_ARB_texture_rgb10_a2ui */\n\n#ifndef GL_ARB_texture_stencil8\n#define GL_ARB_texture_stencil8 1\n#endif /* GL_ARB_texture_stencil8 */\n\n#ifndef GL_ARB_texture_storage\n#define GL_ARB_texture_storage 1\n#endif /* GL_ARB_texture_storage */\n\n#ifndef GL_ARB_texture_storage_multisample\n#define GL_ARB_texture_storage_multisample 1\n#endif /* GL_ARB_texture_storage_multisample */\n\n#ifndef GL_ARB_texture_swizzle\n#define GL_ARB_texture_swizzle 1\n#endif /* GL_ARB_texture_swizzle */\n\n#ifndef GL_ARB_texture_view\n#define GL_ARB_texture_view 1\n#endif /* GL_ARB_texture_view */\n\n#ifndef GL_ARB_timer_query\n#define GL_ARB_timer_query 1\n#endif /* GL_ARB_timer_query */\n\n#ifndef GL_ARB_transform_feedback2\n#define GL_ARB_transform_feedback2 1\n#define GL_TRANSFORM_FEEDBACK_PAUSED      0x8E23\n#define GL_TRANSFORM_FEEDBACK_ACTIVE      0x8E24\n#endif /* GL_ARB_transform_feedback2 */\n\n#ifndef GL_ARB_transform_feedback3\n#define GL_ARB_transform_feedback3 1\n#endif /* GL_ARB_transform_feedback3 */\n\n#ifndef GL_ARB_transform_feedback_instanced\n#define GL_ARB_transform_feedback_instanced 1\n#endif /* GL_ARB_transform_feedback_instanced */\n\n#ifndef GL_ARB_transpose_matrix\n#define GL_ARB_transpose_matrix 1\n#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3\n#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4\n#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB   0x84E5\n#define GL_TRANSPOSE_COLOR_MATRIX_ARB     0x84E6\ntypedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);\ntypedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);\ntypedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);\ntypedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *m);\nGLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *m);\nGLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *m);\nGLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *m);\n#endif\n#endif /* GL_ARB_transpose_matrix */\n\n#ifndef GL_ARB_uniform_buffer_object\n#define GL_ARB_uniform_buffer_object 1\n#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS    0x8A2C\n#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32\n#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45\n#endif /* GL_ARB_uniform_buffer_object */\n\n#ifndef GL_ARB_vertex_array_bgra\n#define GL_ARB_vertex_array_bgra 1\n#endif /* GL_ARB_vertex_array_bgra */\n\n#ifndef GL_ARB_vertex_array_object\n#define GL_ARB_vertex_array_object 1\n#endif /* GL_ARB_vertex_array_object */\n\n#ifndef GL_ARB_vertex_attrib_64bit\n#define GL_ARB_vertex_attrib_64bit 1\n#endif /* GL_ARB_vertex_attrib_64bit */\n\n#ifndef GL_ARB_vertex_attrib_binding\n#define GL_ARB_vertex_attrib_binding 1\n#endif /* GL_ARB_vertex_attrib_binding */\n\n#ifndef GL_ARB_vertex_blend\n#define GL_ARB_vertex_blend 1\n#define GL_MAX_VERTEX_UNITS_ARB           0x86A4\n#define GL_ACTIVE_VERTEX_UNITS_ARB        0x86A5\n#define GL_WEIGHT_SUM_UNITY_ARB           0x86A6\n#define GL_VERTEX_BLEND_ARB               0x86A7\n#define GL_CURRENT_WEIGHT_ARB             0x86A8\n#define GL_WEIGHT_ARRAY_TYPE_ARB          0x86A9\n#define GL_WEIGHT_ARRAY_STRIDE_ARB        0x86AA\n#define GL_WEIGHT_ARRAY_SIZE_ARB          0x86AB\n#define GL_WEIGHT_ARRAY_POINTER_ARB       0x86AC\n#define GL_WEIGHT_ARRAY_ARB               0x86AD\n#define GL_MODELVIEW0_ARB                 0x1700\n#define GL_MODELVIEW1_ARB                 0x850A\n#define GL_MODELVIEW2_ARB                 0x8722\n#define GL_MODELVIEW3_ARB                 0x8723\n#define GL_MODELVIEW4_ARB                 0x8724\n#define GL_MODELVIEW5_ARB                 0x8725\n#define GL_MODELVIEW6_ARB                 0x8726\n#define GL_MODELVIEW7_ARB                 0x8727\n#define GL_MODELVIEW8_ARB                 0x8728\n#define GL_MODELVIEW9_ARB                 0x8729\n#define GL_MODELVIEW10_ARB                0x872A\n#define GL_MODELVIEW11_ARB                0x872B\n#define GL_MODELVIEW12_ARB                0x872C\n#define GL_MODELVIEW13_ARB                0x872D\n#define GL_MODELVIEW14_ARB                0x872E\n#define GL_MODELVIEW15_ARB                0x872F\n#define GL_MODELVIEW16_ARB                0x8730\n#define GL_MODELVIEW17_ARB                0x8731\n#define GL_MODELVIEW18_ARB                0x8732\n#define GL_MODELVIEW19_ARB                0x8733\n#define GL_MODELVIEW20_ARB                0x8734\n#define GL_MODELVIEW21_ARB                0x8735\n#define GL_MODELVIEW22_ARB                0x8736\n#define GL_MODELVIEW23_ARB                0x8737\n#define GL_MODELVIEW24_ARB                0x8738\n#define GL_MODELVIEW25_ARB                0x8739\n#define GL_MODELVIEW26_ARB                0x873A\n#define GL_MODELVIEW27_ARB                0x873B\n#define GL_MODELVIEW28_ARB                0x873C\n#define GL_MODELVIEW29_ARB                0x873D\n#define GL_MODELVIEW30_ARB                0x873E\n#define GL_MODELVIEW31_ARB                0x873F\ntypedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights);\ntypedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glWeightbvARB (GLint size, const GLbyte *weights);\nGLAPI void APIENTRY glWeightsvARB (GLint size, const GLshort *weights);\nGLAPI void APIENTRY glWeightivARB (GLint size, const GLint *weights);\nGLAPI void APIENTRY glWeightfvARB (GLint size, const GLfloat *weights);\nGLAPI void APIENTRY glWeightdvARB (GLint size, const GLdouble *weights);\nGLAPI void APIENTRY glWeightubvARB (GLint size, const GLubyte *weights);\nGLAPI void APIENTRY glWeightusvARB (GLint size, const GLushort *weights);\nGLAPI void APIENTRY glWeightuivARB (GLint size, const GLuint *weights);\nGLAPI void APIENTRY glWeightPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glVertexBlendARB (GLint count);\n#endif\n#endif /* GL_ARB_vertex_blend */\n\n#ifndef GL_ARB_vertex_buffer_object\n#define GL_ARB_vertex_buffer_object 1\ntypedef ptrdiff_t GLsizeiptrARB;\ntypedef ptrdiff_t GLintptrARB;\n#define GL_BUFFER_SIZE_ARB                0x8764\n#define GL_BUFFER_USAGE_ARB               0x8765\n#define GL_ARRAY_BUFFER_ARB               0x8892\n#define GL_ELEMENT_ARRAY_BUFFER_ARB       0x8893\n#define GL_ARRAY_BUFFER_BINDING_ARB       0x8894\n#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895\n#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896\n#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897\n#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898\n#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899\n#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A\n#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B\n#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C\n#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D\n#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E\n#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F\n#define GL_READ_ONLY_ARB                  0x88B8\n#define GL_WRITE_ONLY_ARB                 0x88B9\n#define GL_READ_WRITE_ARB                 0x88BA\n#define GL_BUFFER_ACCESS_ARB              0x88BB\n#define GL_BUFFER_MAPPED_ARB              0x88BC\n#define GL_BUFFER_MAP_POINTER_ARB         0x88BD\n#define GL_STREAM_DRAW_ARB                0x88E0\n#define GL_STREAM_READ_ARB                0x88E1\n#define GL_STREAM_COPY_ARB                0x88E2\n#define GL_STATIC_DRAW_ARB                0x88E4\n#define GL_STATIC_READ_ARB                0x88E5\n#define GL_STATIC_COPY_ARB                0x88E6\n#define GL_DYNAMIC_DRAW_ARB               0x88E8\n#define GL_DYNAMIC_READ_ARB               0x88E9\n#define GL_DYNAMIC_COPY_ARB               0x88EA\ntypedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);\ntypedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);\ntypedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);\ntypedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage);\ntypedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data);\ntypedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data);\ntypedef void *(APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);\ntypedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, void **params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindBufferARB (GLenum target, GLuint buffer);\nGLAPI void APIENTRY glDeleteBuffersARB (GLsizei n, const GLuint *buffers);\nGLAPI void APIENTRY glGenBuffersARB (GLsizei n, GLuint *buffers);\nGLAPI GLboolean APIENTRY glIsBufferARB (GLuint buffer);\nGLAPI void APIENTRY glBufferDataARB (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage);\nGLAPI void APIENTRY glBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data);\nGLAPI void APIENTRY glGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data);\nGLAPI void *APIENTRY glMapBufferARB (GLenum target, GLenum access);\nGLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum target);\nGLAPI void APIENTRY glGetBufferParameterivARB (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetBufferPointervARB (GLenum target, GLenum pname, void **params);\n#endif\n#endif /* GL_ARB_vertex_buffer_object */\n\n#ifndef GL_ARB_vertex_program\n#define GL_ARB_vertex_program 1\n#define GL_COLOR_SUM_ARB                  0x8458\n#define GL_VERTEX_PROGRAM_ARB             0x8620\n#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622\n#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB   0x8623\n#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624\n#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB   0x8625\n#define GL_CURRENT_VERTEX_ATTRIB_ARB      0x8626\n#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB  0x8642\n#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB    0x8643\n#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645\n#define GL_MAX_VERTEX_ATTRIBS_ARB         0x8869\n#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A\n#define GL_PROGRAM_ADDRESS_REGISTERS_ARB  0x88B0\n#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1\n#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2\n#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, void **pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttrib1dARB (GLuint index, GLdouble x);\nGLAPI void APIENTRY glVertexAttrib1dvARB (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib1fARB (GLuint index, GLfloat x);\nGLAPI void APIENTRY glVertexAttrib1fvARB (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib1sARB (GLuint index, GLshort x);\nGLAPI void APIENTRY glVertexAttrib1svARB (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib2dARB (GLuint index, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glVertexAttrib2dvARB (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib2fARB (GLuint index, GLfloat x, GLfloat y);\nGLAPI void APIENTRY glVertexAttrib2fvARB (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib2sARB (GLuint index, GLshort x, GLshort y);\nGLAPI void APIENTRY glVertexAttrib2svARB (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib3dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glVertexAttrib3dvARB (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib3fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glVertexAttrib3fvARB (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib3sARB (GLuint index, GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glVertexAttrib3svARB (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint index, const GLbyte *v);\nGLAPI void APIENTRY glVertexAttrib4NivARB (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4NubARB (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);\nGLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint index, const GLushort *v);\nGLAPI void APIENTRY glVertexAttrib4bvARB (GLuint index, const GLbyte *v);\nGLAPI void APIENTRY glVertexAttrib4dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glVertexAttrib4dvARB (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib4fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glVertexAttrib4fvARB (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib4ivARB (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttrib4sARB (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);\nGLAPI void APIENTRY glVertexAttrib4svARB (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttrib4uivARB (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttrib4usvARB (GLuint index, const GLushort *v);\nGLAPI void APIENTRY glVertexAttribPointerARB (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint index);\nGLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint index);\nGLAPI void APIENTRY glGetVertexAttribdvARB (GLuint index, GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glGetVertexAttribfvARB (GLuint index, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetVertexAttribivARB (GLuint index, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint index, GLenum pname, void **pointer);\n#endif\n#endif /* GL_ARB_vertex_program */\n\n#ifndef GL_ARB_vertex_shader\n#define GL_ARB_vertex_shader 1\n#define GL_VERTEX_SHADER_ARB              0x8B31\n#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A\n#define GL_MAX_VARYING_FLOATS_ARB         0x8B4B\n#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C\n#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D\n#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB   0x8B89\n#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A\ntypedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name);\ntypedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);\ntypedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB programObj, GLuint index, const GLcharARB *name);\nGLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);\nGLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB programObj, const GLcharARB *name);\n#endif\n#endif /* GL_ARB_vertex_shader */\n\n#ifndef GL_ARB_vertex_type_10f_11f_11f_rev\n#define GL_ARB_vertex_type_10f_11f_11f_rev 1\n#endif /* GL_ARB_vertex_type_10f_11f_11f_rev */\n\n#ifndef GL_ARB_vertex_type_2_10_10_10_rev\n#define GL_ARB_vertex_type_2_10_10_10_rev 1\n#endif /* GL_ARB_vertex_type_2_10_10_10_rev */\n\n#ifndef GL_ARB_viewport_array\n#define GL_ARB_viewport_array 1\n#endif /* GL_ARB_viewport_array */\n\n#ifndef GL_ARB_window_pos\n#define GL_ARB_window_pos 1\ntypedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glWindowPos2dARB (GLdouble x, GLdouble y);\nGLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos2fARB (GLfloat x, GLfloat y);\nGLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos2iARB (GLint x, GLint y);\nGLAPI void APIENTRY glWindowPos2ivARB (const GLint *v);\nGLAPI void APIENTRY glWindowPos2sARB (GLshort x, GLshort y);\nGLAPI void APIENTRY glWindowPos2svARB (const GLshort *v);\nGLAPI void APIENTRY glWindowPos3dARB (GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos3fARB (GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos3iARB (GLint x, GLint y, GLint z);\nGLAPI void APIENTRY glWindowPos3ivARB (const GLint *v);\nGLAPI void APIENTRY glWindowPos3sARB (GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glWindowPos3svARB (const GLshort *v);\n#endif\n#endif /* GL_ARB_window_pos */\n\n#ifndef GL_KHR_debug\n#define GL_KHR_debug 1\n#endif /* GL_KHR_debug */\n\n#ifndef GL_KHR_texture_compression_astc_hdr\n#define GL_KHR_texture_compression_astc_hdr 1\n#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR   0x93B0\n#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR   0x93B1\n#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR   0x93B2\n#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR   0x93B3\n#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR   0x93B4\n#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR   0x93B5\n#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR   0x93B6\n#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR   0x93B7\n#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR  0x93B8\n#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR  0x93B9\n#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR  0x93BA\n#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB\n#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC\n#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC\n#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD\n#endif /* GL_KHR_texture_compression_astc_hdr */\n\n#ifndef GL_KHR_texture_compression_astc_ldr\n#define GL_KHR_texture_compression_astc_ldr 1\n#endif /* GL_KHR_texture_compression_astc_ldr */\n\n#ifndef GL_OES_byte_coordinates\n#define GL_OES_byte_coordinates 1\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1BOESPROC) (GLenum texture, GLbyte s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1BVOESPROC) (GLenum texture, const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2BOESPROC) (GLenum texture, GLbyte s, GLbyte t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2BVOESPROC) (GLenum texture, const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3BVOESPROC) (GLenum texture, const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4BVOESPROC) (GLenum texture, const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD1BOESPROC) (GLbyte s);\ntypedef void (APIENTRYP PFNGLTEXCOORD1BVOESPROC) (const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD2BOESPROC) (GLbyte s, GLbyte t);\ntypedef void (APIENTRYP PFNGLTEXCOORD2BVOESPROC) (const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD3BOESPROC) (GLbyte s, GLbyte t, GLbyte r);\ntypedef void (APIENTRYP PFNGLTEXCOORD3BVOESPROC) (const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD4BOESPROC) (GLbyte s, GLbyte t, GLbyte r, GLbyte q);\ntypedef void (APIENTRYP PFNGLTEXCOORD4BVOESPROC) (const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLVERTEX2BOESPROC) (GLbyte x);\ntypedef void (APIENTRYP PFNGLVERTEX2BVOESPROC) (const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLVERTEX3BOESPROC) (GLbyte x, GLbyte y);\ntypedef void (APIENTRYP PFNGLVERTEX3BVOESPROC) (const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLVERTEX4BOESPROC) (GLbyte x, GLbyte y, GLbyte z);\ntypedef void (APIENTRYP PFNGLVERTEX4BVOESPROC) (const GLbyte *coords);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiTexCoord1bOES (GLenum texture, GLbyte s);\nGLAPI void APIENTRY glMultiTexCoord1bvOES (GLenum texture, const GLbyte *coords);\nGLAPI void APIENTRY glMultiTexCoord2bOES (GLenum texture, GLbyte s, GLbyte t);\nGLAPI void APIENTRY glMultiTexCoord2bvOES (GLenum texture, const GLbyte *coords);\nGLAPI void APIENTRY glMultiTexCoord3bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r);\nGLAPI void APIENTRY glMultiTexCoord3bvOES (GLenum texture, const GLbyte *coords);\nGLAPI void APIENTRY glMultiTexCoord4bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q);\nGLAPI void APIENTRY glMultiTexCoord4bvOES (GLenum texture, const GLbyte *coords);\nGLAPI void APIENTRY glTexCoord1bOES (GLbyte s);\nGLAPI void APIENTRY glTexCoord1bvOES (const GLbyte *coords);\nGLAPI void APIENTRY glTexCoord2bOES (GLbyte s, GLbyte t);\nGLAPI void APIENTRY glTexCoord2bvOES (const GLbyte *coords);\nGLAPI void APIENTRY glTexCoord3bOES (GLbyte s, GLbyte t, GLbyte r);\nGLAPI void APIENTRY glTexCoord3bvOES (const GLbyte *coords);\nGLAPI void APIENTRY glTexCoord4bOES (GLbyte s, GLbyte t, GLbyte r, GLbyte q);\nGLAPI void APIENTRY glTexCoord4bvOES (const GLbyte *coords);\nGLAPI void APIENTRY glVertex2bOES (GLbyte x);\nGLAPI void APIENTRY glVertex2bvOES (const GLbyte *coords);\nGLAPI void APIENTRY glVertex3bOES (GLbyte x, GLbyte y);\nGLAPI void APIENTRY glVertex3bvOES (const GLbyte *coords);\nGLAPI void APIENTRY glVertex4bOES (GLbyte x, GLbyte y, GLbyte z);\nGLAPI void APIENTRY glVertex4bvOES (const GLbyte *coords);\n#endif\n#endif /* GL_OES_byte_coordinates */\n\n#ifndef GL_OES_compressed_paletted_texture\n#define GL_OES_compressed_paletted_texture 1\n#define GL_PALETTE4_RGB8_OES              0x8B90\n#define GL_PALETTE4_RGBA8_OES             0x8B91\n#define GL_PALETTE4_R5_G6_B5_OES          0x8B92\n#define GL_PALETTE4_RGBA4_OES             0x8B93\n#define GL_PALETTE4_RGB5_A1_OES           0x8B94\n#define GL_PALETTE8_RGB8_OES              0x8B95\n#define GL_PALETTE8_RGBA8_OES             0x8B96\n#define GL_PALETTE8_R5_G6_B5_OES          0x8B97\n#define GL_PALETTE8_RGBA4_OES             0x8B98\n#define GL_PALETTE8_RGB5_A1_OES           0x8B99\n#endif /* GL_OES_compressed_paletted_texture */\n\n#ifndef GL_OES_fixed_point\n#define GL_OES_fixed_point 1\ntypedef GLint GLfixed;\n#define GL_FIXED_OES                      0x140C\ntypedef void (APIENTRYP PFNGLALPHAFUNCXOESPROC) (GLenum func, GLfixed ref);\ntypedef void (APIENTRYP PFNGLCLEARCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\ntypedef void (APIENTRYP PFNGLCLEARDEPTHXOESPROC) (GLfixed depth);\ntypedef void (APIENTRYP PFNGLCLIPPLANEXOESPROC) (GLenum plane, const GLfixed *equation);\ntypedef void (APIENTRYP PFNGLCOLOR4XOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\ntypedef void (APIENTRYP PFNGLDEPTHRANGEXOESPROC) (GLfixed n, GLfixed f);\ntypedef void (APIENTRYP PFNGLFOGXOESPROC) (GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLFOGXVOESPROC) (GLenum pname, const GLfixed *param);\ntypedef void (APIENTRYP PFNGLFRUSTUMXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f);\ntypedef void (APIENTRYP PFNGLGETCLIPPLANEXOESPROC) (GLenum plane, GLfixed *equation);\ntypedef void (APIENTRYP PFNGLGETFIXEDVOESPROC) (GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLGETTEXENVXVOESPROC) (GLenum target, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLGETTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLLIGHTMODELXOESPROC) (GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLLIGHTMODELXVOESPROC) (GLenum pname, const GLfixed *param);\ntypedef void (APIENTRYP PFNGLLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLLIGHTXVOESPROC) (GLenum light, GLenum pname, const GLfixed *params);\ntypedef void (APIENTRYP PFNGLLINEWIDTHXOESPROC) (GLfixed width);\ntypedef void (APIENTRYP PFNGLLOADMATRIXXOESPROC) (const GLfixed *m);\ntypedef void (APIENTRYP PFNGLMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLMATERIALXVOESPROC) (GLenum face, GLenum pname, const GLfixed *param);\ntypedef void (APIENTRYP PFNGLMULTMATRIXXOESPROC) (const GLfixed *m);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q);\ntypedef void (APIENTRYP PFNGLNORMAL3XOESPROC) (GLfixed nx, GLfixed ny, GLfixed nz);\ntypedef void (APIENTRYP PFNGLORTHOXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERXVOESPROC) (GLenum pname, const GLfixed *params);\ntypedef void (APIENTRYP PFNGLPOINTSIZEXOESPROC) (GLfixed size);\ntypedef void (APIENTRYP PFNGLPOLYGONOFFSETXOESPROC) (GLfixed factor, GLfixed units);\ntypedef void (APIENTRYP PFNGLROTATEXOESPROC) (GLfixed angle, GLfixed x, GLfixed y, GLfixed z);\ntypedef void (APIENTRYP PFNGLSAMPLECOVERAGEOESPROC) (GLfixed value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLSCALEXOESPROC) (GLfixed x, GLfixed y, GLfixed z);\ntypedef void (APIENTRYP PFNGLTEXENVXOESPROC) (GLenum target, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLTEXENVXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params);\ntypedef void (APIENTRYP PFNGLTEXPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params);\ntypedef void (APIENTRYP PFNGLTRANSLATEXOESPROC) (GLfixed x, GLfixed y, GLfixed z);\ntypedef void (APIENTRYP PFNGLACCUMXOESPROC) (GLenum op, GLfixed value);\ntypedef void (APIENTRYP PFNGLBITMAPXOESPROC) (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap);\ntypedef void (APIENTRYP PFNGLBLENDCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\ntypedef void (APIENTRYP PFNGLCLEARACCUMXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\ntypedef void (APIENTRYP PFNGLCOLOR3XOESPROC) (GLfixed red, GLfixed green, GLfixed blue);\ntypedef void (APIENTRYP PFNGLCOLOR3XVOESPROC) (const GLfixed *components);\ntypedef void (APIENTRYP PFNGLCOLOR4XVOESPROC) (const GLfixed *components);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params);\ntypedef void (APIENTRYP PFNGLEVALCOORD1XOESPROC) (GLfixed u);\ntypedef void (APIENTRYP PFNGLEVALCOORD1XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLEVALCOORD2XOESPROC) (GLfixed u, GLfixed v);\ntypedef void (APIENTRYP PFNGLEVALCOORD2XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLFEEDBACKBUFFERXOESPROC) (GLsizei n, GLenum type, const GLfixed *buffer);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLGETLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLGETMAPXVOESPROC) (GLenum target, GLenum query, GLfixed *v);\ntypedef void (APIENTRYP PFNGLGETMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLGETPIXELMAPXVPROC) (GLenum map, GLint size, GLfixed *values);\ntypedef void (APIENTRYP PFNGLGETTEXGENXVOESPROC) (GLenum coord, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERXVOESPROC) (GLenum target, GLint level, GLenum pname, GLfixed *params);\ntypedef void (APIENTRYP PFNGLINDEXXOESPROC) (GLfixed component);\ntypedef void (APIENTRYP PFNGLINDEXXVOESPROC) (const GLfixed *component);\ntypedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXXOESPROC) (const GLfixed *m);\ntypedef void (APIENTRYP PFNGLMAP1XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points);\ntypedef void (APIENTRYP PFNGLMAP2XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points);\ntypedef void (APIENTRYP PFNGLMAPGRID1XOESPROC) (GLint n, GLfixed u1, GLfixed u2);\ntypedef void (APIENTRYP PFNGLMAPGRID2XOESPROC) (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2);\ntypedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXXOESPROC) (const GLfixed *m);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1XOESPROC) (GLenum texture, GLfixed s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1XVOESPROC) (GLenum texture, const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2XOESPROC) (GLenum texture, GLfixed s, GLfixed t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2XVOESPROC) (GLenum texture, const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3XVOESPROC) (GLenum texture, const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4XVOESPROC) (GLenum texture, const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLNORMAL3XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLPASSTHROUGHXOESPROC) (GLfixed token);\ntypedef void (APIENTRYP PFNGLPIXELMAPXPROC) (GLenum map, GLint size, const GLfixed *values);\ntypedef void (APIENTRYP PFNGLPIXELSTOREXPROC) (GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLPIXELTRANSFERXOESPROC) (GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLPIXELZOOMXOESPROC) (GLfixed xfactor, GLfixed yfactor);\ntypedef void (APIENTRYP PFNGLPRIORITIZETEXTURESXOESPROC) (GLsizei n, const GLuint *textures, const GLfixed *priorities);\ntypedef void (APIENTRYP PFNGLRASTERPOS2XOESPROC) (GLfixed x, GLfixed y);\ntypedef void (APIENTRYP PFNGLRASTERPOS2XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLRASTERPOS3XOESPROC) (GLfixed x, GLfixed y, GLfixed z);\ntypedef void (APIENTRYP PFNGLRASTERPOS3XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLRASTERPOS4XOESPROC) (GLfixed x, GLfixed y, GLfixed z, GLfixed w);\ntypedef void (APIENTRYP PFNGLRASTERPOS4XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLRECTXOESPROC) (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2);\ntypedef void (APIENTRYP PFNGLRECTXVOESPROC) (const GLfixed *v1, const GLfixed *v2);\ntypedef void (APIENTRYP PFNGLTEXCOORD1XOESPROC) (GLfixed s);\ntypedef void (APIENTRYP PFNGLTEXCOORD1XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD2XOESPROC) (GLfixed s, GLfixed t);\ntypedef void (APIENTRYP PFNGLTEXCOORD2XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD3XOESPROC) (GLfixed s, GLfixed t, GLfixed r);\ntypedef void (APIENTRYP PFNGLTEXCOORD3XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLTEXCOORD4XOESPROC) (GLfixed s, GLfixed t, GLfixed r, GLfixed q);\ntypedef void (APIENTRYP PFNGLTEXCOORD4XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLTEXGENXOESPROC) (GLenum coord, GLenum pname, GLfixed param);\ntypedef void (APIENTRYP PFNGLTEXGENXVOESPROC) (GLenum coord, GLenum pname, const GLfixed *params);\ntypedef void (APIENTRYP PFNGLVERTEX2XOESPROC) (GLfixed x);\ntypedef void (APIENTRYP PFNGLVERTEX2XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLVERTEX3XOESPROC) (GLfixed x, GLfixed y);\ntypedef void (APIENTRYP PFNGLVERTEX3XVOESPROC) (const GLfixed *coords);\ntypedef void (APIENTRYP PFNGLVERTEX4XOESPROC) (GLfixed x, GLfixed y, GLfixed z);\ntypedef void (APIENTRYP PFNGLVERTEX4XVOESPROC) (const GLfixed *coords);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glAlphaFuncxOES (GLenum func, GLfixed ref);\nGLAPI void APIENTRY glClearColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\nGLAPI void APIENTRY glClearDepthxOES (GLfixed depth);\nGLAPI void APIENTRY glClipPlanexOES (GLenum plane, const GLfixed *equation);\nGLAPI void APIENTRY glColor4xOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\nGLAPI void APIENTRY glDepthRangexOES (GLfixed n, GLfixed f);\nGLAPI void APIENTRY glFogxOES (GLenum pname, GLfixed param);\nGLAPI void APIENTRY glFogxvOES (GLenum pname, const GLfixed *param);\nGLAPI void APIENTRY glFrustumxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f);\nGLAPI void APIENTRY glGetClipPlanexOES (GLenum plane, GLfixed *equation);\nGLAPI void APIENTRY glGetFixedvOES (GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glGetTexEnvxvOES (GLenum target, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glGetTexParameterxvOES (GLenum target, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glLightModelxOES (GLenum pname, GLfixed param);\nGLAPI void APIENTRY glLightModelxvOES (GLenum pname, const GLfixed *param);\nGLAPI void APIENTRY glLightxOES (GLenum light, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glLightxvOES (GLenum light, GLenum pname, const GLfixed *params);\nGLAPI void APIENTRY glLineWidthxOES (GLfixed width);\nGLAPI void APIENTRY glLoadMatrixxOES (const GLfixed *m);\nGLAPI void APIENTRY glMaterialxOES (GLenum face, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glMaterialxvOES (GLenum face, GLenum pname, const GLfixed *param);\nGLAPI void APIENTRY glMultMatrixxOES (const GLfixed *m);\nGLAPI void APIENTRY glMultiTexCoord4xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q);\nGLAPI void APIENTRY glNormal3xOES (GLfixed nx, GLfixed ny, GLfixed nz);\nGLAPI void APIENTRY glOrthoxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f);\nGLAPI void APIENTRY glPointParameterxvOES (GLenum pname, const GLfixed *params);\nGLAPI void APIENTRY glPointSizexOES (GLfixed size);\nGLAPI void APIENTRY glPolygonOffsetxOES (GLfixed factor, GLfixed units);\nGLAPI void APIENTRY glRotatexOES (GLfixed angle, GLfixed x, GLfixed y, GLfixed z);\nGLAPI void APIENTRY glSampleCoverageOES (GLfixed value, GLboolean invert);\nGLAPI void APIENTRY glScalexOES (GLfixed x, GLfixed y, GLfixed z);\nGLAPI void APIENTRY glTexEnvxOES (GLenum target, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glTexEnvxvOES (GLenum target, GLenum pname, const GLfixed *params);\nGLAPI void APIENTRY glTexParameterxOES (GLenum target, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glTexParameterxvOES (GLenum target, GLenum pname, const GLfixed *params);\nGLAPI void APIENTRY glTranslatexOES (GLfixed x, GLfixed y, GLfixed z);\nGLAPI void APIENTRY glAccumxOES (GLenum op, GLfixed value);\nGLAPI void APIENTRY glBitmapxOES (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap);\nGLAPI void APIENTRY glBlendColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\nGLAPI void APIENTRY glClearAccumxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);\nGLAPI void APIENTRY glColor3xOES (GLfixed red, GLfixed green, GLfixed blue);\nGLAPI void APIENTRY glColor3xvOES (const GLfixed *components);\nGLAPI void APIENTRY glColor4xvOES (const GLfixed *components);\nGLAPI void APIENTRY glConvolutionParameterxOES (GLenum target, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glConvolutionParameterxvOES (GLenum target, GLenum pname, const GLfixed *params);\nGLAPI void APIENTRY glEvalCoord1xOES (GLfixed u);\nGLAPI void APIENTRY glEvalCoord1xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glEvalCoord2xOES (GLfixed u, GLfixed v);\nGLAPI void APIENTRY glEvalCoord2xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glFeedbackBufferxOES (GLsizei n, GLenum type, const GLfixed *buffer);\nGLAPI void APIENTRY glGetConvolutionParameterxvOES (GLenum target, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glGetHistogramParameterxvOES (GLenum target, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glGetLightxOES (GLenum light, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glGetMapxvOES (GLenum target, GLenum query, GLfixed *v);\nGLAPI void APIENTRY glGetMaterialxOES (GLenum face, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glGetPixelMapxv (GLenum map, GLint size, GLfixed *values);\nGLAPI void APIENTRY glGetTexGenxvOES (GLenum coord, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glGetTexLevelParameterxvOES (GLenum target, GLint level, GLenum pname, GLfixed *params);\nGLAPI void APIENTRY glIndexxOES (GLfixed component);\nGLAPI void APIENTRY glIndexxvOES (const GLfixed *component);\nGLAPI void APIENTRY glLoadTransposeMatrixxOES (const GLfixed *m);\nGLAPI void APIENTRY glMap1xOES (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points);\nGLAPI void APIENTRY glMap2xOES (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points);\nGLAPI void APIENTRY glMapGrid1xOES (GLint n, GLfixed u1, GLfixed u2);\nGLAPI void APIENTRY glMapGrid2xOES (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2);\nGLAPI void APIENTRY glMultTransposeMatrixxOES (const GLfixed *m);\nGLAPI void APIENTRY glMultiTexCoord1xOES (GLenum texture, GLfixed s);\nGLAPI void APIENTRY glMultiTexCoord1xvOES (GLenum texture, const GLfixed *coords);\nGLAPI void APIENTRY glMultiTexCoord2xOES (GLenum texture, GLfixed s, GLfixed t);\nGLAPI void APIENTRY glMultiTexCoord2xvOES (GLenum texture, const GLfixed *coords);\nGLAPI void APIENTRY glMultiTexCoord3xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r);\nGLAPI void APIENTRY glMultiTexCoord3xvOES (GLenum texture, const GLfixed *coords);\nGLAPI void APIENTRY glMultiTexCoord4xvOES (GLenum texture, const GLfixed *coords);\nGLAPI void APIENTRY glNormal3xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glPassThroughxOES (GLfixed token);\nGLAPI void APIENTRY glPixelMapx (GLenum map, GLint size, const GLfixed *values);\nGLAPI void APIENTRY glPixelStorex (GLenum pname, GLfixed param);\nGLAPI void APIENTRY glPixelTransferxOES (GLenum pname, GLfixed param);\nGLAPI void APIENTRY glPixelZoomxOES (GLfixed xfactor, GLfixed yfactor);\nGLAPI void APIENTRY glPrioritizeTexturesxOES (GLsizei n, const GLuint *textures, const GLfixed *priorities);\nGLAPI void APIENTRY glRasterPos2xOES (GLfixed x, GLfixed y);\nGLAPI void APIENTRY glRasterPos2xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glRasterPos3xOES (GLfixed x, GLfixed y, GLfixed z);\nGLAPI void APIENTRY glRasterPos3xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glRasterPos4xOES (GLfixed x, GLfixed y, GLfixed z, GLfixed w);\nGLAPI void APIENTRY glRasterPos4xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glRectxOES (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2);\nGLAPI void APIENTRY glRectxvOES (const GLfixed *v1, const GLfixed *v2);\nGLAPI void APIENTRY glTexCoord1xOES (GLfixed s);\nGLAPI void APIENTRY glTexCoord1xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glTexCoord2xOES (GLfixed s, GLfixed t);\nGLAPI void APIENTRY glTexCoord2xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glTexCoord3xOES (GLfixed s, GLfixed t, GLfixed r);\nGLAPI void APIENTRY glTexCoord3xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glTexCoord4xOES (GLfixed s, GLfixed t, GLfixed r, GLfixed q);\nGLAPI void APIENTRY glTexCoord4xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glTexGenxOES (GLenum coord, GLenum pname, GLfixed param);\nGLAPI void APIENTRY glTexGenxvOES (GLenum coord, GLenum pname, const GLfixed *params);\nGLAPI void APIENTRY glVertex2xOES (GLfixed x);\nGLAPI void APIENTRY glVertex2xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glVertex3xOES (GLfixed x, GLfixed y);\nGLAPI void APIENTRY glVertex3xvOES (const GLfixed *coords);\nGLAPI void APIENTRY glVertex4xOES (GLfixed x, GLfixed y, GLfixed z);\nGLAPI void APIENTRY glVertex4xvOES (const GLfixed *coords);\n#endif\n#endif /* GL_OES_fixed_point */\n\n#ifndef GL_OES_query_matrix\n#define GL_OES_query_matrix 1\ntypedef GLbitfield (APIENTRYP PFNGLQUERYMATRIXXOESPROC) (GLfixed *mantissa, GLint *exponent);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLbitfield APIENTRY glQueryMatrixxOES (GLfixed *mantissa, GLint *exponent);\n#endif\n#endif /* GL_OES_query_matrix */\n\n#ifndef GL_OES_read_format\n#define GL_OES_read_format 1\n#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A\n#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B\n#endif /* GL_OES_read_format */\n\n#ifndef GL_OES_single_precision\n#define GL_OES_single_precision 1\ntypedef void (APIENTRYP PFNGLCLEARDEPTHFOESPROC) (GLclampf depth);\ntypedef void (APIENTRYP PFNGLCLIPPLANEFOESPROC) (GLenum plane, const GLfloat *equation);\ntypedef void (APIENTRYP PFNGLDEPTHRANGEFOESPROC) (GLclampf n, GLclampf f);\ntypedef void (APIENTRYP PFNGLFRUSTUMFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f);\ntypedef void (APIENTRYP PFNGLGETCLIPPLANEFOESPROC) (GLenum plane, GLfloat *equation);\ntypedef void (APIENTRYP PFNGLORTHOFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glClearDepthfOES (GLclampf depth);\nGLAPI void APIENTRY glClipPlanefOES (GLenum plane, const GLfloat *equation);\nGLAPI void APIENTRY glDepthRangefOES (GLclampf n, GLclampf f);\nGLAPI void APIENTRY glFrustumfOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f);\nGLAPI void APIENTRY glGetClipPlanefOES (GLenum plane, GLfloat *equation);\nGLAPI void APIENTRY glOrthofOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f);\n#endif\n#endif /* GL_OES_single_precision */\n\n#ifndef GL_3DFX_multisample\n#define GL_3DFX_multisample 1\n#define GL_MULTISAMPLE_3DFX               0x86B2\n#define GL_SAMPLE_BUFFERS_3DFX            0x86B3\n#define GL_SAMPLES_3DFX                   0x86B4\n#define GL_MULTISAMPLE_BIT_3DFX           0x20000000\n#endif /* GL_3DFX_multisample */\n\n#ifndef GL_3DFX_tbuffer\n#define GL_3DFX_tbuffer 1\ntypedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTbufferMask3DFX (GLuint mask);\n#endif\n#endif /* GL_3DFX_tbuffer */\n\n#ifndef GL_3DFX_texture_compression_FXT1\n#define GL_3DFX_texture_compression_FXT1 1\n#define GL_COMPRESSED_RGB_FXT1_3DFX       0x86B0\n#define GL_COMPRESSED_RGBA_FXT1_3DFX      0x86B1\n#endif /* GL_3DFX_texture_compression_FXT1 */\n\n#ifndef GL_AMD_blend_minmax_factor\n#define GL_AMD_blend_minmax_factor 1\n#define GL_FACTOR_MIN_AMD                 0x901C\n#define GL_FACTOR_MAX_AMD                 0x901D\n#endif /* GL_AMD_blend_minmax_factor */\n\n#ifndef GL_AMD_conservative_depth\n#define GL_AMD_conservative_depth 1\n#endif /* GL_AMD_conservative_depth */\n\n#ifndef GL_AMD_debug_output\n#define GL_AMD_debug_output 1\ntypedef void (APIENTRY  *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam);\n#define GL_MAX_DEBUG_MESSAGE_LENGTH_AMD   0x9143\n#define GL_MAX_DEBUG_LOGGED_MESSAGES_AMD  0x9144\n#define GL_DEBUG_LOGGED_MESSAGES_AMD      0x9145\n#define GL_DEBUG_SEVERITY_HIGH_AMD        0x9146\n#define GL_DEBUG_SEVERITY_MEDIUM_AMD      0x9147\n#define GL_DEBUG_SEVERITY_LOW_AMD         0x9148\n#define GL_DEBUG_CATEGORY_API_ERROR_AMD   0x9149\n#define GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD 0x914A\n#define GL_DEBUG_CATEGORY_DEPRECATION_AMD 0x914B\n#define GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD 0x914C\n#define GL_DEBUG_CATEGORY_PERFORMANCE_AMD 0x914D\n#define GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD 0x914E\n#define GL_DEBUG_CATEGORY_APPLICATION_AMD 0x914F\n#define GL_DEBUG_CATEGORY_OTHER_AMD       0x9150\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGEENABLEAMDPROC) (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTAMDPROC) (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf);\ntypedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKAMDPROC) (GLDEBUGPROCAMD callback, void *userParam);\ntypedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDebugMessageEnableAMD (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);\nGLAPI void APIENTRY glDebugMessageInsertAMD (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf);\nGLAPI void APIENTRY glDebugMessageCallbackAMD (GLDEBUGPROCAMD callback, void *userParam);\nGLAPI GLuint APIENTRY glGetDebugMessageLogAMD (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message);\n#endif\n#endif /* GL_AMD_debug_output */\n\n#ifndef GL_AMD_depth_clamp_separate\n#define GL_AMD_depth_clamp_separate 1\n#define GL_DEPTH_CLAMP_NEAR_AMD           0x901E\n#define GL_DEPTH_CLAMP_FAR_AMD            0x901F\n#endif /* GL_AMD_depth_clamp_separate */\n\n#ifndef GL_AMD_draw_buffers_blend\n#define GL_AMD_draw_buffers_blend 1\ntypedef void (APIENTRYP PFNGLBLENDFUNCINDEXEDAMDPROC) (GLuint buf, GLenum src, GLenum dst);\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONINDEXEDAMDPROC) (GLuint buf, GLenum mode);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncIndexedAMD (GLuint buf, GLenum src, GLenum dst);\nGLAPI void APIENTRY glBlendFuncSeparateIndexedAMD (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);\nGLAPI void APIENTRY glBlendEquationIndexedAMD (GLuint buf, GLenum mode);\nGLAPI void APIENTRY glBlendEquationSeparateIndexedAMD (GLuint buf, GLenum modeRGB, GLenum modeAlpha);\n#endif\n#endif /* GL_AMD_draw_buffers_blend */\n\n#ifndef GL_AMD_interleaved_elements\n#define GL_AMD_interleaved_elements 1\n#define GL_VERTEX_ELEMENT_SWIZZLE_AMD     0x91A4\n#define GL_VERTEX_ID_SWIZZLE_AMD          0x91A5\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBPARAMETERIAMDPROC) (GLuint index, GLenum pname, GLint param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribParameteriAMD (GLuint index, GLenum pname, GLint param);\n#endif\n#endif /* GL_AMD_interleaved_elements */\n\n#ifndef GL_AMD_multi_draw_indirect\n#define GL_AMD_multi_draw_indirect 1\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTAMDPROC) (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTAMDPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride);\nGLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride);\n#endif\n#endif /* GL_AMD_multi_draw_indirect */\n\n#ifndef GL_AMD_name_gen_delete\n#define GL_AMD_name_gen_delete 1\n#define GL_DATA_BUFFER_AMD                0x9151\n#define GL_PERFORMANCE_MONITOR_AMD        0x9152\n#define GL_QUERY_OBJECT_AMD               0x9153\n#define GL_VERTEX_ARRAY_OBJECT_AMD        0x9154\n#define GL_SAMPLER_OBJECT_AMD             0x9155\ntypedef void (APIENTRYP PFNGLGENNAMESAMDPROC) (GLenum identifier, GLuint num, GLuint *names);\ntypedef void (APIENTRYP PFNGLDELETENAMESAMDPROC) (GLenum identifier, GLuint num, const GLuint *names);\ntypedef GLboolean (APIENTRYP PFNGLISNAMEAMDPROC) (GLenum identifier, GLuint name);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenNamesAMD (GLenum identifier, GLuint num, GLuint *names);\nGLAPI void APIENTRY glDeleteNamesAMD (GLenum identifier, GLuint num, const GLuint *names);\nGLAPI GLboolean APIENTRY glIsNameAMD (GLenum identifier, GLuint name);\n#endif\n#endif /* GL_AMD_name_gen_delete */\n\n#ifndef GL_AMD_occlusion_query_event\n#define GL_AMD_occlusion_query_event 1\n#define GL_OCCLUSION_QUERY_EVENT_MASK_AMD 0x874F\n#define GL_QUERY_DEPTH_PASS_EVENT_BIT_AMD 0x00000001\n#define GL_QUERY_DEPTH_FAIL_EVENT_BIT_AMD 0x00000002\n#define GL_QUERY_STENCIL_FAIL_EVENT_BIT_AMD 0x00000004\n#define GL_QUERY_DEPTH_BOUNDS_FAIL_EVENT_BIT_AMD 0x00000008\n#define GL_QUERY_ALL_EVENT_BITS_AMD       0xFFFFFFFF\ntypedef void (APIENTRYP PFNGLQUERYOBJECTPARAMETERUIAMDPROC) (GLenum target, GLuint id, GLenum pname, GLuint param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glQueryObjectParameteruiAMD (GLenum target, GLuint id, GLenum pname, GLuint param);\n#endif\n#endif /* GL_AMD_occlusion_query_event */\n\n#ifndef GL_AMD_performance_monitor\n#define GL_AMD_performance_monitor 1\n#define GL_COUNTER_TYPE_AMD               0x8BC0\n#define GL_COUNTER_RANGE_AMD              0x8BC1\n#define GL_UNSIGNED_INT64_AMD             0x8BC2\n#define GL_PERCENTAGE_AMD                 0x8BC3\n#define GL_PERFMON_RESULT_AVAILABLE_AMD   0x8BC4\n#define GL_PERFMON_RESULT_SIZE_AMD        0x8BC5\n#define GL_PERFMON_RESULT_AMD             0x8BC6\ntypedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups);\ntypedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);\ntypedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);\ntypedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);\ntypedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data);\ntypedef void (APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);\ntypedef void (APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);\ntypedef void (APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList);\ntypedef void (APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);\ntypedef void (APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);\ntypedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups);\nGLAPI void APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);\nGLAPI void APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);\nGLAPI void APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);\nGLAPI void APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data);\nGLAPI void APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors);\nGLAPI void APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors);\nGLAPI void APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList);\nGLAPI void APIENTRY glBeginPerfMonitorAMD (GLuint monitor);\nGLAPI void APIENTRY glEndPerfMonitorAMD (GLuint monitor);\nGLAPI void APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);\n#endif\n#endif /* GL_AMD_performance_monitor */\n\n#ifndef GL_AMD_pinned_memory\n#define GL_AMD_pinned_memory 1\n#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160\n#endif /* GL_AMD_pinned_memory */\n\n#ifndef GL_AMD_query_buffer_object\n#define GL_AMD_query_buffer_object 1\n#define GL_QUERY_BUFFER_AMD               0x9192\n#define GL_QUERY_BUFFER_BINDING_AMD       0x9193\n#define GL_QUERY_RESULT_NO_WAIT_AMD       0x9194\n#endif /* GL_AMD_query_buffer_object */\n\n#ifndef GL_AMD_sample_positions\n#define GL_AMD_sample_positions 1\n#define GL_SUBSAMPLE_DISTANCE_AMD         0x883F\ntypedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val);\n#endif\n#endif /* GL_AMD_sample_positions */\n\n#ifndef GL_AMD_seamless_cubemap_per_texture\n#define GL_AMD_seamless_cubemap_per_texture 1\n#endif /* GL_AMD_seamless_cubemap_per_texture */\n\n#ifndef GL_AMD_shader_atomic_counter_ops\n#define GL_AMD_shader_atomic_counter_ops 1\n#endif /* GL_AMD_shader_atomic_counter_ops */\n\n#ifndef GL_AMD_shader_stencil_export\n#define GL_AMD_shader_stencil_export 1\n#endif /* GL_AMD_shader_stencil_export */\n\n#ifndef GL_AMD_shader_trinary_minmax\n#define GL_AMD_shader_trinary_minmax 1\n#endif /* GL_AMD_shader_trinary_minmax */\n\n#ifndef GL_AMD_sparse_texture\n#define GL_AMD_sparse_texture 1\n#define GL_VIRTUAL_PAGE_SIZE_X_AMD        0x9195\n#define GL_VIRTUAL_PAGE_SIZE_Y_AMD        0x9196\n#define GL_VIRTUAL_PAGE_SIZE_Z_AMD        0x9197\n#define GL_MAX_SPARSE_TEXTURE_SIZE_AMD    0x9198\n#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_AMD 0x9199\n#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS 0x919A\n#define GL_MIN_SPARSE_LEVEL_AMD           0x919B\n#define GL_MIN_LOD_WARNING_AMD            0x919C\n#define GL_TEXTURE_STORAGE_SPARSE_BIT_AMD 0x00000001\ntypedef void (APIENTRYP PFNGLTEXSTORAGESPARSEAMDPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags);\ntypedef void (APIENTRYP PFNGLTEXTURESTORAGESPARSEAMDPROC) (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexStorageSparseAMD (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags);\nGLAPI void APIENTRY glTextureStorageSparseAMD (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags);\n#endif\n#endif /* GL_AMD_sparse_texture */\n\n#ifndef GL_AMD_stencil_operation_extended\n#define GL_AMD_stencil_operation_extended 1\n#define GL_SET_AMD                        0x874A\n#define GL_REPLACE_VALUE_AMD              0x874B\n#define GL_STENCIL_OP_VALUE_AMD           0x874C\n#define GL_STENCIL_BACK_OP_VALUE_AMD      0x874D\ntypedef void (APIENTRYP PFNGLSTENCILOPVALUEAMDPROC) (GLenum face, GLuint value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glStencilOpValueAMD (GLenum face, GLuint value);\n#endif\n#endif /* GL_AMD_stencil_operation_extended */\n\n#ifndef GL_AMD_texture_texture4\n#define GL_AMD_texture_texture4 1\n#endif /* GL_AMD_texture_texture4 */\n\n#ifndef GL_AMD_transform_feedback3_lines_triangles\n#define GL_AMD_transform_feedback3_lines_triangles 1\n#endif /* GL_AMD_transform_feedback3_lines_triangles */\n\n#ifndef GL_AMD_vertex_shader_layer\n#define GL_AMD_vertex_shader_layer 1\n#endif /* GL_AMD_vertex_shader_layer */\n\n#ifndef GL_AMD_vertex_shader_tessellator\n#define GL_AMD_vertex_shader_tessellator 1\n#define GL_SAMPLER_BUFFER_AMD             0x9001\n#define GL_INT_SAMPLER_BUFFER_AMD         0x9002\n#define GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD 0x9003\n#define GL_TESSELLATION_MODE_AMD          0x9004\n#define GL_TESSELLATION_FACTOR_AMD        0x9005\n#define GL_DISCRETE_AMD                   0x9006\n#define GL_CONTINUOUS_AMD                 0x9007\ntypedef void (APIENTRYP PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor);\ntypedef void (APIENTRYP PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTessellationFactorAMD (GLfloat factor);\nGLAPI void APIENTRY glTessellationModeAMD (GLenum mode);\n#endif\n#endif /* GL_AMD_vertex_shader_tessellator */\n\n#ifndef GL_AMD_vertex_shader_viewport_index\n#define GL_AMD_vertex_shader_viewport_index 1\n#endif /* GL_AMD_vertex_shader_viewport_index */\n\n#ifndef GL_APPLE_aux_depth_stencil\n#define GL_APPLE_aux_depth_stencil 1\n#define GL_AUX_DEPTH_STENCIL_APPLE        0x8A14\n#endif /* GL_APPLE_aux_depth_stencil */\n\n#ifndef GL_APPLE_client_storage\n#define GL_APPLE_client_storage 1\n#define GL_UNPACK_CLIENT_STORAGE_APPLE    0x85B2\n#endif /* GL_APPLE_client_storage */\n\n#ifndef GL_APPLE_element_array\n#define GL_APPLE_element_array 1\n#define GL_ELEMENT_ARRAY_APPLE            0x8A0C\n#define GL_ELEMENT_ARRAY_TYPE_APPLE       0x8A0D\n#define GL_ELEMENT_ARRAY_POINTER_APPLE    0x8A0E\ntypedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const void *pointer);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);\ntypedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glElementPointerAPPLE (GLenum type, const void *pointer);\nGLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum mode, GLint first, GLsizei count);\nGLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);\nGLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);\nGLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);\n#endif\n#endif /* GL_APPLE_element_array */\n\n#ifndef GL_APPLE_fence\n#define GL_APPLE_fence 1\n#define GL_DRAW_PIXELS_APPLE              0x8A0A\n#define GL_FENCE_APPLE                    0x8A0B\ntypedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences);\ntypedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences);\ntypedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence);\ntypedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence);\ntypedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence);\ntypedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence);\ntypedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name);\ntypedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenFencesAPPLE (GLsizei n, GLuint *fences);\nGLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei n, const GLuint *fences);\nGLAPI void APIENTRY glSetFenceAPPLE (GLuint fence);\nGLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint fence);\nGLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint fence);\nGLAPI void APIENTRY glFinishFenceAPPLE (GLuint fence);\nGLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum object, GLuint name);\nGLAPI void APIENTRY glFinishObjectAPPLE (GLenum object, GLint name);\n#endif\n#endif /* GL_APPLE_fence */\n\n#ifndef GL_APPLE_float_pixels\n#define GL_APPLE_float_pixels 1\n#define GL_HALF_APPLE                     0x140B\n#define GL_RGBA_FLOAT32_APPLE             0x8814\n#define GL_RGB_FLOAT32_APPLE              0x8815\n#define GL_ALPHA_FLOAT32_APPLE            0x8816\n#define GL_INTENSITY_FLOAT32_APPLE        0x8817\n#define GL_LUMINANCE_FLOAT32_APPLE        0x8818\n#define GL_LUMINANCE_ALPHA_FLOAT32_APPLE  0x8819\n#define GL_RGBA_FLOAT16_APPLE             0x881A\n#define GL_RGB_FLOAT16_APPLE              0x881B\n#define GL_ALPHA_FLOAT16_APPLE            0x881C\n#define GL_INTENSITY_FLOAT16_APPLE        0x881D\n#define GL_LUMINANCE_FLOAT16_APPLE        0x881E\n#define GL_LUMINANCE_ALPHA_FLOAT16_APPLE  0x881F\n#define GL_COLOR_FLOAT_APPLE              0x8A0F\n#endif /* GL_APPLE_float_pixels */\n\n#ifndef GL_APPLE_flush_buffer_range\n#define GL_APPLE_flush_buffer_range 1\n#define GL_BUFFER_SERIALIZED_MODIFY_APPLE 0x8A12\n#define GL_BUFFER_FLUSHING_UNMAP_APPLE    0x8A13\ntypedef void (APIENTRYP PFNGLBUFFERPARAMETERIAPPLEPROC) (GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target, GLintptr offset, GLsizeiptr size);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBufferParameteriAPPLE (GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glFlushMappedBufferRangeAPPLE (GLenum target, GLintptr offset, GLsizeiptr size);\n#endif\n#endif /* GL_APPLE_flush_buffer_range */\n\n#ifndef GL_APPLE_object_purgeable\n#define GL_APPLE_object_purgeable 1\n#define GL_BUFFER_OBJECT_APPLE            0x85B3\n#define GL_RELEASED_APPLE                 0x8A19\n#define GL_VOLATILE_APPLE                 0x8A1A\n#define GL_RETAINED_APPLE                 0x8A1B\n#define GL_UNDEFINED_APPLE                0x8A1C\n#define GL_PURGEABLE_APPLE                0x8A1D\ntypedef GLenum (APIENTRYP PFNGLOBJECTPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option);\ntypedef GLenum (APIENTRYP PFNGLOBJECTUNPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option);\ntypedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVAPPLEPROC) (GLenum objectType, GLuint name, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLenum APIENTRY glObjectPurgeableAPPLE (GLenum objectType, GLuint name, GLenum option);\nGLAPI GLenum APIENTRY glObjectUnpurgeableAPPLE (GLenum objectType, GLuint name, GLenum option);\nGLAPI void APIENTRY glGetObjectParameterivAPPLE (GLenum objectType, GLuint name, GLenum pname, GLint *params);\n#endif\n#endif /* GL_APPLE_object_purgeable */\n\n#ifndef GL_APPLE_rgb_422\n#define GL_APPLE_rgb_422 1\n#define GL_RGB_422_APPLE                  0x8A1F\n#define GL_UNSIGNED_SHORT_8_8_APPLE       0x85BA\n#define GL_UNSIGNED_SHORT_8_8_REV_APPLE   0x85BB\n#define GL_RGB_RAW_422_APPLE              0x8A51\n#endif /* GL_APPLE_rgb_422 */\n\n#ifndef GL_APPLE_row_bytes\n#define GL_APPLE_row_bytes 1\n#define GL_PACK_ROW_BYTES_APPLE           0x8A15\n#define GL_UNPACK_ROW_BYTES_APPLE         0x8A16\n#endif /* GL_APPLE_row_bytes */\n\n#ifndef GL_APPLE_specular_vector\n#define GL_APPLE_specular_vector 1\n#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0\n#endif /* GL_APPLE_specular_vector */\n\n#ifndef GL_APPLE_texture_range\n#define GL_APPLE_texture_range 1\n#define GL_TEXTURE_RANGE_LENGTH_APPLE     0x85B7\n#define GL_TEXTURE_RANGE_POINTER_APPLE    0x85B8\n#define GL_TEXTURE_STORAGE_HINT_APPLE     0x85BC\n#define GL_STORAGE_PRIVATE_APPLE          0x85BD\n#define GL_STORAGE_CACHED_APPLE           0x85BE\n#define GL_STORAGE_SHARED_APPLE           0x85BF\ntypedef void (APIENTRYP PFNGLTEXTURERANGEAPPLEPROC) (GLenum target, GLsizei length, const void *pointer);\ntypedef void (APIENTRYP PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC) (GLenum target, GLenum pname, void **params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTextureRangeAPPLE (GLenum target, GLsizei length, const void *pointer);\nGLAPI void APIENTRY glGetTexParameterPointervAPPLE (GLenum target, GLenum pname, void **params);\n#endif\n#endif /* GL_APPLE_texture_range */\n\n#ifndef GL_APPLE_transform_hint\n#define GL_APPLE_transform_hint 1\n#define GL_TRANSFORM_HINT_APPLE           0x85B1\n#endif /* GL_APPLE_transform_hint */\n\n#ifndef GL_APPLE_vertex_array_object\n#define GL_APPLE_vertex_array_object 1\n#define GL_VERTEX_ARRAY_BINDING_APPLE     0x85B5\ntypedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);\ntypedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);\ntypedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, GLuint *arrays);\ntypedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint array);\nGLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei n, const GLuint *arrays);\nGLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei n, GLuint *arrays);\nGLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint array);\n#endif\n#endif /* GL_APPLE_vertex_array_object */\n\n#ifndef GL_APPLE_vertex_array_range\n#define GL_APPLE_vertex_array_range 1\n#define GL_VERTEX_ARRAY_RANGE_APPLE       0x851D\n#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E\n#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F\n#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521\n#define GL_STORAGE_CLIENT_APPLE           0x85B4\ntypedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer);\ntypedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei length, void *pointer);\nGLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei length, void *pointer);\nGLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum pname, GLint param);\n#endif\n#endif /* GL_APPLE_vertex_array_range */\n\n#ifndef GL_APPLE_vertex_program_evaluators\n#define GL_APPLE_vertex_program_evaluators 1\n#define GL_VERTEX_ATTRIB_MAP1_APPLE       0x8A00\n#define GL_VERTEX_ATTRIB_MAP2_APPLE       0x8A01\n#define GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE  0x8A02\n#define GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE 0x8A03\n#define GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE 0x8A04\n#define GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE 0x8A05\n#define GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE  0x8A06\n#define GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE 0x8A07\n#define GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE 0x8A08\n#define GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE 0x8A09\ntypedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname);\ntypedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname);\ntypedef GLboolean (APIENTRYP PFNGLISVERTEXATTRIBENABLEDAPPLEPROC) (GLuint index, GLenum pname);\ntypedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);\ntypedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);\ntypedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glEnableVertexAttribAPPLE (GLuint index, GLenum pname);\nGLAPI void APIENTRY glDisableVertexAttribAPPLE (GLuint index, GLenum pname);\nGLAPI GLboolean APIENTRY glIsVertexAttribEnabledAPPLE (GLuint index, GLenum pname);\nGLAPI void APIENTRY glMapVertexAttrib1dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);\nGLAPI void APIENTRY glMapVertexAttrib1fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);\nGLAPI void APIENTRY glMapVertexAttrib2dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);\nGLAPI void APIENTRY glMapVertexAttrib2fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);\n#endif\n#endif /* GL_APPLE_vertex_program_evaluators */\n\n#ifndef GL_APPLE_ycbcr_422\n#define GL_APPLE_ycbcr_422 1\n#define GL_YCBCR_422_APPLE                0x85B9\n#endif /* GL_APPLE_ycbcr_422 */\n\n#ifndef GL_ATI_draw_buffers\n#define GL_ATI_draw_buffers 1\n#define GL_MAX_DRAW_BUFFERS_ATI           0x8824\n#define GL_DRAW_BUFFER0_ATI               0x8825\n#define GL_DRAW_BUFFER1_ATI               0x8826\n#define GL_DRAW_BUFFER2_ATI               0x8827\n#define GL_DRAW_BUFFER3_ATI               0x8828\n#define GL_DRAW_BUFFER4_ATI               0x8829\n#define GL_DRAW_BUFFER5_ATI               0x882A\n#define GL_DRAW_BUFFER6_ATI               0x882B\n#define GL_DRAW_BUFFER7_ATI               0x882C\n#define GL_DRAW_BUFFER8_ATI               0x882D\n#define GL_DRAW_BUFFER9_ATI               0x882E\n#define GL_DRAW_BUFFER10_ATI              0x882F\n#define GL_DRAW_BUFFER11_ATI              0x8830\n#define GL_DRAW_BUFFER12_ATI              0x8831\n#define GL_DRAW_BUFFER13_ATI              0x8832\n#define GL_DRAW_BUFFER14_ATI              0x8833\n#define GL_DRAW_BUFFER15_ATI              0x8834\ntypedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawBuffersATI (GLsizei n, const GLenum *bufs);\n#endif\n#endif /* GL_ATI_draw_buffers */\n\n#ifndef GL_ATI_element_array\n#define GL_ATI_element_array 1\n#define GL_ELEMENT_ARRAY_ATI              0x8768\n#define GL_ELEMENT_ARRAY_TYPE_ATI         0x8769\n#define GL_ELEMENT_ARRAY_POINTER_ATI      0x876A\ntypedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const void *pointer);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glElementPointerATI (GLenum type, const void *pointer);\nGLAPI void APIENTRY glDrawElementArrayATI (GLenum mode, GLsizei count);\nGLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count);\n#endif\n#endif /* GL_ATI_element_array */\n\n#ifndef GL_ATI_envmap_bumpmap\n#define GL_ATI_envmap_bumpmap 1\n#define GL_BUMP_ROT_MATRIX_ATI            0x8775\n#define GL_BUMP_ROT_MATRIX_SIZE_ATI       0x8776\n#define GL_BUMP_NUM_TEX_UNITS_ATI         0x8777\n#define GL_BUMP_TEX_UNITS_ATI             0x8778\n#define GL_DUDV_ATI                       0x8779\n#define GL_DU8DV8_ATI                     0x877A\n#define GL_BUMP_ENVMAP_ATI                0x877B\n#define GL_BUMP_TARGET_ATI                0x877C\ntypedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param);\ntypedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param);\ntypedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param);\ntypedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexBumpParameterivATI (GLenum pname, const GLint *param);\nGLAPI void APIENTRY glTexBumpParameterfvATI (GLenum pname, const GLfloat *param);\nGLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum pname, GLint *param);\nGLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum pname, GLfloat *param);\n#endif\n#endif /* GL_ATI_envmap_bumpmap */\n\n#ifndef GL_ATI_fragment_shader\n#define GL_ATI_fragment_shader 1\n#define GL_FRAGMENT_SHADER_ATI            0x8920\n#define GL_REG_0_ATI                      0x8921\n#define GL_REG_1_ATI                      0x8922\n#define GL_REG_2_ATI                      0x8923\n#define GL_REG_3_ATI                      0x8924\n#define GL_REG_4_ATI                      0x8925\n#define GL_REG_5_ATI                      0x8926\n#define GL_REG_6_ATI                      0x8927\n#define GL_REG_7_ATI                      0x8928\n#define GL_REG_8_ATI                      0x8929\n#define GL_REG_9_ATI                      0x892A\n#define GL_REG_10_ATI                     0x892B\n#define GL_REG_11_ATI                     0x892C\n#define GL_REG_12_ATI                     0x892D\n#define GL_REG_13_ATI                     0x892E\n#define GL_REG_14_ATI                     0x892F\n#define GL_REG_15_ATI                     0x8930\n#define GL_REG_16_ATI                     0x8931\n#define GL_REG_17_ATI                     0x8932\n#define GL_REG_18_ATI                     0x8933\n#define GL_REG_19_ATI                     0x8934\n#define GL_REG_20_ATI                     0x8935\n#define GL_REG_21_ATI                     0x8936\n#define GL_REG_22_ATI                     0x8937\n#define GL_REG_23_ATI                     0x8938\n#define GL_REG_24_ATI                     0x8939\n#define GL_REG_25_ATI                     0x893A\n#define GL_REG_26_ATI                     0x893B\n#define GL_REG_27_ATI                     0x893C\n#define GL_REG_28_ATI                     0x893D\n#define GL_REG_29_ATI                     0x893E\n#define GL_REG_30_ATI                     0x893F\n#define GL_REG_31_ATI                     0x8940\n#define GL_CON_0_ATI                      0x8941\n#define GL_CON_1_ATI                      0x8942\n#define GL_CON_2_ATI                      0x8943\n#define GL_CON_3_ATI                      0x8944\n#define GL_CON_4_ATI                      0x8945\n#define GL_CON_5_ATI                      0x8946\n#define GL_CON_6_ATI                      0x8947\n#define GL_CON_7_ATI                      0x8948\n#define GL_CON_8_ATI                      0x8949\n#define GL_CON_9_ATI                      0x894A\n#define GL_CON_10_ATI                     0x894B\n#define GL_CON_11_ATI                     0x894C\n#define GL_CON_12_ATI                     0x894D\n#define GL_CON_13_ATI                     0x894E\n#define GL_CON_14_ATI                     0x894F\n#define GL_CON_15_ATI                     0x8950\n#define GL_CON_16_ATI                     0x8951\n#define GL_CON_17_ATI                     0x8952\n#define GL_CON_18_ATI                     0x8953\n#define GL_CON_19_ATI                     0x8954\n#define GL_CON_20_ATI                     0x8955\n#define GL_CON_21_ATI                     0x8956\n#define GL_CON_22_ATI                     0x8957\n#define GL_CON_23_ATI                     0x8958\n#define GL_CON_24_ATI                     0x8959\n#define GL_CON_25_ATI                     0x895A\n#define GL_CON_26_ATI                     0x895B\n#define GL_CON_27_ATI                     0x895C\n#define GL_CON_28_ATI                     0x895D\n#define GL_CON_29_ATI                     0x895E\n#define GL_CON_30_ATI                     0x895F\n#define GL_CON_31_ATI                     0x8960\n#define GL_MOV_ATI                        0x8961\n#define GL_ADD_ATI                        0x8963\n#define GL_MUL_ATI                        0x8964\n#define GL_SUB_ATI                        0x8965\n#define GL_DOT3_ATI                       0x8966\n#define GL_DOT4_ATI                       0x8967\n#define GL_MAD_ATI                        0x8968\n#define GL_LERP_ATI                       0x8969\n#define GL_CND_ATI                        0x896A\n#define GL_CND0_ATI                       0x896B\n#define GL_DOT2_ADD_ATI                   0x896C\n#define GL_SECONDARY_INTERPOLATOR_ATI     0x896D\n#define GL_NUM_FRAGMENT_REGISTERS_ATI     0x896E\n#define GL_NUM_FRAGMENT_CONSTANTS_ATI     0x896F\n#define GL_NUM_PASSES_ATI                 0x8970\n#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI  0x8971\n#define GL_NUM_INSTRUCTIONS_TOTAL_ATI     0x8972\n#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973\n#define GL_NUM_LOOPBACK_COMPONENTS_ATI    0x8974\n#define GL_COLOR_ALPHA_PAIRING_ATI        0x8975\n#define GL_SWIZZLE_STR_ATI                0x8976\n#define GL_SWIZZLE_STQ_ATI                0x8977\n#define GL_SWIZZLE_STR_DR_ATI             0x8978\n#define GL_SWIZZLE_STQ_DQ_ATI             0x8979\n#define GL_SWIZZLE_STRQ_ATI               0x897A\n#define GL_SWIZZLE_STRQ_DQ_ATI            0x897B\n#define GL_RED_BIT_ATI                    0x00000001\n#define GL_GREEN_BIT_ATI                  0x00000002\n#define GL_BLUE_BIT_ATI                   0x00000004\n#define GL_2X_BIT_ATI                     0x00000001\n#define GL_4X_BIT_ATI                     0x00000002\n#define GL_8X_BIT_ATI                     0x00000004\n#define GL_HALF_BIT_ATI                   0x00000008\n#define GL_QUARTER_BIT_ATI                0x00000010\n#define GL_EIGHTH_BIT_ATI                 0x00000020\n#define GL_SATURATE_BIT_ATI               0x00000040\n#define GL_COMP_BIT_ATI                   0x00000002\n#define GL_NEGATE_BIT_ATI                 0x00000004\n#define GL_BIAS_BIT_ATI                   0x00000008\ntypedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range);\ntypedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void);\ntypedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void);\ntypedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle);\ntypedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle);\ntypedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);\ntypedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);\ntypedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);\ntypedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);\ntypedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);\ntypedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);\ntypedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint range);\nGLAPI void APIENTRY glBindFragmentShaderATI (GLuint id);\nGLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint id);\nGLAPI void APIENTRY glBeginFragmentShaderATI (void);\nGLAPI void APIENTRY glEndFragmentShaderATI (void);\nGLAPI void APIENTRY glPassTexCoordATI (GLuint dst, GLuint coord, GLenum swizzle);\nGLAPI void APIENTRY glSampleMapATI (GLuint dst, GLuint interp, GLenum swizzle);\nGLAPI void APIENTRY glColorFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);\nGLAPI void APIENTRY glColorFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);\nGLAPI void APIENTRY glColorFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);\nGLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);\nGLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);\nGLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);\nGLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint dst, const GLfloat *value);\n#endif\n#endif /* GL_ATI_fragment_shader */\n\n#ifndef GL_ATI_map_object_buffer\n#define GL_ATI_map_object_buffer 1\ntypedef void *(APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void *APIENTRY glMapObjectBufferATI (GLuint buffer);\nGLAPI void APIENTRY glUnmapObjectBufferATI (GLuint buffer);\n#endif\n#endif /* GL_ATI_map_object_buffer */\n\n#ifndef GL_ATI_meminfo\n#define GL_ATI_meminfo 1\n#define GL_VBO_FREE_MEMORY_ATI            0x87FB\n#define GL_TEXTURE_FREE_MEMORY_ATI        0x87FC\n#define GL_RENDERBUFFER_FREE_MEMORY_ATI   0x87FD\n#endif /* GL_ATI_meminfo */\n\n#ifndef GL_ATI_pixel_format_float\n#define GL_ATI_pixel_format_float 1\n#define GL_RGBA_FLOAT_MODE_ATI            0x8820\n#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835\n#endif /* GL_ATI_pixel_format_float */\n\n#ifndef GL_ATI_pn_triangles\n#define GL_ATI_pn_triangles 1\n#define GL_PN_TRIANGLES_ATI               0x87F0\n#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1\n#define GL_PN_TRIANGLES_POINT_MODE_ATI    0x87F2\n#define GL_PN_TRIANGLES_NORMAL_MODE_ATI   0x87F3\n#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4\n#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5\n#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6\n#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7\n#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8\ntypedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPNTrianglesiATI (GLenum pname, GLint param);\nGLAPI void APIENTRY glPNTrianglesfATI (GLenum pname, GLfloat param);\n#endif\n#endif /* GL_ATI_pn_triangles */\n\n#ifndef GL_ATI_separate_stencil\n#define GL_ATI_separate_stencil 1\n#define GL_STENCIL_BACK_FUNC_ATI          0x8800\n#define GL_STENCIL_BACK_FAIL_ATI          0x8801\n#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802\n#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803\ntypedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);\ntypedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glStencilOpSeparateATI (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);\nGLAPI void APIENTRY glStencilFuncSeparateATI (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);\n#endif\n#endif /* GL_ATI_separate_stencil */\n\n#ifndef GL_ATI_text_fragment_shader\n#define GL_ATI_text_fragment_shader 1\n#define GL_TEXT_FRAGMENT_SHADER_ATI       0x8200\n#endif /* GL_ATI_text_fragment_shader */\n\n#ifndef GL_ATI_texture_env_combine3\n#define GL_ATI_texture_env_combine3 1\n#define GL_MODULATE_ADD_ATI               0x8744\n#define GL_MODULATE_SIGNED_ADD_ATI        0x8745\n#define GL_MODULATE_SUBTRACT_ATI          0x8746\n#endif /* GL_ATI_texture_env_combine3 */\n\n#ifndef GL_ATI_texture_float\n#define GL_ATI_texture_float 1\n#define GL_RGBA_FLOAT32_ATI               0x8814\n#define GL_RGB_FLOAT32_ATI                0x8815\n#define GL_ALPHA_FLOAT32_ATI              0x8816\n#define GL_INTENSITY_FLOAT32_ATI          0x8817\n#define GL_LUMINANCE_FLOAT32_ATI          0x8818\n#define GL_LUMINANCE_ALPHA_FLOAT32_ATI    0x8819\n#define GL_RGBA_FLOAT16_ATI               0x881A\n#define GL_RGB_FLOAT16_ATI                0x881B\n#define GL_ALPHA_FLOAT16_ATI              0x881C\n#define GL_INTENSITY_FLOAT16_ATI          0x881D\n#define GL_LUMINANCE_FLOAT16_ATI          0x881E\n#define GL_LUMINANCE_ALPHA_FLOAT16_ATI    0x881F\n#endif /* GL_ATI_texture_float */\n\n#ifndef GL_ATI_texture_mirror_once\n#define GL_ATI_texture_mirror_once 1\n#define GL_MIRROR_CLAMP_ATI               0x8742\n#define GL_MIRROR_CLAMP_TO_EDGE_ATI       0x8743\n#endif /* GL_ATI_texture_mirror_once */\n\n#ifndef GL_ATI_vertex_array_object\n#define GL_ATI_vertex_array_object 1\n#define GL_STATIC_ATI                     0x8760\n#define GL_DYNAMIC_ATI                    0x8761\n#define GL_PRESERVE_ATI                   0x8762\n#define GL_DISCARD_ATI                    0x8763\n#define GL_OBJECT_BUFFER_SIZE_ATI         0x8764\n#define GL_OBJECT_BUFFER_USAGE_ATI        0x8765\n#define GL_ARRAY_OBJECT_BUFFER_ATI        0x8766\n#define GL_ARRAY_OBJECT_OFFSET_ATI        0x8767\ntypedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const void *pointer, GLenum usage);\ntypedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve);\ntypedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);\ntypedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);\ntypedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei size, const void *pointer, GLenum usage);\nGLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint buffer);\nGLAPI void APIENTRY glUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve);\nGLAPI void APIENTRY glGetObjectBufferfvATI (GLuint buffer, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetObjectBufferivATI (GLuint buffer, GLenum pname, GLint *params);\nGLAPI void APIENTRY glFreeObjectBufferATI (GLuint buffer);\nGLAPI void APIENTRY glArrayObjectATI (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);\nGLAPI void APIENTRY glGetArrayObjectfvATI (GLenum array, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetArrayObjectivATI (GLenum array, GLenum pname, GLint *params);\nGLAPI void APIENTRY glVariantArrayObjectATI (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);\nGLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint id, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint id, GLenum pname, GLint *params);\n#endif\n#endif /* GL_ATI_vertex_array_object */\n\n#ifndef GL_ATI_vertex_attrib_array_object\n#define GL_ATI_vertex_attrib_array_object 1\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);\nGLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint index, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint index, GLenum pname, GLint *params);\n#endif\n#endif /* GL_ATI_vertex_attrib_array_object */\n\n#ifndef GL_ATI_vertex_streams\n#define GL_ATI_vertex_streams 1\n#define GL_MAX_VERTEX_STREAMS_ATI         0x876B\n#define GL_VERTEX_STREAM0_ATI             0x876C\n#define GL_VERTEX_STREAM1_ATI             0x876D\n#define GL_VERTEX_STREAM2_ATI             0x876E\n#define GL_VERTEX_STREAM3_ATI             0x876F\n#define GL_VERTEX_STREAM4_ATI             0x8770\n#define GL_VERTEX_STREAM5_ATI             0x8771\n#define GL_VERTEX_STREAM6_ATI             0x8772\n#define GL_VERTEX_STREAM7_ATI             0x8773\n#define GL_VERTEX_SOURCE_ATI              0x8774\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);\ntypedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);\ntypedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream);\ntypedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexStream1sATI (GLenum stream, GLshort x);\nGLAPI void APIENTRY glVertexStream1svATI (GLenum stream, const GLshort *coords);\nGLAPI void APIENTRY glVertexStream1iATI (GLenum stream, GLint x);\nGLAPI void APIENTRY glVertexStream1ivATI (GLenum stream, const GLint *coords);\nGLAPI void APIENTRY glVertexStream1fATI (GLenum stream, GLfloat x);\nGLAPI void APIENTRY glVertexStream1fvATI (GLenum stream, const GLfloat *coords);\nGLAPI void APIENTRY glVertexStream1dATI (GLenum stream, GLdouble x);\nGLAPI void APIENTRY glVertexStream1dvATI (GLenum stream, const GLdouble *coords);\nGLAPI void APIENTRY glVertexStream2sATI (GLenum stream, GLshort x, GLshort y);\nGLAPI void APIENTRY glVertexStream2svATI (GLenum stream, const GLshort *coords);\nGLAPI void APIENTRY glVertexStream2iATI (GLenum stream, GLint x, GLint y);\nGLAPI void APIENTRY glVertexStream2ivATI (GLenum stream, const GLint *coords);\nGLAPI void APIENTRY glVertexStream2fATI (GLenum stream, GLfloat x, GLfloat y);\nGLAPI void APIENTRY glVertexStream2fvATI (GLenum stream, const GLfloat *coords);\nGLAPI void APIENTRY glVertexStream2dATI (GLenum stream, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glVertexStream2dvATI (GLenum stream, const GLdouble *coords);\nGLAPI void APIENTRY glVertexStream3sATI (GLenum stream, GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glVertexStream3svATI (GLenum stream, const GLshort *coords);\nGLAPI void APIENTRY glVertexStream3iATI (GLenum stream, GLint x, GLint y, GLint z);\nGLAPI void APIENTRY glVertexStream3ivATI (GLenum stream, const GLint *coords);\nGLAPI void APIENTRY glVertexStream3fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glVertexStream3fvATI (GLenum stream, const GLfloat *coords);\nGLAPI void APIENTRY glVertexStream3dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glVertexStream3dvATI (GLenum stream, const GLdouble *coords);\nGLAPI void APIENTRY glVertexStream4sATI (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);\nGLAPI void APIENTRY glVertexStream4svATI (GLenum stream, const GLshort *coords);\nGLAPI void APIENTRY glVertexStream4iATI (GLenum stream, GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glVertexStream4ivATI (GLenum stream, const GLint *coords);\nGLAPI void APIENTRY glVertexStream4fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glVertexStream4fvATI (GLenum stream, const GLfloat *coords);\nGLAPI void APIENTRY glVertexStream4dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glVertexStream4dvATI (GLenum stream, const GLdouble *coords);\nGLAPI void APIENTRY glNormalStream3bATI (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);\nGLAPI void APIENTRY glNormalStream3bvATI (GLenum stream, const GLbyte *coords);\nGLAPI void APIENTRY glNormalStream3sATI (GLenum stream, GLshort nx, GLshort ny, GLshort nz);\nGLAPI void APIENTRY glNormalStream3svATI (GLenum stream, const GLshort *coords);\nGLAPI void APIENTRY glNormalStream3iATI (GLenum stream, GLint nx, GLint ny, GLint nz);\nGLAPI void APIENTRY glNormalStream3ivATI (GLenum stream, const GLint *coords);\nGLAPI void APIENTRY glNormalStream3fATI (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);\nGLAPI void APIENTRY glNormalStream3fvATI (GLenum stream, const GLfloat *coords);\nGLAPI void APIENTRY glNormalStream3dATI (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);\nGLAPI void APIENTRY glNormalStream3dvATI (GLenum stream, const GLdouble *coords);\nGLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum stream);\nGLAPI void APIENTRY glVertexBlendEnviATI (GLenum pname, GLint param);\nGLAPI void APIENTRY glVertexBlendEnvfATI (GLenum pname, GLfloat param);\n#endif\n#endif /* GL_ATI_vertex_streams */\n\n#ifndef GL_EXT_422_pixels\n#define GL_EXT_422_pixels 1\n#define GL_422_EXT                        0x80CC\n#define GL_422_REV_EXT                    0x80CD\n#define GL_422_AVERAGE_EXT                0x80CE\n#define GL_422_REV_AVERAGE_EXT            0x80CF\n#endif /* GL_EXT_422_pixels */\n\n#ifndef GL_EXT_abgr\n#define GL_EXT_abgr 1\n#define GL_ABGR_EXT                       0x8000\n#endif /* GL_EXT_abgr */\n\n#ifndef GL_EXT_bgra\n#define GL_EXT_bgra 1\n#define GL_BGR_EXT                        0x80E0\n#define GL_BGRA_EXT                       0x80E1\n#endif /* GL_EXT_bgra */\n\n#ifndef GL_EXT_bindable_uniform\n#define GL_EXT_bindable_uniform 1\n#define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2\n#define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3\n#define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4\n#define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT  0x8DED\n#define GL_UNIFORM_BUFFER_EXT             0x8DEE\n#define GL_UNIFORM_BUFFER_BINDING_EXT     0x8DEF\ntypedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer);\ntypedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location);\ntypedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glUniformBufferEXT (GLuint program, GLint location, GLuint buffer);\nGLAPI GLint APIENTRY glGetUniformBufferSizeEXT (GLuint program, GLint location);\nGLAPI GLintptr APIENTRY glGetUniformOffsetEXT (GLuint program, GLint location);\n#endif\n#endif /* GL_EXT_bindable_uniform */\n\n#ifndef GL_EXT_blend_color\n#define GL_EXT_blend_color 1\n#define GL_CONSTANT_COLOR_EXT             0x8001\n#define GL_ONE_MINUS_CONSTANT_COLOR_EXT   0x8002\n#define GL_CONSTANT_ALPHA_EXT             0x8003\n#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT   0x8004\n#define GL_BLEND_COLOR_EXT                0x8005\ntypedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendColorEXT (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);\n#endif\n#endif /* GL_EXT_blend_color */\n\n#ifndef GL_EXT_blend_equation_separate\n#define GL_EXT_blend_equation_separate 1\n#define GL_BLEND_EQUATION_RGB_EXT         0x8009\n#define GL_BLEND_EQUATION_ALPHA_EXT       0x883D\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha);\n#endif\n#endif /* GL_EXT_blend_equation_separate */\n\n#ifndef GL_EXT_blend_func_separate\n#define GL_EXT_blend_func_separate 1\n#define GL_BLEND_DST_RGB_EXT              0x80C8\n#define GL_BLEND_SRC_RGB_EXT              0x80C9\n#define GL_BLEND_DST_ALPHA_EXT            0x80CA\n#define GL_BLEND_SRC_ALPHA_EXT            0x80CB\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\n#endif\n#endif /* GL_EXT_blend_func_separate */\n\n#ifndef GL_EXT_blend_logic_op\n#define GL_EXT_blend_logic_op 1\n#endif /* GL_EXT_blend_logic_op */\n\n#ifndef GL_EXT_blend_minmax\n#define GL_EXT_blend_minmax 1\n#define GL_MIN_EXT                        0x8007\n#define GL_MAX_EXT                        0x8008\n#define GL_FUNC_ADD_EXT                   0x8006\n#define GL_BLEND_EQUATION_EXT             0x8009\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationEXT (GLenum mode);\n#endif\n#endif /* GL_EXT_blend_minmax */\n\n#ifndef GL_EXT_blend_subtract\n#define GL_EXT_blend_subtract 1\n#define GL_FUNC_SUBTRACT_EXT              0x800A\n#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B\n#endif /* GL_EXT_blend_subtract */\n\n#ifndef GL_EXT_clip_volume_hint\n#define GL_EXT_clip_volume_hint 1\n#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT  0x80F0\n#endif /* GL_EXT_clip_volume_hint */\n\n#ifndef GL_EXT_cmyka\n#define GL_EXT_cmyka 1\n#define GL_CMYK_EXT                       0x800C\n#define GL_CMYKA_EXT                      0x800D\n#define GL_PACK_CMYK_HINT_EXT             0x800E\n#define GL_UNPACK_CMYK_HINT_EXT           0x800F\n#endif /* GL_EXT_cmyka */\n\n#ifndef GL_EXT_color_subtable\n#define GL_EXT_color_subtable 1\ntypedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data);\ntypedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);\n#endif\n#endif /* GL_EXT_color_subtable */\n\n#ifndef GL_EXT_compiled_vertex_array\n#define GL_EXT_compiled_vertex_array 1\n#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT   0x81A8\n#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT   0x81A9\ntypedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);\ntypedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count);\nGLAPI void APIENTRY glUnlockArraysEXT (void);\n#endif\n#endif /* GL_EXT_compiled_vertex_array */\n\n#ifndef GL_EXT_convolution\n#define GL_EXT_convolution 1\n#define GL_CONVOLUTION_1D_EXT             0x8010\n#define GL_CONVOLUTION_2D_EXT             0x8011\n#define GL_SEPARABLE_2D_EXT               0x8012\n#define GL_CONVOLUTION_BORDER_MODE_EXT    0x8013\n#define GL_CONVOLUTION_FILTER_SCALE_EXT   0x8014\n#define GL_CONVOLUTION_FILTER_BIAS_EXT    0x8015\n#define GL_REDUCE_EXT                     0x8016\n#define GL_CONVOLUTION_FORMAT_EXT         0x8017\n#define GL_CONVOLUTION_WIDTH_EXT          0x8018\n#define GL_CONVOLUTION_HEIGHT_EXT         0x8019\n#define GL_MAX_CONVOLUTION_WIDTH_EXT      0x801A\n#define GL_MAX_CONVOLUTION_HEIGHT_EXT     0x801B\n#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C\n#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D\n#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E\n#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F\n#define GL_POST_CONVOLUTION_RED_BIAS_EXT  0x8020\n#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021\n#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022\n#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *image);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span);\ntypedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image);\nGLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image);\nGLAPI void APIENTRY glConvolutionParameterfEXT (GLenum target, GLenum pname, GLfloat params);\nGLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glConvolutionParameteriEXT (GLenum target, GLenum pname, GLint params);\nGLAPI void APIENTRY glConvolutionParameterivEXT (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum target, GLenum format, GLenum type, void *image);\nGLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetSeparableFilterEXT (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span);\nGLAPI void APIENTRY glSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column);\n#endif\n#endif /* GL_EXT_convolution */\n\n#ifndef GL_EXT_coordinate_frame\n#define GL_EXT_coordinate_frame 1\n#define GL_TANGENT_ARRAY_EXT              0x8439\n#define GL_BINORMAL_ARRAY_EXT             0x843A\n#define GL_CURRENT_TANGENT_EXT            0x843B\n#define GL_CURRENT_BINORMAL_EXT           0x843C\n#define GL_TANGENT_ARRAY_TYPE_EXT         0x843E\n#define GL_TANGENT_ARRAY_STRIDE_EXT       0x843F\n#define GL_BINORMAL_ARRAY_TYPE_EXT        0x8440\n#define GL_BINORMAL_ARRAY_STRIDE_EXT      0x8441\n#define GL_TANGENT_ARRAY_POINTER_EXT      0x8442\n#define GL_BINORMAL_ARRAY_POINTER_EXT     0x8443\n#define GL_MAP1_TANGENT_EXT               0x8444\n#define GL_MAP2_TANGENT_EXT               0x8445\n#define GL_MAP1_BINORMAL_EXT              0x8446\n#define GL_MAP2_BINORMAL_EXT              0x8447\ntypedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz);\ntypedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v);\ntypedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz);\ntypedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz);\ntypedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz);\ntypedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz);\ntypedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz);\ntypedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v);\ntypedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz);\ntypedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz);\ntypedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz);\ntypedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz);\ntypedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTangent3bEXT (GLbyte tx, GLbyte ty, GLbyte tz);\nGLAPI void APIENTRY glTangent3bvEXT (const GLbyte *v);\nGLAPI void APIENTRY glTangent3dEXT (GLdouble tx, GLdouble ty, GLdouble tz);\nGLAPI void APIENTRY glTangent3dvEXT (const GLdouble *v);\nGLAPI void APIENTRY glTangent3fEXT (GLfloat tx, GLfloat ty, GLfloat tz);\nGLAPI void APIENTRY glTangent3fvEXT (const GLfloat *v);\nGLAPI void APIENTRY glTangent3iEXT (GLint tx, GLint ty, GLint tz);\nGLAPI void APIENTRY glTangent3ivEXT (const GLint *v);\nGLAPI void APIENTRY glTangent3sEXT (GLshort tx, GLshort ty, GLshort tz);\nGLAPI void APIENTRY glTangent3svEXT (const GLshort *v);\nGLAPI void APIENTRY glBinormal3bEXT (GLbyte bx, GLbyte by, GLbyte bz);\nGLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *v);\nGLAPI void APIENTRY glBinormal3dEXT (GLdouble bx, GLdouble by, GLdouble bz);\nGLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *v);\nGLAPI void APIENTRY glBinormal3fEXT (GLfloat bx, GLfloat by, GLfloat bz);\nGLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *v);\nGLAPI void APIENTRY glBinormal3iEXT (GLint bx, GLint by, GLint bz);\nGLAPI void APIENTRY glBinormal3ivEXT (const GLint *v);\nGLAPI void APIENTRY glBinormal3sEXT (GLshort bx, GLshort by, GLshort bz);\nGLAPI void APIENTRY glBinormal3svEXT (const GLshort *v);\nGLAPI void APIENTRY glTangentPointerEXT (GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glBinormalPointerEXT (GLenum type, GLsizei stride, const void *pointer);\n#endif\n#endif /* GL_EXT_coordinate_frame */\n\n#ifndef GL_EXT_copy_texture\n#define GL_EXT_copy_texture 1\ntypedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);\ntypedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);\ntypedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCopyTexImage1DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);\nGLAPI void APIENTRY glCopyTexImage2DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);\nGLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\n#endif\n#endif /* GL_EXT_copy_texture */\n\n#ifndef GL_EXT_cull_vertex\n#define GL_EXT_cull_vertex 1\n#define GL_CULL_VERTEX_EXT                0x81AA\n#define GL_CULL_VERTEX_EYE_POSITION_EXT   0x81AB\n#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC\ntypedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCullParameterdvEXT (GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glCullParameterfvEXT (GLenum pname, GLfloat *params);\n#endif\n#endif /* GL_EXT_cull_vertex */\n\n#ifndef GL_EXT_debug_label\n#define GL_EXT_debug_label 1\n#define GL_PROGRAM_PIPELINE_OBJECT_EXT    0x8A4F\n#define GL_PROGRAM_OBJECT_EXT             0x8B40\n#define GL_SHADER_OBJECT_EXT              0x8B48\n#define GL_BUFFER_OBJECT_EXT              0x9151\n#define GL_QUERY_OBJECT_EXT               0x9153\n#define GL_VERTEX_ARRAY_OBJECT_EXT        0x9154\ntypedef void (APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label);\ntypedef void (APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label);\nGLAPI void APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);\n#endif\n#endif /* GL_EXT_debug_label */\n\n#ifndef GL_EXT_debug_marker\n#define GL_EXT_debug_marker 1\ntypedef void (APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker);\ntypedef void (APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker);\ntypedef void (APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker);\nGLAPI void APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker);\nGLAPI void APIENTRY glPopGroupMarkerEXT (void);\n#endif\n#endif /* GL_EXT_debug_marker */\n\n#ifndef GL_EXT_depth_bounds_test\n#define GL_EXT_depth_bounds_test 1\n#define GL_DEPTH_BOUNDS_TEST_EXT          0x8890\n#define GL_DEPTH_BOUNDS_EXT               0x8891\ntypedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDepthBoundsEXT (GLclampd zmin, GLclampd zmax);\n#endif\n#endif /* GL_EXT_depth_bounds_test */\n\n#ifndef GL_EXT_direct_state_access\n#define GL_EXT_direct_state_access 1\n#define GL_PROGRAM_MATRIX_EXT             0x8E2D\n#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT   0x8E2E\n#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F\ntypedef void (APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m);\ntypedef void (APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m);\ntypedef void (APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m);\ntypedef void (APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m);\ntypedef void (APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode);\ntypedef void (APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);\ntypedef void (APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);\ntypedef void (APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode);\ntypedef void (APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode);\ntypedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask);\ntypedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask);\ntypedef void (APIENTRYP PFNGLTEXTUREPARAMETERFEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLTEXTUREPARAMETERIEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);\ntypedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);\ntypedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels);\ntypedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLMULTITEXENVFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLMULTITEXENVIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLMULTITEXGENDEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble param);\ntypedef void (APIENTRYP PFNGLMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params);\ntypedef void (APIENTRYP PFNGLMULTITEXGENFEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLMULTITEXGENIEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLMULTITEXPARAMETERIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLMULTITEXPARAMETERFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);\ntypedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);\ntypedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels);\ntypedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index);\ntypedef void (APIENTRYP PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat *data);\ntypedef void (APIENTRYP PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble *data);\ntypedef void (APIENTRYP PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, void **data);\ntypedef void (APIENTRYP PFNGLENABLEINDEXEDEXTPROC) (GLenum target, GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLEINDEXEDEXTPROC) (GLenum target, GLuint index);\ntypedef GLboolean (APIENTRYP PFNGLISENABLEDINDEXEDEXTPROC) (GLenum target, GLuint index);\ntypedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *data);\ntypedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, void *img);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits);\ntypedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, void *img);\ntypedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m);\ntypedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m);\ntypedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m);\ntypedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m);\ntypedef void (APIENTRYP PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage);\ntypedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data);\ntypedef void *(APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access);\ntypedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, void **params);\ntypedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLTEXTUREBUFFEREXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer);\ntypedef void (APIENTRYP PFNGLMULTITEXBUFFEREXTPROC) (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer);\ntypedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC) (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLint *params);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLuint *params);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLint *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint *params);\ntypedef void (APIENTRYP PFNGLENABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index);\ntypedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLdouble *params);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, void *string);\ntypedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC) (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC) (GLuint framebuffer, GLenum target);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target);\ntypedef void (APIENTRYP PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit, GLenum target);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode);\ntypedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face);\ntypedef void (APIENTRYP PFNGLTEXTURERENDERBUFFEREXTPROC) (GLuint texture, GLenum target, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLMULTITEXRENDERBUFFEREXTPROC) (GLenum texunit, GLenum target, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYINDEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYNORMALOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLENABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array);\ntypedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array);\ntypedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index);\ntypedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERVEXTPROC) (GLuint vaobj, GLenum pname, GLint *param);\ntypedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERVEXTPROC) (GLuint vaobj, GLenum pname, void **param);\ntypedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);\ntypedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);\ntypedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access);\ntypedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length);\ntypedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags);\ntypedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data);\ntypedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data);\ntypedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC) (GLuint framebuffer, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\ntypedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEEXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);\ntypedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);\ntypedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);\ntypedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);\ntypedef void (APIENTRYP PFNGLTEXTUREPAGECOMMITMENTEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC) (GLuint vaobj, GLuint index, GLuint divisor);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m);\nGLAPI void APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m);\nGLAPI void APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m);\nGLAPI void APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m);\nGLAPI void APIENTRY glMatrixLoadIdentityEXT (GLenum mode);\nGLAPI void APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);\nGLAPI void APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);\nGLAPI void APIENTRY glMatrixPopEXT (GLenum mode);\nGLAPI void APIENTRY glMatrixPushEXT (GLenum mode);\nGLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask);\nGLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask);\nGLAPI void APIENTRY glTextureParameterfEXT (GLuint texture, GLenum target, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glTextureParameteriEXT (GLuint texture, GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glCopyTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);\nGLAPI void APIENTRY glCopyTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);\nGLAPI void APIENTRY glCopyTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glCopyTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetTextureImageEXT (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels);\nGLAPI void APIENTRY glGetTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetTextureLevelParameterfvEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetTextureLevelParameterivEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params);\nGLAPI void APIENTRY glTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glCopyTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture);\nGLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glMultiTexEnvfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glMultiTexEnviEXT (GLenum texunit, GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glMultiTexGendEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble param);\nGLAPI void APIENTRY glMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params);\nGLAPI void APIENTRY glMultiTexGenfEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glMultiTexGeniEXT (GLenum texunit, GLenum coord, GLenum pname, GLint param);\nGLAPI void APIENTRY glMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glGetMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glGetMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, GLint *params);\nGLAPI void APIENTRY glMultiTexParameteriEXT (GLenum texunit, GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glMultiTexParameterfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glCopyMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);\nGLAPI void APIENTRY glCopyMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);\nGLAPI void APIENTRY glCopyMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glCopyMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetMultiTexImageEXT (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels);\nGLAPI void APIENTRY glGetMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMultiTexLevelParameterfvEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMultiTexLevelParameterivEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params);\nGLAPI void APIENTRY glMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glCopyMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index);\nGLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index);\nGLAPI void APIENTRY glGetFloatIndexedvEXT (GLenum target, GLuint index, GLfloat *data);\nGLAPI void APIENTRY glGetDoubleIndexedvEXT (GLenum target, GLuint index, GLdouble *data);\nGLAPI void APIENTRY glGetPointerIndexedvEXT (GLenum target, GLuint index, void **data);\nGLAPI void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index);\nGLAPI void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index);\nGLAPI GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index);\nGLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data);\nGLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data);\nGLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, void *img);\nGLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits);\nGLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, void *img);\nGLAPI void APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m);\nGLAPI void APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m);\nGLAPI void APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m);\nGLAPI void APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m);\nGLAPI void APIENTRY glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage);\nGLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data);\nGLAPI void *APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access);\nGLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer);\nGLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, void **params);\nGLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data);\nGLAPI void APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0);\nGLAPI void APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1);\nGLAPI void APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);\nGLAPI void APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);\nGLAPI void APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0);\nGLAPI void APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1);\nGLAPI void APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);\nGLAPI void APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);\nGLAPI void APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);\nGLAPI void APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);\nGLAPI void APIENTRY glTextureBufferEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer);\nGLAPI void APIENTRY glMultiTexBufferEXT (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer);\nGLAPI void APIENTRY glTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, const GLuint *params);\nGLAPI void APIENTRY glGetTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, const GLuint *params);\nGLAPI void APIENTRY glGetMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0);\nGLAPI void APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1);\nGLAPI void APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);\nGLAPI void APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\nGLAPI void APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glNamedProgramLocalParameters4fvEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params);\nGLAPI void APIENTRY glNamedProgramLocalParameterI4iEXT (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glNamedProgramLocalParameterI4ivEXT (GLuint program, GLenum target, GLuint index, const GLint *params);\nGLAPI void APIENTRY glNamedProgramLocalParametersI4ivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params);\nGLAPI void APIENTRY glNamedProgramLocalParameterI4uiEXT (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\nGLAPI void APIENTRY glNamedProgramLocalParameterI4uivEXT (GLuint program, GLenum target, GLuint index, const GLuint *params);\nGLAPI void APIENTRY glNamedProgramLocalParametersI4uivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params);\nGLAPI void APIENTRY glGetNamedProgramLocalParameterIivEXT (GLuint program, GLenum target, GLuint index, GLint *params);\nGLAPI void APIENTRY glGetNamedProgramLocalParameterIuivEXT (GLuint program, GLenum target, GLuint index, GLuint *params);\nGLAPI void APIENTRY glEnableClientStateiEXT (GLenum array, GLuint index);\nGLAPI void APIENTRY glDisableClientStateiEXT (GLenum array, GLuint index);\nGLAPI void APIENTRY glGetFloati_vEXT (GLenum pname, GLuint index, GLfloat *params);\nGLAPI void APIENTRY glGetDoublei_vEXT (GLenum pname, GLuint index, GLdouble *params);\nGLAPI void APIENTRY glGetPointeri_vEXT (GLenum pname, GLuint index, void **params);\nGLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string);\nGLAPI void APIENTRY glNamedProgramLocalParameter4dEXT (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glNamedProgramLocalParameter4dvEXT (GLuint program, GLenum target, GLuint index, const GLdouble *params);\nGLAPI void APIENTRY glNamedProgramLocalParameter4fEXT (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glNamedProgramLocalParameter4fvEXT (GLuint program, GLenum target, GLuint index, const GLfloat *params);\nGLAPI void APIENTRY glGetNamedProgramLocalParameterdvEXT (GLuint program, GLenum target, GLuint index, GLdouble *params);\nGLAPI void APIENTRY glGetNamedProgramLocalParameterfvEXT (GLuint program, GLenum target, GLuint index, GLfloat *params);\nGLAPI void APIENTRY glGetNamedProgramivEXT (GLuint program, GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetNamedProgramStringEXT (GLuint program, GLenum target, GLenum pname, void *string);\nGLAPI void APIENTRY glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params);\nGLAPI void APIENTRY glNamedRenderbufferStorageMultisampleEXT (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glNamedRenderbufferStorageMultisampleCoverageEXT (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI GLenum APIENTRY glCheckNamedFramebufferStatusEXT (GLuint framebuffer, GLenum target);\nGLAPI void APIENTRY glNamedFramebufferTexture1DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\nGLAPI void APIENTRY glNamedFramebufferTexture2DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\nGLAPI void APIENTRY glNamedFramebufferTexture3DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);\nGLAPI void APIENTRY glNamedFramebufferRenderbufferEXT (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);\nGLAPI void APIENTRY glGetNamedFramebufferAttachmentParameterivEXT (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGenerateTextureMipmapEXT (GLuint texture, GLenum target);\nGLAPI void APIENTRY glGenerateMultiTexMipmapEXT (GLenum texunit, GLenum target);\nGLAPI void APIENTRY glFramebufferDrawBufferEXT (GLuint framebuffer, GLenum mode);\nGLAPI void APIENTRY glFramebufferDrawBuffersEXT (GLuint framebuffer, GLsizei n, const GLenum *bufs);\nGLAPI void APIENTRY glFramebufferReadBufferEXT (GLuint framebuffer, GLenum mode);\nGLAPI void APIENTRY glGetFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params);\nGLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);\nGLAPI void APIENTRY glNamedFramebufferTextureEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);\nGLAPI void APIENTRY glNamedFramebufferTextureLayerEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);\nGLAPI void APIENTRY glNamedFramebufferTextureFaceEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face);\nGLAPI void APIENTRY glTextureRenderbufferEXT (GLuint texture, GLenum target, GLuint renderbuffer);\nGLAPI void APIENTRY glMultiTexRenderbufferEXT (GLenum texunit, GLenum target, GLuint renderbuffer);\nGLAPI void APIENTRY glVertexArrayVertexOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayEdgeFlagOffsetEXT (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayIndexOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayNormalOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayMultiTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayFogCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArraySecondaryColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayVertexAttribOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glVertexArrayVertexAttribIOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glEnableVertexArrayEXT (GLuint vaobj, GLenum array);\nGLAPI void APIENTRY glDisableVertexArrayEXT (GLuint vaobj, GLenum array);\nGLAPI void APIENTRY glEnableVertexArrayAttribEXT (GLuint vaobj, GLuint index);\nGLAPI void APIENTRY glDisableVertexArrayAttribEXT (GLuint vaobj, GLuint index);\nGLAPI void APIENTRY glGetVertexArrayIntegervEXT (GLuint vaobj, GLenum pname, GLint *param);\nGLAPI void APIENTRY glGetVertexArrayPointervEXT (GLuint vaobj, GLenum pname, void **param);\nGLAPI void APIENTRY glGetVertexArrayIntegeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, GLint *param);\nGLAPI void APIENTRY glGetVertexArrayPointeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, void **param);\nGLAPI void *APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access);\nGLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length);\nGLAPI void APIENTRY glNamedBufferStorageEXT (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags);\nGLAPI void APIENTRY glClearNamedBufferDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data);\nGLAPI void APIENTRY glNamedFramebufferParameteriEXT (GLuint framebuffer, GLenum pname, GLint param);\nGLAPI void APIENTRY glGetNamedFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params);\nGLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x);\nGLAPI void APIENTRY glProgramUniform2dEXT (GLuint program, GLint location, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glProgramUniform3dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glProgramUniform4dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glProgramUniform1dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform2dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform3dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniform4dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix2x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix3x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glProgramUniformMatrix4x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);\nGLAPI void APIENTRY glTextureBufferRangeEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);\nGLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);\nGLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);\nGLAPI void APIENTRY glTextureStorage2DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);\nGLAPI void APIENTRY glTextureStorage3DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);\nGLAPI void APIENTRY glVertexArrayBindVertexBufferEXT (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);\nGLAPI void APIENTRY glVertexArrayVertexAttribFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);\nGLAPI void APIENTRY glVertexArrayVertexAttribIFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\nGLAPI void APIENTRY glVertexArrayVertexAttribLFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);\nGLAPI void APIENTRY glVertexArrayVertexAttribBindingEXT (GLuint vaobj, GLuint attribindex, GLuint bindingindex);\nGLAPI void APIENTRY glVertexArrayVertexBindingDivisorEXT (GLuint vaobj, GLuint bindingindex, GLuint divisor);\nGLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);\nGLAPI void APIENTRY glTexturePageCommitmentEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident);\nGLAPI void APIENTRY glVertexArrayVertexAttribDivisorEXT (GLuint vaobj, GLuint index, GLuint divisor);\n#endif\n#endif /* GL_EXT_direct_state_access */\n\n#ifndef GL_EXT_draw_buffers2\n#define GL_EXT_draw_buffers2 1\ntypedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);\n#endif\n#endif /* GL_EXT_draw_buffers2 */\n\n#ifndef GL_EXT_draw_instanced\n#define GL_EXT_draw_instanced 1\ntypedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount);\nGLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);\n#endif\n#endif /* GL_EXT_draw_instanced */\n\n#ifndef GL_EXT_draw_range_elements\n#define GL_EXT_draw_range_elements 1\n#define GL_MAX_ELEMENTS_VERTICES_EXT      0x80E8\n#define GL_MAX_ELEMENTS_INDICES_EXT       0x80E9\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices);\n#endif\n#endif /* GL_EXT_draw_range_elements */\n\n#ifndef GL_EXT_fog_coord\n#define GL_EXT_fog_coord 1\n#define GL_FOG_COORDINATE_SOURCE_EXT      0x8450\n#define GL_FOG_COORDINATE_EXT             0x8451\n#define GL_FRAGMENT_DEPTH_EXT             0x8452\n#define GL_CURRENT_FOG_COORDINATE_EXT     0x8453\n#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT  0x8454\n#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455\n#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456\n#define GL_FOG_COORDINATE_ARRAY_EXT       0x8457\ntypedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord);\ntypedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFogCoordfEXT (GLfloat coord);\nGLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *coord);\nGLAPI void APIENTRY glFogCoorddEXT (GLdouble coord);\nGLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *coord);\nGLAPI void APIENTRY glFogCoordPointerEXT (GLenum type, GLsizei stride, const void *pointer);\n#endif\n#endif /* GL_EXT_fog_coord */\n\n#ifndef GL_EXT_framebuffer_blit\n#define GL_EXT_framebuffer_blit 1\n#define GL_READ_FRAMEBUFFER_EXT           0x8CA8\n#define GL_DRAW_FRAMEBUFFER_EXT           0x8CA9\n#define GL_DRAW_FRAMEBUFFER_BINDING_EXT   0x8CA6\n#define GL_READ_FRAMEBUFFER_BINDING_EXT   0x8CAA\ntypedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlitFramebufferEXT (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);\n#endif\n#endif /* GL_EXT_framebuffer_blit */\n\n#ifndef GL_EXT_framebuffer_multisample\n#define GL_EXT_framebuffer_multisample 1\n#define GL_RENDERBUFFER_SAMPLES_EXT       0x8CAB\n#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56\n#define GL_MAX_SAMPLES_EXT                0x8D57\ntypedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);\n#endif\n#endif /* GL_EXT_framebuffer_multisample */\n\n#ifndef GL_EXT_framebuffer_multisample_blit_scaled\n#define GL_EXT_framebuffer_multisample_blit_scaled 1\n#define GL_SCALED_RESOLVE_FASTEST_EXT     0x90BA\n#define GL_SCALED_RESOLVE_NICEST_EXT      0x90BB\n#endif /* GL_EXT_framebuffer_multisample_blit_scaled */\n\n#ifndef GL_EXT_framebuffer_object\n#define GL_EXT_framebuffer_object 1\n#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506\n#define GL_MAX_RENDERBUFFER_SIZE_EXT      0x84E8\n#define GL_FRAMEBUFFER_BINDING_EXT        0x8CA6\n#define GL_RENDERBUFFER_BINDING_EXT       0x8CA7\n#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0\n#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4\n#define GL_FRAMEBUFFER_COMPLETE_EXT       0x8CD5\n#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6\n#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7\n#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9\n#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA\n#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB\n#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC\n#define GL_FRAMEBUFFER_UNSUPPORTED_EXT    0x8CDD\n#define GL_MAX_COLOR_ATTACHMENTS_EXT      0x8CDF\n#define GL_COLOR_ATTACHMENT0_EXT          0x8CE0\n#define GL_COLOR_ATTACHMENT1_EXT          0x8CE1\n#define GL_COLOR_ATTACHMENT2_EXT          0x8CE2\n#define GL_COLOR_ATTACHMENT3_EXT          0x8CE3\n#define GL_COLOR_ATTACHMENT4_EXT          0x8CE4\n#define GL_COLOR_ATTACHMENT5_EXT          0x8CE5\n#define GL_COLOR_ATTACHMENT6_EXT          0x8CE6\n#define GL_COLOR_ATTACHMENT7_EXT          0x8CE7\n#define GL_COLOR_ATTACHMENT8_EXT          0x8CE8\n#define GL_COLOR_ATTACHMENT9_EXT          0x8CE9\n#define GL_COLOR_ATTACHMENT10_EXT         0x8CEA\n#define GL_COLOR_ATTACHMENT11_EXT         0x8CEB\n#define GL_COLOR_ATTACHMENT12_EXT         0x8CEC\n#define GL_COLOR_ATTACHMENT13_EXT         0x8CED\n#define GL_COLOR_ATTACHMENT14_EXT         0x8CEE\n#define GL_COLOR_ATTACHMENT15_EXT         0x8CEF\n#define GL_DEPTH_ATTACHMENT_EXT           0x8D00\n#define GL_STENCIL_ATTACHMENT_EXT         0x8D20\n#define GL_FRAMEBUFFER_EXT                0x8D40\n#define GL_RENDERBUFFER_EXT               0x8D41\n#define GL_RENDERBUFFER_WIDTH_EXT         0x8D42\n#define GL_RENDERBUFFER_HEIGHT_EXT        0x8D43\n#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44\n#define GL_STENCIL_INDEX1_EXT             0x8D46\n#define GL_STENCIL_INDEX4_EXT             0x8D47\n#define GL_STENCIL_INDEX8_EXT             0x8D48\n#define GL_STENCIL_INDEX16_EXT            0x8D49\n#define GL_RENDERBUFFER_RED_SIZE_EXT      0x8D50\n#define GL_RENDERBUFFER_GREEN_SIZE_EXT    0x8D51\n#define GL_RENDERBUFFER_BLUE_SIZE_EXT     0x8D52\n#define GL_RENDERBUFFER_ALPHA_SIZE_EXT    0x8D53\n#define GL_RENDERBUFFER_DEPTH_SIZE_EXT    0x8D54\n#define GL_RENDERBUFFER_STENCIL_SIZE_EXT  0x8D55\ntypedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers);\ntypedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers);\ntypedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);\ntypedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer);\ntypedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer);\ntypedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers);\ntypedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers);\ntypedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);\ntypedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint renderbuffer);\nGLAPI void APIENTRY glBindRenderbufferEXT (GLenum target, GLuint renderbuffer);\nGLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei n, const GLuint *renderbuffers);\nGLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei n, GLuint *renderbuffers);\nGLAPI void APIENTRY glRenderbufferStorageEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);\nGLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint framebuffer);\nGLAPI void APIENTRY glBindFramebufferEXT (GLenum target, GLuint framebuffer);\nGLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei n, const GLuint *framebuffers);\nGLAPI void APIENTRY glGenFramebuffersEXT (GLsizei n, GLuint *framebuffers);\nGLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum target);\nGLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\nGLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);\nGLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);\nGLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);\nGLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum target, GLenum attachment, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGenerateMipmapEXT (GLenum target);\n#endif\n#endif /* GL_EXT_framebuffer_object */\n\n#ifndef GL_EXT_framebuffer_sRGB\n#define GL_EXT_framebuffer_sRGB 1\n#define GL_FRAMEBUFFER_SRGB_EXT           0x8DB9\n#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT   0x8DBA\n#endif /* GL_EXT_framebuffer_sRGB */\n\n#ifndef GL_EXT_geometry_shader4\n#define GL_EXT_geometry_shader4 1\n#define GL_GEOMETRY_SHADER_EXT            0x8DD9\n#define GL_GEOMETRY_VERTICES_OUT_EXT      0x8DDA\n#define GL_GEOMETRY_INPUT_TYPE_EXT        0x8DDB\n#define GL_GEOMETRY_OUTPUT_TYPE_EXT       0x8DDC\n#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29\n#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD\n#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE\n#define GL_MAX_VARYING_COMPONENTS_EXT     0x8B4B\n#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF\n#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0\n#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1\n#define GL_LINES_ADJACENCY_EXT            0x000A\n#define GL_LINE_STRIP_ADJACENCY_EXT       0x000B\n#define GL_TRIANGLES_ADJACENCY_EXT        0x000C\n#define GL_TRIANGLE_STRIP_ADJACENCY_EXT   0x000D\n#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8\n#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9\n#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7\n#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4\n#define GL_PROGRAM_POINT_SIZE_EXT         0x8642\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value);\n#endif\n#endif /* GL_EXT_geometry_shader4 */\n\n#ifndef GL_EXT_gpu_program_parameters\n#define GL_EXT_gpu_program_parameters 1\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramEnvParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params);\nGLAPI void APIENTRY glProgramLocalParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params);\n#endif\n#endif /* GL_EXT_gpu_program_parameters */\n\n#ifndef GL_EXT_gpu_shader4\n#define GL_EXT_gpu_shader4 1\n#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT 0x88FD\n#define GL_SAMPLER_1D_ARRAY_EXT           0x8DC0\n#define GL_SAMPLER_2D_ARRAY_EXT           0x8DC1\n#define GL_SAMPLER_BUFFER_EXT             0x8DC2\n#define GL_SAMPLER_1D_ARRAY_SHADOW_EXT    0x8DC3\n#define GL_SAMPLER_2D_ARRAY_SHADOW_EXT    0x8DC4\n#define GL_SAMPLER_CUBE_SHADOW_EXT        0x8DC5\n#define GL_UNSIGNED_INT_VEC2_EXT          0x8DC6\n#define GL_UNSIGNED_INT_VEC3_EXT          0x8DC7\n#define GL_UNSIGNED_INT_VEC4_EXT          0x8DC8\n#define GL_INT_SAMPLER_1D_EXT             0x8DC9\n#define GL_INT_SAMPLER_2D_EXT             0x8DCA\n#define GL_INT_SAMPLER_3D_EXT             0x8DCB\n#define GL_INT_SAMPLER_CUBE_EXT           0x8DCC\n#define GL_INT_SAMPLER_2D_RECT_EXT        0x8DCD\n#define GL_INT_SAMPLER_1D_ARRAY_EXT       0x8DCE\n#define GL_INT_SAMPLER_2D_ARRAY_EXT       0x8DCF\n#define GL_INT_SAMPLER_BUFFER_EXT         0x8DD0\n#define GL_UNSIGNED_INT_SAMPLER_1D_EXT    0x8DD1\n#define GL_UNSIGNED_INT_SAMPLER_2D_EXT    0x8DD2\n#define GL_UNSIGNED_INT_SAMPLER_3D_EXT    0x8DD3\n#define GL_UNSIGNED_INT_SAMPLER_CUBE_EXT  0x8DD4\n#define GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT 0x8DD5\n#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT 0x8DD6\n#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT 0x8DD7\n#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8\n#define GL_MIN_PROGRAM_TEXEL_OFFSET_EXT   0x8904\n#define GL_MAX_PROGRAM_TEXEL_OFFSET_EXT   0x8905\ntypedef void (APIENTRYP PFNGLGETUNIFORMUIVEXTPROC) (GLuint program, GLint location, GLuint *params);\ntypedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name);\ntypedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONEXTPROC) (GLuint program, const GLchar *name);\ntypedef void (APIENTRYP PFNGLUNIFORM1UIEXTPROC) (GLint location, GLuint v0);\ntypedef void (APIENTRYP PFNGLUNIFORM2UIEXTPROC) (GLint location, GLuint v0, GLuint v1);\ntypedef void (APIENTRYP PFNGLUNIFORM3UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2);\ntypedef void (APIENTRYP PFNGLUNIFORM4UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\ntypedef void (APIENTRYP PFNGLUNIFORM1UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetUniformuivEXT (GLuint program, GLint location, GLuint *params);\nGLAPI void APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name);\nGLAPI GLint APIENTRY glGetFragDataLocationEXT (GLuint program, const GLchar *name);\nGLAPI void APIENTRY glUniform1uiEXT (GLint location, GLuint v0);\nGLAPI void APIENTRY glUniform2uiEXT (GLint location, GLuint v0, GLuint v1);\nGLAPI void APIENTRY glUniform3uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2);\nGLAPI void APIENTRY glUniform4uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);\nGLAPI void APIENTRY glUniform1uivEXT (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glUniform2uivEXT (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glUniform3uivEXT (GLint location, GLsizei count, const GLuint *value);\nGLAPI void APIENTRY glUniform4uivEXT (GLint location, GLsizei count, const GLuint *value);\n#endif\n#endif /* GL_EXT_gpu_shader4 */\n\n#ifndef GL_EXT_histogram\n#define GL_EXT_histogram 1\n#define GL_HISTOGRAM_EXT                  0x8024\n#define GL_PROXY_HISTOGRAM_EXT            0x8025\n#define GL_HISTOGRAM_WIDTH_EXT            0x8026\n#define GL_HISTOGRAM_FORMAT_EXT           0x8027\n#define GL_HISTOGRAM_RED_SIZE_EXT         0x8028\n#define GL_HISTOGRAM_GREEN_SIZE_EXT       0x8029\n#define GL_HISTOGRAM_BLUE_SIZE_EXT        0x802A\n#define GL_HISTOGRAM_ALPHA_SIZE_EXT       0x802B\n#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT   0x802C\n#define GL_HISTOGRAM_SINK_EXT             0x802D\n#define GL_MINMAX_EXT                     0x802E\n#define GL_MINMAX_FORMAT_EXT              0x802F\n#define GL_MINMAX_SINK_EXT                0x8030\n#define GL_TABLE_TOO_LARGE_EXT            0x8031\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\ntypedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);\ntypedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink);\ntypedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\nGLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMinmaxEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values);\nGLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glHistogramEXT (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);\nGLAPI void APIENTRY glMinmaxEXT (GLenum target, GLenum internalformat, GLboolean sink);\nGLAPI void APIENTRY glResetHistogramEXT (GLenum target);\nGLAPI void APIENTRY glResetMinmaxEXT (GLenum target);\n#endif\n#endif /* GL_EXT_histogram */\n\n#ifndef GL_EXT_index_array_formats\n#define GL_EXT_index_array_formats 1\n#define GL_IUI_V2F_EXT                    0x81AD\n#define GL_IUI_V3F_EXT                    0x81AE\n#define GL_IUI_N3F_V2F_EXT                0x81AF\n#define GL_IUI_N3F_V3F_EXT                0x81B0\n#define GL_T2F_IUI_V2F_EXT                0x81B1\n#define GL_T2F_IUI_V3F_EXT                0x81B2\n#define GL_T2F_IUI_N3F_V2F_EXT            0x81B3\n#define GL_T2F_IUI_N3F_V3F_EXT            0x81B4\n#endif /* GL_EXT_index_array_formats */\n\n#ifndef GL_EXT_index_func\n#define GL_EXT_index_func 1\n#define GL_INDEX_TEST_EXT                 0x81B5\n#define GL_INDEX_TEST_FUNC_EXT            0x81B6\n#define GL_INDEX_TEST_REF_EXT             0x81B7\ntypedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glIndexFuncEXT (GLenum func, GLclampf ref);\n#endif\n#endif /* GL_EXT_index_func */\n\n#ifndef GL_EXT_index_material\n#define GL_EXT_index_material 1\n#define GL_INDEX_MATERIAL_EXT             0x81B8\n#define GL_INDEX_MATERIAL_PARAMETER_EXT   0x81B9\n#define GL_INDEX_MATERIAL_FACE_EXT        0x81BA\ntypedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glIndexMaterialEXT (GLenum face, GLenum mode);\n#endif\n#endif /* GL_EXT_index_material */\n\n#ifndef GL_EXT_index_texture\n#define GL_EXT_index_texture 1\n#endif /* GL_EXT_index_texture */\n\n#ifndef GL_EXT_light_texture\n#define GL_EXT_light_texture 1\n#define GL_FRAGMENT_MATERIAL_EXT          0x8349\n#define GL_FRAGMENT_NORMAL_EXT            0x834A\n#define GL_FRAGMENT_COLOR_EXT             0x834C\n#define GL_ATTENUATION_EXT                0x834D\n#define GL_SHADOW_ATTENUATION_EXT         0x834E\n#define GL_TEXTURE_APPLICATION_MODE_EXT   0x834F\n#define GL_TEXTURE_LIGHT_EXT              0x8350\n#define GL_TEXTURE_MATERIAL_FACE_EXT      0x8351\n#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352\ntypedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);\ntypedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);\ntypedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glApplyTextureEXT (GLenum mode);\nGLAPI void APIENTRY glTextureLightEXT (GLenum pname);\nGLAPI void APIENTRY glTextureMaterialEXT (GLenum face, GLenum mode);\n#endif\n#endif /* GL_EXT_light_texture */\n\n#ifndef GL_EXT_misc_attribute\n#define GL_EXT_misc_attribute 1\n#endif /* GL_EXT_misc_attribute */\n\n#ifndef GL_EXT_multi_draw_arrays\n#define GL_EXT_multi_draw_arrays 1\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);\nGLAPI void APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount);\n#endif\n#endif /* GL_EXT_multi_draw_arrays */\n\n#ifndef GL_EXT_multisample\n#define GL_EXT_multisample 1\n#define GL_MULTISAMPLE_EXT                0x809D\n#define GL_SAMPLE_ALPHA_TO_MASK_EXT       0x809E\n#define GL_SAMPLE_ALPHA_TO_ONE_EXT        0x809F\n#define GL_SAMPLE_MASK_EXT                0x80A0\n#define GL_1PASS_EXT                      0x80A1\n#define GL_2PASS_0_EXT                    0x80A2\n#define GL_2PASS_1_EXT                    0x80A3\n#define GL_4PASS_0_EXT                    0x80A4\n#define GL_4PASS_1_EXT                    0x80A5\n#define GL_4PASS_2_EXT                    0x80A6\n#define GL_4PASS_3_EXT                    0x80A7\n#define GL_SAMPLE_BUFFERS_EXT             0x80A8\n#define GL_SAMPLES_EXT                    0x80A9\n#define GL_SAMPLE_MASK_VALUE_EXT          0x80AA\n#define GL_SAMPLE_MASK_INVERT_EXT         0x80AB\n#define GL_SAMPLE_PATTERN_EXT             0x80AC\n#define GL_MULTISAMPLE_BIT_EXT            0x20000000\ntypedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSampleMaskEXT (GLclampf value, GLboolean invert);\nGLAPI void APIENTRY glSamplePatternEXT (GLenum pattern);\n#endif\n#endif /* GL_EXT_multisample */\n\n#ifndef GL_EXT_packed_depth_stencil\n#define GL_EXT_packed_depth_stencil 1\n#define GL_DEPTH_STENCIL_EXT              0x84F9\n#define GL_UNSIGNED_INT_24_8_EXT          0x84FA\n#define GL_DEPTH24_STENCIL8_EXT           0x88F0\n#define GL_TEXTURE_STENCIL_SIZE_EXT       0x88F1\n#endif /* GL_EXT_packed_depth_stencil */\n\n#ifndef GL_EXT_packed_float\n#define GL_EXT_packed_float 1\n#define GL_R11F_G11F_B10F_EXT             0x8C3A\n#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT 0x8C3B\n#define GL_RGBA_SIGNED_COMPONENTS_EXT     0x8C3C\n#endif /* GL_EXT_packed_float */\n\n#ifndef GL_EXT_packed_pixels\n#define GL_EXT_packed_pixels 1\n#define GL_UNSIGNED_BYTE_3_3_2_EXT        0x8032\n#define GL_UNSIGNED_SHORT_4_4_4_4_EXT     0x8033\n#define GL_UNSIGNED_SHORT_5_5_5_1_EXT     0x8034\n#define GL_UNSIGNED_INT_8_8_8_8_EXT       0x8035\n#define GL_UNSIGNED_INT_10_10_10_2_EXT    0x8036\n#endif /* GL_EXT_packed_pixels */\n\n#ifndef GL_EXT_paletted_texture\n#define GL_EXT_paletted_texture 1\n#define GL_COLOR_INDEX1_EXT               0x80E2\n#define GL_COLOR_INDEX2_EXT               0x80E3\n#define GL_COLOR_INDEX4_EXT               0x80E4\n#define GL_COLOR_INDEX8_EXT               0x80E5\n#define GL_COLOR_INDEX12_EXT              0x80E6\n#define GL_COLOR_INDEX16_EXT              0x80E7\n#define GL_TEXTURE_INDEX_SIZE_EXT         0x80ED\ntypedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, void *data);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table);\nGLAPI void APIENTRY glGetColorTableEXT (GLenum target, GLenum format, GLenum type, void *data);\nGLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);\n#endif\n#endif /* GL_EXT_paletted_texture */\n\n#ifndef GL_EXT_pixel_buffer_object\n#define GL_EXT_pixel_buffer_object 1\n#define GL_PIXEL_PACK_BUFFER_EXT          0x88EB\n#define GL_PIXEL_UNPACK_BUFFER_EXT        0x88EC\n#define GL_PIXEL_PACK_BUFFER_BINDING_EXT  0x88ED\n#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF\n#endif /* GL_EXT_pixel_buffer_object */\n\n#ifndef GL_EXT_pixel_transform\n#define GL_EXT_pixel_transform 1\n#define GL_PIXEL_TRANSFORM_2D_EXT         0x8330\n#define GL_PIXEL_MAG_FILTER_EXT           0x8331\n#define GL_PIXEL_MIN_FILTER_EXT           0x8332\n#define GL_PIXEL_CUBIC_WEIGHT_EXT         0x8333\n#define GL_CUBIC_EXT                      0x8334\n#define GL_AVERAGE_EXT                    0x8335\n#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336\n#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337\n#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT  0x8338\ntypedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum target, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glGetPixelTransformParameterivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetPixelTransformParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);\n#endif\n#endif /* GL_EXT_pixel_transform */\n\n#ifndef GL_EXT_pixel_transform_color_table\n#define GL_EXT_pixel_transform_color_table 1\n#endif /* GL_EXT_pixel_transform_color_table */\n\n#ifndef GL_EXT_point_parameters\n#define GL_EXT_point_parameters 1\n#define GL_POINT_SIZE_MIN_EXT             0x8126\n#define GL_POINT_SIZE_MAX_EXT             0x8127\n#define GL_POINT_FADE_THRESHOLD_SIZE_EXT  0x8128\n#define GL_DISTANCE_ATTENUATION_EXT       0x8129\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameterfEXT (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glPointParameterfvEXT (GLenum pname, const GLfloat *params);\n#endif\n#endif /* GL_EXT_point_parameters */\n\n#ifndef GL_EXT_polygon_offset\n#define GL_EXT_polygon_offset 1\n#define GL_POLYGON_OFFSET_EXT             0x8037\n#define GL_POLYGON_OFFSET_FACTOR_EXT      0x8038\n#define GL_POLYGON_OFFSET_BIAS_EXT        0x8039\ntypedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPolygonOffsetEXT (GLfloat factor, GLfloat bias);\n#endif\n#endif /* GL_EXT_polygon_offset */\n\n#ifndef GL_EXT_provoking_vertex\n#define GL_EXT_provoking_vertex 1\n#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT 0x8E4C\n#define GL_FIRST_VERTEX_CONVENTION_EXT    0x8E4D\n#define GL_LAST_VERTEX_CONVENTION_EXT     0x8E4E\n#define GL_PROVOKING_VERTEX_EXT           0x8E4F\ntypedef void (APIENTRYP PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProvokingVertexEXT (GLenum mode);\n#endif\n#endif /* GL_EXT_provoking_vertex */\n\n#ifndef GL_EXT_rescale_normal\n#define GL_EXT_rescale_normal 1\n#define GL_RESCALE_NORMAL_EXT             0x803A\n#endif /* GL_EXT_rescale_normal */\n\n#ifndef GL_EXT_secondary_color\n#define GL_EXT_secondary_color 1\n#define GL_COLOR_SUM_EXT                  0x8458\n#define GL_CURRENT_SECONDARY_COLOR_EXT    0x8459\n#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A\n#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B\n#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C\n#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D\n#define GL_SECONDARY_COLOR_ARRAY_EXT      0x845E\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte red, GLbyte green, GLbyte blue);\nGLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *v);\nGLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble red, GLdouble green, GLdouble blue);\nGLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *v);\nGLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat red, GLfloat green, GLfloat blue);\nGLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *v);\nGLAPI void APIENTRY glSecondaryColor3iEXT (GLint red, GLint green, GLint blue);\nGLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *v);\nGLAPI void APIENTRY glSecondaryColor3sEXT (GLshort red, GLshort green, GLshort blue);\nGLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *v);\nGLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte red, GLubyte green, GLubyte blue);\nGLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *v);\nGLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint red, GLuint green, GLuint blue);\nGLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *v);\nGLAPI void APIENTRY glSecondaryColor3usEXT (GLushort red, GLushort green, GLushort blue);\nGLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *v);\nGLAPI void APIENTRY glSecondaryColorPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer);\n#endif\n#endif /* GL_EXT_secondary_color */\n\n#ifndef GL_EXT_separate_shader_objects\n#define GL_EXT_separate_shader_objects 1\n#define GL_ACTIVE_PROGRAM_EXT             0x8B8D\ntypedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program);\ntypedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program);\ntypedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glUseShaderProgramEXT (GLenum type, GLuint program);\nGLAPI void APIENTRY glActiveProgramEXT (GLuint program);\nGLAPI GLuint APIENTRY glCreateShaderProgramEXT (GLenum type, const GLchar *string);\n#endif\n#endif /* GL_EXT_separate_shader_objects */\n\n#ifndef GL_EXT_separate_specular_color\n#define GL_EXT_separate_specular_color 1\n#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT  0x81F8\n#define GL_SINGLE_COLOR_EXT               0x81F9\n#define GL_SEPARATE_SPECULAR_COLOR_EXT    0x81FA\n#endif /* GL_EXT_separate_specular_color */\n\n#ifndef GL_EXT_shader_image_load_store\n#define GL_EXT_shader_image_load_store 1\n#define GL_MAX_IMAGE_UNITS_EXT            0x8F38\n#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT 0x8F39\n#define GL_IMAGE_BINDING_NAME_EXT         0x8F3A\n#define GL_IMAGE_BINDING_LEVEL_EXT        0x8F3B\n#define GL_IMAGE_BINDING_LAYERED_EXT      0x8F3C\n#define GL_IMAGE_BINDING_LAYER_EXT        0x8F3D\n#define GL_IMAGE_BINDING_ACCESS_EXT       0x8F3E\n#define GL_IMAGE_1D_EXT                   0x904C\n#define GL_IMAGE_2D_EXT                   0x904D\n#define GL_IMAGE_3D_EXT                   0x904E\n#define GL_IMAGE_2D_RECT_EXT              0x904F\n#define GL_IMAGE_CUBE_EXT                 0x9050\n#define GL_IMAGE_BUFFER_EXT               0x9051\n#define GL_IMAGE_1D_ARRAY_EXT             0x9052\n#define GL_IMAGE_2D_ARRAY_EXT             0x9053\n#define GL_IMAGE_CUBE_MAP_ARRAY_EXT       0x9054\n#define GL_IMAGE_2D_MULTISAMPLE_EXT       0x9055\n#define GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9056\n#define GL_INT_IMAGE_1D_EXT               0x9057\n#define GL_INT_IMAGE_2D_EXT               0x9058\n#define GL_INT_IMAGE_3D_EXT               0x9059\n#define GL_INT_IMAGE_2D_RECT_EXT          0x905A\n#define GL_INT_IMAGE_CUBE_EXT             0x905B\n#define GL_INT_IMAGE_BUFFER_EXT           0x905C\n#define GL_INT_IMAGE_1D_ARRAY_EXT         0x905D\n#define GL_INT_IMAGE_2D_ARRAY_EXT         0x905E\n#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT   0x905F\n#define GL_INT_IMAGE_2D_MULTISAMPLE_EXT   0x9060\n#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9061\n#define GL_UNSIGNED_INT_IMAGE_1D_EXT      0x9062\n#define GL_UNSIGNED_INT_IMAGE_2D_EXT      0x9063\n#define GL_UNSIGNED_INT_IMAGE_3D_EXT      0x9064\n#define GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT 0x9065\n#define GL_UNSIGNED_INT_IMAGE_CUBE_EXT    0x9066\n#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT  0x9067\n#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT 0x9068\n#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT 0x9069\n#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A\n#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT 0x906B\n#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x906C\n#define GL_MAX_IMAGE_SAMPLES_EXT          0x906D\n#define GL_IMAGE_BINDING_FORMAT_EXT       0x906E\n#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT 0x00000001\n#define GL_ELEMENT_ARRAY_BARRIER_BIT_EXT  0x00000002\n#define GL_UNIFORM_BARRIER_BIT_EXT        0x00000004\n#define GL_TEXTURE_FETCH_BARRIER_BIT_EXT  0x00000008\n#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT 0x00000020\n#define GL_COMMAND_BARRIER_BIT_EXT        0x00000040\n#define GL_PIXEL_BUFFER_BARRIER_BIT_EXT   0x00000080\n#define GL_TEXTURE_UPDATE_BARRIER_BIT_EXT 0x00000100\n#define GL_BUFFER_UPDATE_BARRIER_BIT_EXT  0x00000200\n#define GL_FRAMEBUFFER_BARRIER_BIT_EXT    0x00000400\n#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT 0x00000800\n#define GL_ATOMIC_COUNTER_BARRIER_BIT_EXT 0x00001000\n#define GL_ALL_BARRIER_BITS_EXT           0xFFFFFFFF\ntypedef void (APIENTRYP PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format);\ntypedef void (APIENTRYP PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindImageTextureEXT (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format);\nGLAPI void APIENTRY glMemoryBarrierEXT (GLbitfield barriers);\n#endif\n#endif /* GL_EXT_shader_image_load_store */\n\n#ifndef GL_EXT_shader_integer_mix\n#define GL_EXT_shader_integer_mix 1\n#endif /* GL_EXT_shader_integer_mix */\n\n#ifndef GL_EXT_shadow_funcs\n#define GL_EXT_shadow_funcs 1\n#endif /* GL_EXT_shadow_funcs */\n\n#ifndef GL_EXT_shared_texture_palette\n#define GL_EXT_shared_texture_palette 1\n#define GL_SHARED_TEXTURE_PALETTE_EXT     0x81FB\n#endif /* GL_EXT_shared_texture_palette */\n\n#ifndef GL_EXT_stencil_clear_tag\n#define GL_EXT_stencil_clear_tag 1\n#define GL_STENCIL_TAG_BITS_EXT           0x88F2\n#define GL_STENCIL_CLEAR_TAG_VALUE_EXT    0x88F3\ntypedef void (APIENTRYP PFNGLSTENCILCLEARTAGEXTPROC) (GLsizei stencilTagBits, GLuint stencilClearTag);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glStencilClearTagEXT (GLsizei stencilTagBits, GLuint stencilClearTag);\n#endif\n#endif /* GL_EXT_stencil_clear_tag */\n\n#ifndef GL_EXT_stencil_two_side\n#define GL_EXT_stencil_two_side 1\n#define GL_STENCIL_TEST_TWO_SIDE_EXT      0x8910\n#define GL_ACTIVE_STENCIL_FACE_EXT        0x8911\ntypedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glActiveStencilFaceEXT (GLenum face);\n#endif\n#endif /* GL_EXT_stencil_two_side */\n\n#ifndef GL_EXT_stencil_wrap\n#define GL_EXT_stencil_wrap 1\n#define GL_INCR_WRAP_EXT                  0x8507\n#define GL_DECR_WRAP_EXT                  0x8508\n#endif /* GL_EXT_stencil_wrap */\n\n#ifndef GL_EXT_subtexture\n#define GL_EXT_subtexture 1\ntypedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);\n#endif\n#endif /* GL_EXT_subtexture */\n\n#ifndef GL_EXT_texture\n#define GL_EXT_texture 1\n#define GL_ALPHA4_EXT                     0x803B\n#define GL_ALPHA8_EXT                     0x803C\n#define GL_ALPHA12_EXT                    0x803D\n#define GL_ALPHA16_EXT                    0x803E\n#define GL_LUMINANCE4_EXT                 0x803F\n#define GL_LUMINANCE8_EXT                 0x8040\n#define GL_LUMINANCE12_EXT                0x8041\n#define GL_LUMINANCE16_EXT                0x8042\n#define GL_LUMINANCE4_ALPHA4_EXT          0x8043\n#define GL_LUMINANCE6_ALPHA2_EXT          0x8044\n#define GL_LUMINANCE8_ALPHA8_EXT          0x8045\n#define GL_LUMINANCE12_ALPHA4_EXT         0x8046\n#define GL_LUMINANCE12_ALPHA12_EXT        0x8047\n#define GL_LUMINANCE16_ALPHA16_EXT        0x8048\n#define GL_INTENSITY_EXT                  0x8049\n#define GL_INTENSITY4_EXT                 0x804A\n#define GL_INTENSITY8_EXT                 0x804B\n#define GL_INTENSITY12_EXT                0x804C\n#define GL_INTENSITY16_EXT                0x804D\n#define GL_RGB2_EXT                       0x804E\n#define GL_RGB4_EXT                       0x804F\n#define GL_RGB5_EXT                       0x8050\n#define GL_RGB8_EXT                       0x8051\n#define GL_RGB10_EXT                      0x8052\n#define GL_RGB12_EXT                      0x8053\n#define GL_RGB16_EXT                      0x8054\n#define GL_RGBA2_EXT                      0x8055\n#define GL_RGBA4_EXT                      0x8056\n#define GL_RGB5_A1_EXT                    0x8057\n#define GL_RGBA8_EXT                      0x8058\n#define GL_RGB10_A2_EXT                   0x8059\n#define GL_RGBA12_EXT                     0x805A\n#define GL_RGBA16_EXT                     0x805B\n#define GL_TEXTURE_RED_SIZE_EXT           0x805C\n#define GL_TEXTURE_GREEN_SIZE_EXT         0x805D\n#define GL_TEXTURE_BLUE_SIZE_EXT          0x805E\n#define GL_TEXTURE_ALPHA_SIZE_EXT         0x805F\n#define GL_TEXTURE_LUMINANCE_SIZE_EXT     0x8060\n#define GL_TEXTURE_INTENSITY_SIZE_EXT     0x8061\n#define GL_REPLACE_EXT                    0x8062\n#define GL_PROXY_TEXTURE_1D_EXT           0x8063\n#define GL_PROXY_TEXTURE_2D_EXT           0x8064\n#define GL_TEXTURE_TOO_LARGE_EXT          0x8065\n#endif /* GL_EXT_texture */\n\n#ifndef GL_EXT_texture3D\n#define GL_EXT_texture3D 1\n#define GL_PACK_SKIP_IMAGES_EXT           0x806B\n#define GL_PACK_IMAGE_HEIGHT_EXT          0x806C\n#define GL_UNPACK_SKIP_IMAGES_EXT         0x806D\n#define GL_UNPACK_IMAGE_HEIGHT_EXT        0x806E\n#define GL_TEXTURE_3D_EXT                 0x806F\n#define GL_PROXY_TEXTURE_3D_EXT           0x8070\n#define GL_TEXTURE_DEPTH_EXT              0x8071\n#define GL_TEXTURE_WRAP_R_EXT             0x8072\n#define GL_MAX_3D_TEXTURE_SIZE_EXT        0x8073\ntypedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);\n#endif\n#endif /* GL_EXT_texture3D */\n\n#ifndef GL_EXT_texture_array\n#define GL_EXT_texture_array 1\n#define GL_TEXTURE_1D_ARRAY_EXT           0x8C18\n#define GL_PROXY_TEXTURE_1D_ARRAY_EXT     0x8C19\n#define GL_TEXTURE_2D_ARRAY_EXT           0x8C1A\n#define GL_PROXY_TEXTURE_2D_ARRAY_EXT     0x8C1B\n#define GL_TEXTURE_BINDING_1D_ARRAY_EXT   0x8C1C\n#define GL_TEXTURE_BINDING_2D_ARRAY_EXT   0x8C1D\n#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT   0x88FF\n#define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E\n#endif /* GL_EXT_texture_array */\n\n#ifndef GL_EXT_texture_buffer_object\n#define GL_EXT_texture_buffer_object 1\n#define GL_TEXTURE_BUFFER_EXT             0x8C2A\n#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT    0x8C2B\n#define GL_TEXTURE_BINDING_BUFFER_EXT     0x8C2C\n#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D\n#define GL_TEXTURE_BUFFER_FORMAT_EXT      0x8C2E\ntypedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer);\n#endif\n#endif /* GL_EXT_texture_buffer_object */\n\n#ifndef GL_EXT_texture_compression_latc\n#define GL_EXT_texture_compression_latc 1\n#define GL_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70\n#define GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71\n#define GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72\n#define GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73\n#endif /* GL_EXT_texture_compression_latc */\n\n#ifndef GL_EXT_texture_compression_rgtc\n#define GL_EXT_texture_compression_rgtc 1\n#define GL_COMPRESSED_RED_RGTC1_EXT       0x8DBB\n#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC\n#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD\n#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE\n#endif /* GL_EXT_texture_compression_rgtc */\n\n#ifndef GL_EXT_texture_compression_s3tc\n#define GL_EXT_texture_compression_s3tc 1\n#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT   0x83F0\n#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT  0x83F1\n#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2\n#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3\n#endif /* GL_EXT_texture_compression_s3tc */\n\n#ifndef GL_EXT_texture_cube_map\n#define GL_EXT_texture_cube_map 1\n#define GL_NORMAL_MAP_EXT                 0x8511\n#define GL_REFLECTION_MAP_EXT             0x8512\n#define GL_TEXTURE_CUBE_MAP_EXT           0x8513\n#define GL_TEXTURE_BINDING_CUBE_MAP_EXT   0x8514\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518\n#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519\n#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A\n#define GL_PROXY_TEXTURE_CUBE_MAP_EXT     0x851B\n#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT  0x851C\n#endif /* GL_EXT_texture_cube_map */\n\n#ifndef GL_EXT_texture_env_add\n#define GL_EXT_texture_env_add 1\n#endif /* GL_EXT_texture_env_add */\n\n#ifndef GL_EXT_texture_env_combine\n#define GL_EXT_texture_env_combine 1\n#define GL_COMBINE_EXT                    0x8570\n#define GL_COMBINE_RGB_EXT                0x8571\n#define GL_COMBINE_ALPHA_EXT              0x8572\n#define GL_RGB_SCALE_EXT                  0x8573\n#define GL_ADD_SIGNED_EXT                 0x8574\n#define GL_INTERPOLATE_EXT                0x8575\n#define GL_CONSTANT_EXT                   0x8576\n#define GL_PRIMARY_COLOR_EXT              0x8577\n#define GL_PREVIOUS_EXT                   0x8578\n#define GL_SOURCE0_RGB_EXT                0x8580\n#define GL_SOURCE1_RGB_EXT                0x8581\n#define GL_SOURCE2_RGB_EXT                0x8582\n#define GL_SOURCE0_ALPHA_EXT              0x8588\n#define GL_SOURCE1_ALPHA_EXT              0x8589\n#define GL_SOURCE2_ALPHA_EXT              0x858A\n#define GL_OPERAND0_RGB_EXT               0x8590\n#define GL_OPERAND1_RGB_EXT               0x8591\n#define GL_OPERAND2_RGB_EXT               0x8592\n#define GL_OPERAND0_ALPHA_EXT             0x8598\n#define GL_OPERAND1_ALPHA_EXT             0x8599\n#define GL_OPERAND2_ALPHA_EXT             0x859A\n#endif /* GL_EXT_texture_env_combine */\n\n#ifndef GL_EXT_texture_env_dot3\n#define GL_EXT_texture_env_dot3 1\n#define GL_DOT3_RGB_EXT                   0x8740\n#define GL_DOT3_RGBA_EXT                  0x8741\n#endif /* GL_EXT_texture_env_dot3 */\n\n#ifndef GL_EXT_texture_filter_anisotropic\n#define GL_EXT_texture_filter_anisotropic 1\n#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE\n#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF\n#endif /* GL_EXT_texture_filter_anisotropic */\n\n#ifndef GL_EXT_texture_integer\n#define GL_EXT_texture_integer 1\n#define GL_RGBA32UI_EXT                   0x8D70\n#define GL_RGB32UI_EXT                    0x8D71\n#define GL_ALPHA32UI_EXT                  0x8D72\n#define GL_INTENSITY32UI_EXT              0x8D73\n#define GL_LUMINANCE32UI_EXT              0x8D74\n#define GL_LUMINANCE_ALPHA32UI_EXT        0x8D75\n#define GL_RGBA16UI_EXT                   0x8D76\n#define GL_RGB16UI_EXT                    0x8D77\n#define GL_ALPHA16UI_EXT                  0x8D78\n#define GL_INTENSITY16UI_EXT              0x8D79\n#define GL_LUMINANCE16UI_EXT              0x8D7A\n#define GL_LUMINANCE_ALPHA16UI_EXT        0x8D7B\n#define GL_RGBA8UI_EXT                    0x8D7C\n#define GL_RGB8UI_EXT                     0x8D7D\n#define GL_ALPHA8UI_EXT                   0x8D7E\n#define GL_INTENSITY8UI_EXT               0x8D7F\n#define GL_LUMINANCE8UI_EXT               0x8D80\n#define GL_LUMINANCE_ALPHA8UI_EXT         0x8D81\n#define GL_RGBA32I_EXT                    0x8D82\n#define GL_RGB32I_EXT                     0x8D83\n#define GL_ALPHA32I_EXT                   0x8D84\n#define GL_INTENSITY32I_EXT               0x8D85\n#define GL_LUMINANCE32I_EXT               0x8D86\n#define GL_LUMINANCE_ALPHA32I_EXT         0x8D87\n#define GL_RGBA16I_EXT                    0x8D88\n#define GL_RGB16I_EXT                     0x8D89\n#define GL_ALPHA16I_EXT                   0x8D8A\n#define GL_INTENSITY16I_EXT               0x8D8B\n#define GL_LUMINANCE16I_EXT               0x8D8C\n#define GL_LUMINANCE_ALPHA16I_EXT         0x8D8D\n#define GL_RGBA8I_EXT                     0x8D8E\n#define GL_RGB8I_EXT                      0x8D8F\n#define GL_ALPHA8I_EXT                    0x8D90\n#define GL_INTENSITY8I_EXT                0x8D91\n#define GL_LUMINANCE8I_EXT                0x8D92\n#define GL_LUMINANCE_ALPHA8I_EXT          0x8D93\n#define GL_RED_INTEGER_EXT                0x8D94\n#define GL_GREEN_INTEGER_EXT              0x8D95\n#define GL_BLUE_INTEGER_EXT               0x8D96\n#define GL_ALPHA_INTEGER_EXT              0x8D97\n#define GL_RGB_INTEGER_EXT                0x8D98\n#define GL_RGBA_INTEGER_EXT               0x8D99\n#define GL_BGR_INTEGER_EXT                0x8D9A\n#define GL_BGRA_INTEGER_EXT               0x8D9B\n#define GL_LUMINANCE_INTEGER_EXT          0x8D9C\n#define GL_LUMINANCE_ALPHA_INTEGER_EXT    0x8D9D\n#define GL_RGBA_INTEGER_MODE_EXT          0x8D9E\ntypedef void (APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLCLEARCOLORIIEXTPROC) (GLint red, GLint green, GLint blue, GLint alpha);\ntypedef void (APIENTRYP PFNGLCLEARCOLORIUIEXTPROC) (GLuint red, GLuint green, GLuint blue, GLuint alpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params);\nGLAPI void APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glClearColorIiEXT (GLint red, GLint green, GLint blue, GLint alpha);\nGLAPI void APIENTRY glClearColorIuiEXT (GLuint red, GLuint green, GLuint blue, GLuint alpha);\n#endif\n#endif /* GL_EXT_texture_integer */\n\n#ifndef GL_EXT_texture_lod_bias\n#define GL_EXT_texture_lod_bias 1\n#define GL_MAX_TEXTURE_LOD_BIAS_EXT       0x84FD\n#define GL_TEXTURE_FILTER_CONTROL_EXT     0x8500\n#define GL_TEXTURE_LOD_BIAS_EXT           0x8501\n#endif /* GL_EXT_texture_lod_bias */\n\n#ifndef GL_EXT_texture_mirror_clamp\n#define GL_EXT_texture_mirror_clamp 1\n#define GL_MIRROR_CLAMP_EXT               0x8742\n#define GL_MIRROR_CLAMP_TO_EDGE_EXT       0x8743\n#define GL_MIRROR_CLAMP_TO_BORDER_EXT     0x8912\n#endif /* GL_EXT_texture_mirror_clamp */\n\n#ifndef GL_EXT_texture_object\n#define GL_EXT_texture_object 1\n#define GL_TEXTURE_PRIORITY_EXT           0x8066\n#define GL_TEXTURE_RESIDENT_EXT           0x8067\n#define GL_TEXTURE_1D_BINDING_EXT         0x8068\n#define GL_TEXTURE_2D_BINDING_EXT         0x8069\n#define GL_TEXTURE_3D_BINDING_EXT         0x806A\ntypedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences);\ntypedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture);\ntypedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures);\ntypedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures);\ntypedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture);\ntypedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei n, const GLuint *textures, GLboolean *residences);\nGLAPI void APIENTRY glBindTextureEXT (GLenum target, GLuint texture);\nGLAPI void APIENTRY glDeleteTexturesEXT (GLsizei n, const GLuint *textures);\nGLAPI void APIENTRY glGenTexturesEXT (GLsizei n, GLuint *textures);\nGLAPI GLboolean APIENTRY glIsTextureEXT (GLuint texture);\nGLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei n, const GLuint *textures, const GLclampf *priorities);\n#endif\n#endif /* GL_EXT_texture_object */\n\n#ifndef GL_EXT_texture_perturb_normal\n#define GL_EXT_texture_perturb_normal 1\n#define GL_PERTURB_EXT                    0x85AE\n#define GL_TEXTURE_NORMAL_EXT             0x85AF\ntypedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTextureNormalEXT (GLenum mode);\n#endif\n#endif /* GL_EXT_texture_perturb_normal */\n\n#ifndef GL_EXT_texture_sRGB\n#define GL_EXT_texture_sRGB 1\n#define GL_SRGB_EXT                       0x8C40\n#define GL_SRGB8_EXT                      0x8C41\n#define GL_SRGB_ALPHA_EXT                 0x8C42\n#define GL_SRGB8_ALPHA8_EXT               0x8C43\n#define GL_SLUMINANCE_ALPHA_EXT           0x8C44\n#define GL_SLUMINANCE8_ALPHA8_EXT         0x8C45\n#define GL_SLUMINANCE_EXT                 0x8C46\n#define GL_SLUMINANCE8_EXT                0x8C47\n#define GL_COMPRESSED_SRGB_EXT            0x8C48\n#define GL_COMPRESSED_SRGB_ALPHA_EXT      0x8C49\n#define GL_COMPRESSED_SLUMINANCE_EXT      0x8C4A\n#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B\n#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT  0x8C4C\n#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D\n#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E\n#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F\n#endif /* GL_EXT_texture_sRGB */\n\n#ifndef GL_EXT_texture_sRGB_decode\n#define GL_EXT_texture_sRGB_decode 1\n#define GL_TEXTURE_SRGB_DECODE_EXT        0x8A48\n#define GL_DECODE_EXT                     0x8A49\n#define GL_SKIP_DECODE_EXT                0x8A4A\n#endif /* GL_EXT_texture_sRGB_decode */\n\n#ifndef GL_EXT_texture_shared_exponent\n#define GL_EXT_texture_shared_exponent 1\n#define GL_RGB9_E5_EXT                    0x8C3D\n#define GL_UNSIGNED_INT_5_9_9_9_REV_EXT   0x8C3E\n#define GL_TEXTURE_SHARED_SIZE_EXT        0x8C3F\n#endif /* GL_EXT_texture_shared_exponent */\n\n#ifndef GL_EXT_texture_snorm\n#define GL_EXT_texture_snorm 1\n#define GL_ALPHA_SNORM                    0x9010\n#define GL_LUMINANCE_SNORM                0x9011\n#define GL_LUMINANCE_ALPHA_SNORM          0x9012\n#define GL_INTENSITY_SNORM                0x9013\n#define GL_ALPHA8_SNORM                   0x9014\n#define GL_LUMINANCE8_SNORM               0x9015\n#define GL_LUMINANCE8_ALPHA8_SNORM        0x9016\n#define GL_INTENSITY8_SNORM               0x9017\n#define GL_ALPHA16_SNORM                  0x9018\n#define GL_LUMINANCE16_SNORM              0x9019\n#define GL_LUMINANCE16_ALPHA16_SNORM      0x901A\n#define GL_INTENSITY16_SNORM              0x901B\n#define GL_RED_SNORM                      0x8F90\n#define GL_RG_SNORM                       0x8F91\n#define GL_RGB_SNORM                      0x8F92\n#define GL_RGBA_SNORM                     0x8F93\n#endif /* GL_EXT_texture_snorm */\n\n#ifndef GL_EXT_texture_swizzle\n#define GL_EXT_texture_swizzle 1\n#define GL_TEXTURE_SWIZZLE_R_EXT          0x8E42\n#define GL_TEXTURE_SWIZZLE_G_EXT          0x8E43\n#define GL_TEXTURE_SWIZZLE_B_EXT          0x8E44\n#define GL_TEXTURE_SWIZZLE_A_EXT          0x8E45\n#define GL_TEXTURE_SWIZZLE_RGBA_EXT       0x8E46\n#endif /* GL_EXT_texture_swizzle */\n\n#ifndef GL_EXT_timer_query\n#define GL_EXT_timer_query 1\n#define GL_TIME_ELAPSED_EXT               0x88BF\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params);\ntypedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params);\nGLAPI void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params);\n#endif\n#endif /* GL_EXT_timer_query */\n\n#ifndef GL_EXT_transform_feedback\n#define GL_EXT_transform_feedback 1\n#define GL_TRANSFORM_FEEDBACK_BUFFER_EXT  0x8C8E\n#define GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT 0x8C84\n#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT 0x8C85\n#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT 0x8C8F\n#define GL_INTERLEAVED_ATTRIBS_EXT        0x8C8C\n#define GL_SEPARATE_ATTRIBS_EXT           0x8C8D\n#define GL_PRIMITIVES_GENERATED_EXT       0x8C87\n#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT 0x8C88\n#define GL_RASTERIZER_DISCARD_EXT         0x8C89\n#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT 0x8C8A\n#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT 0x8C8B\n#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT 0x8C80\n#define GL_TRANSFORM_FEEDBACK_VARYINGS_EXT 0x8C83\n#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT 0x8C7F\n#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT 0x8C76\ntypedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKEXTPROC) (GLenum primitiveMode);\ntypedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKEXTPROC) (void);\ntypedef void (APIENTRYP PFNGLBINDBUFFERRANGEEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLBINDBUFFEROFFSETEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset);\ntypedef void (APIENTRYP PFNGLBINDBUFFERBASEEXTPROC) (GLenum target, GLuint index, GLuint buffer);\ntypedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSEXTPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);\ntypedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGEXTPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginTransformFeedbackEXT (GLenum primitiveMode);\nGLAPI void APIENTRY glEndTransformFeedbackEXT (void);\nGLAPI void APIENTRY glBindBufferRangeEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);\nGLAPI void APIENTRY glBindBufferOffsetEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset);\nGLAPI void APIENTRY glBindBufferBaseEXT (GLenum target, GLuint index, GLuint buffer);\nGLAPI void APIENTRY glTransformFeedbackVaryingsEXT (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode);\nGLAPI void APIENTRY glGetTransformFeedbackVaryingEXT (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);\n#endif\n#endif /* GL_EXT_transform_feedback */\n\n#ifndef GL_EXT_vertex_array\n#define GL_EXT_vertex_array 1\n#define GL_VERTEX_ARRAY_EXT               0x8074\n#define GL_NORMAL_ARRAY_EXT               0x8075\n#define GL_COLOR_ARRAY_EXT                0x8076\n#define GL_INDEX_ARRAY_EXT                0x8077\n#define GL_TEXTURE_COORD_ARRAY_EXT        0x8078\n#define GL_EDGE_FLAG_ARRAY_EXT            0x8079\n#define GL_VERTEX_ARRAY_SIZE_EXT          0x807A\n#define GL_VERTEX_ARRAY_TYPE_EXT          0x807B\n#define GL_VERTEX_ARRAY_STRIDE_EXT        0x807C\n#define GL_VERTEX_ARRAY_COUNT_EXT         0x807D\n#define GL_NORMAL_ARRAY_TYPE_EXT          0x807E\n#define GL_NORMAL_ARRAY_STRIDE_EXT        0x807F\n#define GL_NORMAL_ARRAY_COUNT_EXT         0x8080\n#define GL_COLOR_ARRAY_SIZE_EXT           0x8081\n#define GL_COLOR_ARRAY_TYPE_EXT           0x8082\n#define GL_COLOR_ARRAY_STRIDE_EXT         0x8083\n#define GL_COLOR_ARRAY_COUNT_EXT          0x8084\n#define GL_INDEX_ARRAY_TYPE_EXT           0x8085\n#define GL_INDEX_ARRAY_STRIDE_EXT         0x8086\n#define GL_INDEX_ARRAY_COUNT_EXT          0x8087\n#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT   0x8088\n#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT   0x8089\n#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A\n#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT  0x808B\n#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT     0x808C\n#define GL_EDGE_FLAG_ARRAY_COUNT_EXT      0x808D\n#define GL_VERTEX_ARRAY_POINTER_EXT       0x808E\n#define GL_NORMAL_ARRAY_POINTER_EXT       0x808F\n#define GL_COLOR_ARRAY_POINTER_EXT        0x8090\n#define GL_INDEX_ARRAY_POINTER_EXT        0x8091\n#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092\n#define GL_EDGE_FLAG_ARRAY_POINTER_EXT    0x8093\ntypedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);\ntypedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer);\ntypedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count);\ntypedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer);\ntypedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, void **params);\ntypedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer);\ntypedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer);\ntypedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glArrayElementEXT (GLint i);\nGLAPI void APIENTRY glColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer);\nGLAPI void APIENTRY glDrawArraysEXT (GLenum mode, GLint first, GLsizei count);\nGLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei stride, GLsizei count, const GLboolean *pointer);\nGLAPI void APIENTRY glGetPointervEXT (GLenum pname, void **params);\nGLAPI void APIENTRY glIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer);\nGLAPI void APIENTRY glNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer);\nGLAPI void APIENTRY glTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer);\nGLAPI void APIENTRY glVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer);\n#endif\n#endif /* GL_EXT_vertex_array */\n\n#ifndef GL_EXT_vertex_array_bgra\n#define GL_EXT_vertex_array_bgra 1\n#endif /* GL_EXT_vertex_array_bgra */\n\n#ifndef GL_EXT_vertex_attrib_64bit\n#define GL_EXT_vertex_attrib_64bit 1\n#define GL_DOUBLE_VEC2_EXT                0x8FFC\n#define GL_DOUBLE_VEC3_EXT                0x8FFD\n#define GL_DOUBLE_VEC4_EXT                0x8FFE\n#define GL_DOUBLE_MAT2_EXT                0x8F46\n#define GL_DOUBLE_MAT3_EXT                0x8F47\n#define GL_DOUBLE_MAT4_EXT                0x8F48\n#define GL_DOUBLE_MAT2x3_EXT              0x8F49\n#define GL_DOUBLE_MAT2x4_EXT              0x8F4A\n#define GL_DOUBLE_MAT3x2_EXT              0x8F4B\n#define GL_DOUBLE_MAT3x4_EXT              0x8F4C\n#define GL_DOUBLE_MAT4x2_EXT              0x8F4D\n#define GL_DOUBLE_MAT4x3_EXT              0x8F4E\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1DEXTPROC) (GLuint index, GLdouble x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2DEXTPROC) (GLuint index, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVEXTPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVEXTPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVEXTPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVEXTPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribL1dEXT (GLuint index, GLdouble x);\nGLAPI void APIENTRY glVertexAttribL2dEXT (GLuint index, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glVertexAttribL3dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glVertexAttribL4dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glVertexAttribL1dvEXT (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribL2dvEXT (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribL3dvEXT (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribL4dvEXT (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribLPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glGetVertexAttribLdvEXT (GLuint index, GLenum pname, GLdouble *params);\n#endif\n#endif /* GL_EXT_vertex_attrib_64bit */\n\n#ifndef GL_EXT_vertex_shader\n#define GL_EXT_vertex_shader 1\n#define GL_VERTEX_SHADER_EXT              0x8780\n#define GL_VERTEX_SHADER_BINDING_EXT      0x8781\n#define GL_OP_INDEX_EXT                   0x8782\n#define GL_OP_NEGATE_EXT                  0x8783\n#define GL_OP_DOT3_EXT                    0x8784\n#define GL_OP_DOT4_EXT                    0x8785\n#define GL_OP_MUL_EXT                     0x8786\n#define GL_OP_ADD_EXT                     0x8787\n#define GL_OP_MADD_EXT                    0x8788\n#define GL_OP_FRAC_EXT                    0x8789\n#define GL_OP_MAX_EXT                     0x878A\n#define GL_OP_MIN_EXT                     0x878B\n#define GL_OP_SET_GE_EXT                  0x878C\n#define GL_OP_SET_LT_EXT                  0x878D\n#define GL_OP_CLAMP_EXT                   0x878E\n#define GL_OP_FLOOR_EXT                   0x878F\n#define GL_OP_ROUND_EXT                   0x8790\n#define GL_OP_EXP_BASE_2_EXT              0x8791\n#define GL_OP_LOG_BASE_2_EXT              0x8792\n#define GL_OP_POWER_EXT                   0x8793\n#define GL_OP_RECIP_EXT                   0x8794\n#define GL_OP_RECIP_SQRT_EXT              0x8795\n#define GL_OP_SUB_EXT                     0x8796\n#define GL_OP_CROSS_PRODUCT_EXT           0x8797\n#define GL_OP_MULTIPLY_MATRIX_EXT         0x8798\n#define GL_OP_MOV_EXT                     0x8799\n#define GL_OUTPUT_VERTEX_EXT              0x879A\n#define GL_OUTPUT_COLOR0_EXT              0x879B\n#define GL_OUTPUT_COLOR1_EXT              0x879C\n#define GL_OUTPUT_TEXTURE_COORD0_EXT      0x879D\n#define GL_OUTPUT_TEXTURE_COORD1_EXT      0x879E\n#define GL_OUTPUT_TEXTURE_COORD2_EXT      0x879F\n#define GL_OUTPUT_TEXTURE_COORD3_EXT      0x87A0\n#define GL_OUTPUT_TEXTURE_COORD4_EXT      0x87A1\n#define GL_OUTPUT_TEXTURE_COORD5_EXT      0x87A2\n#define GL_OUTPUT_TEXTURE_COORD6_EXT      0x87A3\n#define GL_OUTPUT_TEXTURE_COORD7_EXT      0x87A4\n#define GL_OUTPUT_TEXTURE_COORD8_EXT      0x87A5\n#define GL_OUTPUT_TEXTURE_COORD9_EXT      0x87A6\n#define GL_OUTPUT_TEXTURE_COORD10_EXT     0x87A7\n#define GL_OUTPUT_TEXTURE_COORD11_EXT     0x87A8\n#define GL_OUTPUT_TEXTURE_COORD12_EXT     0x87A9\n#define GL_OUTPUT_TEXTURE_COORD13_EXT     0x87AA\n#define GL_OUTPUT_TEXTURE_COORD14_EXT     0x87AB\n#define GL_OUTPUT_TEXTURE_COORD15_EXT     0x87AC\n#define GL_OUTPUT_TEXTURE_COORD16_EXT     0x87AD\n#define GL_OUTPUT_TEXTURE_COORD17_EXT     0x87AE\n#define GL_OUTPUT_TEXTURE_COORD18_EXT     0x87AF\n#define GL_OUTPUT_TEXTURE_COORD19_EXT     0x87B0\n#define GL_OUTPUT_TEXTURE_COORD20_EXT     0x87B1\n#define GL_OUTPUT_TEXTURE_COORD21_EXT     0x87B2\n#define GL_OUTPUT_TEXTURE_COORD22_EXT     0x87B3\n#define GL_OUTPUT_TEXTURE_COORD23_EXT     0x87B4\n#define GL_OUTPUT_TEXTURE_COORD24_EXT     0x87B5\n#define GL_OUTPUT_TEXTURE_COORD25_EXT     0x87B6\n#define GL_OUTPUT_TEXTURE_COORD26_EXT     0x87B7\n#define GL_OUTPUT_TEXTURE_COORD27_EXT     0x87B8\n#define GL_OUTPUT_TEXTURE_COORD28_EXT     0x87B9\n#define GL_OUTPUT_TEXTURE_COORD29_EXT     0x87BA\n#define GL_OUTPUT_TEXTURE_COORD30_EXT     0x87BB\n#define GL_OUTPUT_TEXTURE_COORD31_EXT     0x87BC\n#define GL_OUTPUT_FOG_EXT                 0x87BD\n#define GL_SCALAR_EXT                     0x87BE\n#define GL_VECTOR_EXT                     0x87BF\n#define GL_MATRIX_EXT                     0x87C0\n#define GL_VARIANT_EXT                    0x87C1\n#define GL_INVARIANT_EXT                  0x87C2\n#define GL_LOCAL_CONSTANT_EXT             0x87C3\n#define GL_LOCAL_EXT                      0x87C4\n#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5\n#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6\n#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7\n#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8\n#define GL_MAX_VERTEX_SHADER_LOCALS_EXT   0x87C9\n#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA\n#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB\n#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC\n#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD\n#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE\n#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF\n#define GL_VERTEX_SHADER_VARIANTS_EXT     0x87D0\n#define GL_VERTEX_SHADER_INVARIANTS_EXT   0x87D1\n#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2\n#define GL_VERTEX_SHADER_LOCALS_EXT       0x87D3\n#define GL_VERTEX_SHADER_OPTIMIZED_EXT    0x87D4\n#define GL_X_EXT                          0x87D5\n#define GL_Y_EXT                          0x87D6\n#define GL_Z_EXT                          0x87D7\n#define GL_W_EXT                          0x87D8\n#define GL_NEGATIVE_X_EXT                 0x87D9\n#define GL_NEGATIVE_Y_EXT                 0x87DA\n#define GL_NEGATIVE_Z_EXT                 0x87DB\n#define GL_NEGATIVE_W_EXT                 0x87DC\n#define GL_ZERO_EXT                       0x87DD\n#define GL_ONE_EXT                        0x87DE\n#define GL_NEGATIVE_ONE_EXT               0x87DF\n#define GL_NORMALIZED_RANGE_EXT           0x87E0\n#define GL_FULL_RANGE_EXT                 0x87E1\n#define GL_CURRENT_VERTEX_EXT             0x87E2\n#define GL_MVP_MATRIX_EXT                 0x87E3\n#define GL_VARIANT_VALUE_EXT              0x87E4\n#define GL_VARIANT_DATATYPE_EXT           0x87E5\n#define GL_VARIANT_ARRAY_STRIDE_EXT       0x87E6\n#define GL_VARIANT_ARRAY_TYPE_EXT         0x87E7\n#define GL_VARIANT_ARRAY_EXT              0x87E8\n#define GL_VARIANT_ARRAY_POINTER_EXT      0x87E9\n#define GL_INVARIANT_VALUE_EXT            0x87EA\n#define GL_INVARIANT_DATATYPE_EXT         0x87EB\n#define GL_LOCAL_CONSTANT_VALUE_EXT       0x87EC\n#define GL_LOCAL_CONSTANT_DATATYPE_EXT    0x87ED\ntypedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void);\ntypedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void);\ntypedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id);\ntypedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range);\ntypedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1);\ntypedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);\ntypedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);\ntypedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);\ntypedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);\ntypedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);\ntypedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);\ntypedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);\ntypedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const void *addr);\ntypedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const void *addr);\ntypedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr);\ntypedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr);\ntypedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr);\ntypedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr);\ntypedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr);\ntypedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr);\ntypedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr);\ntypedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr);\ntypedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const void *addr);\ntypedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);\ntypedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value);\ntypedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value);\ntypedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value);\ntypedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value);\ntypedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value);\ntypedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap);\ntypedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);\ntypedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);\ntypedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);\ntypedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, void **data);\ntypedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);\ntypedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);\ntypedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);\ntypedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);\ntypedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);\ntypedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginVertexShaderEXT (void);\nGLAPI void APIENTRY glEndVertexShaderEXT (void);\nGLAPI void APIENTRY glBindVertexShaderEXT (GLuint id);\nGLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint range);\nGLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint id);\nGLAPI void APIENTRY glShaderOp1EXT (GLenum op, GLuint res, GLuint arg1);\nGLAPI void APIENTRY glShaderOp2EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2);\nGLAPI void APIENTRY glShaderOp3EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);\nGLAPI void APIENTRY glSwizzleEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);\nGLAPI void APIENTRY glWriteMaskEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);\nGLAPI void APIENTRY glInsertComponentEXT (GLuint res, GLuint src, GLuint num);\nGLAPI void APIENTRY glExtractComponentEXT (GLuint res, GLuint src, GLuint num);\nGLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);\nGLAPI void APIENTRY glSetInvariantEXT (GLuint id, GLenum type, const void *addr);\nGLAPI void APIENTRY glSetLocalConstantEXT (GLuint id, GLenum type, const void *addr);\nGLAPI void APIENTRY glVariantbvEXT (GLuint id, const GLbyte *addr);\nGLAPI void APIENTRY glVariantsvEXT (GLuint id, const GLshort *addr);\nGLAPI void APIENTRY glVariantivEXT (GLuint id, const GLint *addr);\nGLAPI void APIENTRY glVariantfvEXT (GLuint id, const GLfloat *addr);\nGLAPI void APIENTRY glVariantdvEXT (GLuint id, const GLdouble *addr);\nGLAPI void APIENTRY glVariantubvEXT (GLuint id, const GLubyte *addr);\nGLAPI void APIENTRY glVariantusvEXT (GLuint id, const GLushort *addr);\nGLAPI void APIENTRY glVariantuivEXT (GLuint id, const GLuint *addr);\nGLAPI void APIENTRY glVariantPointerEXT (GLuint id, GLenum type, GLuint stride, const void *addr);\nGLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint id);\nGLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint id);\nGLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum light, GLenum value);\nGLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum face, GLenum value);\nGLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum unit, GLenum coord, GLenum value);\nGLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum unit, GLenum value);\nGLAPI GLuint APIENTRY glBindParameterEXT (GLenum value);\nGLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint id, GLenum cap);\nGLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data);\nGLAPI void APIENTRY glGetVariantIntegervEXT (GLuint id, GLenum value, GLint *data);\nGLAPI void APIENTRY glGetVariantFloatvEXT (GLuint id, GLenum value, GLfloat *data);\nGLAPI void APIENTRY glGetVariantPointervEXT (GLuint id, GLenum value, void **data);\nGLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data);\nGLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint id, GLenum value, GLint *data);\nGLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint id, GLenum value, GLfloat *data);\nGLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint id, GLenum value, GLboolean *data);\nGLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint id, GLenum value, GLint *data);\nGLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint id, GLenum value, GLfloat *data);\n#endif\n#endif /* GL_EXT_vertex_shader */\n\n#ifndef GL_EXT_vertex_weighting\n#define GL_EXT_vertex_weighting 1\n#define GL_MODELVIEW0_STACK_DEPTH_EXT     0x0BA3\n#define GL_MODELVIEW1_STACK_DEPTH_EXT     0x8502\n#define GL_MODELVIEW0_MATRIX_EXT          0x0BA6\n#define GL_MODELVIEW1_MATRIX_EXT          0x8506\n#define GL_VERTEX_WEIGHTING_EXT           0x8509\n#define GL_MODELVIEW0_EXT                 0x1700\n#define GL_MODELVIEW1_EXT                 0x850A\n#define GL_CURRENT_VERTEX_WEIGHT_EXT      0x850B\n#define GL_VERTEX_WEIGHT_ARRAY_EXT        0x850C\n#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT   0x850D\n#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT   0x850E\n#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F\n#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexWeightfEXT (GLfloat weight);\nGLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *weight);\nGLAPI void APIENTRY glVertexWeightPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer);\n#endif\n#endif /* GL_EXT_vertex_weighting */\n\n#ifndef GL_EXT_x11_sync_object\n#define GL_EXT_x11_sync_object 1\n#define GL_SYNC_X11_FENCE_EXT             0x90E1\ntypedef GLsync (APIENTRYP PFNGLIMPORTSYNCEXTPROC) (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags);\n#endif\n#endif /* GL_EXT_x11_sync_object */\n\n#ifndef GL_GREMEDY_frame_terminator\n#define GL_GREMEDY_frame_terminator 1\ntypedef void (APIENTRYP PFNGLFRAMETERMINATORGREMEDYPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFrameTerminatorGREMEDY (void);\n#endif\n#endif /* GL_GREMEDY_frame_terminator */\n\n#ifndef GL_GREMEDY_string_marker\n#define GL_GREMEDY_string_marker 1\ntypedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const void *string);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei len, const void *string);\n#endif\n#endif /* GL_GREMEDY_string_marker */\n\n#ifndef GL_HP_convolution_border_modes\n#define GL_HP_convolution_border_modes 1\n#define GL_IGNORE_BORDER_HP               0x8150\n#define GL_CONSTANT_BORDER_HP             0x8151\n#define GL_REPLICATE_BORDER_HP            0x8153\n#define GL_CONVOLUTION_BORDER_COLOR_HP    0x8154\n#endif /* GL_HP_convolution_border_modes */\n\n#ifndef GL_HP_image_transform\n#define GL_HP_image_transform 1\n#define GL_IMAGE_SCALE_X_HP               0x8155\n#define GL_IMAGE_SCALE_Y_HP               0x8156\n#define GL_IMAGE_TRANSLATE_X_HP           0x8157\n#define GL_IMAGE_TRANSLATE_Y_HP           0x8158\n#define GL_IMAGE_ROTATE_ANGLE_HP          0x8159\n#define GL_IMAGE_ROTATE_ORIGIN_X_HP       0x815A\n#define GL_IMAGE_ROTATE_ORIGIN_Y_HP       0x815B\n#define GL_IMAGE_MAG_FILTER_HP            0x815C\n#define GL_IMAGE_MIN_FILTER_HP            0x815D\n#define GL_IMAGE_CUBIC_WEIGHT_HP          0x815E\n#define GL_CUBIC_HP                       0x815F\n#define GL_AVERAGE_HP                     0x8160\n#define GL_IMAGE_TRANSFORM_2D_HP          0x8161\n#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162\n#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163\ntypedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glImageTransformParameteriHP (GLenum target, GLenum pname, GLint param);\nGLAPI void APIENTRY glImageTransformParameterfHP (GLenum target, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glImageTransformParameterivHP (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glImageTransformParameterfvHP (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum target, GLenum pname, GLfloat *params);\n#endif\n#endif /* GL_HP_image_transform */\n\n#ifndef GL_HP_occlusion_test\n#define GL_HP_occlusion_test 1\n#define GL_OCCLUSION_TEST_HP              0x8165\n#define GL_OCCLUSION_TEST_RESULT_HP       0x8166\n#endif /* GL_HP_occlusion_test */\n\n#ifndef GL_HP_texture_lighting\n#define GL_HP_texture_lighting 1\n#define GL_TEXTURE_LIGHTING_MODE_HP       0x8167\n#define GL_TEXTURE_POST_SPECULAR_HP       0x8168\n#define GL_TEXTURE_PRE_SPECULAR_HP        0x8169\n#endif /* GL_HP_texture_lighting */\n\n#ifndef GL_IBM_cull_vertex\n#define GL_IBM_cull_vertex 1\n#define GL_CULL_VERTEX_IBM                103050\n#endif /* GL_IBM_cull_vertex */\n\n#ifndef GL_IBM_multimode_draw_arrays\n#define GL_IBM_multimode_draw_arrays 1\ntypedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);\ntypedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);\nGLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride);\n#endif\n#endif /* GL_IBM_multimode_draw_arrays */\n\n#ifndef GL_IBM_rasterpos_clip\n#define GL_IBM_rasterpos_clip 1\n#define GL_RASTER_POSITION_UNCLIPPED_IBM  0x19262\n#endif /* GL_IBM_rasterpos_clip */\n\n#ifndef GL_IBM_static_data\n#define GL_IBM_static_data 1\n#define GL_ALL_STATIC_DATA_IBM            103060\n#define GL_STATIC_VERTEX_ARRAY_IBM        103061\ntypedef void (APIENTRYP PFNGLFLUSHSTATICDATAIBMPROC) (GLenum target);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFlushStaticDataIBM (GLenum target);\n#endif\n#endif /* GL_IBM_static_data */\n\n#ifndef GL_IBM_texture_mirrored_repeat\n#define GL_IBM_texture_mirrored_repeat 1\n#define GL_MIRRORED_REPEAT_IBM            0x8370\n#endif /* GL_IBM_texture_mirrored_repeat */\n\n#ifndef GL_IBM_vertex_array_lists\n#define GL_IBM_vertex_array_lists 1\n#define GL_VERTEX_ARRAY_LIST_IBM          103070\n#define GL_NORMAL_ARRAY_LIST_IBM          103071\n#define GL_COLOR_ARRAY_LIST_IBM           103072\n#define GL_INDEX_ARRAY_LIST_IBM           103073\n#define GL_TEXTURE_COORD_ARRAY_LIST_IBM   103074\n#define GL_EDGE_FLAG_ARRAY_LIST_IBM       103075\n#define GL_FOG_COORDINATE_ARRAY_LIST_IBM  103076\n#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077\n#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM   103080\n#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM   103081\n#define GL_COLOR_ARRAY_LIST_STRIDE_IBM    103082\n#define GL_INDEX_ARRAY_LIST_STRIDE_IBM    103083\n#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084\n#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085\n#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086\n#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087\ntypedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\nGLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\nGLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint stride, const GLboolean **pointer, GLint ptrstride);\nGLAPI void APIENTRY glFogCoordPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride);\nGLAPI void APIENTRY glIndexPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride);\nGLAPI void APIENTRY glNormalPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride);\nGLAPI void APIENTRY glTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\nGLAPI void APIENTRY glVertexPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride);\n#endif\n#endif /* GL_IBM_vertex_array_lists */\n\n#ifndef GL_INGR_blend_func_separate\n#define GL_INGR_blend_func_separate 1\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\n#endif\n#endif /* GL_INGR_blend_func_separate */\n\n#ifndef GL_INGR_color_clamp\n#define GL_INGR_color_clamp 1\n#define GL_RED_MIN_CLAMP_INGR             0x8560\n#define GL_GREEN_MIN_CLAMP_INGR           0x8561\n#define GL_BLUE_MIN_CLAMP_INGR            0x8562\n#define GL_ALPHA_MIN_CLAMP_INGR           0x8563\n#define GL_RED_MAX_CLAMP_INGR             0x8564\n#define GL_GREEN_MAX_CLAMP_INGR           0x8565\n#define GL_BLUE_MAX_CLAMP_INGR            0x8566\n#define GL_ALPHA_MAX_CLAMP_INGR           0x8567\n#endif /* GL_INGR_color_clamp */\n\n#ifndef GL_INGR_interlace_read\n#define GL_INGR_interlace_read 1\n#define GL_INTERLACE_READ_INGR            0x8568\n#endif /* GL_INGR_interlace_read */\n\n#ifndef GL_INTEL_fragment_shader_ordering\n#define GL_INTEL_fragment_shader_ordering 1\n#endif /* GL_INTEL_fragment_shader_ordering */\n\n#ifndef GL_INTEL_map_texture\n#define GL_INTEL_map_texture 1\n#define GL_TEXTURE_MEMORY_LAYOUT_INTEL    0x83FF\n#define GL_LAYOUT_DEFAULT_INTEL           0\n#define GL_LAYOUT_LINEAR_INTEL            1\n#define GL_LAYOUT_LINEAR_CPU_CACHED_INTEL 2\ntypedef void (APIENTRYP PFNGLSYNCTEXTUREINTELPROC) (GLuint texture);\ntypedef void (APIENTRYP PFNGLUNMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level);\ntypedef void *(APIENTRYP PFNGLMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSyncTextureINTEL (GLuint texture);\nGLAPI void APIENTRY glUnmapTexture2DINTEL (GLuint texture, GLint level);\nGLAPI void *APIENTRY glMapTexture2DINTEL (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout);\n#endif\n#endif /* GL_INTEL_map_texture */\n\n#ifndef GL_INTEL_parallel_arrays\n#define GL_INTEL_parallel_arrays 1\n#define GL_PARALLEL_ARRAYS_INTEL          0x83F4\n#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5\n#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6\n#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7\n#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8\ntypedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer);\ntypedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const void **pointer);\ntypedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer);\ntypedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexPointervINTEL (GLint size, GLenum type, const void **pointer);\nGLAPI void APIENTRY glNormalPointervINTEL (GLenum type, const void **pointer);\nGLAPI void APIENTRY glColorPointervINTEL (GLint size, GLenum type, const void **pointer);\nGLAPI void APIENTRY glTexCoordPointervINTEL (GLint size, GLenum type, const void **pointer);\n#endif\n#endif /* GL_INTEL_parallel_arrays */\n\n#ifndef GL_INTEL_performance_query\n#define GL_INTEL_performance_query 1\n#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000\n#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001\n#define GL_PERFQUERY_WAIT_INTEL           0x83FB\n#define GL_PERFQUERY_FLUSH_INTEL          0x83FA\n#define GL_PERFQUERY_DONOT_FLUSH_INTEL    0x83F9\n#define GL_PERFQUERY_COUNTER_EVENT_INTEL  0x94F0\n#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1\n#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2\n#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3\n#define GL_PERFQUERY_COUNTER_RAW_INTEL    0x94F4\n#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5\n#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8\n#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9\n#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA\n#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB\n#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC\n#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD\n#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE\n#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF\n#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500\ntypedef void (APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle);\ntypedef void (APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle);\ntypedef void (APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle);\ntypedef void (APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle);\ntypedef void (APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId);\ntypedef void (APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId);\ntypedef void (APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue);\ntypedef void (APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten);\ntypedef void (APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId);\ntypedef void (APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle);\nGLAPI void APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle);\nGLAPI void APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle);\nGLAPI void APIENTRY glEndPerfQueryINTEL (GLuint queryHandle);\nGLAPI void APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId);\nGLAPI void APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId);\nGLAPI void APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue);\nGLAPI void APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten);\nGLAPI void APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId);\nGLAPI void APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask);\n#endif\n#endif /* GL_INTEL_performance_query */\n\n#ifndef GL_MESAX_texture_stack\n#define GL_MESAX_texture_stack 1\n#define GL_TEXTURE_1D_STACK_MESAX         0x8759\n#define GL_TEXTURE_2D_STACK_MESAX         0x875A\n#define GL_PROXY_TEXTURE_1D_STACK_MESAX   0x875B\n#define GL_PROXY_TEXTURE_2D_STACK_MESAX   0x875C\n#define GL_TEXTURE_1D_STACK_BINDING_MESAX 0x875D\n#define GL_TEXTURE_2D_STACK_BINDING_MESAX 0x875E\n#endif /* GL_MESAX_texture_stack */\n\n#ifndef GL_MESA_pack_invert\n#define GL_MESA_pack_invert 1\n#define GL_PACK_INVERT_MESA               0x8758\n#endif /* GL_MESA_pack_invert */\n\n#ifndef GL_MESA_resize_buffers\n#define GL_MESA_resize_buffers 1\ntypedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glResizeBuffersMESA (void);\n#endif\n#endif /* GL_MESA_resize_buffers */\n\n#ifndef GL_MESA_window_pos\n#define GL_MESA_window_pos 1\ntypedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w);\ntypedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glWindowPos2dMESA (GLdouble x, GLdouble y);\nGLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos2fMESA (GLfloat x, GLfloat y);\nGLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos2iMESA (GLint x, GLint y);\nGLAPI void APIENTRY glWindowPos2ivMESA (const GLint *v);\nGLAPI void APIENTRY glWindowPos2sMESA (GLshort x, GLshort y);\nGLAPI void APIENTRY glWindowPos2svMESA (const GLshort *v);\nGLAPI void APIENTRY glWindowPos3dMESA (GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos3fMESA (GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos3iMESA (GLint x, GLint y, GLint z);\nGLAPI void APIENTRY glWindowPos3ivMESA (const GLint *v);\nGLAPI void APIENTRY glWindowPos3sMESA (GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glWindowPos3svMESA (const GLshort *v);\nGLAPI void APIENTRY glWindowPos4dMESA (GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *v);\nGLAPI void APIENTRY glWindowPos4fMESA (GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *v);\nGLAPI void APIENTRY glWindowPos4iMESA (GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glWindowPos4ivMESA (const GLint *v);\nGLAPI void APIENTRY glWindowPos4sMESA (GLshort x, GLshort y, GLshort z, GLshort w);\nGLAPI void APIENTRY glWindowPos4svMESA (const GLshort *v);\n#endif\n#endif /* GL_MESA_window_pos */\n\n#ifndef GL_MESA_ycbcr_texture\n#define GL_MESA_ycbcr_texture 1\n#define GL_UNSIGNED_SHORT_8_8_MESA        0x85BA\n#define GL_UNSIGNED_SHORT_8_8_REV_MESA    0x85BB\n#define GL_YCBCR_MESA                     0x8757\n#endif /* GL_MESA_ycbcr_texture */\n\n#ifndef GL_NVX_conditional_render\n#define GL_NVX_conditional_render 1\ntypedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVXPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVXPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginConditionalRenderNVX (GLuint id);\nGLAPI void APIENTRY glEndConditionalRenderNVX (void);\n#endif\n#endif /* GL_NVX_conditional_render */\n\n#ifndef GL_NV_bindless_multi_draw_indirect\n#define GL_NV_bindless_multi_draw_indirect 1\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiDrawArraysIndirectBindlessNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount);\nGLAPI void APIENTRY glMultiDrawElementsIndirectBindlessNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount);\n#endif\n#endif /* GL_NV_bindless_multi_draw_indirect */\n\n#ifndef GL_NV_bindless_texture\n#define GL_NV_bindless_texture 1\ntypedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture);\ntypedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler);\ntypedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle);\ntypedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle);\ntypedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);\ntypedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access);\ntypedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle);\ntypedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value);\ntypedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values);\ntypedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle);\ntypedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint64 APIENTRY glGetTextureHandleNV (GLuint texture);\nGLAPI GLuint64 APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler);\nGLAPI void APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle);\nGLAPI void APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle);\nGLAPI GLuint64 APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);\nGLAPI void APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access);\nGLAPI void APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle);\nGLAPI void APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value);\nGLAPI void APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value);\nGLAPI void APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value);\nGLAPI void APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values);\nGLAPI GLboolean APIENTRY glIsTextureHandleResidentNV (GLuint64 handle);\nGLAPI GLboolean APIENTRY glIsImageHandleResidentNV (GLuint64 handle);\n#endif\n#endif /* GL_NV_bindless_texture */\n\n#ifndef GL_NV_blend_equation_advanced\n#define GL_NV_blend_equation_advanced 1\n#define GL_BLEND_OVERLAP_NV               0x9281\n#define GL_BLEND_PREMULTIPLIED_SRC_NV     0x9280\n#define GL_BLUE_NV                        0x1905\n#define GL_COLORBURN_NV                   0x929A\n#define GL_COLORDODGE_NV                  0x9299\n#define GL_CONJOINT_NV                    0x9284\n#define GL_CONTRAST_NV                    0x92A1\n#define GL_DARKEN_NV                      0x9297\n#define GL_DIFFERENCE_NV                  0x929E\n#define GL_DISJOINT_NV                    0x9283\n#define GL_DST_ATOP_NV                    0x928F\n#define GL_DST_IN_NV                      0x928B\n#define GL_DST_NV                         0x9287\n#define GL_DST_OUT_NV                     0x928D\n#define GL_DST_OVER_NV                    0x9289\n#define GL_EXCLUSION_NV                   0x92A0\n#define GL_GREEN_NV                       0x1904\n#define GL_HARDLIGHT_NV                   0x929B\n#define GL_HARDMIX_NV                     0x92A9\n#define GL_HSL_COLOR_NV                   0x92AF\n#define GL_HSL_HUE_NV                     0x92AD\n#define GL_HSL_LUMINOSITY_NV              0x92B0\n#define GL_HSL_SATURATION_NV              0x92AE\n#define GL_INVERT_OVG_NV                  0x92B4\n#define GL_INVERT_RGB_NV                  0x92A3\n#define GL_LIGHTEN_NV                     0x9298\n#define GL_LINEARBURN_NV                  0x92A5\n#define GL_LINEARDODGE_NV                 0x92A4\n#define GL_LINEARLIGHT_NV                 0x92A7\n#define GL_MINUS_CLAMPED_NV               0x92B3\n#define GL_MINUS_NV                       0x929F\n#define GL_MULTIPLY_NV                    0x9294\n#define GL_OVERLAY_NV                     0x9296\n#define GL_PINLIGHT_NV                    0x92A8\n#define GL_PLUS_CLAMPED_ALPHA_NV          0x92B2\n#define GL_PLUS_CLAMPED_NV                0x92B1\n#define GL_PLUS_DARKER_NV                 0x9292\n#define GL_PLUS_NV                        0x9291\n#define GL_RED_NV                         0x1903\n#define GL_SCREEN_NV                      0x9295\n#define GL_SOFTLIGHT_NV                   0x929C\n#define GL_SRC_ATOP_NV                    0x928E\n#define GL_SRC_IN_NV                      0x928A\n#define GL_SRC_NV                         0x9286\n#define GL_SRC_OUT_NV                     0x928C\n#define GL_SRC_OVER_NV                    0x9288\n#define GL_UNCORRELATED_NV                0x9282\n#define GL_VIVIDLIGHT_NV                  0x92A6\n#define GL_XOR_NV                         0x1506\ntypedef void (APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value);\ntypedef void (APIENTRYP PFNGLBLENDBARRIERNVPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendParameteriNV (GLenum pname, GLint value);\nGLAPI void APIENTRY glBlendBarrierNV (void);\n#endif\n#endif /* GL_NV_blend_equation_advanced */\n\n#ifndef GL_NV_blend_equation_advanced_coherent\n#define GL_NV_blend_equation_advanced_coherent 1\n#define GL_BLEND_ADVANCED_COHERENT_NV     0x9285\n#endif /* GL_NV_blend_equation_advanced_coherent */\n\n#ifndef GL_NV_blend_square\n#define GL_NV_blend_square 1\n#endif /* GL_NV_blend_square */\n\n#ifndef GL_NV_compute_program5\n#define GL_NV_compute_program5 1\n#define GL_COMPUTE_PROGRAM_NV             0x90FB\n#define GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV 0x90FC\n#endif /* GL_NV_compute_program5 */\n\n#ifndef GL_NV_conditional_render\n#define GL_NV_conditional_render 1\n#define GL_QUERY_WAIT_NV                  0x8E13\n#define GL_QUERY_NO_WAIT_NV               0x8E14\n#define GL_QUERY_BY_REGION_WAIT_NV        0x8E15\n#define GL_QUERY_BY_REGION_NO_WAIT_NV     0x8E16\ntypedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode);\ntypedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode);\nGLAPI void APIENTRY glEndConditionalRenderNV (void);\n#endif\n#endif /* GL_NV_conditional_render */\n\n#ifndef GL_NV_copy_depth_to_color\n#define GL_NV_copy_depth_to_color 1\n#define GL_DEPTH_STENCIL_TO_RGBA_NV       0x886E\n#define GL_DEPTH_STENCIL_TO_BGRA_NV       0x886F\n#endif /* GL_NV_copy_depth_to_color */\n\n#ifndef GL_NV_copy_image\n#define GL_NV_copy_image 1\ntypedef void (APIENTRYP PFNGLCOPYIMAGESUBDATANVPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCopyImageSubDataNV (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);\n#endif\n#endif /* GL_NV_copy_image */\n\n#ifndef GL_NV_deep_texture3D\n#define GL_NV_deep_texture3D 1\n#define GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV 0x90D0\n#define GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV   0x90D1\n#endif /* GL_NV_deep_texture3D */\n\n#ifndef GL_NV_depth_buffer_float\n#define GL_NV_depth_buffer_float 1\n#define GL_DEPTH_COMPONENT32F_NV          0x8DAB\n#define GL_DEPTH32F_STENCIL8_NV           0x8DAC\n#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV_NV 0x8DAD\n#define GL_DEPTH_BUFFER_FLOAT_MODE_NV     0x8DAF\ntypedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar);\ntypedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth);\ntypedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar);\nGLAPI void APIENTRY glClearDepthdNV (GLdouble depth);\nGLAPI void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax);\n#endif\n#endif /* GL_NV_depth_buffer_float */\n\n#ifndef GL_NV_depth_clamp\n#define GL_NV_depth_clamp 1\n#define GL_DEPTH_CLAMP_NV                 0x864F\n#endif /* GL_NV_depth_clamp */\n\n#ifndef GL_NV_draw_texture\n#define GL_NV_draw_texture 1\ntypedef void (APIENTRYP PFNGLDRAWTEXTURENVPROC) (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawTextureNV (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1);\n#endif\n#endif /* GL_NV_draw_texture */\n\n#ifndef GL_NV_evaluators\n#define GL_NV_evaluators 1\n#define GL_EVAL_2D_NV                     0x86C0\n#define GL_EVAL_TRIANGULAR_2D_NV          0x86C1\n#define GL_MAP_TESSELLATION_NV            0x86C2\n#define GL_MAP_ATTRIB_U_ORDER_NV          0x86C3\n#define GL_MAP_ATTRIB_V_ORDER_NV          0x86C4\n#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5\n#define GL_EVAL_VERTEX_ATTRIB0_NV         0x86C6\n#define GL_EVAL_VERTEX_ATTRIB1_NV         0x86C7\n#define GL_EVAL_VERTEX_ATTRIB2_NV         0x86C8\n#define GL_EVAL_VERTEX_ATTRIB3_NV         0x86C9\n#define GL_EVAL_VERTEX_ATTRIB4_NV         0x86CA\n#define GL_EVAL_VERTEX_ATTRIB5_NV         0x86CB\n#define GL_EVAL_VERTEX_ATTRIB6_NV         0x86CC\n#define GL_EVAL_VERTEX_ATTRIB7_NV         0x86CD\n#define GL_EVAL_VERTEX_ATTRIB8_NV         0x86CE\n#define GL_EVAL_VERTEX_ATTRIB9_NV         0x86CF\n#define GL_EVAL_VERTEX_ATTRIB10_NV        0x86D0\n#define GL_EVAL_VERTEX_ATTRIB11_NV        0x86D1\n#define GL_EVAL_VERTEX_ATTRIB12_NV        0x86D2\n#define GL_EVAL_VERTEX_ATTRIB13_NV        0x86D3\n#define GL_EVAL_VERTEX_ATTRIB14_NV        0x86D4\n#define GL_EVAL_VERTEX_ATTRIB15_NV        0x86D5\n#define GL_MAX_MAP_TESSELLATION_NV        0x86D6\n#define GL_MAX_RATIONAL_EVAL_ORDER_NV     0x86D7\ntypedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points);\ntypedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points);\ntypedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points);\nGLAPI void APIENTRY glMapParameterivNV (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glMapParameterfvNV (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glGetMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points);\nGLAPI void APIENTRY glGetMapParameterivNV (GLenum target, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMapParameterfvNV (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum target, GLuint index, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glEvalMapsNV (GLenum target, GLenum mode);\n#endif\n#endif /* GL_NV_evaluators */\n\n#ifndef GL_NV_explicit_multisample\n#define GL_NV_explicit_multisample 1\n#define GL_SAMPLE_POSITION_NV             0x8E50\n#define GL_SAMPLE_MASK_NV                 0x8E51\n#define GL_SAMPLE_MASK_VALUE_NV           0x8E52\n#define GL_TEXTURE_BINDING_RENDERBUFFER_NV 0x8E53\n#define GL_TEXTURE_RENDERBUFFER_DATA_STORE_BINDING_NV 0x8E54\n#define GL_TEXTURE_RENDERBUFFER_NV        0x8E55\n#define GL_SAMPLER_RENDERBUFFER_NV        0x8E56\n#define GL_INT_SAMPLER_RENDERBUFFER_NV    0x8E57\n#define GL_UNSIGNED_INT_SAMPLER_RENDERBUFFER_NV 0x8E58\n#define GL_MAX_SAMPLE_MASK_WORDS_NV       0x8E59\ntypedef void (APIENTRYP PFNGLGETMULTISAMPLEFVNVPROC) (GLenum pname, GLuint index, GLfloat *val);\ntypedef void (APIENTRYP PFNGLSAMPLEMASKINDEXEDNVPROC) (GLuint index, GLbitfield mask);\ntypedef void (APIENTRYP PFNGLTEXRENDERBUFFERNVPROC) (GLenum target, GLuint renderbuffer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetMultisamplefvNV (GLenum pname, GLuint index, GLfloat *val);\nGLAPI void APIENTRY glSampleMaskIndexedNV (GLuint index, GLbitfield mask);\nGLAPI void APIENTRY glTexRenderbufferNV (GLenum target, GLuint renderbuffer);\n#endif\n#endif /* GL_NV_explicit_multisample */\n\n#ifndef GL_NV_fence\n#define GL_NV_fence 1\n#define GL_ALL_COMPLETED_NV               0x84F2\n#define GL_FENCE_STATUS_NV                0x84F3\n#define GL_FENCE_CONDITION_NV             0x84F4\ntypedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);\ntypedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);\ntypedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);\ntypedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);\ntypedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);\ntypedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences);\nGLAPI void APIENTRY glGenFencesNV (GLsizei n, GLuint *fences);\nGLAPI GLboolean APIENTRY glIsFenceNV (GLuint fence);\nGLAPI GLboolean APIENTRY glTestFenceNV (GLuint fence);\nGLAPI void APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params);\nGLAPI void APIENTRY glFinishFenceNV (GLuint fence);\nGLAPI void APIENTRY glSetFenceNV (GLuint fence, GLenum condition);\n#endif\n#endif /* GL_NV_fence */\n\n#ifndef GL_NV_float_buffer\n#define GL_NV_float_buffer 1\n#define GL_FLOAT_R_NV                     0x8880\n#define GL_FLOAT_RG_NV                    0x8881\n#define GL_FLOAT_RGB_NV                   0x8882\n#define GL_FLOAT_RGBA_NV                  0x8883\n#define GL_FLOAT_R16_NV                   0x8884\n#define GL_FLOAT_R32_NV                   0x8885\n#define GL_FLOAT_RG16_NV                  0x8886\n#define GL_FLOAT_RG32_NV                  0x8887\n#define GL_FLOAT_RGB16_NV                 0x8888\n#define GL_FLOAT_RGB32_NV                 0x8889\n#define GL_FLOAT_RGBA16_NV                0x888A\n#define GL_FLOAT_RGBA32_NV                0x888B\n#define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C\n#define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D\n#define GL_FLOAT_RGBA_MODE_NV             0x888E\n#endif /* GL_NV_float_buffer */\n\n#ifndef GL_NV_fog_distance\n#define GL_NV_fog_distance 1\n#define GL_FOG_DISTANCE_MODE_NV           0x855A\n#define GL_EYE_RADIAL_NV                  0x855B\n#define GL_EYE_PLANE_ABSOLUTE_NV          0x855C\n#endif /* GL_NV_fog_distance */\n\n#ifndef GL_NV_fragment_program\n#define GL_NV_fragment_program 1\n#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868\n#define GL_FRAGMENT_PROGRAM_NV            0x8870\n#define GL_MAX_TEXTURE_COORDS_NV          0x8871\n#define GL_MAX_TEXTURE_IMAGE_UNITS_NV     0x8872\n#define GL_FRAGMENT_PROGRAM_BINDING_NV    0x8873\n#define GL_PROGRAM_ERROR_STRING_NV        0x8874\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);\nGLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);\nGLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);\nGLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);\n#endif\n#endif /* GL_NV_fragment_program */\n\n#ifndef GL_NV_fragment_program2\n#define GL_NV_fragment_program2 1\n#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4\n#define GL_MAX_PROGRAM_CALL_DEPTH_NV      0x88F5\n#define GL_MAX_PROGRAM_IF_DEPTH_NV        0x88F6\n#define GL_MAX_PROGRAM_LOOP_DEPTH_NV      0x88F7\n#define GL_MAX_PROGRAM_LOOP_COUNT_NV      0x88F8\n#endif /* GL_NV_fragment_program2 */\n\n#ifndef GL_NV_fragment_program4\n#define GL_NV_fragment_program4 1\n#endif /* GL_NV_fragment_program4 */\n\n#ifndef GL_NV_fragment_program_option\n#define GL_NV_fragment_program_option 1\n#endif /* GL_NV_fragment_program_option */\n\n#ifndef GL_NV_framebuffer_multisample_coverage\n#define GL_NV_framebuffer_multisample_coverage 1\n#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB\n#define GL_RENDERBUFFER_COLOR_SAMPLES_NV  0x8E10\n#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11\n#define GL_MULTISAMPLE_COVERAGE_MODES_NV  0x8E12\ntypedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);\n#endif\n#endif /* GL_NV_framebuffer_multisample_coverage */\n\n#ifndef GL_NV_geometry_program4\n#define GL_NV_geometry_program4 1\n#define GL_GEOMETRY_PROGRAM_NV            0x8C26\n#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27\n#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28\ntypedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);\ntypedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramVertexLimitNV (GLenum target, GLint limit);\nGLAPI void APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level);\nGLAPI void APIENTRY glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);\nGLAPI void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);\n#endif\n#endif /* GL_NV_geometry_program4 */\n\n#ifndef GL_NV_geometry_shader4\n#define GL_NV_geometry_shader4 1\n#endif /* GL_NV_geometry_shader4 */\n\n#ifndef GL_NV_gpu_program4\n#define GL_NV_gpu_program4 1\n#define GL_MIN_PROGRAM_TEXEL_OFFSET_NV    0x8904\n#define GL_MAX_PROGRAM_TEXEL_OFFSET_NV    0x8905\n#define GL_PROGRAM_ATTRIB_COMPONENTS_NV   0x8906\n#define GL_PROGRAM_RESULT_COMPONENTS_NV   0x8907\n#define GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV 0x8908\n#define GL_MAX_PROGRAM_RESULT_COMPONENTS_NV 0x8909\n#define GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV 0x8DA5\n#define GL_MAX_PROGRAM_GENERIC_RESULTS_NV 0x8DA6\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramLocalParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glProgramLocalParameterI4ivNV (GLenum target, GLuint index, const GLint *params);\nGLAPI void APIENTRY glProgramLocalParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params);\nGLAPI void APIENTRY glProgramLocalParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\nGLAPI void APIENTRY glProgramLocalParameterI4uivNV (GLenum target, GLuint index, const GLuint *params);\nGLAPI void APIENTRY glProgramLocalParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params);\nGLAPI void APIENTRY glProgramEnvParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glProgramEnvParameterI4ivNV (GLenum target, GLuint index, const GLint *params);\nGLAPI void APIENTRY glProgramEnvParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params);\nGLAPI void APIENTRY glProgramEnvParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\nGLAPI void APIENTRY glProgramEnvParameterI4uivNV (GLenum target, GLuint index, const GLuint *params);\nGLAPI void APIENTRY glProgramEnvParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params);\nGLAPI void APIENTRY glGetProgramLocalParameterIivNV (GLenum target, GLuint index, GLint *params);\nGLAPI void APIENTRY glGetProgramLocalParameterIuivNV (GLenum target, GLuint index, GLuint *params);\nGLAPI void APIENTRY glGetProgramEnvParameterIivNV (GLenum target, GLuint index, GLint *params);\nGLAPI void APIENTRY glGetProgramEnvParameterIuivNV (GLenum target, GLuint index, GLuint *params);\n#endif\n#endif /* GL_NV_gpu_program4 */\n\n#ifndef GL_NV_gpu_program5\n#define GL_NV_gpu_program5 1\n#define GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV 0x8E5A\n#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5B\n#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5C\n#define GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV 0x8E5D\n#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5E\n#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5F\n#define GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV 0x8F44\n#define GL_MAX_PROGRAM_SUBROUTINE_NUM_NV  0x8F45\ntypedef void (APIENTRYP PFNGLPROGRAMSUBROUTINEPARAMETERSUIVNVPROC) (GLenum target, GLsizei count, const GLuint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMSUBROUTINEPARAMETERUIVNVPROC) (GLenum target, GLuint index, GLuint *param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramSubroutineParametersuivNV (GLenum target, GLsizei count, const GLuint *params);\nGLAPI void APIENTRY glGetProgramSubroutineParameteruivNV (GLenum target, GLuint index, GLuint *param);\n#endif\n#endif /* GL_NV_gpu_program5 */\n\n#ifndef GL_NV_gpu_program5_mem_extended\n#define GL_NV_gpu_program5_mem_extended 1\n#endif /* GL_NV_gpu_program5_mem_extended */\n\n#ifndef GL_NV_gpu_shader5\n#define GL_NV_gpu_shader5 1\ntypedef int64_t GLint64EXT;\n#define GL_INT64_NV                       0x140E\n#define GL_UNSIGNED_INT64_NV              0x140F\n#define GL_INT8_NV                        0x8FE0\n#define GL_INT8_VEC2_NV                   0x8FE1\n#define GL_INT8_VEC3_NV                   0x8FE2\n#define GL_INT8_VEC4_NV                   0x8FE3\n#define GL_INT16_NV                       0x8FE4\n#define GL_INT16_VEC2_NV                  0x8FE5\n#define GL_INT16_VEC3_NV                  0x8FE6\n#define GL_INT16_VEC4_NV                  0x8FE7\n#define GL_INT64_VEC2_NV                  0x8FE9\n#define GL_INT64_VEC3_NV                  0x8FEA\n#define GL_INT64_VEC4_NV                  0x8FEB\n#define GL_UNSIGNED_INT8_NV               0x8FEC\n#define GL_UNSIGNED_INT8_VEC2_NV          0x8FED\n#define GL_UNSIGNED_INT8_VEC3_NV          0x8FEE\n#define GL_UNSIGNED_INT8_VEC4_NV          0x8FEF\n#define GL_UNSIGNED_INT16_NV              0x8FF0\n#define GL_UNSIGNED_INT16_VEC2_NV         0x8FF1\n#define GL_UNSIGNED_INT16_VEC3_NV         0x8FF2\n#define GL_UNSIGNED_INT16_VEC4_NV         0x8FF3\n#define GL_UNSIGNED_INT64_VEC2_NV         0x8FF5\n#define GL_UNSIGNED_INT64_VEC3_NV         0x8FF6\n#define GL_UNSIGNED_INT64_VEC4_NV         0x8FF7\n#define GL_FLOAT16_NV                     0x8FF8\n#define GL_FLOAT16_VEC2_NV                0x8FF9\n#define GL_FLOAT16_VEC3_NV                0x8FFA\n#define GL_FLOAT16_VEC4_NV                0x8FFB\ntypedef void (APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x);\ntypedef void (APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y);\ntypedef void (APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);\ntypedef void (APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);\ntypedef void (APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x);\ntypedef void (APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y);\ntypedef void (APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);\ntypedef void (APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);\ntypedef void (APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glUniform1i64NV (GLint location, GLint64EXT x);\nGLAPI void APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y);\nGLAPI void APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);\nGLAPI void APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);\nGLAPI void APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x);\nGLAPI void APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y);\nGLAPI void APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);\nGLAPI void APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);\nGLAPI void APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params);\nGLAPI void APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x);\nGLAPI void APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);\nGLAPI void APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);\nGLAPI void APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);\nGLAPI void APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);\nGLAPI void APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x);\nGLAPI void APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);\nGLAPI void APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);\nGLAPI void APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);\nGLAPI void APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\n#endif\n#endif /* GL_NV_gpu_shader5 */\n\n#ifndef GL_NV_half_float\n#define GL_NV_half_float 1\ntypedef unsigned short GLhalfNV;\n#define GL_HALF_FLOAT_NV                  0x140B\ntypedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y);\ntypedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z);\ntypedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);\ntypedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);\ntypedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);\ntypedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);\ntypedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s);\ntypedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t);\ntypedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r);\ntypedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);\ntypedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);\ntypedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog);\ntypedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight);\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertex2hNV (GLhalfNV x, GLhalfNV y);\nGLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glVertex3hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z);\nGLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glVertex4hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);\nGLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glNormal3hNV (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);\nGLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue);\nGLAPI void APIENTRY glColor3hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glColor4hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);\nGLAPI void APIENTRY glColor4hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glTexCoord1hNV (GLhalfNV s);\nGLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glTexCoord2hNV (GLhalfNV s, GLhalfNV t);\nGLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glTexCoord3hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r);\nGLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glTexCoord4hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);\nGLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glMultiTexCoord1hNV (GLenum target, GLhalfNV s);\nGLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum target, const GLhalfNV *v);\nGLAPI void APIENTRY glMultiTexCoord2hNV (GLenum target, GLhalfNV s, GLhalfNV t);\nGLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum target, const GLhalfNV *v);\nGLAPI void APIENTRY glMultiTexCoord3hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);\nGLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum target, const GLhalfNV *v);\nGLAPI void APIENTRY glMultiTexCoord4hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);\nGLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum target, const GLhalfNV *v);\nGLAPI void APIENTRY glFogCoordhNV (GLhalfNV fog);\nGLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *fog);\nGLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue);\nGLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *v);\nGLAPI void APIENTRY glVertexWeighthNV (GLhalfNV weight);\nGLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *weight);\nGLAPI void APIENTRY glVertexAttrib1hNV (GLuint index, GLhalfNV x);\nGLAPI void APIENTRY glVertexAttrib1hvNV (GLuint index, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttrib2hNV (GLuint index, GLhalfNV x, GLhalfNV y);\nGLAPI void APIENTRY glVertexAttrib2hvNV (GLuint index, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttrib3hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);\nGLAPI void APIENTRY glVertexAttrib3hvNV (GLuint index, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttrib4hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);\nGLAPI void APIENTRY glVertexAttrib4hvNV (GLuint index, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttribs1hvNV (GLuint index, GLsizei n, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttribs2hvNV (GLuint index, GLsizei n, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttribs3hvNV (GLuint index, GLsizei n, const GLhalfNV *v);\nGLAPI void APIENTRY glVertexAttribs4hvNV (GLuint index, GLsizei n, const GLhalfNV *v);\n#endif\n#endif /* GL_NV_half_float */\n\n#ifndef GL_NV_light_max_exponent\n#define GL_NV_light_max_exponent 1\n#define GL_MAX_SHININESS_NV               0x8504\n#define GL_MAX_SPOT_EXPONENT_NV           0x8505\n#endif /* GL_NV_light_max_exponent */\n\n#ifndef GL_NV_multisample_coverage\n#define GL_NV_multisample_coverage 1\n#define GL_COLOR_SAMPLES_NV               0x8E20\n#endif /* GL_NV_multisample_coverage */\n\n#ifndef GL_NV_multisample_filter_hint\n#define GL_NV_multisample_filter_hint 1\n#define GL_MULTISAMPLE_FILTER_HINT_NV     0x8534\n#endif /* GL_NV_multisample_filter_hint */\n\n#ifndef GL_NV_occlusion_query\n#define GL_NV_occlusion_query 1\n#define GL_PIXEL_COUNTER_BITS_NV          0x8864\n#define GL_CURRENT_OCCLUSION_QUERY_ID_NV  0x8865\n#define GL_PIXEL_COUNT_NV                 0x8866\n#define GL_PIXEL_COUNT_AVAILABLE_NV       0x8867\ntypedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids);\ntypedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids);\ntypedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void);\ntypedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei n, GLuint *ids);\nGLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei n, const GLuint *ids);\nGLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint id);\nGLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint id);\nGLAPI void APIENTRY glEndOcclusionQueryNV (void);\nGLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint id, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint id, GLenum pname, GLuint *params);\n#endif\n#endif /* GL_NV_occlusion_query */\n\n#ifndef GL_NV_packed_depth_stencil\n#define GL_NV_packed_depth_stencil 1\n#define GL_DEPTH_STENCIL_NV               0x84F9\n#define GL_UNSIGNED_INT_24_8_NV           0x84FA\n#endif /* GL_NV_packed_depth_stencil */\n\n#ifndef GL_NV_parameter_buffer_object\n#define GL_NV_parameter_buffer_object 1\n#define GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV 0x8DA0\n#define GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV 0x8DA1\n#define GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV 0x8DA2\n#define GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV 0x8DA3\n#define GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV 0x8DA4\ntypedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params);\ntypedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIUIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params);\nGLAPI void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params);\nGLAPI void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params);\n#endif\n#endif /* GL_NV_parameter_buffer_object */\n\n#ifndef GL_NV_parameter_buffer_object2\n#define GL_NV_parameter_buffer_object2 1\n#endif /* GL_NV_parameter_buffer_object2 */\n\n#ifndef GL_NV_path_rendering\n#define GL_NV_path_rendering 1\n#define GL_PATH_FORMAT_SVG_NV             0x9070\n#define GL_PATH_FORMAT_PS_NV              0x9071\n#define GL_STANDARD_FONT_NAME_NV          0x9072\n#define GL_SYSTEM_FONT_NAME_NV            0x9073\n#define GL_FILE_NAME_NV                   0x9074\n#define GL_PATH_STROKE_WIDTH_NV           0x9075\n#define GL_PATH_END_CAPS_NV               0x9076\n#define GL_PATH_INITIAL_END_CAP_NV        0x9077\n#define GL_PATH_TERMINAL_END_CAP_NV       0x9078\n#define GL_PATH_JOIN_STYLE_NV             0x9079\n#define GL_PATH_MITER_LIMIT_NV            0x907A\n#define GL_PATH_DASH_CAPS_NV              0x907B\n#define GL_PATH_INITIAL_DASH_CAP_NV       0x907C\n#define GL_PATH_TERMINAL_DASH_CAP_NV      0x907D\n#define GL_PATH_DASH_OFFSET_NV            0x907E\n#define GL_PATH_CLIENT_LENGTH_NV          0x907F\n#define GL_PATH_FILL_MODE_NV              0x9080\n#define GL_PATH_FILL_MASK_NV              0x9081\n#define GL_PATH_FILL_COVER_MODE_NV        0x9082\n#define GL_PATH_STROKE_COVER_MODE_NV      0x9083\n#define GL_PATH_STROKE_MASK_NV            0x9084\n#define GL_COUNT_UP_NV                    0x9088\n#define GL_COUNT_DOWN_NV                  0x9089\n#define GL_PATH_OBJECT_BOUNDING_BOX_NV    0x908A\n#define GL_CONVEX_HULL_NV                 0x908B\n#define GL_BOUNDING_BOX_NV                0x908D\n#define GL_TRANSLATE_X_NV                 0x908E\n#define GL_TRANSLATE_Y_NV                 0x908F\n#define GL_TRANSLATE_2D_NV                0x9090\n#define GL_TRANSLATE_3D_NV                0x9091\n#define GL_AFFINE_2D_NV                   0x9092\n#define GL_AFFINE_3D_NV                   0x9094\n#define GL_TRANSPOSE_AFFINE_2D_NV         0x9096\n#define GL_TRANSPOSE_AFFINE_3D_NV         0x9098\n#define GL_UTF8_NV                        0x909A\n#define GL_UTF16_NV                       0x909B\n#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C\n#define GL_PATH_COMMAND_COUNT_NV          0x909D\n#define GL_PATH_COORD_COUNT_NV            0x909E\n#define GL_PATH_DASH_ARRAY_COUNT_NV       0x909F\n#define GL_PATH_COMPUTED_LENGTH_NV        0x90A0\n#define GL_PATH_FILL_BOUNDING_BOX_NV      0x90A1\n#define GL_PATH_STROKE_BOUNDING_BOX_NV    0x90A2\n#define GL_SQUARE_NV                      0x90A3\n#define GL_ROUND_NV                       0x90A4\n#define GL_TRIANGULAR_NV                  0x90A5\n#define GL_BEVEL_NV                       0x90A6\n#define GL_MITER_REVERT_NV                0x90A7\n#define GL_MITER_TRUNCATE_NV              0x90A8\n#define GL_SKIP_MISSING_GLYPH_NV          0x90A9\n#define GL_USE_MISSING_GLYPH_NV           0x90AA\n#define GL_PATH_ERROR_POSITION_NV         0x90AB\n#define GL_PATH_FOG_GEN_MODE_NV           0x90AC\n#define GL_ACCUM_ADJACENT_PAIRS_NV        0x90AD\n#define GL_ADJACENT_PAIRS_NV              0x90AE\n#define GL_FIRST_TO_REST_NV               0x90AF\n#define GL_PATH_GEN_MODE_NV               0x90B0\n#define GL_PATH_GEN_COEFF_NV              0x90B1\n#define GL_PATH_GEN_COLOR_FORMAT_NV       0x90B2\n#define GL_PATH_GEN_COMPONENTS_NV         0x90B3\n#define GL_PATH_STENCIL_FUNC_NV           0x90B7\n#define GL_PATH_STENCIL_REF_NV            0x90B8\n#define GL_PATH_STENCIL_VALUE_MASK_NV     0x90B9\n#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD\n#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE\n#define GL_PATH_COVER_DEPTH_FUNC_NV       0x90BF\n#define GL_PATH_DASH_OFFSET_RESET_NV      0x90B4\n#define GL_MOVE_TO_RESETS_NV              0x90B5\n#define GL_MOVE_TO_CONTINUES_NV           0x90B6\n#define GL_CLOSE_PATH_NV                  0x00\n#define GL_MOVE_TO_NV                     0x02\n#define GL_RELATIVE_MOVE_TO_NV            0x03\n#define GL_LINE_TO_NV                     0x04\n#define GL_RELATIVE_LINE_TO_NV            0x05\n#define GL_HORIZONTAL_LINE_TO_NV          0x06\n#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07\n#define GL_VERTICAL_LINE_TO_NV            0x08\n#define GL_RELATIVE_VERTICAL_LINE_TO_NV   0x09\n#define GL_QUADRATIC_CURVE_TO_NV          0x0A\n#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B\n#define GL_CUBIC_CURVE_TO_NV              0x0C\n#define GL_RELATIVE_CUBIC_CURVE_TO_NV     0x0D\n#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV   0x0E\n#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F\n#define GL_SMOOTH_CUBIC_CURVE_TO_NV       0x10\n#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11\n#define GL_SMALL_CCW_ARC_TO_NV            0x12\n#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV   0x13\n#define GL_SMALL_CW_ARC_TO_NV             0x14\n#define GL_RELATIVE_SMALL_CW_ARC_TO_NV    0x15\n#define GL_LARGE_CCW_ARC_TO_NV            0x16\n#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV   0x17\n#define GL_LARGE_CW_ARC_TO_NV             0x18\n#define GL_RELATIVE_LARGE_CW_ARC_TO_NV    0x19\n#define GL_RESTART_PATH_NV                0xF0\n#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV    0xF2\n#define GL_DUP_LAST_CUBIC_CURVE_TO_NV     0xF4\n#define GL_RECT_NV                        0xF6\n#define GL_CIRCULAR_CCW_ARC_TO_NV         0xF8\n#define GL_CIRCULAR_CW_ARC_TO_NV          0xFA\n#define GL_CIRCULAR_TANGENT_ARC_TO_NV     0xFC\n#define GL_ARC_TO_NV                      0xFE\n#define GL_RELATIVE_ARC_TO_NV             0xFF\n#define GL_BOLD_BIT_NV                    0x01\n#define GL_ITALIC_BIT_NV                  0x02\n#define GL_GLYPH_WIDTH_BIT_NV             0x01\n#define GL_GLYPH_HEIGHT_BIT_NV            0x02\n#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04\n#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08\n#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10\n#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20\n#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40\n#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80\n#define GL_GLYPH_HAS_KERNING_BIT_NV       0x100\n#define GL_FONT_X_MIN_BOUNDS_BIT_NV       0x00010000\n#define GL_FONT_Y_MIN_BOUNDS_BIT_NV       0x00020000\n#define GL_FONT_X_MAX_BOUNDS_BIT_NV       0x00040000\n#define GL_FONT_Y_MAX_BOUNDS_BIT_NV       0x00080000\n#define GL_FONT_UNITS_PER_EM_BIT_NV       0x00100000\n#define GL_FONT_ASCENDER_BIT_NV           0x00200000\n#define GL_FONT_DESCENDER_BIT_NV          0x00400000\n#define GL_FONT_HEIGHT_BIT_NV             0x00800000\n#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV  0x01000000\n#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000\n#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000\n#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000\n#define GL_FONT_HAS_KERNING_BIT_NV        0x10000000\n#define GL_PRIMARY_COLOR_NV               0x852C\n#define GL_SECONDARY_COLOR_NV             0x852D\ntypedef GLuint (APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range);\ntypedef void (APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range);\ntypedef GLboolean (APIENTRYP PFNGLISPATHNVPROC) (GLuint path);\ntypedef void (APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);\ntypedef void (APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords);\ntypedef void (APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);\ntypedef void (APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords);\ntypedef void (APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString);\ntypedef void (APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);\ntypedef void (APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);\ntypedef void (APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights);\ntypedef void (APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath);\ntypedef void (APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight);\ntypedef void (APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues);\ntypedef void (APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value);\ntypedef void (APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value);\ntypedef void (APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value);\ntypedef void (APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value);\ntypedef void (APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray);\ntypedef void (APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask);\ntypedef void (APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units);\ntypedef void (APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask);\ntypedef void (APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask);\ntypedef void (APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues);\ntypedef void (APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues);\ntypedef void (APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func);\ntypedef void (APIENTRYP PFNGLPATHCOLORGENNVPROC) (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs);\ntypedef void (APIENTRYP PFNGLPATHTEXGENNVPROC) (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs);\ntypedef void (APIENTRYP PFNGLPATHFOGGENNVPROC) (GLenum genMode);\ntypedef void (APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode);\ntypedef void (APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode);\ntypedef void (APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);\ntypedef void (APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);\ntypedef void (APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value);\ntypedef void (APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value);\ntypedef void (APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands);\ntypedef void (APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords);\ntypedef void (APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray);\ntypedef void (APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics);\ntypedef void (APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics);\ntypedef void (APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing);\ntypedef void (APIENTRYP PFNGLGETPATHCOLORGENIVNVPROC) (GLenum color, GLenum pname, GLint *value);\ntypedef void (APIENTRYP PFNGLGETPATHCOLORGENFVNVPROC) (GLenum color, GLenum pname, GLfloat *value);\ntypedef void (APIENTRYP PFNGLGETPATHTEXGENIVNVPROC) (GLenum texCoordSet, GLenum pname, GLint *value);\ntypedef void (APIENTRYP PFNGLGETPATHTEXGENFVNVPROC) (GLenum texCoordSet, GLenum pname, GLfloat *value);\ntypedef GLboolean (APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y);\ntypedef GLboolean (APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y);\ntypedef GLfloat (APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments);\ntypedef GLboolean (APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint APIENTRY glGenPathsNV (GLsizei range);\nGLAPI void APIENTRY glDeletePathsNV (GLuint path, GLsizei range);\nGLAPI GLboolean APIENTRY glIsPathNV (GLuint path);\nGLAPI void APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);\nGLAPI void APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords);\nGLAPI void APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);\nGLAPI void APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords);\nGLAPI void APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString);\nGLAPI void APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);\nGLAPI void APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);\nGLAPI void APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights);\nGLAPI void APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath);\nGLAPI void APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight);\nGLAPI void APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues);\nGLAPI void APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value);\nGLAPI void APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value);\nGLAPI void APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value);\nGLAPI void APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value);\nGLAPI void APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray);\nGLAPI void APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask);\nGLAPI void APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units);\nGLAPI void APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask);\nGLAPI void APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask);\nGLAPI void APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues);\nGLAPI void APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues);\nGLAPI void APIENTRY glPathCoverDepthFuncNV (GLenum func);\nGLAPI void APIENTRY glPathColorGenNV (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs);\nGLAPI void APIENTRY glPathTexGenNV (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs);\nGLAPI void APIENTRY glPathFogGenNV (GLenum genMode);\nGLAPI void APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode);\nGLAPI void APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode);\nGLAPI void APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);\nGLAPI void APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);\nGLAPI void APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value);\nGLAPI void APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value);\nGLAPI void APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands);\nGLAPI void APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords);\nGLAPI void APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray);\nGLAPI void APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics);\nGLAPI void APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics);\nGLAPI void APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing);\nGLAPI void APIENTRY glGetPathColorGenivNV (GLenum color, GLenum pname, GLint *value);\nGLAPI void APIENTRY glGetPathColorGenfvNV (GLenum color, GLenum pname, GLfloat *value);\nGLAPI void APIENTRY glGetPathTexGenivNV (GLenum texCoordSet, GLenum pname, GLint *value);\nGLAPI void APIENTRY glGetPathTexGenfvNV (GLenum texCoordSet, GLenum pname, GLfloat *value);\nGLAPI GLboolean APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y);\nGLAPI GLboolean APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y);\nGLAPI GLfloat APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments);\nGLAPI GLboolean APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY);\n#endif\n#endif /* GL_NV_path_rendering */\n\n#ifndef GL_NV_pixel_data_range\n#define GL_NV_pixel_data_range 1\n#define GL_WRITE_PIXEL_DATA_RANGE_NV      0x8878\n#define GL_READ_PIXEL_DATA_RANGE_NV       0x8879\n#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A\n#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B\n#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C\n#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D\ntypedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, const void *pointer);\ntypedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelDataRangeNV (GLenum target, GLsizei length, const void *pointer);\nGLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum target);\n#endif\n#endif /* GL_NV_pixel_data_range */\n\n#ifndef GL_NV_point_sprite\n#define GL_NV_point_sprite 1\n#define GL_POINT_SPRITE_NV                0x8861\n#define GL_COORD_REPLACE_NV               0x8862\n#define GL_POINT_SPRITE_R_MODE_NV         0x8863\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameteriNV (GLenum pname, GLint param);\nGLAPI void APIENTRY glPointParameterivNV (GLenum pname, const GLint *params);\n#endif\n#endif /* GL_NV_point_sprite */\n\n#ifndef GL_NV_present_video\n#define GL_NV_present_video 1\n#define GL_FRAME_NV                       0x8E26\n#define GL_FIELDS_NV                      0x8E27\n#define GL_CURRENT_TIME_NV                0x8E28\n#define GL_NUM_FILL_STREAMS_NV            0x8E29\n#define GL_PRESENT_TIME_NV                0x8E2A\n#define GL_PRESENT_DURATION_NV            0x8E2B\ntypedef void (APIENTRYP PFNGLPRESENTFRAMEKEYEDNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1);\ntypedef void (APIENTRYP PFNGLPRESENTFRAMEDUALFILLNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3);\ntypedef void (APIENTRYP PFNGLGETVIDEOIVNVPROC) (GLuint video_slot, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVIDEOUIVNVPROC) (GLuint video_slot, GLenum pname, GLuint *params);\ntypedef void (APIENTRYP PFNGLGETVIDEOI64VNVPROC) (GLuint video_slot, GLenum pname, GLint64EXT *params);\ntypedef void (APIENTRYP PFNGLGETVIDEOUI64VNVPROC) (GLuint video_slot, GLenum pname, GLuint64EXT *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPresentFrameKeyedNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1);\nGLAPI void APIENTRY glPresentFrameDualFillNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3);\nGLAPI void APIENTRY glGetVideoivNV (GLuint video_slot, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVideouivNV (GLuint video_slot, GLenum pname, GLuint *params);\nGLAPI void APIENTRY glGetVideoi64vNV (GLuint video_slot, GLenum pname, GLint64EXT *params);\nGLAPI void APIENTRY glGetVideoui64vNV (GLuint video_slot, GLenum pname, GLuint64EXT *params);\n#endif\n#endif /* GL_NV_present_video */\n\n#ifndef GL_NV_primitive_restart\n#define GL_NV_primitive_restart 1\n#define GL_PRIMITIVE_RESTART_NV           0x8558\n#define GL_PRIMITIVE_RESTART_INDEX_NV     0x8559\ntypedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);\ntypedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPrimitiveRestartNV (void);\nGLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint index);\n#endif\n#endif /* GL_NV_primitive_restart */\n\n#ifndef GL_NV_register_combiners\n#define GL_NV_register_combiners 1\n#define GL_REGISTER_COMBINERS_NV          0x8522\n#define GL_VARIABLE_A_NV                  0x8523\n#define GL_VARIABLE_B_NV                  0x8524\n#define GL_VARIABLE_C_NV                  0x8525\n#define GL_VARIABLE_D_NV                  0x8526\n#define GL_VARIABLE_E_NV                  0x8527\n#define GL_VARIABLE_F_NV                  0x8528\n#define GL_VARIABLE_G_NV                  0x8529\n#define GL_CONSTANT_COLOR0_NV             0x852A\n#define GL_CONSTANT_COLOR1_NV             0x852B\n#define GL_SPARE0_NV                      0x852E\n#define GL_SPARE1_NV                      0x852F\n#define GL_DISCARD_NV                     0x8530\n#define GL_E_TIMES_F_NV                   0x8531\n#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532\n#define GL_UNSIGNED_IDENTITY_NV           0x8536\n#define GL_UNSIGNED_INVERT_NV             0x8537\n#define GL_EXPAND_NORMAL_NV               0x8538\n#define GL_EXPAND_NEGATE_NV               0x8539\n#define GL_HALF_BIAS_NORMAL_NV            0x853A\n#define GL_HALF_BIAS_NEGATE_NV            0x853B\n#define GL_SIGNED_IDENTITY_NV             0x853C\n#define GL_SIGNED_NEGATE_NV               0x853D\n#define GL_SCALE_BY_TWO_NV                0x853E\n#define GL_SCALE_BY_FOUR_NV               0x853F\n#define GL_SCALE_BY_ONE_HALF_NV           0x8540\n#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV   0x8541\n#define GL_COMBINER_INPUT_NV              0x8542\n#define GL_COMBINER_MAPPING_NV            0x8543\n#define GL_COMBINER_COMPONENT_USAGE_NV    0x8544\n#define GL_COMBINER_AB_DOT_PRODUCT_NV     0x8545\n#define GL_COMBINER_CD_DOT_PRODUCT_NV     0x8546\n#define GL_COMBINER_MUX_SUM_NV            0x8547\n#define GL_COMBINER_SCALE_NV              0x8548\n#define GL_COMBINER_BIAS_NV               0x8549\n#define GL_COMBINER_AB_OUTPUT_NV          0x854A\n#define GL_COMBINER_CD_OUTPUT_NV          0x854B\n#define GL_COMBINER_SUM_OUTPUT_NV         0x854C\n#define GL_MAX_GENERAL_COMBINERS_NV       0x854D\n#define GL_NUM_GENERAL_COMBINERS_NV       0x854E\n#define GL_COLOR_SUM_CLAMP_NV             0x854F\n#define GL_COMBINER0_NV                   0x8550\n#define GL_COMBINER1_NV                   0x8551\n#define GL_COMBINER2_NV                   0x8552\n#define GL_COMBINER3_NV                   0x8553\n#define GL_COMBINER4_NV                   0x8554\n#define GL_COMBINER5_NV                   0x8555\n#define GL_COMBINER6_NV                   0x8556\n#define GL_COMBINER7_NV                   0x8557\ntypedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);\ntypedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);\ntypedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);\ntypedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCombinerParameterfvNV (GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glCombinerParameterfNV (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glCombinerParameterivNV (GLenum pname, const GLint *params);\nGLAPI void APIENTRY glCombinerParameteriNV (GLenum pname, GLint param);\nGLAPI void APIENTRY glCombinerInputNV (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);\nGLAPI void APIENTRY glCombinerOutputNV (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);\nGLAPI void APIENTRY glFinalCombinerInputNV (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);\nGLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum stage, GLenum portion, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum variable, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum variable, GLenum pname, GLint *params);\n#endif\n#endif /* GL_NV_register_combiners */\n\n#ifndef GL_NV_register_combiners2\n#define GL_NV_register_combiners2 1\n#define GL_PER_STAGE_CONSTANTS_NV         0x8535\ntypedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params);\n#endif\n#endif /* GL_NV_register_combiners2 */\n\n#ifndef GL_NV_shader_atomic_counters\n#define GL_NV_shader_atomic_counters 1\n#endif /* GL_NV_shader_atomic_counters */\n\n#ifndef GL_NV_shader_atomic_float\n#define GL_NV_shader_atomic_float 1\n#endif /* GL_NV_shader_atomic_float */\n\n#ifndef GL_NV_shader_buffer_load\n#define GL_NV_shader_buffer_load 1\n#define GL_BUFFER_GPU_ADDRESS_NV          0x8F1D\n#define GL_GPU_ADDRESS_NV                 0x8F34\n#define GL_MAX_SHADER_BUFFER_ADDRESS_NV   0x8F35\ntypedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access);\ntypedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target);\ntypedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target);\ntypedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access);\ntypedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer);\ntypedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params);\ntypedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params);\ntypedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result);\ntypedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value);\ntypedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);\ntypedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value);\ntypedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMakeBufferResidentNV (GLenum target, GLenum access);\nGLAPI void APIENTRY glMakeBufferNonResidentNV (GLenum target);\nGLAPI GLboolean APIENTRY glIsBufferResidentNV (GLenum target);\nGLAPI void APIENTRY glMakeNamedBufferResidentNV (GLuint buffer, GLenum access);\nGLAPI void APIENTRY glMakeNamedBufferNonResidentNV (GLuint buffer);\nGLAPI GLboolean APIENTRY glIsNamedBufferResidentNV (GLuint buffer);\nGLAPI void APIENTRY glGetBufferParameterui64vNV (GLenum target, GLenum pname, GLuint64EXT *params);\nGLAPI void APIENTRY glGetNamedBufferParameterui64vNV (GLuint buffer, GLenum pname, GLuint64EXT *params);\nGLAPI void APIENTRY glGetIntegerui64vNV (GLenum value, GLuint64EXT *result);\nGLAPI void APIENTRY glUniformui64NV (GLint location, GLuint64EXT value);\nGLAPI void APIENTRY glUniformui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);\nGLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params);\nGLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value);\nGLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);\n#endif\n#endif /* GL_NV_shader_buffer_load */\n\n#ifndef GL_NV_shader_buffer_store\n#define GL_NV_shader_buffer_store 1\n#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010\n#endif /* GL_NV_shader_buffer_store */\n\n#ifndef GL_NV_shader_storage_buffer_object\n#define GL_NV_shader_storage_buffer_object 1\n#endif /* GL_NV_shader_storage_buffer_object */\n\n#ifndef GL_NV_tessellation_program5\n#define GL_NV_tessellation_program5 1\n#define GL_MAX_PROGRAM_PATCH_ATTRIBS_NV   0x86D8\n#define GL_TESS_CONTROL_PROGRAM_NV        0x891E\n#define GL_TESS_EVALUATION_PROGRAM_NV     0x891F\n#define GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV 0x8C74\n#define GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV 0x8C75\n#endif /* GL_NV_tessellation_program5 */\n\n#ifndef GL_NV_texgen_emboss\n#define GL_NV_texgen_emboss 1\n#define GL_EMBOSS_LIGHT_NV                0x855D\n#define GL_EMBOSS_CONSTANT_NV             0x855E\n#define GL_EMBOSS_MAP_NV                  0x855F\n#endif /* GL_NV_texgen_emboss */\n\n#ifndef GL_NV_texgen_reflection\n#define GL_NV_texgen_reflection 1\n#define GL_NORMAL_MAP_NV                  0x8511\n#define GL_REFLECTION_MAP_NV              0x8512\n#endif /* GL_NV_texgen_reflection */\n\n#ifndef GL_NV_texture_barrier\n#define GL_NV_texture_barrier 1\ntypedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTextureBarrierNV (void);\n#endif\n#endif /* GL_NV_texture_barrier */\n\n#ifndef GL_NV_texture_compression_vtc\n#define GL_NV_texture_compression_vtc 1\n#endif /* GL_NV_texture_compression_vtc */\n\n#ifndef GL_NV_texture_env_combine4\n#define GL_NV_texture_env_combine4 1\n#define GL_COMBINE4_NV                    0x8503\n#define GL_SOURCE3_RGB_NV                 0x8583\n#define GL_SOURCE3_ALPHA_NV               0x858B\n#define GL_OPERAND3_RGB_NV                0x8593\n#define GL_OPERAND3_ALPHA_NV              0x859B\n#endif /* GL_NV_texture_env_combine4 */\n\n#ifndef GL_NV_texture_expand_normal\n#define GL_NV_texture_expand_normal 1\n#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F\n#endif /* GL_NV_texture_expand_normal */\n\n#ifndef GL_NV_texture_multisample\n#define GL_NV_texture_multisample 1\n#define GL_TEXTURE_COVERAGE_SAMPLES_NV    0x9045\n#define GL_TEXTURE_COLOR_SAMPLES_NV       0x9046\ntypedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);\ntypedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);\ntypedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexImage2DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);\nGLAPI void APIENTRY glTexImage3DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);\nGLAPI void APIENTRY glTextureImage2DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);\nGLAPI void APIENTRY glTextureImage3DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);\nGLAPI void APIENTRY glTextureImage2DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);\nGLAPI void APIENTRY glTextureImage3DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);\n#endif\n#endif /* GL_NV_texture_multisample */\n\n#ifndef GL_NV_texture_rectangle\n#define GL_NV_texture_rectangle 1\n#define GL_TEXTURE_RECTANGLE_NV           0x84F5\n#define GL_TEXTURE_BINDING_RECTANGLE_NV   0x84F6\n#define GL_PROXY_TEXTURE_RECTANGLE_NV     0x84F7\n#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV  0x84F8\n#endif /* GL_NV_texture_rectangle */\n\n#ifndef GL_NV_texture_shader\n#define GL_NV_texture_shader 1\n#define GL_OFFSET_TEXTURE_RECTANGLE_NV    0x864C\n#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D\n#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E\n#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9\n#define GL_UNSIGNED_INT_S8_S8_8_8_NV      0x86DA\n#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV  0x86DB\n#define GL_DSDT_MAG_INTENSITY_NV          0x86DC\n#define GL_SHADER_CONSISTENT_NV           0x86DD\n#define GL_TEXTURE_SHADER_NV              0x86DE\n#define GL_SHADER_OPERATION_NV            0x86DF\n#define GL_CULL_MODES_NV                  0x86E0\n#define GL_OFFSET_TEXTURE_MATRIX_NV       0x86E1\n#define GL_OFFSET_TEXTURE_SCALE_NV        0x86E2\n#define GL_OFFSET_TEXTURE_BIAS_NV         0x86E3\n#define GL_OFFSET_TEXTURE_2D_MATRIX_NV    0x86E1\n#define GL_OFFSET_TEXTURE_2D_SCALE_NV     0x86E2\n#define GL_OFFSET_TEXTURE_2D_BIAS_NV      0x86E3\n#define GL_PREVIOUS_TEXTURE_INPUT_NV      0x86E4\n#define GL_CONST_EYE_NV                   0x86E5\n#define GL_PASS_THROUGH_NV                0x86E6\n#define GL_CULL_FRAGMENT_NV               0x86E7\n#define GL_OFFSET_TEXTURE_2D_NV           0x86E8\n#define GL_DEPENDENT_AR_TEXTURE_2D_NV     0x86E9\n#define GL_DEPENDENT_GB_TEXTURE_2D_NV     0x86EA\n#define GL_DOT_PRODUCT_NV                 0x86EC\n#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV   0x86ED\n#define GL_DOT_PRODUCT_TEXTURE_2D_NV      0x86EE\n#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0\n#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1\n#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2\n#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3\n#define GL_HILO_NV                        0x86F4\n#define GL_DSDT_NV                        0x86F5\n#define GL_DSDT_MAG_NV                    0x86F6\n#define GL_DSDT_MAG_VIB_NV                0x86F7\n#define GL_HILO16_NV                      0x86F8\n#define GL_SIGNED_HILO_NV                 0x86F9\n#define GL_SIGNED_HILO16_NV               0x86FA\n#define GL_SIGNED_RGBA_NV                 0x86FB\n#define GL_SIGNED_RGBA8_NV                0x86FC\n#define GL_SIGNED_RGB_NV                  0x86FE\n#define GL_SIGNED_RGB8_NV                 0x86FF\n#define GL_SIGNED_LUMINANCE_NV            0x8701\n#define GL_SIGNED_LUMINANCE8_NV           0x8702\n#define GL_SIGNED_LUMINANCE_ALPHA_NV      0x8703\n#define GL_SIGNED_LUMINANCE8_ALPHA8_NV    0x8704\n#define GL_SIGNED_ALPHA_NV                0x8705\n#define GL_SIGNED_ALPHA8_NV               0x8706\n#define GL_SIGNED_INTENSITY_NV            0x8707\n#define GL_SIGNED_INTENSITY8_NV           0x8708\n#define GL_DSDT8_NV                       0x8709\n#define GL_DSDT8_MAG8_NV                  0x870A\n#define GL_DSDT8_MAG8_INTENSITY8_NV       0x870B\n#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV   0x870C\n#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D\n#define GL_HI_SCALE_NV                    0x870E\n#define GL_LO_SCALE_NV                    0x870F\n#define GL_DS_SCALE_NV                    0x8710\n#define GL_DT_SCALE_NV                    0x8711\n#define GL_MAGNITUDE_SCALE_NV             0x8712\n#define GL_VIBRANCE_SCALE_NV              0x8713\n#define GL_HI_BIAS_NV                     0x8714\n#define GL_LO_BIAS_NV                     0x8715\n#define GL_DS_BIAS_NV                     0x8716\n#define GL_DT_BIAS_NV                     0x8717\n#define GL_MAGNITUDE_BIAS_NV              0x8718\n#define GL_VIBRANCE_BIAS_NV               0x8719\n#define GL_TEXTURE_BORDER_VALUES_NV       0x871A\n#define GL_TEXTURE_HI_SIZE_NV             0x871B\n#define GL_TEXTURE_LO_SIZE_NV             0x871C\n#define GL_TEXTURE_DS_SIZE_NV             0x871D\n#define GL_TEXTURE_DT_SIZE_NV             0x871E\n#define GL_TEXTURE_MAG_SIZE_NV            0x871F\n#endif /* GL_NV_texture_shader */\n\n#ifndef GL_NV_texture_shader2\n#define GL_NV_texture_shader2 1\n#define GL_DOT_PRODUCT_TEXTURE_3D_NV      0x86EF\n#endif /* GL_NV_texture_shader2 */\n\n#ifndef GL_NV_texture_shader3\n#define GL_NV_texture_shader3 1\n#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850\n#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851\n#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852\n#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853\n#define GL_OFFSET_HILO_TEXTURE_2D_NV      0x8854\n#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855\n#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856\n#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857\n#define GL_DEPENDENT_HILO_TEXTURE_2D_NV   0x8858\n#define GL_DEPENDENT_RGB_TEXTURE_3D_NV    0x8859\n#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A\n#define GL_DOT_PRODUCT_PASS_THROUGH_NV    0x885B\n#define GL_DOT_PRODUCT_TEXTURE_1D_NV      0x885C\n#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D\n#define GL_HILO8_NV                       0x885E\n#define GL_SIGNED_HILO8_NV                0x885F\n#define GL_FORCE_BLUE_TO_ONE_NV           0x8860\n#endif /* GL_NV_texture_shader3 */\n\n#ifndef GL_NV_transform_feedback\n#define GL_NV_transform_feedback 1\n#define GL_BACK_PRIMARY_COLOR_NV          0x8C77\n#define GL_BACK_SECONDARY_COLOR_NV        0x8C78\n#define GL_TEXTURE_COORD_NV               0x8C79\n#define GL_CLIP_DISTANCE_NV               0x8C7A\n#define GL_VERTEX_ID_NV                   0x8C7B\n#define GL_PRIMITIVE_ID_NV                0x8C7C\n#define GL_GENERIC_ATTRIB_NV              0x8C7D\n#define GL_TRANSFORM_FEEDBACK_ATTRIBS_NV  0x8C7E\n#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV 0x8C7F\n#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV 0x8C80\n#define GL_ACTIVE_VARYINGS_NV             0x8C81\n#define GL_ACTIVE_VARYING_MAX_LENGTH_NV   0x8C82\n#define GL_TRANSFORM_FEEDBACK_VARYINGS_NV 0x8C83\n#define GL_TRANSFORM_FEEDBACK_BUFFER_START_NV 0x8C84\n#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV 0x8C85\n#define GL_TRANSFORM_FEEDBACK_RECORD_NV   0x8C86\n#define GL_PRIMITIVES_GENERATED_NV        0x8C87\n#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV 0x8C88\n#define GL_RASTERIZER_DISCARD_NV          0x8C89\n#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV 0x8C8A\n#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV 0x8C8B\n#define GL_INTERLEAVED_ATTRIBS_NV         0x8C8C\n#define GL_SEPARATE_ATTRIBS_NV            0x8C8D\n#define GL_TRANSFORM_FEEDBACK_BUFFER_NV   0x8C8E\n#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV 0x8C8F\n#define GL_LAYER_NV                       0x8DAA\n#define GL_NEXT_BUFFER_NV                 -2\n#define GL_SKIP_COMPONENTS4_NV            -3\n#define GL_SKIP_COMPONENTS3_NV            -4\n#define GL_SKIP_COMPONENTS2_NV            -5\n#define GL_SKIP_COMPONENTS1_NV            -6\ntypedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode);\ntypedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void);\ntypedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLuint count, const GLint *attribs, GLenum bufferMode);\ntypedef void (APIENTRYP PFNGLBINDBUFFERRANGENVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);\ntypedef void (APIENTRYP PFNGLBINDBUFFEROFFSETNVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset);\ntypedef void (APIENTRYP PFNGLBINDBUFFERBASENVPROC) (GLenum target, GLuint index, GLuint buffer);\ntypedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC) (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode);\ntypedef void (APIENTRYP PFNGLACTIVEVARYINGNVPROC) (GLuint program, const GLchar *name);\ntypedef GLint (APIENTRYP PFNGLGETVARYINGLOCATIONNVPROC) (GLuint program, const GLchar *name);\ntypedef void (APIENTRYP PFNGLGETACTIVEVARYINGNVPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);\ntypedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC) (GLuint program, GLuint index, GLint *location);\ntypedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode);\nGLAPI void APIENTRY glEndTransformFeedbackNV (void);\nGLAPI void APIENTRY glTransformFeedbackAttribsNV (GLuint count, const GLint *attribs, GLenum bufferMode);\nGLAPI void APIENTRY glBindBufferRangeNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);\nGLAPI void APIENTRY glBindBufferOffsetNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset);\nGLAPI void APIENTRY glBindBufferBaseNV (GLenum target, GLuint index, GLuint buffer);\nGLAPI void APIENTRY glTransformFeedbackVaryingsNV (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode);\nGLAPI void APIENTRY glActiveVaryingNV (GLuint program, const GLchar *name);\nGLAPI GLint APIENTRY glGetVaryingLocationNV (GLuint program, const GLchar *name);\nGLAPI void APIENTRY glGetActiveVaryingNV (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);\nGLAPI void APIENTRY glGetTransformFeedbackVaryingNV (GLuint program, GLuint index, GLint *location);\nGLAPI void APIENTRY glTransformFeedbackStreamAttribsNV (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode);\n#endif\n#endif /* GL_NV_transform_feedback */\n\n#ifndef GL_NV_transform_feedback2\n#define GL_NV_transform_feedback2 1\n#define GL_TRANSFORM_FEEDBACK_NV          0x8E22\n#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV 0x8E23\n#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV 0x8E24\n#define GL_TRANSFORM_FEEDBACK_BINDING_NV  0x8E25\ntypedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKNVPROC) (GLenum target, GLuint id);\ntypedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSNVPROC) (GLsizei n, const GLuint *ids);\ntypedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSNVPROC) (GLsizei n, GLuint *ids);\ntypedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKNVPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKNVPROC) (void);\ntypedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKNVPROC) (void);\ntypedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKNVPROC) (GLenum mode, GLuint id);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindTransformFeedbackNV (GLenum target, GLuint id);\nGLAPI void APIENTRY glDeleteTransformFeedbacksNV (GLsizei n, const GLuint *ids);\nGLAPI void APIENTRY glGenTransformFeedbacksNV (GLsizei n, GLuint *ids);\nGLAPI GLboolean APIENTRY glIsTransformFeedbackNV (GLuint id);\nGLAPI void APIENTRY glPauseTransformFeedbackNV (void);\nGLAPI void APIENTRY glResumeTransformFeedbackNV (void);\nGLAPI void APIENTRY glDrawTransformFeedbackNV (GLenum mode, GLuint id);\n#endif\n#endif /* GL_NV_transform_feedback2 */\n\n#ifndef GL_NV_vdpau_interop\n#define GL_NV_vdpau_interop 1\ntypedef GLintptr GLvdpauSurfaceNV;\n#define GL_SURFACE_STATE_NV               0x86EB\n#define GL_SURFACE_REGISTERED_NV          0x86FD\n#define GL_SURFACE_MAPPED_NV              0x8700\n#define GL_WRITE_DISCARD_NV               0x88BE\ntypedef void (APIENTRYP PFNGLVDPAUINITNVPROC) (const void *vdpDevice, const void *getProcAddress);\ntypedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void);\ntypedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);\ntypedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);\ntypedef GLboolean (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface);\ntypedef void (APIENTRYP PFNGLVDPAUUNREGISTERSURFACENVPROC) (GLvdpauSurfaceNV surface);\ntypedef void (APIENTRYP PFNGLVDPAUGETSURFACEIVNVPROC) (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);\ntypedef void (APIENTRYP PFNGLVDPAUSURFACEACCESSNVPROC) (GLvdpauSurfaceNV surface, GLenum access);\ntypedef void (APIENTRYP PFNGLVDPAUMAPSURFACESNVPROC) (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces);\ntypedef void (APIENTRYP PFNGLVDPAUUNMAPSURFACESNVPROC) (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVDPAUInitNV (const void *vdpDevice, const void *getProcAddress);\nGLAPI void APIENTRY glVDPAUFiniNV (void);\nGLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);\nGLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);\nGLAPI GLboolean APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface);\nGLAPI void APIENTRY glVDPAUUnregisterSurfaceNV (GLvdpauSurfaceNV surface);\nGLAPI void APIENTRY glVDPAUGetSurfaceivNV (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);\nGLAPI void APIENTRY glVDPAUSurfaceAccessNV (GLvdpauSurfaceNV surface, GLenum access);\nGLAPI void APIENTRY glVDPAUMapSurfacesNV (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces);\nGLAPI void APIENTRY glVDPAUUnmapSurfacesNV (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces);\n#endif\n#endif /* GL_NV_vdpau_interop */\n\n#ifndef GL_NV_vertex_array_range\n#define GL_NV_vertex_array_range 1\n#define GL_VERTEX_ARRAY_RANGE_NV          0x851D\n#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV   0x851E\n#define GL_VERTEX_ARRAY_RANGE_VALID_NV    0x851F\n#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520\n#define GL_VERTEX_ARRAY_RANGE_POINTER_NV  0x8521\ntypedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const void *pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFlushVertexArrayRangeNV (void);\nGLAPI void APIENTRY glVertexArrayRangeNV (GLsizei length, const void *pointer);\n#endif\n#endif /* GL_NV_vertex_array_range */\n\n#ifndef GL_NV_vertex_array_range2\n#define GL_NV_vertex_array_range2 1\n#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533\n#endif /* GL_NV_vertex_array_range2 */\n\n#ifndef GL_NV_vertex_attrib_integer_64bit\n#define GL_NV_vertex_attrib_integer_64bit 1\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT *v);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT *params);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribL1i64NV (GLuint index, GLint64EXT x);\nGLAPI void APIENTRY glVertexAttribL2i64NV (GLuint index, GLint64EXT x, GLint64EXT y);\nGLAPI void APIENTRY glVertexAttribL3i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z);\nGLAPI void APIENTRY glVertexAttribL4i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);\nGLAPI void APIENTRY glVertexAttribL1i64vNV (GLuint index, const GLint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL2i64vNV (GLuint index, const GLint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL3i64vNV (GLuint index, const GLint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL4i64vNV (GLuint index, const GLint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL1ui64NV (GLuint index, GLuint64EXT x);\nGLAPI void APIENTRY glVertexAttribL2ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y);\nGLAPI void APIENTRY glVertexAttribL3ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);\nGLAPI void APIENTRY glVertexAttribL4ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);\nGLAPI void APIENTRY glVertexAttribL1ui64vNV (GLuint index, const GLuint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL2ui64vNV (GLuint index, const GLuint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL3ui64vNV (GLuint index, const GLuint64EXT *v);\nGLAPI void APIENTRY glVertexAttribL4ui64vNV (GLuint index, const GLuint64EXT *v);\nGLAPI void APIENTRY glGetVertexAttribLi64vNV (GLuint index, GLenum pname, GLint64EXT *params);\nGLAPI void APIENTRY glGetVertexAttribLui64vNV (GLuint index, GLenum pname, GLuint64EXT *params);\nGLAPI void APIENTRY glVertexAttribLFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride);\n#endif\n#endif /* GL_NV_vertex_attrib_integer_64bit */\n\n#ifndef GL_NV_vertex_buffer_unified_memory\n#define GL_NV_vertex_buffer_unified_memory 1\n#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E\n#define GL_ELEMENT_ARRAY_UNIFIED_NV       0x8F1F\n#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20\n#define GL_VERTEX_ARRAY_ADDRESS_NV        0x8F21\n#define GL_NORMAL_ARRAY_ADDRESS_NV        0x8F22\n#define GL_COLOR_ARRAY_ADDRESS_NV         0x8F23\n#define GL_INDEX_ARRAY_ADDRESS_NV         0x8F24\n#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25\n#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV     0x8F26\n#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27\n#define GL_FOG_COORD_ARRAY_ADDRESS_NV     0x8F28\n#define GL_ELEMENT_ARRAY_ADDRESS_NV       0x8F29\n#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV  0x8F2A\n#define GL_VERTEX_ARRAY_LENGTH_NV         0x8F2B\n#define GL_NORMAL_ARRAY_LENGTH_NV         0x8F2C\n#define GL_COLOR_ARRAY_LENGTH_NV          0x8F2D\n#define GL_INDEX_ARRAY_LENGTH_NV          0x8F2E\n#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV  0x8F2F\n#define GL_EDGE_FLAG_ARRAY_LENGTH_NV      0x8F30\n#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31\n#define GL_FOG_COORD_ARRAY_LENGTH_NV      0x8F32\n#define GL_ELEMENT_ARRAY_LENGTH_NV        0x8F33\n#define GL_DRAW_INDIRECT_UNIFIED_NV       0x8F40\n#define GL_DRAW_INDIRECT_ADDRESS_NV       0x8F41\n#define GL_DRAW_INDIRECT_LENGTH_NV        0x8F42\ntypedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);\ntypedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);\ntypedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBufferAddressRangeNV (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);\nGLAPI void APIENTRY glVertexFormatNV (GLint size, GLenum type, GLsizei stride);\nGLAPI void APIENTRY glNormalFormatNV (GLenum type, GLsizei stride);\nGLAPI void APIENTRY glColorFormatNV (GLint size, GLenum type, GLsizei stride);\nGLAPI void APIENTRY glIndexFormatNV (GLenum type, GLsizei stride);\nGLAPI void APIENTRY glTexCoordFormatNV (GLint size, GLenum type, GLsizei stride);\nGLAPI void APIENTRY glEdgeFlagFormatNV (GLsizei stride);\nGLAPI void APIENTRY glSecondaryColorFormatNV (GLint size, GLenum type, GLsizei stride);\nGLAPI void APIENTRY glFogCoordFormatNV (GLenum type, GLsizei stride);\nGLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);\nGLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride);\nGLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result);\n#endif\n#endif /* GL_NV_vertex_buffer_unified_memory */\n\n#ifndef GL_NV_vertex_program\n#define GL_NV_vertex_program 1\n#define GL_VERTEX_PROGRAM_NV              0x8620\n#define GL_VERTEX_STATE_PROGRAM_NV        0x8621\n#define GL_ATTRIB_ARRAY_SIZE_NV           0x8623\n#define GL_ATTRIB_ARRAY_STRIDE_NV         0x8624\n#define GL_ATTRIB_ARRAY_TYPE_NV           0x8625\n#define GL_CURRENT_ATTRIB_NV              0x8626\n#define GL_PROGRAM_LENGTH_NV              0x8627\n#define GL_PROGRAM_STRING_NV              0x8628\n#define GL_MODELVIEW_PROJECTION_NV        0x8629\n#define GL_IDENTITY_NV                    0x862A\n#define GL_INVERSE_NV                     0x862B\n#define GL_TRANSPOSE_NV                   0x862C\n#define GL_INVERSE_TRANSPOSE_NV           0x862D\n#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E\n#define GL_MAX_TRACK_MATRICES_NV          0x862F\n#define GL_MATRIX0_NV                     0x8630\n#define GL_MATRIX1_NV                     0x8631\n#define GL_MATRIX2_NV                     0x8632\n#define GL_MATRIX3_NV                     0x8633\n#define GL_MATRIX4_NV                     0x8634\n#define GL_MATRIX5_NV                     0x8635\n#define GL_MATRIX6_NV                     0x8636\n#define GL_MATRIX7_NV                     0x8637\n#define GL_CURRENT_MATRIX_STACK_DEPTH_NV  0x8640\n#define GL_CURRENT_MATRIX_NV              0x8641\n#define GL_VERTEX_PROGRAM_POINT_SIZE_NV   0x8642\n#define GL_VERTEX_PROGRAM_TWO_SIDE_NV     0x8643\n#define GL_PROGRAM_PARAMETER_NV           0x8644\n#define GL_ATTRIB_ARRAY_POINTER_NV        0x8645\n#define GL_PROGRAM_TARGET_NV              0x8646\n#define GL_PROGRAM_RESIDENT_NV            0x8647\n#define GL_TRACK_MATRIX_NV                0x8648\n#define GL_TRACK_MATRIX_TRANSFORM_NV      0x8649\n#define GL_VERTEX_PROGRAM_BINDING_NV      0x864A\n#define GL_PROGRAM_ERROR_POSITION_NV      0x864B\n#define GL_VERTEX_ATTRIB_ARRAY0_NV        0x8650\n#define GL_VERTEX_ATTRIB_ARRAY1_NV        0x8651\n#define GL_VERTEX_ATTRIB_ARRAY2_NV        0x8652\n#define GL_VERTEX_ATTRIB_ARRAY3_NV        0x8653\n#define GL_VERTEX_ATTRIB_ARRAY4_NV        0x8654\n#define GL_VERTEX_ATTRIB_ARRAY5_NV        0x8655\n#define GL_VERTEX_ATTRIB_ARRAY6_NV        0x8656\n#define GL_VERTEX_ATTRIB_ARRAY7_NV        0x8657\n#define GL_VERTEX_ATTRIB_ARRAY8_NV        0x8658\n#define GL_VERTEX_ATTRIB_ARRAY9_NV        0x8659\n#define GL_VERTEX_ATTRIB_ARRAY10_NV       0x865A\n#define GL_VERTEX_ATTRIB_ARRAY11_NV       0x865B\n#define GL_VERTEX_ATTRIB_ARRAY12_NV       0x865C\n#define GL_VERTEX_ATTRIB_ARRAY13_NV       0x865D\n#define GL_VERTEX_ATTRIB_ARRAY14_NV       0x865E\n#define GL_VERTEX_ATTRIB_ARRAY15_NV       0x865F\n#define GL_MAP1_VERTEX_ATTRIB0_4_NV       0x8660\n#define GL_MAP1_VERTEX_ATTRIB1_4_NV       0x8661\n#define GL_MAP1_VERTEX_ATTRIB2_4_NV       0x8662\n#define GL_MAP1_VERTEX_ATTRIB3_4_NV       0x8663\n#define GL_MAP1_VERTEX_ATTRIB4_4_NV       0x8664\n#define GL_MAP1_VERTEX_ATTRIB5_4_NV       0x8665\n#define GL_MAP1_VERTEX_ATTRIB6_4_NV       0x8666\n#define GL_MAP1_VERTEX_ATTRIB7_4_NV       0x8667\n#define GL_MAP1_VERTEX_ATTRIB8_4_NV       0x8668\n#define GL_MAP1_VERTEX_ATTRIB9_4_NV       0x8669\n#define GL_MAP1_VERTEX_ATTRIB10_4_NV      0x866A\n#define GL_MAP1_VERTEX_ATTRIB11_4_NV      0x866B\n#define GL_MAP1_VERTEX_ATTRIB12_4_NV      0x866C\n#define GL_MAP1_VERTEX_ATTRIB13_4_NV      0x866D\n#define GL_MAP1_VERTEX_ATTRIB14_4_NV      0x866E\n#define GL_MAP1_VERTEX_ATTRIB15_4_NV      0x866F\n#define GL_MAP2_VERTEX_ATTRIB0_4_NV       0x8670\n#define GL_MAP2_VERTEX_ATTRIB1_4_NV       0x8671\n#define GL_MAP2_VERTEX_ATTRIB2_4_NV       0x8672\n#define GL_MAP2_VERTEX_ATTRIB3_4_NV       0x8673\n#define GL_MAP2_VERTEX_ATTRIB4_4_NV       0x8674\n#define GL_MAP2_VERTEX_ATTRIB5_4_NV       0x8675\n#define GL_MAP2_VERTEX_ATTRIB6_4_NV       0x8676\n#define GL_MAP2_VERTEX_ATTRIB7_4_NV       0x8677\n#define GL_MAP2_VERTEX_ATTRIB8_4_NV       0x8678\n#define GL_MAP2_VERTEX_ATTRIB9_4_NV       0x8679\n#define GL_MAP2_VERTEX_ATTRIB10_4_NV      0x867A\n#define GL_MAP2_VERTEX_ATTRIB11_4_NV      0x867B\n#define GL_MAP2_VERTEX_ATTRIB12_4_NV      0x867C\n#define GL_MAP2_VERTEX_ATTRIB13_4_NV      0x867D\n#define GL_MAP2_VERTEX_ATTRIB14_4_NV      0x867E\n#define GL_MAP2_VERTEX_ATTRIB15_4_NV      0x867F\ntypedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences);\ntypedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id);\ntypedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);\ntypedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs);\ntypedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program);\ntypedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, void **pointer);\ntypedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id);\ntypedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);\ntypedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei n, const GLuint *programs, GLboolean *residences);\nGLAPI void APIENTRY glBindProgramNV (GLenum target, GLuint id);\nGLAPI void APIENTRY glDeleteProgramsNV (GLsizei n, const GLuint *programs);\nGLAPI void APIENTRY glExecuteProgramNV (GLenum target, GLuint id, const GLfloat *params);\nGLAPI void APIENTRY glGenProgramsNV (GLsizei n, GLuint *programs);\nGLAPI void APIENTRY glGetProgramParameterdvNV (GLenum target, GLuint index, GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glGetProgramParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetProgramivNV (GLuint id, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetProgramStringNV (GLuint id, GLenum pname, GLubyte *program);\nGLAPI void APIENTRY glGetTrackMatrixivNV (GLenum target, GLuint address, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribdvNV (GLuint index, GLenum pname, GLdouble *params);\nGLAPI void APIENTRY glGetVertexAttribfvNV (GLuint index, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetVertexAttribivNV (GLuint index, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint index, GLenum pname, void **pointer);\nGLAPI GLboolean APIENTRY glIsProgramNV (GLuint id);\nGLAPI void APIENTRY glLoadProgramNV (GLenum target, GLuint id, GLsizei len, const GLubyte *program);\nGLAPI void APIENTRY glProgramParameter4dNV (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLsizei count, const GLdouble *v);\nGLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLsizei count, const GLfloat *v);\nGLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei n, const GLuint *programs);\nGLAPI void APIENTRY glTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform);\nGLAPI void APIENTRY glVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glVertexAttrib1dNV (GLuint index, GLdouble x);\nGLAPI void APIENTRY glVertexAttrib1dvNV (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib1fNV (GLuint index, GLfloat x);\nGLAPI void APIENTRY glVertexAttrib1fvNV (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib1sNV (GLuint index, GLshort x);\nGLAPI void APIENTRY glVertexAttrib1svNV (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib2dNV (GLuint index, GLdouble x, GLdouble y);\nGLAPI void APIENTRY glVertexAttrib2dvNV (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib2fNV (GLuint index, GLfloat x, GLfloat y);\nGLAPI void APIENTRY glVertexAttrib2fvNV (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib2sNV (GLuint index, GLshort x, GLshort y);\nGLAPI void APIENTRY glVertexAttrib2svNV (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib3dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z);\nGLAPI void APIENTRY glVertexAttrib3dvNV (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib3fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glVertexAttrib3fvNV (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib3sNV (GLuint index, GLshort x, GLshort y, GLshort z);\nGLAPI void APIENTRY glVertexAttrib3svNV (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\nGLAPI void APIENTRY glVertexAttrib4dvNV (GLuint index, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttrib4fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glVertexAttrib4fvNV (GLuint index, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttrib4sNV (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);\nGLAPI void APIENTRY glVertexAttrib4svNV (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttrib4ubNV (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);\nGLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttribs1dvNV (GLuint index, GLsizei count, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribs1fvNV (GLuint index, GLsizei count, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttribs1svNV (GLuint index, GLsizei count, const GLshort *v);\nGLAPI void APIENTRY glVertexAttribs2dvNV (GLuint index, GLsizei count, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribs2fvNV (GLuint index, GLsizei count, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttribs2svNV (GLuint index, GLsizei count, const GLshort *v);\nGLAPI void APIENTRY glVertexAttribs3dvNV (GLuint index, GLsizei count, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribs3fvNV (GLuint index, GLsizei count, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttribs3svNV (GLuint index, GLsizei count, const GLshort *v);\nGLAPI void APIENTRY glVertexAttribs4dvNV (GLuint index, GLsizei count, const GLdouble *v);\nGLAPI void APIENTRY glVertexAttribs4fvNV (GLuint index, GLsizei count, const GLfloat *v);\nGLAPI void APIENTRY glVertexAttribs4svNV (GLuint index, GLsizei count, const GLshort *v);\nGLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint index, GLsizei count, const GLubyte *v);\n#endif\n#endif /* GL_NV_vertex_program */\n\n#ifndef GL_NV_vertex_program1_1\n#define GL_NV_vertex_program1_1 1\n#endif /* GL_NV_vertex_program1_1 */\n\n#ifndef GL_NV_vertex_program2\n#define GL_NV_vertex_program2 1\n#endif /* GL_NV_vertex_program2 */\n\n#ifndef GL_NV_vertex_program2_option\n#define GL_NV_vertex_program2_option 1\n#endif /* GL_NV_vertex_program2_option */\n\n#ifndef GL_NV_vertex_program3\n#define GL_NV_vertex_program3 1\n#endif /* GL_NV_vertex_program3 */\n\n#ifndef GL_NV_vertex_program4\n#define GL_NV_vertex_program4 1\n#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV 0x88FD\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1IEXTPROC) (GLuint index, GLint x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2IEXTPROC) (GLuint index, GLint x, GLint y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3IEXTPROC) (GLuint index, GLint x, GLint y, GLint z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4IEXTPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIEXTPROC) (GLuint index, GLuint x);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIEXTPROC) (GLuint index, GLuint x, GLuint y);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVEXTPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVEXTPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVEXTPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVEXTPROC) (GLuint index, const GLint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVEXTPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVEXTPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVEXTPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVEXTPROC) (GLuint index, const GLuint *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVEXTPROC) (GLuint index, const GLbyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVEXTPROC) (GLuint index, const GLshort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVEXTPROC) (GLuint index, const GLubyte *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVEXTPROC) (GLuint index, const GLushort *v);\ntypedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVEXTPROC) (GLuint index, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVEXTPROC) (GLuint index, GLenum pname, GLuint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribI1iEXT (GLuint index, GLint x);\nGLAPI void APIENTRY glVertexAttribI2iEXT (GLuint index, GLint x, GLint y);\nGLAPI void APIENTRY glVertexAttribI3iEXT (GLuint index, GLint x, GLint y, GLint z);\nGLAPI void APIENTRY glVertexAttribI4iEXT (GLuint index, GLint x, GLint y, GLint z, GLint w);\nGLAPI void APIENTRY glVertexAttribI1uiEXT (GLuint index, GLuint x);\nGLAPI void APIENTRY glVertexAttribI2uiEXT (GLuint index, GLuint x, GLuint y);\nGLAPI void APIENTRY glVertexAttribI3uiEXT (GLuint index, GLuint x, GLuint y, GLuint z);\nGLAPI void APIENTRY glVertexAttribI4uiEXT (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);\nGLAPI void APIENTRY glVertexAttribI1ivEXT (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI2ivEXT (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI3ivEXT (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI4ivEXT (GLuint index, const GLint *v);\nGLAPI void APIENTRY glVertexAttribI1uivEXT (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI2uivEXT (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI3uivEXT (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI4uivEXT (GLuint index, const GLuint *v);\nGLAPI void APIENTRY glVertexAttribI4bvEXT (GLuint index, const GLbyte *v);\nGLAPI void APIENTRY glVertexAttribI4svEXT (GLuint index, const GLshort *v);\nGLAPI void APIENTRY glVertexAttribI4ubvEXT (GLuint index, const GLubyte *v);\nGLAPI void APIENTRY glVertexAttribI4usvEXT (GLuint index, const GLushort *v);\nGLAPI void APIENTRY glVertexAttribIPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer);\nGLAPI void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params);\n#endif\n#endif /* GL_NV_vertex_program4 */\n\n#ifndef GL_NV_video_capture\n#define GL_NV_video_capture 1\n#define GL_VIDEO_BUFFER_NV                0x9020\n#define GL_VIDEO_BUFFER_BINDING_NV        0x9021\n#define GL_FIELD_UPPER_NV                 0x9022\n#define GL_FIELD_LOWER_NV                 0x9023\n#define GL_NUM_VIDEO_CAPTURE_STREAMS_NV   0x9024\n#define GL_NEXT_VIDEO_CAPTURE_BUFFER_STATUS_NV 0x9025\n#define GL_VIDEO_CAPTURE_TO_422_SUPPORTED_NV 0x9026\n#define GL_LAST_VIDEO_CAPTURE_STATUS_NV   0x9027\n#define GL_VIDEO_BUFFER_PITCH_NV          0x9028\n#define GL_VIDEO_COLOR_CONVERSION_MATRIX_NV 0x9029\n#define GL_VIDEO_COLOR_CONVERSION_MAX_NV  0x902A\n#define GL_VIDEO_COLOR_CONVERSION_MIN_NV  0x902B\n#define GL_VIDEO_COLOR_CONVERSION_OFFSET_NV 0x902C\n#define GL_VIDEO_BUFFER_INTERNAL_FORMAT_NV 0x902D\n#define GL_PARTIAL_SUCCESS_NV             0x902E\n#define GL_SUCCESS_NV                     0x902F\n#define GL_FAILURE_NV                     0x9030\n#define GL_YCBYCR8_422_NV                 0x9031\n#define GL_YCBAYCR8A_4224_NV              0x9032\n#define GL_Z6Y10Z6CB10Z6Y10Z6CR10_422_NV  0x9033\n#define GL_Z6Y10Z6CB10Z6A10Z6Y10Z6CR10Z6A10_4224_NV 0x9034\n#define GL_Z4Y12Z4CB12Z4Y12Z4CR12_422_NV  0x9035\n#define GL_Z4Y12Z4CB12Z4A12Z4Y12Z4CR12Z4A12_4224_NV 0x9036\n#define GL_Z4Y12Z4CB12Z4CR12_444_NV       0x9037\n#define GL_VIDEO_CAPTURE_FRAME_WIDTH_NV   0x9038\n#define GL_VIDEO_CAPTURE_FRAME_HEIGHT_NV  0x9039\n#define GL_VIDEO_CAPTURE_FIELD_UPPER_HEIGHT_NV 0x903A\n#define GL_VIDEO_CAPTURE_FIELD_LOWER_HEIGHT_NV 0x903B\n#define GL_VIDEO_CAPTURE_SURFACE_ORIGIN_NV 0x903C\ntypedef void (APIENTRYP PFNGLBEGINVIDEOCAPTURENVPROC) (GLuint video_capture_slot);\ntypedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMBUFFERNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset);\ntypedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMTEXTURENVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture);\ntypedef void (APIENTRYP PFNGLENDVIDEOCAPTURENVPROC) (GLuint video_capture_slot);\ntypedef void (APIENTRYP PFNGLGETVIDEOCAPTUREIVNVPROC) (GLuint video_capture_slot, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params);\ntypedef GLenum (APIENTRYP PFNGLVIDEOCAPTURENVPROC) (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time);\ntypedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginVideoCaptureNV (GLuint video_capture_slot);\nGLAPI void APIENTRY glBindVideoCaptureStreamBufferNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset);\nGLAPI void APIENTRY glBindVideoCaptureStreamTextureNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture);\nGLAPI void APIENTRY glEndVideoCaptureNV (GLuint video_capture_slot);\nGLAPI void APIENTRY glGetVideoCaptureivNV (GLuint video_capture_slot, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVideoCaptureStreamivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetVideoCaptureStreamfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetVideoCaptureStreamdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params);\nGLAPI GLenum APIENTRY glVideoCaptureNV (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time);\nGLAPI void APIENTRY glVideoCaptureStreamParameterivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glVideoCaptureStreamParameterfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glVideoCaptureStreamParameterdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params);\n#endif\n#endif /* GL_NV_video_capture */\n\n#ifndef GL_OML_interlace\n#define GL_OML_interlace 1\n#define GL_INTERLACE_OML                  0x8980\n#define GL_INTERLACE_READ_OML             0x8981\n#endif /* GL_OML_interlace */\n\n#ifndef GL_OML_resample\n#define GL_OML_resample 1\n#define GL_PACK_RESAMPLE_OML              0x8984\n#define GL_UNPACK_RESAMPLE_OML            0x8985\n#define GL_RESAMPLE_REPLICATE_OML         0x8986\n#define GL_RESAMPLE_ZERO_FILL_OML         0x8987\n#define GL_RESAMPLE_AVERAGE_OML           0x8988\n#define GL_RESAMPLE_DECIMATE_OML          0x8989\n#endif /* GL_OML_resample */\n\n#ifndef GL_OML_subsample\n#define GL_OML_subsample 1\n#define GL_FORMAT_SUBSAMPLE_24_24_OML     0x8982\n#define GL_FORMAT_SUBSAMPLE_244_244_OML   0x8983\n#endif /* GL_OML_subsample */\n\n#ifndef GL_PGI_misc_hints\n#define GL_PGI_misc_hints 1\n#define GL_PREFER_DOUBLEBUFFER_HINT_PGI   0x1A1F8\n#define GL_CONSERVE_MEMORY_HINT_PGI       0x1A1FD\n#define GL_RECLAIM_MEMORY_HINT_PGI        0x1A1FE\n#define GL_NATIVE_GRAPHICS_HANDLE_PGI     0x1A202\n#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203\n#define GL_NATIVE_GRAPHICS_END_HINT_PGI   0x1A204\n#define GL_ALWAYS_FAST_HINT_PGI           0x1A20C\n#define GL_ALWAYS_SOFT_HINT_PGI           0x1A20D\n#define GL_ALLOW_DRAW_OBJ_HINT_PGI        0x1A20E\n#define GL_ALLOW_DRAW_WIN_HINT_PGI        0x1A20F\n#define GL_ALLOW_DRAW_FRG_HINT_PGI        0x1A210\n#define GL_ALLOW_DRAW_MEM_HINT_PGI        0x1A211\n#define GL_STRICT_DEPTHFUNC_HINT_PGI      0x1A216\n#define GL_STRICT_LIGHTING_HINT_PGI       0x1A217\n#define GL_STRICT_SCISSOR_HINT_PGI        0x1A218\n#define GL_FULL_STIPPLE_HINT_PGI          0x1A219\n#define GL_CLIP_NEAR_HINT_PGI             0x1A220\n#define GL_CLIP_FAR_HINT_PGI              0x1A221\n#define GL_WIDE_LINE_HINT_PGI             0x1A222\n#define GL_BACK_NORMALS_HINT_PGI          0x1A223\ntypedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glHintPGI (GLenum target, GLint mode);\n#endif\n#endif /* GL_PGI_misc_hints */\n\n#ifndef GL_PGI_vertex_hints\n#define GL_PGI_vertex_hints 1\n#define GL_VERTEX_DATA_HINT_PGI           0x1A22A\n#define GL_VERTEX_CONSISTENT_HINT_PGI     0x1A22B\n#define GL_MATERIAL_SIDE_HINT_PGI         0x1A22C\n#define GL_MAX_VERTEX_HINT_PGI            0x1A22D\n#define GL_COLOR3_BIT_PGI                 0x00010000\n#define GL_COLOR4_BIT_PGI                 0x00020000\n#define GL_EDGEFLAG_BIT_PGI               0x00040000\n#define GL_INDEX_BIT_PGI                  0x00080000\n#define GL_MAT_AMBIENT_BIT_PGI            0x00100000\n#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000\n#define GL_MAT_DIFFUSE_BIT_PGI            0x00400000\n#define GL_MAT_EMISSION_BIT_PGI           0x00800000\n#define GL_MAT_COLOR_INDEXES_BIT_PGI      0x01000000\n#define GL_MAT_SHININESS_BIT_PGI          0x02000000\n#define GL_MAT_SPECULAR_BIT_PGI           0x04000000\n#define GL_NORMAL_BIT_PGI                 0x08000000\n#define GL_TEXCOORD1_BIT_PGI              0x10000000\n#define GL_TEXCOORD2_BIT_PGI              0x20000000\n#define GL_TEXCOORD3_BIT_PGI              0x40000000\n#define GL_TEXCOORD4_BIT_PGI              0x80000000\n#define GL_VERTEX23_BIT_PGI               0x00000004\n#define GL_VERTEX4_BIT_PGI                0x00000008\n#endif /* GL_PGI_vertex_hints */\n\n#ifndef GL_REND_screen_coordinates\n#define GL_REND_screen_coordinates 1\n#define GL_SCREEN_COORDINATES_REND        0x8490\n#define GL_INVERTED_SCREEN_W_REND         0x8491\n#endif /* GL_REND_screen_coordinates */\n\n#ifndef GL_S3_s3tc\n#define GL_S3_s3tc 1\n#define GL_RGB_S3TC                       0x83A0\n#define GL_RGB4_S3TC                      0x83A1\n#define GL_RGBA_S3TC                      0x83A2\n#define GL_RGBA4_S3TC                     0x83A3\n#define GL_RGBA_DXT5_S3TC                 0x83A4\n#define GL_RGBA4_DXT5_S3TC                0x83A5\n#endif /* GL_S3_s3tc */\n\n#ifndef GL_SGIS_detail_texture\n#define GL_SGIS_detail_texture 1\n#define GL_DETAIL_TEXTURE_2D_SGIS         0x8095\n#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096\n#define GL_LINEAR_DETAIL_SGIS             0x8097\n#define GL_LINEAR_DETAIL_ALPHA_SGIS       0x8098\n#define GL_LINEAR_DETAIL_COLOR_SGIS       0x8099\n#define GL_DETAIL_TEXTURE_LEVEL_SGIS      0x809A\n#define GL_DETAIL_TEXTURE_MODE_SGIS       0x809B\n#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C\ntypedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points);\nGLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum target, GLfloat *points);\n#endif\n#endif /* GL_SGIS_detail_texture */\n\n#ifndef GL_SGIS_fog_function\n#define GL_SGIS_fog_function 1\n#define GL_FOG_FUNC_SGIS                  0x812A\n#define GL_FOG_FUNC_POINTS_SGIS           0x812B\n#define GL_MAX_FOG_FUNC_POINTS_SGIS       0x812C\ntypedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFogFuncSGIS (GLsizei n, const GLfloat *points);\nGLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *points);\n#endif\n#endif /* GL_SGIS_fog_function */\n\n#ifndef GL_SGIS_generate_mipmap\n#define GL_SGIS_generate_mipmap 1\n#define GL_GENERATE_MIPMAP_SGIS           0x8191\n#define GL_GENERATE_MIPMAP_HINT_SGIS      0x8192\n#endif /* GL_SGIS_generate_mipmap */\n\n#ifndef GL_SGIS_multisample\n#define GL_SGIS_multisample 1\n#define GL_MULTISAMPLE_SGIS               0x809D\n#define GL_SAMPLE_ALPHA_TO_MASK_SGIS      0x809E\n#define GL_SAMPLE_ALPHA_TO_ONE_SGIS       0x809F\n#define GL_SAMPLE_MASK_SGIS               0x80A0\n#define GL_1PASS_SGIS                     0x80A1\n#define GL_2PASS_0_SGIS                   0x80A2\n#define GL_2PASS_1_SGIS                   0x80A3\n#define GL_4PASS_0_SGIS                   0x80A4\n#define GL_4PASS_1_SGIS                   0x80A5\n#define GL_4PASS_2_SGIS                   0x80A6\n#define GL_4PASS_3_SGIS                   0x80A7\n#define GL_SAMPLE_BUFFERS_SGIS            0x80A8\n#define GL_SAMPLES_SGIS                   0x80A9\n#define GL_SAMPLE_MASK_VALUE_SGIS         0x80AA\n#define GL_SAMPLE_MASK_INVERT_SGIS        0x80AB\n#define GL_SAMPLE_PATTERN_SGIS            0x80AC\ntypedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSampleMaskSGIS (GLclampf value, GLboolean invert);\nGLAPI void APIENTRY glSamplePatternSGIS (GLenum pattern);\n#endif\n#endif /* GL_SGIS_multisample */\n\n#ifndef GL_SGIS_pixel_texture\n#define GL_SGIS_pixel_texture 1\n#define GL_PIXEL_TEXTURE_SGIS             0x8353\n#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354\n#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355\n#define GL_PIXEL_GROUP_COLOR_SGIS         0x8356\ntypedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum pname, GLint param);\nGLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum pname, const GLint *params);\nGLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum pname, GLfloat *params);\n#endif\n#endif /* GL_SGIS_pixel_texture */\n\n#ifndef GL_SGIS_point_line_texgen\n#define GL_SGIS_point_line_texgen 1\n#define GL_EYE_DISTANCE_TO_POINT_SGIS     0x81F0\n#define GL_OBJECT_DISTANCE_TO_POINT_SGIS  0x81F1\n#define GL_EYE_DISTANCE_TO_LINE_SGIS      0x81F2\n#define GL_OBJECT_DISTANCE_TO_LINE_SGIS   0x81F3\n#define GL_EYE_POINT_SGIS                 0x81F4\n#define GL_OBJECT_POINT_SGIS              0x81F5\n#define GL_EYE_LINE_SGIS                  0x81F6\n#define GL_OBJECT_LINE_SGIS               0x81F7\n#endif /* GL_SGIS_point_line_texgen */\n\n#ifndef GL_SGIS_point_parameters\n#define GL_SGIS_point_parameters 1\n#define GL_POINT_SIZE_MIN_SGIS            0x8126\n#define GL_POINT_SIZE_MAX_SGIS            0x8127\n#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128\n#define GL_DISTANCE_ATTENUATION_SGIS      0x8129\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameterfSGIS (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glPointParameterfvSGIS (GLenum pname, const GLfloat *params);\n#endif\n#endif /* GL_SGIS_point_parameters */\n\n#ifndef GL_SGIS_sharpen_texture\n#define GL_SGIS_sharpen_texture 1\n#define GL_LINEAR_SHARPEN_SGIS            0x80AD\n#define GL_LINEAR_SHARPEN_ALPHA_SGIS      0x80AE\n#define GL_LINEAR_SHARPEN_COLOR_SGIS      0x80AF\n#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0\ntypedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points);\nGLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum target, GLfloat *points);\n#endif\n#endif /* GL_SGIS_sharpen_texture */\n\n#ifndef GL_SGIS_texture4D\n#define GL_SGIS_texture4D 1\n#define GL_PACK_SKIP_VOLUMES_SGIS         0x8130\n#define GL_PACK_IMAGE_DEPTH_SGIS          0x8131\n#define GL_UNPACK_SKIP_VOLUMES_SGIS       0x8132\n#define GL_UNPACK_IMAGE_DEPTH_SGIS        0x8133\n#define GL_TEXTURE_4D_SGIS                0x8134\n#define GL_PROXY_TEXTURE_4D_SGIS          0x8135\n#define GL_TEXTURE_4DSIZE_SGIS            0x8136\n#define GL_TEXTURE_WRAP_Q_SGIS            0x8137\n#define GL_MAX_4D_TEXTURE_SIZE_SGIS       0x8138\n#define GL_TEXTURE_4D_BINDING_SGIS        0x814F\ntypedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels);\ntypedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexImage4DSGIS (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels);\nGLAPI void APIENTRY glTexSubImage4DSGIS (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels);\n#endif\n#endif /* GL_SGIS_texture4D */\n\n#ifndef GL_SGIS_texture_border_clamp\n#define GL_SGIS_texture_border_clamp 1\n#define GL_CLAMP_TO_BORDER_SGIS           0x812D\n#endif /* GL_SGIS_texture_border_clamp */\n\n#ifndef GL_SGIS_texture_color_mask\n#define GL_SGIS_texture_color_mask 1\n#define GL_TEXTURE_COLOR_WRITEMASK_SGIS   0x81EF\ntypedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);\n#endif\n#endif /* GL_SGIS_texture_color_mask */\n\n#ifndef GL_SGIS_texture_edge_clamp\n#define GL_SGIS_texture_edge_clamp 1\n#define GL_CLAMP_TO_EDGE_SGIS             0x812F\n#endif /* GL_SGIS_texture_edge_clamp */\n\n#ifndef GL_SGIS_texture_filter4\n#define GL_SGIS_texture_filter4 1\n#define GL_FILTER4_SGIS                   0x8146\n#define GL_TEXTURE_FILTER4_SIZE_SGIS      0x8147\ntypedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);\ntypedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights);\nGLAPI void APIENTRY glTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);\n#endif\n#endif /* GL_SGIS_texture_filter4 */\n\n#ifndef GL_SGIS_texture_lod\n#define GL_SGIS_texture_lod 1\n#define GL_TEXTURE_MIN_LOD_SGIS           0x813A\n#define GL_TEXTURE_MAX_LOD_SGIS           0x813B\n#define GL_TEXTURE_BASE_LEVEL_SGIS        0x813C\n#define GL_TEXTURE_MAX_LEVEL_SGIS         0x813D\n#endif /* GL_SGIS_texture_lod */\n\n#ifndef GL_SGIS_texture_select\n#define GL_SGIS_texture_select 1\n#define GL_DUAL_ALPHA4_SGIS               0x8110\n#define GL_DUAL_ALPHA8_SGIS               0x8111\n#define GL_DUAL_ALPHA12_SGIS              0x8112\n#define GL_DUAL_ALPHA16_SGIS              0x8113\n#define GL_DUAL_LUMINANCE4_SGIS           0x8114\n#define GL_DUAL_LUMINANCE8_SGIS           0x8115\n#define GL_DUAL_LUMINANCE12_SGIS          0x8116\n#define GL_DUAL_LUMINANCE16_SGIS          0x8117\n#define GL_DUAL_INTENSITY4_SGIS           0x8118\n#define GL_DUAL_INTENSITY8_SGIS           0x8119\n#define GL_DUAL_INTENSITY12_SGIS          0x811A\n#define GL_DUAL_INTENSITY16_SGIS          0x811B\n#define GL_DUAL_LUMINANCE_ALPHA4_SGIS     0x811C\n#define GL_DUAL_LUMINANCE_ALPHA8_SGIS     0x811D\n#define GL_QUAD_ALPHA4_SGIS               0x811E\n#define GL_QUAD_ALPHA8_SGIS               0x811F\n#define GL_QUAD_LUMINANCE4_SGIS           0x8120\n#define GL_QUAD_LUMINANCE8_SGIS           0x8121\n#define GL_QUAD_INTENSITY4_SGIS           0x8122\n#define GL_QUAD_INTENSITY8_SGIS           0x8123\n#define GL_DUAL_TEXTURE_SELECT_SGIS       0x8124\n#define GL_QUAD_TEXTURE_SELECT_SGIS       0x8125\n#endif /* GL_SGIS_texture_select */\n\n#ifndef GL_SGIX_async\n#define GL_SGIX_async 1\n#define GL_ASYNC_MARKER_SGIX              0x8329\ntypedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker);\ntypedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp);\ntypedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp);\ntypedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range);\ntypedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range);\ntypedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glAsyncMarkerSGIX (GLuint marker);\nGLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *markerp);\nGLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *markerp);\nGLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei range);\nGLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint marker, GLsizei range);\nGLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint marker);\n#endif\n#endif /* GL_SGIX_async */\n\n#ifndef GL_SGIX_async_histogram\n#define GL_SGIX_async_histogram 1\n#define GL_ASYNC_HISTOGRAM_SGIX           0x832C\n#define GL_MAX_ASYNC_HISTOGRAM_SGIX       0x832D\n#endif /* GL_SGIX_async_histogram */\n\n#ifndef GL_SGIX_async_pixel\n#define GL_SGIX_async_pixel 1\n#define GL_ASYNC_TEX_IMAGE_SGIX           0x835C\n#define GL_ASYNC_DRAW_PIXELS_SGIX         0x835D\n#define GL_ASYNC_READ_PIXELS_SGIX         0x835E\n#define GL_MAX_ASYNC_TEX_IMAGE_SGIX       0x835F\n#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX     0x8360\n#define GL_MAX_ASYNC_READ_PIXELS_SGIX     0x8361\n#endif /* GL_SGIX_async_pixel */\n\n#ifndef GL_SGIX_blend_alpha_minmax\n#define GL_SGIX_blend_alpha_minmax 1\n#define GL_ALPHA_MIN_SGIX                 0x8320\n#define GL_ALPHA_MAX_SGIX                 0x8321\n#endif /* GL_SGIX_blend_alpha_minmax */\n\n#ifndef GL_SGIX_calligraphic_fragment\n#define GL_SGIX_calligraphic_fragment 1\n#define GL_CALLIGRAPHIC_FRAGMENT_SGIX     0x8183\n#endif /* GL_SGIX_calligraphic_fragment */\n\n#ifndef GL_SGIX_clipmap\n#define GL_SGIX_clipmap 1\n#define GL_LINEAR_CLIPMAP_LINEAR_SGIX     0x8170\n#define GL_TEXTURE_CLIPMAP_CENTER_SGIX    0x8171\n#define GL_TEXTURE_CLIPMAP_FRAME_SGIX     0x8172\n#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX    0x8173\n#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174\n#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175\n#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX     0x8176\n#define GL_MAX_CLIPMAP_DEPTH_SGIX         0x8177\n#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178\n#define GL_NEAREST_CLIPMAP_NEAREST_SGIX   0x844D\n#define GL_NEAREST_CLIPMAP_LINEAR_SGIX    0x844E\n#define GL_LINEAR_CLIPMAP_NEAREST_SGIX    0x844F\n#endif /* GL_SGIX_clipmap */\n\n#ifndef GL_SGIX_convolution_accuracy\n#define GL_SGIX_convolution_accuracy 1\n#define GL_CONVOLUTION_HINT_SGIX          0x8316\n#endif /* GL_SGIX_convolution_accuracy */\n\n#ifndef GL_SGIX_depth_pass_instrument\n#define GL_SGIX_depth_pass_instrument 1\n#endif /* GL_SGIX_depth_pass_instrument */\n\n#ifndef GL_SGIX_depth_texture\n#define GL_SGIX_depth_texture 1\n#define GL_DEPTH_COMPONENT16_SGIX         0x81A5\n#define GL_DEPTH_COMPONENT24_SGIX         0x81A6\n#define GL_DEPTH_COMPONENT32_SGIX         0x81A7\n#endif /* GL_SGIX_depth_texture */\n\n#ifndef GL_SGIX_flush_raster\n#define GL_SGIX_flush_raster 1\ntypedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFlushRasterSGIX (void);\n#endif\n#endif /* GL_SGIX_flush_raster */\n\n#ifndef GL_SGIX_fog_offset\n#define GL_SGIX_fog_offset 1\n#define GL_FOG_OFFSET_SGIX                0x8198\n#define GL_FOG_OFFSET_VALUE_SGIX          0x8199\n#endif /* GL_SGIX_fog_offset */\n\n#ifndef GL_SGIX_fragment_lighting\n#define GL_SGIX_fragment_lighting 1\n#define GL_FRAGMENT_LIGHTING_SGIX         0x8400\n#define GL_FRAGMENT_COLOR_MATERIAL_SGIX   0x8401\n#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402\n#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403\n#define GL_MAX_FRAGMENT_LIGHTS_SGIX       0x8404\n#define GL_MAX_ACTIVE_LIGHTS_SGIX         0x8405\n#define GL_CURRENT_RASTER_NORMAL_SGIX     0x8406\n#define GL_LIGHT_ENV_MODE_SGIX            0x8407\n#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408\n#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409\n#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A\n#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B\n#define GL_FRAGMENT_LIGHT0_SGIX           0x840C\n#define GL_FRAGMENT_LIGHT1_SGIX           0x840D\n#define GL_FRAGMENT_LIGHT2_SGIX           0x840E\n#define GL_FRAGMENT_LIGHT3_SGIX           0x840F\n#define GL_FRAGMENT_LIGHT4_SGIX           0x8410\n#define GL_FRAGMENT_LIGHT5_SGIX           0x8411\n#define GL_FRAGMENT_LIGHT6_SGIX           0x8412\n#define GL_FRAGMENT_LIGHT7_SGIX           0x8413\ntypedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum face, GLenum mode);\nGLAPI void APIENTRY glFragmentLightfSGIX (GLenum light, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glFragmentLightfvSGIX (GLenum light, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glFragmentLightiSGIX (GLenum light, GLenum pname, GLint param);\nGLAPI void APIENTRY glFragmentLightivSGIX (GLenum light, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum pname, GLint param);\nGLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum pname, const GLint *params);\nGLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum face, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum face, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum face, GLenum pname, GLint param);\nGLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum face, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum light, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum light, GLenum pname, GLint *params);\nGLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum face, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum face, GLenum pname, GLint *params);\nGLAPI void APIENTRY glLightEnviSGIX (GLenum pname, GLint param);\n#endif\n#endif /* GL_SGIX_fragment_lighting */\n\n#ifndef GL_SGIX_framezoom\n#define GL_SGIX_framezoom 1\n#define GL_FRAMEZOOM_SGIX                 0x818B\n#define GL_FRAMEZOOM_FACTOR_SGIX          0x818C\n#define GL_MAX_FRAMEZOOM_FACTOR_SGIX      0x818D\ntypedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFrameZoomSGIX (GLint factor);\n#endif\n#endif /* GL_SGIX_framezoom */\n\n#ifndef GL_SGIX_igloo_interface\n#define GL_SGIX_igloo_interface 1\ntypedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const void *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glIglooInterfaceSGIX (GLenum pname, const void *params);\n#endif\n#endif /* GL_SGIX_igloo_interface */\n\n#ifndef GL_SGIX_instruments\n#define GL_SGIX_instruments 1\n#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180\n#define GL_INSTRUMENT_MEASUREMENTS_SGIX   0x8181\ntypedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void);\ntypedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer);\ntypedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p);\ntypedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker);\ntypedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void);\ntypedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLint APIENTRY glGetInstrumentsSGIX (void);\nGLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei size, GLint *buffer);\nGLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *marker_p);\nGLAPI void APIENTRY glReadInstrumentsSGIX (GLint marker);\nGLAPI void APIENTRY glStartInstrumentsSGIX (void);\nGLAPI void APIENTRY glStopInstrumentsSGIX (GLint marker);\n#endif\n#endif /* GL_SGIX_instruments */\n\n#ifndef GL_SGIX_interlace\n#define GL_SGIX_interlace 1\n#define GL_INTERLACE_SGIX                 0x8094\n#endif /* GL_SGIX_interlace */\n\n#ifndef GL_SGIX_ir_instrument1\n#define GL_SGIX_ir_instrument1 1\n#define GL_IR_INSTRUMENT1_SGIX            0x817F\n#endif /* GL_SGIX_ir_instrument1 */\n\n#ifndef GL_SGIX_list_priority\n#define GL_SGIX_list_priority 1\n#define GL_LIST_PRIORITY_SGIX             0x8182\ntypedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetListParameterfvSGIX (GLuint list, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetListParameterivSGIX (GLuint list, GLenum pname, GLint *params);\nGLAPI void APIENTRY glListParameterfSGIX (GLuint list, GLenum pname, GLfloat param);\nGLAPI void APIENTRY glListParameterfvSGIX (GLuint list, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glListParameteriSGIX (GLuint list, GLenum pname, GLint param);\nGLAPI void APIENTRY glListParameterivSGIX (GLuint list, GLenum pname, const GLint *params);\n#endif\n#endif /* GL_SGIX_list_priority */\n\n#ifndef GL_SGIX_pixel_texture\n#define GL_SGIX_pixel_texture 1\n#define GL_PIXEL_TEX_GEN_SGIX             0x8139\n#define GL_PIXEL_TEX_GEN_MODE_SGIX        0x832B\ntypedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelTexGenSGIX (GLenum mode);\n#endif\n#endif /* GL_SGIX_pixel_texture */\n\n#ifndef GL_SGIX_pixel_tiles\n#define GL_SGIX_pixel_tiles 1\n#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E\n#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F\n#define GL_PIXEL_TILE_WIDTH_SGIX          0x8140\n#define GL_PIXEL_TILE_HEIGHT_SGIX         0x8141\n#define GL_PIXEL_TILE_GRID_WIDTH_SGIX     0x8142\n#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX    0x8143\n#define GL_PIXEL_TILE_GRID_DEPTH_SGIX     0x8144\n#define GL_PIXEL_TILE_CACHE_SIZE_SGIX     0x8145\n#endif /* GL_SGIX_pixel_tiles */\n\n#ifndef GL_SGIX_polynomial_ffd\n#define GL_SGIX_polynomial_ffd 1\n#define GL_TEXTURE_DEFORMATION_BIT_SGIX   0x00000001\n#define GL_GEOMETRY_DEFORMATION_BIT_SGIX  0x00000002\n#define GL_GEOMETRY_DEFORMATION_SGIX      0x8194\n#define GL_TEXTURE_DEFORMATION_SGIX       0x8195\n#define GL_DEFORMATIONS_MASK_SGIX         0x8196\n#define GL_MAX_DEFORMATION_ORDER_SGIX     0x8197\ntypedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);\ntypedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask);\ntypedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDeformationMap3dSGIX (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);\nGLAPI void APIENTRY glDeformationMap3fSGIX (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);\nGLAPI void APIENTRY glDeformSGIX (GLbitfield mask);\nGLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield mask);\n#endif\n#endif /* GL_SGIX_polynomial_ffd */\n\n#ifndef GL_SGIX_reference_plane\n#define GL_SGIX_reference_plane 1\n#define GL_REFERENCE_PLANE_SGIX           0x817D\n#define GL_REFERENCE_PLANE_EQUATION_SGIX  0x817E\ntypedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *equation);\n#endif\n#endif /* GL_SGIX_reference_plane */\n\n#ifndef GL_SGIX_resample\n#define GL_SGIX_resample 1\n#define GL_PACK_RESAMPLE_SGIX             0x842C\n#define GL_UNPACK_RESAMPLE_SGIX           0x842D\n#define GL_RESAMPLE_REPLICATE_SGIX        0x842E\n#define GL_RESAMPLE_ZERO_FILL_SGIX        0x842F\n#define GL_RESAMPLE_DECIMATE_SGIX         0x8430\n#endif /* GL_SGIX_resample */\n\n#ifndef GL_SGIX_scalebias_hint\n#define GL_SGIX_scalebias_hint 1\n#define GL_SCALEBIAS_HINT_SGIX            0x8322\n#endif /* GL_SGIX_scalebias_hint */\n\n#ifndef GL_SGIX_shadow\n#define GL_SGIX_shadow 1\n#define GL_TEXTURE_COMPARE_SGIX           0x819A\n#define GL_TEXTURE_COMPARE_OPERATOR_SGIX  0x819B\n#define GL_TEXTURE_LEQUAL_R_SGIX          0x819C\n#define GL_TEXTURE_GEQUAL_R_SGIX          0x819D\n#endif /* GL_SGIX_shadow */\n\n#ifndef GL_SGIX_shadow_ambient\n#define GL_SGIX_shadow_ambient 1\n#define GL_SHADOW_AMBIENT_SGIX            0x80BF\n#endif /* GL_SGIX_shadow_ambient */\n\n#ifndef GL_SGIX_sprite\n#define GL_SGIX_sprite 1\n#define GL_SPRITE_SGIX                    0x8148\n#define GL_SPRITE_MODE_SGIX               0x8149\n#define GL_SPRITE_AXIS_SGIX               0x814A\n#define GL_SPRITE_TRANSLATION_SGIX        0x814B\n#define GL_SPRITE_AXIAL_SGIX              0x814C\n#define GL_SPRITE_OBJECT_ALIGNED_SGIX     0x814D\n#define GL_SPRITE_EYE_ALIGNED_SGIX        0x814E\ntypedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSpriteParameterfSGIX (GLenum pname, GLfloat param);\nGLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glSpriteParameteriSGIX (GLenum pname, GLint param);\nGLAPI void APIENTRY glSpriteParameterivSGIX (GLenum pname, const GLint *params);\n#endif\n#endif /* GL_SGIX_sprite */\n\n#ifndef GL_SGIX_subsample\n#define GL_SGIX_subsample 1\n#define GL_PACK_SUBSAMPLE_RATE_SGIX       0x85A0\n#define GL_UNPACK_SUBSAMPLE_RATE_SGIX     0x85A1\n#define GL_PIXEL_SUBSAMPLE_4444_SGIX      0x85A2\n#define GL_PIXEL_SUBSAMPLE_2424_SGIX      0x85A3\n#define GL_PIXEL_SUBSAMPLE_4242_SGIX      0x85A4\n#endif /* GL_SGIX_subsample */\n\n#ifndef GL_SGIX_tag_sample_buffer\n#define GL_SGIX_tag_sample_buffer 1\ntypedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTagSampleBufferSGIX (void);\n#endif\n#endif /* GL_SGIX_tag_sample_buffer */\n\n#ifndef GL_SGIX_texture_add_env\n#define GL_SGIX_texture_add_env 1\n#define GL_TEXTURE_ENV_BIAS_SGIX          0x80BE\n#endif /* GL_SGIX_texture_add_env */\n\n#ifndef GL_SGIX_texture_coordinate_clamp\n#define GL_SGIX_texture_coordinate_clamp 1\n#define GL_TEXTURE_MAX_CLAMP_S_SGIX       0x8369\n#define GL_TEXTURE_MAX_CLAMP_T_SGIX       0x836A\n#define GL_TEXTURE_MAX_CLAMP_R_SGIX       0x836B\n#endif /* GL_SGIX_texture_coordinate_clamp */\n\n#ifndef GL_SGIX_texture_lod_bias\n#define GL_SGIX_texture_lod_bias 1\n#define GL_TEXTURE_LOD_BIAS_S_SGIX        0x818E\n#define GL_TEXTURE_LOD_BIAS_T_SGIX        0x818F\n#define GL_TEXTURE_LOD_BIAS_R_SGIX        0x8190\n#endif /* GL_SGIX_texture_lod_bias */\n\n#ifndef GL_SGIX_texture_multi_buffer\n#define GL_SGIX_texture_multi_buffer 1\n#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E\n#endif /* GL_SGIX_texture_multi_buffer */\n\n#ifndef GL_SGIX_texture_scale_bias\n#define GL_SGIX_texture_scale_bias 1\n#define GL_POST_TEXTURE_FILTER_BIAS_SGIX  0x8179\n#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A\n#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B\n#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C\n#endif /* GL_SGIX_texture_scale_bias */\n\n#ifndef GL_SGIX_vertex_preclip\n#define GL_SGIX_vertex_preclip 1\n#define GL_VERTEX_PRECLIP_SGIX            0x83EE\n#define GL_VERTEX_PRECLIP_HINT_SGIX       0x83EF\n#endif /* GL_SGIX_vertex_preclip */\n\n#ifndef GL_SGIX_ycrcb\n#define GL_SGIX_ycrcb 1\n#define GL_YCRCB_422_SGIX                 0x81BB\n#define GL_YCRCB_444_SGIX                 0x81BC\n#endif /* GL_SGIX_ycrcb */\n\n#ifndef GL_SGIX_ycrcb_subsample\n#define GL_SGIX_ycrcb_subsample 1\n#endif /* GL_SGIX_ycrcb_subsample */\n\n#ifndef GL_SGIX_ycrcba\n#define GL_SGIX_ycrcba 1\n#define GL_YCRCB_SGIX                     0x8318\n#define GL_YCRCBA_SGIX                    0x8319\n#endif /* GL_SGIX_ycrcba */\n\n#ifndef GL_SGI_color_matrix\n#define GL_SGI_color_matrix 1\n#define GL_COLOR_MATRIX_SGI               0x80B1\n#define GL_COLOR_MATRIX_STACK_DEPTH_SGI   0x80B2\n#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3\n#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4\n#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5\n#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6\n#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7\n#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8\n#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9\n#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA\n#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB\n#endif /* GL_SGI_color_matrix */\n\n#ifndef GL_SGI_color_table\n#define GL_SGI_color_table 1\n#define GL_COLOR_TABLE_SGI                0x80D0\n#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1\n#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2\n#define GL_PROXY_COLOR_TABLE_SGI          0x80D3\n#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4\n#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5\n#define GL_COLOR_TABLE_SCALE_SGI          0x80D6\n#define GL_COLOR_TABLE_BIAS_SGI           0x80D7\n#define GL_COLOR_TABLE_FORMAT_SGI         0x80D8\n#define GL_COLOR_TABLE_WIDTH_SGI          0x80D9\n#define GL_COLOR_TABLE_RED_SIZE_SGI       0x80DA\n#define GL_COLOR_TABLE_GREEN_SIZE_SGI     0x80DB\n#define GL_COLOR_TABLE_BLUE_SIZE_SGI      0x80DC\n#define GL_COLOR_TABLE_ALPHA_SIZE_SGI     0x80DD\n#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE\n#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF\ntypedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table);\ntypedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params);\ntypedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, void *table);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table);\nGLAPI void APIENTRY glColorTableParameterfvSGI (GLenum target, GLenum pname, const GLfloat *params);\nGLAPI void APIENTRY glColorTableParameterivSGI (GLenum target, GLenum pname, const GLint *params);\nGLAPI void APIENTRY glCopyColorTableSGI (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);\nGLAPI void APIENTRY glGetColorTableSGI (GLenum target, GLenum format, GLenum type, void *table);\nGLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params);\nGLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params);\n#endif\n#endif /* GL_SGI_color_table */\n\n#ifndef GL_SGI_texture_color_table\n#define GL_SGI_texture_color_table 1\n#define GL_TEXTURE_COLOR_TABLE_SGI        0x80BC\n#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI  0x80BD\n#endif /* GL_SGI_texture_color_table */\n\n#ifndef GL_SUNX_constant_data\n#define GL_SUNX_constant_data 1\n#define GL_UNPACK_CONSTANT_DATA_SUNX      0x81D5\n#define GL_TEXTURE_CONSTANT_DATA_SUNX     0x81D6\ntypedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFinishTextureSUNX (void);\n#endif\n#endif /* GL_SUNX_constant_data */\n\n#ifndef GL_SUN_convolution_border_modes\n#define GL_SUN_convolution_border_modes 1\n#define GL_WRAP_BORDER_SUN                0x81D4\n#endif /* GL_SUN_convolution_border_modes */\n\n#ifndef GL_SUN_global_alpha\n#define GL_SUN_global_alpha 1\n#define GL_GLOBAL_ALPHA_SUN               0x81D9\n#define GL_GLOBAL_ALPHA_FACTOR_SUN        0x81DA\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor);\ntypedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte factor);\nGLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort factor);\nGLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint factor);\nGLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat factor);\nGLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble factor);\nGLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte factor);\nGLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort factor);\nGLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint factor);\n#endif\n#endif /* GL_SUN_global_alpha */\n\n#ifndef GL_SUN_mesh_array\n#define GL_SUN_mesh_array 1\n#define GL_QUAD_MESH_SUN                  0x8614\n#define GL_TRIANGLE_MESH_SUN              0x8615\ntypedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width);\n#endif\n#endif /* GL_SUN_mesh_array */\n\n#ifndef GL_SUN_slice_accum\n#define GL_SUN_slice_accum 1\n#define GL_SLICE_ACCUM_SUN                0x85CC\n#endif /* GL_SUN_slice_accum */\n\n#ifndef GL_SUN_triangle_list\n#define GL_SUN_triangle_list 1\n#define GL_RESTART_SUN                    0x0001\n#define GL_REPLACE_MIDDLE_SUN             0x0002\n#define GL_REPLACE_OLDEST_SUN             0x0003\n#define GL_TRIANGLE_LIST_SUN              0x81D7\n#define GL_REPLACEMENT_CODE_SUN           0x81D8\n#define GL_REPLACEMENT_CODE_ARRAY_SUN     0x85C0\n#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1\n#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2\n#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3\n#define GL_R1UI_V3F_SUN                   0x85C4\n#define GL_R1UI_C4UB_V3F_SUN              0x85C5\n#define GL_R1UI_C3F_V3F_SUN               0x85C6\n#define GL_R1UI_N3F_V3F_SUN               0x85C7\n#define GL_R1UI_C4F_N3F_V3F_SUN           0x85C8\n#define GL_R1UI_T2F_V3F_SUN               0x85C9\n#define GL_R1UI_T2F_N3F_V3F_SUN           0x85CA\n#define GL_R1UI_T2F_C4F_N3F_V3F_SUN       0x85CB\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const void **pointer);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glReplacementCodeuiSUN (GLuint code);\nGLAPI void APIENTRY glReplacementCodeusSUN (GLushort code);\nGLAPI void APIENTRY glReplacementCodeubSUN (GLubyte code);\nGLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *code);\nGLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *code);\nGLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *code);\nGLAPI void APIENTRY glReplacementCodePointerSUN (GLenum type, GLsizei stride, const void **pointer);\n#endif\n#endif /* GL_SUN_triangle_list */\n\n#ifndef GL_SUN_vertex\n#define GL_SUN_vertex 1\ntypedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);\ntypedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\ntypedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);\nGLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *c, const GLfloat *v);\nGLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *c, const GLfloat *v);\nGLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *c, const GLfloat *v);\nGLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *c, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *tc, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *tc, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *tc, const GLubyte *c, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\nGLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint rc, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *rc, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *rc, const GLubyte *c, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);\n#endif\n#endif /* GL_SUN_vertex */\n\n#ifndef GL_WIN_phong_shading\n#define GL_WIN_phong_shading 1\n#define GL_PHONG_WIN                      0x80EA\n#define GL_PHONG_HINT_WIN                 0x80EB\n#endif /* GL_WIN_phong_shading */\n\n#ifndef GL_WIN_specular_fog\n#define GL_WIN_specular_fog 1\n#define GL_FOG_SPECULAR_TEXTURE_WIN       0x80EC\n#endif /* GL_WIN_specular_fog */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "tests/caveview/glext_list.h",
    "content": "GLARB(ActiveTexture,ACTIVETEXTURE)\nGLARB(ClientActiveTexture,CLIENTACTIVETEXTURE)\nGLARB(MultiTexCoord2f,MULTITEXCOORD2F)\nGLEXT(TexImage3D,TEXIMAGE3D)\nGLEXT(TexSubImage3D,TEXSUBIMAGE3D)\nGLEXT(GenerateMipmap,GENERATEMIPMAP)\nGLARB(DebugMessageCallback,DEBUGMESSAGECALLBACK)\n\nGLCORE(VertexAttribIPointer,VERTEXATTRIBIPOINTER)\n\nGLEXT(BindFramebuffer,BINDFRAMEBUFFER)\nGLEXT(DeleteFramebuffers,DELETEFRAMEBUFFERS)\nGLEXT(GenFramebuffers,GENFRAMEBUFFERS)\nGLEXT(CheckFramebufferStatus,CHECKFRAMEBUFFERSTATUS)\nGLEXT(FramebufferTexture2D,FRAMEBUFFERTEXTURE2D)\nGLEXT(BindRenderBuffer,BINDRENDERBUFFER)\nGLEXT(RenderbufferStorage,RENDERBUFFERSTORAGE)\nGLEXT(GenRenderbuffers,GENRENDERBUFFERS)\nGLEXT(BindRenderbuffer,BINDRENDERBUFFER)\nGLEXT(FramebufferRenderbuffer,FRAMEBUFFERRENDERBUFFER)\nGLEXT(GenerateMipmap,GENERATEMIPMAP)\n\nGLARB(BindBuffer   ,BINDBUFFER,)\nGLARB(GenBuffers   ,GENBUFFERS   )\nGLARB(DeleteBuffers,DELETEBUFFERS)\nGLARB(BufferData   ,BUFFERDATA   )\nGLARB(BufferSubData,BUFFERSUBDATA)\nGLARB(MapBuffer    ,MAPBUFFER    )\nGLARB(UnmapBuffer  ,UNMAPBUFFER  )\nGLARB(TexBuffer    ,TEXBUFFER    )\n\nGLEXT(NamedBufferStorage,NAMEDBUFFERSTORAGE)\nGLE(BufferStorage,BUFFERSTORAGE)\nGLE(GetStringi,GETSTRINGI)"
  },
  {
    "path": "tests/caveview/main.c",
    "content": ""
  },
  {
    "path": "tests/caveview/stb_gl.h",
    "content": "// stbgl - v0.04 - Sean Barrett 2008 - public domain\n//\n// Note that the gl extensions support requires glext.h. In fact, it works\n// if you just concatenate glext.h onto the end of this file. In that case,\n// this file is covered by the SGI FreeB license, and is not public domain.\n//\n// Extension usage:\n//\n//    1. Make a file called something like \"extlist.txt\" which contains stuff like:\n//         GLE(ShaderSourceARB,SHADERSOURCEARB)\n//         GLE(Uniform1iARB,UNIFORM1IARB)\n//         GLARB(ActiveTexture,ACTIVETEXTURE)   // same as GLE(ActiveTextureARB,ACTIVETEXTUREARB)\n//         GLARB(ClientActiveTexture,CLIENTACTIVETEXTURE)\n//         GLE(MultiTexCoord2f,MULTITEXCOORD2F)\n//\n//    2. To declare functions (to make a header file), do this:\n//         #define STB_GLEXT_DECLARE \"extlist.txt\"\n//         #include \"stb_gl.h\"\n//\n//       A good way to do this is to define STB_GLEXT_DECLARE project-wide.\n//\n//    3. To define functions (implement), do this in some C file:\n//         #define STB_GLEXT_DEFINE \"extlist.txt\"\n//         #include \"stb_gl.h\"\n//\n//       If you've already defined STB_GLEXT_DECLARE, you can just do:\n//         #define STB_GLEXT_DEFINE_DECLARE\n//         #include \"stb_gl.h\"\n//\n//    4. Now you need to initialize:\n//\n//         stbgl_initExtensions();\n\n\n#ifndef INCLUDE_STB_GL_H\n#define INCLUDE_STB_GL_H\n\n#define STB_GL\n\n#ifdef _WIN32\n#ifndef WINGDIAPI\n#define CALLBACK    __stdcall\n#define WINGDIAPI   __declspec(dllimport)\n#define APIENTRY    __stdcall\n#endif\n#endif //_WIN32\n\n#include <stddef.h>\n\n#include <gl/gl.h>\n#include <gl/glu.h>\n\n#ifndef M_PI\n#define M_PI  3.14159265358979323846f\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// like gluPerspective, but:\n//    fov is chosen to satisfy both hfov <= max_hfov & vfov <= max_vfov;\n//            set one to 179 or 0 to ignore it\n//    zoom is applied separately, so you can do linear zoom without\n//            mucking with trig with fov; 1 -> use exact fov\n//    'aspect' is inferred from the current viewport, and ignores the\n//            possibility of non-square pixels\nextern void stbgl_Perspective(float zoom, float max_hfov, float max_vfov, float znear, float zfar);\nextern void stbgl_PerspectiveViewport(int x, int y, int w, int h, float zoom, float max_hfov, float max_vfov, float znear, float zfar);\nextern void stbgl_initCamera_zup_facing_x(void);\nextern void stbgl_initCamera_zup_facing_y(void);\nextern void stbgl_positionCameraWithEulerAngles(float *loc, float *ang);\nextern void stbgl_drawRect(float x0, float y0, float x1, float y1);\nextern void stbgl_drawRectTC(float x0, float y0, float x1, float y1, float s0, float t0, float s1, float t1);\nextern void stbgl_drawBox(float x, float y, float z, float sx, float sy, float sz, int cw);\n\nextern int stbgl_hasExtension(char *ext);\nextern void stbgl_SimpleLight(int index, float bright, float x, float y, float z);\nextern void stbgl_GlobalAmbient(float r, float g, float b);\n\nextern int stbgl_LoadTexture(char *filename, char *props); // only if stb_image is available\n\nextern int stbgl_TestTexture(int w);\nextern int stbgl_TestTextureEx(int w, char *scale_table, int checks_log2, int r1,int g1,int b1, int r2, int b2, int g2);\nextern unsigned int stbgl_rand(void); // internal, but exposed just in case; LCG, so use middle bits\n\nextern int stbgl_TexImage2D(int texid, int w, int h, void *data, char *props);\nextern int stbgl_TexImage2D_Extra(int texid, int w, int h, void *data, int chan, char *props, int preserve_data);\n// \"props\" is a series of characters (and blocks of characters), a la fopen()'s mode,\n// e.g.:\n//   GLuint texid = stbgl_LoadTexture(\"myfile.jpg\", \"mbc\")\n//      means: load the image \"myfile.jpg\", and do the following:\n//                generate mipmaps\n//                use bilinear filtering (not trilinear)\n//                use clamp-to-edge on both channels\n//\n// input descriptor: AT MOST ONE\n//   TEXT     MEANING\n//    1         1 channel of input (intensity/alpha)\n//    2         2 channels of input (luminance, alpha)\n//    3         3 channels of input (RGB)\n//    4         4 channels of input (RGBA)\n//    l         1 channel of input (luminance)\n//    a         1 channel of input (alpha)\n//    la        2 channels of input (lum/alpha)\n//    rgb       3 channels of input (RGB)\n//    ycocg     3 channels of input (YCoCg - forces YCoCg output)\n//    ycocgj    4 channels of input (YCoCgJunk - forces YCoCg output)\n//    rgba      4 channels of input (RGBA)\n//    \n// output descriptor: AT MOST ONE\n//   TEXT     MEANING\n//    A         1 channel of output (alpha)\n//    I         1 channel of output (intensity)\n//    LA        2 channels of output (lum/alpha)\n//    RGB       3 channels of output (RGB)\n//    RGBA      4 channels of output (RGBA)\n//    DXT1      encode as a DXT1 texture (RGB unless input has RGBA)\n//    DXT3      encode as a DXT3 texture\n//    DXT5      encode as a DXT5 texture\n//    YCoCg     encode as a DXT5 texture with Y in alpha, CoCg in RG\n//    D         GL_DEPTH_COMPONENT\n//    NONE      no input/output, don't call TexImage2D at all\n//\n// when reading from a file or using another interface with an explicit\n// channel count, the input descriptor is ignored and instead the channel\n// count is used as the input descriptor. if the file read is a DXT DDS,\n// then it is passed directly to OpenGL in the file format.\n//\n// if an input descriptor is supplied but no output descriptor, the output\n// is assumed to be the same as the input. if an output descriptor is supplied\n// but no input descriptor, the input is assumed to be the same as the\n// output. if neither is supplied, the input is assumed to be 4-channel.\n// If DXT1 or YCoCG output is requested with no input, the input is assumed\n// to be 4-channel but the alpha channel is ignored.\n//\n// filtering descriptor (default is no mipmaps)\n//   TEXT     MEANING\n//    m         generate mipmaps\n//    M         mipmaps are provided, concatenated at end of data (from largest to smallest)\n//    t         use trilinear filtering (default if mipmapped)\n//    b         use bilinear filtering (default if not-mipmapped)\n//    n         use nearest-neighbor sampling\n//\n// wrapping descriptor\n//   TEXT     MEANING\n//    w         wrap (default)\n//    c         clamp-to-edge\n//    C         GL_CLAMP (uses border color)\n//\n// If only one wrapping descriptor is supplied, it is applied to both channels.\n//\n// special:\n//   TEXT     MEANING\n//    f         input data is floats (default unsigned bytes)\n//    F         input&output data is floats (default unsigned bytes)\n//    p         explicitly pre-multiply the alpha\n//    P         pad to power-of-two (default stretches)\n//    NP2       non-power-of-two\n//    +         can overwrite the texture data with temp data\n//    !         free the texture data with \"free\"\n//\n// the properties string can also include spaces\n\n#ifdef __cplusplus\n}\n#endif\n\n\n#ifdef STB_GL_IMPLEMENTATION\n#include <math.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <memory.h>\n\nint stbgl_hasExtension(char *ext)\n{\n   const char *s = glGetString(GL_EXTENSIONS);\n   for(;;) {\n      char *e = ext;\n      for (;;) {\n         if (*e == 0) {\n            if (*s == 0 || *s == ' ') return 1;\n            break;\n         }\n         if (*s != *e)\n            break;\n         ++s, ++e;\n      }\n      while (*s && *s != ' ') ++s;\n      if (!*s) return 0;\n      ++s; // skip space\n   }\n}\n\nvoid stbgl_drawRect(float x0, float y0, float x1, float y1)\n{\n   glBegin(GL_POLYGON);\n      glTexCoord2f(0,0); glVertex2f(x0,y0);\n      glTexCoord2f(1,0); glVertex2f(x1,y0);\n      glTexCoord2f(1,1); glVertex2f(x1,y1);\n      glTexCoord2f(0,1); glVertex2f(x0,y1);\n   glEnd();\n}\n\nvoid stbgl_drawRectTC(float x0, float y0, float x1, float y1, float s0, float t0, float s1, float t1)\n{\n   glBegin(GL_POLYGON);\n      glTexCoord2f(s0,t0); glVertex2f(x0,y0);\n      glTexCoord2f(s1,t0); glVertex2f(x1,y0);\n      glTexCoord2f(s1,t1); glVertex2f(x1,y1);\n      glTexCoord2f(s0,t1); glVertex2f(x0,y1);\n   glEnd();\n}\n\nvoid stbgl_drawBox(float x, float y, float z, float sx, float sy, float sz, int cw)\n{\n   float x0,y0,z0,x1,y1,z1;\n   sx /=2, sy/=2, sz/=2;\n   x0 = x-sx; y0 = y-sy; z0 = z-sz;\n   x1 = x+sx; y1 = y+sy; z1 = z+sz;\n\n   glBegin(GL_QUADS);\n      if (cw) {\n         glNormal3f(0,0,-1);\n         glTexCoord2f(0,0); glVertex3f(x0,y0,z0);\n         glTexCoord2f(1,0); glVertex3f(x1,y0,z0);\n         glTexCoord2f(1,1); glVertex3f(x1,y1,z0);\n         glTexCoord2f(0,1); glVertex3f(x0,y1,z0);\n\n         glNormal3f(0,0,1);\n         glTexCoord2f(0,0); glVertex3f(x1,y0,z1);\n         glTexCoord2f(1,0); glVertex3f(x0,y0,z1);\n         glTexCoord2f(1,1); glVertex3f(x0,y1,z1);\n         glTexCoord2f(0,1); glVertex3f(x1,y1,z1);\n\n         glNormal3f(-1,0,0);\n         glTexCoord2f(0,0); glVertex3f(x0,y1,z1);\n         glTexCoord2f(1,0); glVertex3f(x0,y0,z1);\n         glTexCoord2f(1,1); glVertex3f(x0,y0,z0);\n         glTexCoord2f(0,1); glVertex3f(x0,y1,z0);\n\n         glNormal3f(1,0,0);\n         glTexCoord2f(0,0); glVertex3f(x1,y0,z1);\n         glTexCoord2f(1,0); glVertex3f(x1,y1,z1);\n         glTexCoord2f(1,1); glVertex3f(x1,y1,z0);\n         glTexCoord2f(0,1); glVertex3f(x1,y0,z0);\n\n         glNormal3f(0,-1,0);\n         glTexCoord2f(0,0); glVertex3f(x0,y0,z1);\n         glTexCoord2f(1,0); glVertex3f(x1,y0,z1);\n         glTexCoord2f(1,1); glVertex3f(x1,y0,z0);\n         glTexCoord2f(0,1); glVertex3f(x0,y0,z0);\n\n         glNormal3f(0,1,0);\n         glTexCoord2f(0,0); glVertex3f(x1,y1,z1);\n         glTexCoord2f(1,0); glVertex3f(x0,y1,z1);\n         glTexCoord2f(1,1); glVertex3f(x0,y1,z0);\n         glTexCoord2f(0,1); glVertex3f(x1,y1,z0);\n      } else {\n         glNormal3f(0,0,-1);\n         glTexCoord2f(0,0); glVertex3f(x0,y0,z0);\n         glTexCoord2f(0,1); glVertex3f(x0,y1,z0);\n         glTexCoord2f(1,1); glVertex3f(x1,y1,z0);\n         glTexCoord2f(1,0); glVertex3f(x1,y0,z0);\n\n         glNormal3f(0,0,1);\n         glTexCoord2f(0,0); glVertex3f(x1,y0,z1);\n         glTexCoord2f(0,1); glVertex3f(x1,y1,z1);\n         glTexCoord2f(1,1); glVertex3f(x0,y1,z1);\n         glTexCoord2f(1,0); glVertex3f(x0,y0,z1);\n\n         glNormal3f(-1,0,0);\n         glTexCoord2f(0,0); glVertex3f(x0,y1,z1);\n         glTexCoord2f(0,1); glVertex3f(x0,y1,z0);\n         glTexCoord2f(1,1); glVertex3f(x0,y0,z0);\n         glTexCoord2f(1,0); glVertex3f(x0,y0,z1);\n\n         glNormal3f(1,0,0);\n         glTexCoord2f(0,0); glVertex3f(x1,y0,z1);\n         glTexCoord2f(0,1); glVertex3f(x1,y0,z0);\n         glTexCoord2f(1,1); glVertex3f(x1,y1,z0);\n         glTexCoord2f(1,0); glVertex3f(x1,y1,z1);\n\n         glNormal3f(0,-1,0);\n         glTexCoord2f(0,0); glVertex3f(x0,y0,z1);\n         glTexCoord2f(0,1); glVertex3f(x0,y0,z0);\n         glTexCoord2f(1,1); glVertex3f(x1,y0,z0);\n         glTexCoord2f(1,0); glVertex3f(x1,y0,z1);\n\n         glNormal3f(0,1,0);\n         glTexCoord2f(0,0); glVertex3f(x1,y1,z1);\n         glTexCoord2f(0,1); glVertex3f(x1,y1,z0);\n         glTexCoord2f(1,1); glVertex3f(x0,y1,z0);\n         glTexCoord2f(1,0); glVertex3f(x0,y1,z1);\n      }\n   glEnd();\n}\n\nvoid stbgl_SimpleLight(int index, float bright, float x, float y, float z)\n{\n   float d = (float) (1.0f/sqrt(x*x+y*y+z*z));\n   float dir[4] = { x*d,y*d,z*d,0 }, zero[4] = { 0,0,0,0 };\n   float c[4] = { bright,bright,bright,0 };\n   GLuint light = GL_LIGHT0 + index;\n   glLightfv(light, GL_POSITION, dir);\n   glLightfv(light, GL_DIFFUSE, c);\n   glLightfv(light, GL_AMBIENT, zero);\n   glLightfv(light, GL_SPECULAR, zero);\n   glEnable(light);\n   glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);\n   glEnable(GL_COLOR_MATERIAL);\n}\n\nvoid stbgl_GlobalAmbient(float r, float g, float b)\n{\n   float v[4] = { r,g,b,0 };\n   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, v);\n}\n\n\n#define stbgl_rad2deg(r)  ((r)*180.0f / M_PI)\n#define stbgl_deg2rad(r)  ((r)/180.0f * M_PI)\n\nvoid stbgl_Perspective(float zoom, float max_hfov, float max_vfov, float znear, float zfar)\n{\n   float unit_width, unit_height, aspect, vfov;\n   int data[4],w,h;\n   glGetIntegerv(GL_VIEWPORT, data);\n   w = data[2];\n   h = data[3];\n   aspect = (float) w / h;\n\n   if (max_hfov <= 0) max_hfov = 179;\n   if (max_vfov <= 0) max_vfov = 179;\n\n   // convert max_hfov, max_vfov to worldspace width at depth=1\n   unit_width  = (float) tan(stbgl_deg2rad(max_hfov/2)) * 2;\n   unit_height = (float) tan(stbgl_deg2rad(max_vfov/2)) * 2;\n   // check if hfov = max_hfov is enough to satisfy it\n   if (unit_width <= aspect * unit_height) {\n      float height = unit_width / aspect;\n      vfov = (float) atan((     height/2) / zoom);\n   } else {\n      vfov = (float) atan((unit_height/2) / zoom);\n   }\n   vfov = (float) stbgl_rad2deg(vfov * 2);\n   gluPerspective(vfov, aspect, znear, zfar);\n}\n\nvoid stbgl_PerspectiveViewport(int x, int y, int w, int h, float zoom, float min_hfov, float min_vfov, float znear, float zfar)\n{\n   if (znear <= 0.0001f) znear = 0.0001f;\n   glViewport(x,y,w,h);\n   glScissor(x,y,w,h);\n   glMatrixMode(GL_PROJECTION);\n   glLoadIdentity();\n   stbgl_Perspective(zoom, min_hfov, min_vfov, znear, zfar);\n   glMatrixMode(GL_MODELVIEW);\n}\n\n// point the camera along the positive X axis, Z-up\nvoid stbgl_initCamera_zup_facing_x(void)\n{\n   glRotatef(-90, 1,0,0);\n   glRotatef( 90, 0,0,1);\n}\n\n// point the camera along the positive Y axis, Z-up\nvoid stbgl_initCamera_zup_facing_y(void)\n{\n   glRotatef(-90, 1,0,0);\n}\n\n// setup a camera using Euler angles\nvoid stbgl_positionCameraWithEulerAngles(float *loc, float *ang)\n{\n   glRotatef(-ang[1], 0,1,0);\n   glRotatef(-ang[0], 1,0,0);\n   glRotatef(-ang[2], 0,0,1);\n   glTranslatef(-loc[0], -loc[1], -loc[2]);\n}\n\nstatic int stbgl_m(char *a, char *b)\n{\n   // skip first character\n   do { ++a,++b; } while (*b && *a == *b);\n   return *b == 0;\n}\n\n#ifdef STBI_VERSION\n#ifndef STBI_NO_STDIO\nint stbgl_LoadTexture(char *filename, char *props)\n{\n   // @TODO: handle DDS files directly\n   int res;\n   void *data;\n   int w,h,c;\n   #ifndef STBI_NO_HDR\n   if (stbi_is_hdr(filename)) {\n      data = stbi_loadf(filename, &w, &h, &c, 0);\n      if (!data) return 0;\n      res = stbgl_TexImage2D_Extra(0, w,h,data, -c, props, 0);\n      free(data);\n      return res;\n   }\n   #endif\n\n   data = stbi_load(filename, &w, &h, &c, 0);\n   if (!data) return 0;\n   res = stbgl_TexImage2D_Extra(0, w,h,data, c, props, 0);\n   free(data);\n   return res;\n}\n#endif\n#endif // STBI_VERSION\n\nint stbgl_TexImage2D(int texid, int w, int h, void *data, char *props)\n{\n   return stbgl_TexImage2D_Extra(texid, w, h, data, 0, props,1);\n}\n\nint stbgl_TestTexture(int w)\n{\n   char scale_table[] = { 10,20,30,30,35,40,5,18,25,13,7,5,3,3,2,2,2,2,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0 };\n   return stbgl_TestTextureEx(w, scale_table, 2, 140,130,200, 180,200,170);\n}\n\nunsigned int stbgl_rand(void)\n{\n   static unsigned int stbgl__rand_seed = 3248980923; // random typing\n   return stbgl__rand_seed = stbgl__rand_seed * 2147001325 + 715136305; // BCPL generator\n}\n\n// wish this could be smaller, since it's so frivolous\nint stbgl_TestTextureEx(int w, char *scale_table, int checks_log2, int r1,int g1,int b1, int r2, int b2, int g2)\n{\n   int rt[2] = {r1,r2}, gt[2] = {g1,g2}, bt[2] = {b1,b2};\n   signed char modded[256];\n   int i,j, m = w-1, s,k,scale;\n   unsigned char *data = (unsigned char *) malloc(w*w*3);\n   assert((m & w) == 0);\n   data[0] = 128;\n   for (s=0; s < 16; ++s) if ((1 << s) == w) break;\n   assert(w == (1 << s));\n   // plasma fractal noise\n   for (k=s-1; k >= 0; --k) {\n      int step = 1 << k;\n      // interpolate from \"parents\"\n      for (j=0; j < w; j += step*2) {\n         for (i=0; i < w; i += step*2) {\n            int i1 = i+step, j1=j+step;\n            int i2 = (i+step*2)&m, j2 = (j+step*2)&m;\n            int p00 = data[(j*w+i )*3], p01 = data[(j2*w+i )*3];\n            int p10 = data[(j*w+i2)*3], p11 = data[(j2*w+i2)*3];\n            data[(j*w+i1)*3] = (p00+p10)>>1;\n            data[(j1*w+i)*3] = (p00+p01)>>1;\n            data[(j1*w+i1)*3]= (p00+p01+p10+p11)>>2;\n         }\n      }\n      scale = scale_table[s-k+1];\n      if (!scale) continue; // just interpolate down the remaining data\n      for (j=0,i=0; i < 256; i += 2, j == scale ? j=0 : ++j)\n         modded[i] = j, modded[i+1] = -j; // precompute i%scale (plus sign)\n      for (j=0; j < w; j += step)\n         for (i=0; i < w; i += step) {\n            int x = data[(j*w+i)*3] + modded[(stbgl_rand() >> 12) & 255];\n            data[(j*w+i)*3] = x < 0 ? 0 : x > 255 ? 255 : x;\n         }\n   }\n   for (j=0; j < w; ++j)\n      for (i=0; i < w; ++i) {\n         int check = ((i^j) & (1 << (s-checks_log2))) == 0;\n         int v = data[(j*w+i)*3] >> 2;\n         data[(j*w+i)*3+0] = rt[check]-v;\n         data[(j*w+i)*3+1] = gt[check]-v;\n         data[(j*w+i)*3+2] = bt[check]-v;\n      }\n   return stbgl_TexImage2D(0, w, w, data, \"3m!\"); // 3 channels, mipmap, free\n}\n\n#ifdef _WIN32\n#ifndef WINGDIAPI\ntypedef int (__stdcall *stbgl__voidfunc)(void);\n__declspec(dllimport) stbgl__voidfunc wglGetProcAddress(char *);\n#endif\n#define STB__HAS_WGLPROC\nstatic void (__stdcall *stbgl__CompressedTexImage2DARB)(int target, int level,\n                                   int internalformat, int width,\n                                   int height, int border, \n                                   int imageSize, void *data);\nstatic void stbgl__initCompTex(void)\n{\n   *((void **) &stbgl__CompressedTexImage2DARB) = (void *) wglGetProcAddress(\"glCompressedTexImage2DARB\");\n}\n#else\nstatic void (*stbgl__CompressedTexImage2DARB)(int target, int level,\n                                   int internalformat, int width,\n                                   int height, int border, \n                                   int imageSize, void *data);\nstatic void stbgl__initCompTex(void)\n{\n}\n#endif // _WIN32\n\n#define STBGL_COMPRESSED_RGB_S3TC_DXT1    0x83F0\n#define STBGL_COMPRESSED_RGBA_S3TC_DXT1   0x83F1\n#define STBGL_COMPRESSED_RGBA_S3TC_DXT3   0x83F2\n#define STBGL_COMPRESSED_RGBA_S3TC_DXT5   0x83F3\n\n#ifdef STB_COMPRESS_DXT_BLOCK\nstatic void stbgl__convert(uint8 *p, uint8 *q, int n, int input_desc, uint8 *end)\n{\n   int i;\n   switch (input_desc) {\n      case GL_RED:\n      case GL_LUMINANCE: for (i=0; i < n; ++i,p+=4) p[0] = p[1] = p[2] = q[0], p[3]=255, q+=1; break;\n      case GL_ALPHA:     for (i=0; i < n; ++i,p+=4) p[0] = p[1] = p[2] = 0, p[3] = q[0], q+=1; break;\n      case GL_LUMINANCE_ALPHA: for (i=0; i < n; ++i,p+=4) p[0] = p[1] = p[2] = q[0], p[3]=q[1], q+=2; break;\n      case GL_RGB:       for (i=0; i < n; ++i,p+=4) p[0]=q[0],p[1]=q[1],p[2]=q[2],p[3]=255,q+=3; break;\n      case GL_RGBA:      memcpy(p, q, n*4); break;\n      case GL_INTENSITY: for (i=0; i < n; ++i,p+=4) p[0] = p[1] = p[2] = p[3] = q[0], q+=1; break;\n   }\n   assert(p <= end);\n}\n\nstatic void stbgl__compress(uint8 *p, uint8 *rgba, int w, int h, int output_desc, uint8 *end)\n{\n   int i,j,y,y2;\n   int alpha = (output_desc == STBGL_COMPRESSED_RGBA_S3TC_DXT5);\n   for (j=0; j < w; j += 4) {\n      int x=4;\n      for (i=0; i < h; i += 4) {\n         uint8 block[16*4];\n         if (i+3 >= w) x = w-i;\n         for (y=0; y < 4; ++y) {\n            if (j+y >= h) break;\n            memcpy(block+y*16, rgba + w*4*(j+y) + i*4, x*4);\n         }\n         if (x < 4) {\n            switch (x) {\n               case 0: assert(0);\n               case 1:\n                  for (y2=0; y2 < y; ++y2) {\n                     memcpy(block+y2*16+1*4, block+y2*16+0*4, 4);\n                     memcpy(block+y2*16+2*4, block+y2*16+0*4, 8);\n                  }\n                  break;\n               case 2:\n                  for (y2=0; y2 < y; ++y2)\n                     memcpy(block+y2*16+2*4, block+y2*16+0*4, 8);\n                  break;\n               case 3:\n                  for (y2=0; y2 < y; ++y2)\n                     memcpy(block+y2*16+3*4, block+y2*16+1*4, 4);\n                  break;\n            }\n         }\n         y2 = 0;\n         for(; y<4; ++y,++y2)\n            memcpy(block+y*16, block+y2*16, 4*4);\n         stb_compress_dxt_block(p, block, alpha, 10);\n         p += alpha ? 16 : 8;\n      }\n   }\n   assert(p <= end);\n}\n#endif // STB_COMPRESS_DXT_BLOCK\n\n// use the reserved temporary-use enumerant range, since no\n// OpenGL enumerants should fall in that range\nenum\n{\n   STBGL_UNDEFINED = 0x6000,\n   STBGL_YCOCG,\n   STBGL_YCOCGJ,\n   STBGL_GEN_MIPMAPS,\n   STBGL_MIPMAPS,\n   STBGL_NO_DOWNLOAD,\n};\n\n#define STBGL_CLAMP_TO_EDGE               0x812F\n#define STBGL_CLAMP_TO_BORDER             0x812D\n\n#define STBGL_DEPTH_COMPONENT16           0x81A5\n#define STBGL_DEPTH_COMPONENT24           0x81A6\n#define STBGL_DEPTH_COMPONENT32           0x81A7\n\nint stbgl_TexImage2D_Extra(int texid, int w, int h, void *data, int chan, char *props, int preserve_data)\n{\n   static int has_s3tc = -1; // haven't checked yet\n   int free_data = 0, is_compressed = 0;\n   int pad_to_power_of_two = 0, non_power_of_two = 0;\n   int premultiply_alpha = 0; // @TODO\n   int float_tex   = 0; // @TODO\n   int input_type  = GL_UNSIGNED_BYTE;\n   int input_desc  = STBGL_UNDEFINED;\n   int output_desc = STBGL_UNDEFINED;\n   int mipmaps     = STBGL_UNDEFINED;\n   int filter      = STBGL_UNDEFINED, mag_filter;\n   int wrap_s = STBGL_UNDEFINED, wrap_t = STBGL_UNDEFINED;\n\n   // parse out the properties\n   if (props == NULL) props = \"\";\n   while (*props) {\n      switch (*props) {\n         case '1' :  input_desc = GL_LUMINANCE; break;\n         case '2' :  input_desc = GL_LUMINANCE_ALPHA; break;\n         case '3' :  input_desc = GL_RGB; break;\n         case '4' :  input_desc = GL_RGBA; break;\n         case 'l' :  if (props[1] == 'a') { input_desc = GL_LUMINANCE_ALPHA; ++props; }\n                     else input_desc = GL_LUMINANCE;\n                     break;\n         case 'a' :  input_desc = GL_ALPHA; break;\n         case 'r' :  if (stbgl_m(props, \"rgba\")) { input_desc = GL_RGBA; props += 3; break; }\n                     if (stbgl_m(props, \"rgb\")) { input_desc = GL_RGB; props += 2; break; }\n                     input_desc = GL_RED;\n                     break;\n         case 'y' :  if (stbgl_m(props, \"ycocg\")) {\n                        if (props[5] == 'j') { props += 5; input_desc = STBGL_YCOCGJ; }\n                        else { props += 4; input_desc = STBGL_YCOCG; }\n                        break;\n                     }\n                     return 0;\n         case 'L' :  if (props[1] == 'A') { output_desc = GL_LUMINANCE_ALPHA; ++props; }\n                     else output_desc = GL_LUMINANCE;\n                     break;\n         case 'I' :  output_desc = GL_INTENSITY; break;\n         case 'A' :  output_desc = GL_ALPHA; break;\n         case 'R' :  if (stbgl_m(props, \"RGBA\")) { output_desc = GL_RGBA; props += 3; break; }\n                     if (stbgl_m(props, \"RGB\")) { output_desc = GL_RGB; props += 2; break; }\n                     output_desc = GL_RED;\n                     break;\n         case 'Y' :  if (stbgl_m(props, \"YCoCg\") || stbgl_m(props, \"YCOCG\")) {\n                        props += 4;\n                        output_desc = STBGL_YCOCG;\n                        break;\n                     }\n                     return 0;\n         case 'D' :  if (stbgl_m(props, \"DXT\")) {\n                        switch (props[3]) {\n                           case '1': output_desc = STBGL_COMPRESSED_RGB_S3TC_DXT1; break;\n                           case '3': output_desc = STBGL_COMPRESSED_RGBA_S3TC_DXT3; break;\n                           case '5': output_desc = STBGL_COMPRESSED_RGBA_S3TC_DXT5; break;\n                           default: return 0;\n                        }\n                        props += 3;\n                     } else if (stbgl_m(props, \"D16\")) {\n                        output_desc = STBGL_DEPTH_COMPONENT16;\n                        input_desc  = GL_DEPTH_COMPONENT;\n                        props += 2;\n                     } else if (stbgl_m(props, \"D24\")) {\n                        output_desc = STBGL_DEPTH_COMPONENT24;\n                        input_desc  = GL_DEPTH_COMPONENT;\n                        props += 2;\n                     } else if (stbgl_m(props, \"D32\")) {\n                        output_desc = STBGL_DEPTH_COMPONENT32;\n                        input_desc  = GL_DEPTH_COMPONENT;\n                        props += 2;\n                     } else {\n                        output_desc = GL_DEPTH_COMPONENT;\n                        input_desc  = GL_DEPTH_COMPONENT;\n                     }\n                     break;\n         case 'N' :  if (stbgl_m(props, \"NONE\")) {\n                        props += 3;\n                        input_desc = STBGL_NO_DOWNLOAD;\n                        output_desc = STBGL_NO_DOWNLOAD;\n                        break;\n                     }\n                     if (stbgl_m(props, \"NP2\")) {\n                        non_power_of_two = 1;\n                        props += 2;\n                        break;\n                     }\n                     return 0;\n         case 'm' :  mipmaps = STBGL_GEN_MIPMAPS; break;\n         case 'M' :  mipmaps = STBGL_MIPMAPS; break;\n         case 't' :  filter = GL_LINEAR_MIPMAP_LINEAR; break;\n         case 'b' :  filter = GL_LINEAR; break;\n         case 'n' :  filter = GL_NEAREST; break;\n         case 'w' :  if (wrap_s == STBGL_UNDEFINED) wrap_s = GL_REPEAT; else wrap_t = GL_REPEAT; break;\n         case 'C' :  if (wrap_s == STBGL_UNDEFINED) wrap_s = STBGL_CLAMP_TO_BORDER; else wrap_t = STBGL_CLAMP_TO_BORDER; break;\n         case 'c' :  if (wrap_s == STBGL_UNDEFINED) wrap_s = STBGL_CLAMP_TO_EDGE; else wrap_t = STBGL_CLAMP_TO_EDGE; break;\n         case 'f' :  input_type = GL_FLOAT; break;\n         case 'F' :  input_type = GL_FLOAT; float_tex = 1; break;\n         case 'p' :  premultiply_alpha = 1; break;\n         case 'P' :  pad_to_power_of_two = 1; break;\n         case '+' :  preserve_data = 0; break;\n         case '!' :  preserve_data = 0; free_data = 1; break;\n         case ' ' :  break;\n         case '-' :  break;\n         default  :  if (free_data) free(data);\n                     return 0;\n      }\n      ++props;\n   }\n   \n   // override input_desc based on channel count\n   if (output_desc != STBGL_NO_DOWNLOAD) {\n      switch (abs(chan)) {\n         case 1: input_desc = GL_LUMINANCE; break;\n         case 2: input_desc = GL_LUMINANCE_ALPHA; break;\n         case 3: input_desc = GL_RGB; break;\n         case 4: input_desc = GL_RGBA; break;\n         case 0: break;\n         default: return 0;\n      }\n   }\n\n   // override input_desc based on channel info\n   if (chan > 0) { input_type = GL_UNSIGNED_BYTE; }\n   if (chan < 0) { input_type = GL_FLOAT; }\n\n   if (output_desc == GL_ALPHA) {\n      if (input_desc == GL_LUMINANCE)\n         input_desc = GL_ALPHA;\n      if (input_desc == GL_RGB) {\n         // force a presumably-mono image to alpha\n         // @TODO handle 'preserve_data' case?\n         if (data && !preserve_data && input_type == GL_UNSIGNED_BYTE) {\n            int i;\n            unsigned char *p = (unsigned char *) data, *q = p;\n            for (i=0; i < w*h; ++i) {\n               *q = (p[0] + 2*p[1] + p[2]) >> 2;\n               p += 3;\n               q += 1;\n            }\n            input_desc = GL_ALPHA;\n         }\n      }\n   }\n\n   // set undefined input/output based on the other\n   if (input_desc == STBGL_UNDEFINED && output_desc == STBGL_UNDEFINED) {\n      input_desc = output_desc = GL_RGBA;\n   } else if (output_desc == STBGL_UNDEFINED) {\n      switch (input_desc) {\n         case GL_LUMINANCE:\n         case GL_ALPHA:\n         case GL_LUMINANCE_ALPHA:\n         case GL_RGB:\n         case GL_RGBA:\n            output_desc = input_desc;\n            break;\n         case GL_RED:\n            output_desc = GL_INTENSITY;\n            break;\n         case STBGL_YCOCG:\n         case STBGL_YCOCGJ:\n            output_desc = STBGL_YCOCG;\n            break;\n         default: assert(0); return 0;\n      }\n   } else if (input_desc == STBGL_UNDEFINED) {\n      switch (output_desc) {\n         case GL_LUMINANCE:\n         case GL_ALPHA:\n         case GL_LUMINANCE_ALPHA:\n         case GL_RGB:\n         case GL_RGBA:\n            input_desc = output_desc;\n            break;\n         case GL_INTENSITY:\n            input_desc = GL_RED;\n            break;\n         case STBGL_YCOCG:\n         case STBGL_COMPRESSED_RGB_S3TC_DXT1:\n         case STBGL_COMPRESSED_RGBA_S3TC_DXT3:\n         case STBGL_COMPRESSED_RGBA_S3TC_DXT5:\n            input_desc = GL_RGBA;\n            break;\n      }\n   } else {\n      if (output_desc == STBGL_COMPRESSED_RGB_S3TC_DXT1) {\n         // if input has alpha, force output alpha\n         switch (input_desc) {\n            case GL_ALPHA:\n            case GL_LUMINANCE_ALPHA:\n            case GL_RGBA:\n               output_desc = STBGL_COMPRESSED_RGBA_S3TC_DXT5;\n               break;\n         }\n      }\n   }\n\n   switch(input_desc) {\n      case GL_LUMINANCE:\n      case GL_RED:\n      case GL_ALPHA:\n         chan = 1;\n         break;\n      case GL_LUMINANCE_ALPHA:\n         chan = 2;\n         break;\n      case GL_RGB:\n         chan = 3;\n         break;\n      case GL_RGBA:\n         chan = 4;\n         break;\n   }\n\n   if (pad_to_power_of_two && ((w & (w-1)) || (h & (h-1)))) {\n      if (output_desc != STBGL_NO_DOWNLOAD && input_type == GL_UNSIGNED_BYTE && chan > 0) {\n         unsigned char *new_data;\n         int w2 = w, h2 = h, j;\n         while (w & (w-1))\n            w = (w | (w>>1))+1;\n         while (h & (h-1))\n            h = (h | (h>>1))+1;\n         new_data = malloc(w * h * chan);\n         for (j=0; j < h2; ++j) {\n            memcpy(new_data + j * w * chan, (char *) data+j*w2*chan, w2*chan);\n            memset(new_data + (j * w+w2) * chan, 0, (w-w2)*chan);\n         }\n         for (; j < h; ++j)\n            memset(new_data + j*w*chan, 0, w*chan);\n         if (free_data)\n            free(data);\n         data = new_data;\n         free_data = 1;\n      }\n   }\n\n   switch (output_desc) {\n      case STBGL_COMPRESSED_RGB_S3TC_DXT1:\n      case STBGL_COMPRESSED_RGBA_S3TC_DXT1:\n      case STBGL_COMPRESSED_RGBA_S3TC_DXT3:\n      case STBGL_COMPRESSED_RGBA_S3TC_DXT5:\n         is_compressed = 1;\n         if (has_s3tc == -1) {\n            has_s3tc = stbgl_hasExtension(\"GL_EXT_texture_compression_s3tc\");\n            if (has_s3tc) stbgl__initCompTex();\n         }\n         if (!has_s3tc) {\n            is_compressed = 0;\n            if (output_desc == STBGL_COMPRESSED_RGB_S3TC_DXT1)\n               output_desc = GL_RGB;\n            else\n               output_desc = GL_RGBA;\n         }\n   }\n\n   if (output_desc == STBGL_YCOCG) {\n      assert(0);\n      output_desc = GL_RGB; // @TODO!\n      if (free_data) free(data);\n      return 0;\n   }\n\n   mag_filter = 0;\n   if (mipmaps != STBGL_UNDEFINED) {\n      switch (filter) {\n         case STBGL_UNDEFINED: filter = GL_LINEAR_MIPMAP_LINEAR; break;\n         case GL_NEAREST     : mag_filter = GL_NEAREST; filter = GL_LINEAR_MIPMAP_LINEAR; break;\n         case GL_LINEAR      : filter = GL_LINEAR_MIPMAP_NEAREST; break;\n      }\n   } else {\n      if (filter == STBGL_UNDEFINED)\n         filter = GL_LINEAR;\n   }\n\n   // update filtering\n   if (!mag_filter) {\n      if (filter == GL_NEAREST)\n         mag_filter = GL_NEAREST;\n      else\n         mag_filter = GL_LINEAR;\n   }\n\n   // update wrap/clamp\n   if (wrap_s == STBGL_UNDEFINED) wrap_s = GL_REPEAT;\n   if (wrap_t == STBGL_UNDEFINED) wrap_t = wrap_s;\n\n   // if no texture id, generate one\n   if (texid == 0) {\n      GLuint tex;\n      glGenTextures(1, &tex);\n      if (tex == 0) { if (free_data) free(data); return 0; }\n      texid = tex;\n   }\n\n   if (data == NULL && mipmaps == STBGL_GEN_MIPMAPS)\n      mipmaps = STBGL_MIPMAPS;\n\n   if (output_desc == STBGL_NO_DOWNLOAD)\n      mipmaps = STBGL_NO_DOWNLOAD;\n\n   glBindTexture(GL_TEXTURE_2D, texid);\n\n#ifdef STB_COMPRESS_DXT_BLOCK\n   if (!is_compressed || !stbgl__CompressedTexImage2DARB || output_desc == STBGL_COMPRESSED_RGBA_S3TC_DXT3 || data == NULL)\n#endif\n   {\n      switch (mipmaps) {\n         case STBGL_NO_DOWNLOAD:\n            break;\n\n         case STBGL_UNDEFINED:\n            // check if actually power-of-two\n            if (non_power_of_two || ((w & (w-1)) == 0 && (h & (h-1)) == 0))\n               glTexImage2D(GL_TEXTURE_2D, 0, output_desc, w, h, 0, input_desc, input_type, data);\n            else\n               gluBuild2DMipmaps(GL_TEXTURE_2D, output_desc, w, h, input_desc, input_type, data);\n               // not power of two, so use glu to resize (generates mipmaps needlessly)\n            break;\n\n         case STBGL_MIPMAPS: {\n            int level = 0;\n            int size = input_type == GL_FLOAT ? sizeof(float) : 1;\n            if (data == NULL) size = 0; // reuse same block of memory for all mipmaps\n            assert((w & (w-1)) == 0 && (h & (h-1)) == 0); // verify power-of-two\n            while (w > 1 && h > 1) {\n               glTexImage2D(GL_TEXTURE_2D, level, output_desc, w, h, 0, input_desc, input_type, data);\n               data = (void *) ((char *) data + w * h * size * chan);\n               if (w > 1) w >>= 1;\n               if (h > 1) h >>= 1;\n               ++level;\n            }\n            break;\n         }\n         case STBGL_GEN_MIPMAPS:\n            gluBuild2DMipmaps(GL_TEXTURE_2D, output_desc, w, h, input_desc, input_type, data);\n            break;\n\n         default:\n            assert(0);\n            if (free_data) free(data);\n            return 0;\n      }\n#ifdef STB_COMPRESS_DXT_BLOCK\n   } else {\n      uint8 *out, *rgba=0, *end_out, *end_rgba;\n      int level = 0, alpha = (output_desc != STBGL_COMPRESSED_RGB_S3TC_DXT1);\n      int size = input_type == GL_FLOAT ? sizeof(float) : 1;\n      int osize = alpha ? 16 : 8;\n      if (!free_data && mipmaps == STBGL_GEN_MIPMAPS) {\n         uint8 *temp = malloc(w*h*chan);\n         if (!temp) { if (free_data) free(data); return 0; }\n         memcpy(temp, data, w*h*chan);\n         if (free_data) free(data);\n         free_data = 1;\n         data = temp;\n      }\n      if (chan != 4 || size != 1) {\n         rgba = malloc(w*h*4);\n         if (!rgba) return 0;\n         end_rgba = rgba+w*h*4;\n      }\n      out = malloc((w+3)*(h+3)/16*osize); // enough storage for the s3tc data\n      if (!out) return 0;\n      end_out = out + ((w+3)*(h+3))/16*osize;\n\n      for(;;) {\n         if (chan != 4)\n            stbgl__convert(rgba, data, w*h, input_desc, end_rgba);\n         stbgl__compress(out, rgba ? rgba : data, w, h, output_desc, end_out);\n         stbgl__CompressedTexImage2DARB(GL_TEXTURE_2D, level, output_desc, w, h, 0, ((w+3)&~3)*((h+3)&~3)/16*osize, out);\n         //glTexImage2D(GL_TEXTURE_2D, level, alpha?GL_RGBA:GL_RGB, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba ? rgba : data);\n\n         if (mipmaps == STBGL_UNDEFINED) break;\n         if (w <= 1 && h <= 1) break;\n         if (mipmaps == STBGL_MIPMAPS) data = (void *) ((char *) data + w * h * size * chan);\n         if (mipmaps == STBGL_GEN_MIPMAPS) {\n            int w2 = w>>1, h2=h>>1, i,j,k, s=w*chan;\n            uint8 *p = data, *q=data;\n            if (w == 1) {\n               for (j=0; j < h2; ++j) {\n                  for (k=0; k < chan; ++k)\n                     *p++ = (q[k] + q[s+k] + 1) >> 1;\n                  q += s*2;\n               }\n            } else if (h == 1) {\n               for (i=0; i < w2; ++i) {\n                  for (k=0; k < chan; ++k)\n                     *p++ = (q[k] + q[k+chan] + 1) >> 1;\n                  q += chan*2;\n               }\n            } else {\n               for (j=0; j < h2; ++j) {\n                  for (i=0; i < w2; ++i) {\n                     for (k=0; k < chan; ++k)\n                        *p++ = (q[k] + q[k+chan] + q[s+k] + q[s+k+chan] + 2) >> 2;\n                     q += chan*2;\n                  }\n                  q += s;\n               }\n            }\n         }\n         if (w > 1) w >>= 1;\n         if (h > 1) h >>= 1;\n         ++level;\n      }\n      if (out) free(out);\n      if (rgba) free(rgba);\n#endif // STB_COMPRESS_DXT_BLOCK\n   }\n\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s);\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t);\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);\n\n   if (free_data) free(data);\n   return texid;\n}\n\n#endif // STB_DEFINE\n#undef STB_EXTERN\n\n#endif //INCLUDE_STB_GL_H\n\n// Extension handling... must be outside the INCLUDE_ brackets\n\n#if defined(STB_GLEXT_DEFINE) || defined(STB_GLEXT_DECLARE)\n\n#ifndef STB_GLEXT_SKIP_DURING_RECURSION\n\n#ifndef GL_GLEXT_VERSION\n\n   // First check if glext.h is concatenated on the end of this file\n   // (if it's concatenated on the beginning, we'll have GL_GLEXT_VERSION)\n\n   #define  STB_GLEXT_SKIP_DURING_RECURSION\n   #include __FILE__\n   #undef   STB_GLEXT_SKIP_DURING_RECURSION\n\n   // now check if it's still undefined; if so, try going for it by name;\n   // if this errors, that's fine, since we can't compile without it\n\n   #ifndef GL_GLEXT_VERSION\n   #include \"glext.h\"\n   #endif\n#endif\n\n#define GLARB(a,b) GLE(a##ARB,b##ARB)\n#define GLEXT(a,b) GLE(a##EXT,b##EXT)\n#define GLNV(a,b)  GLE(a##NV ,b##NV)\n#define GLATI(a,b) GLE(a##ATI,b##ATI)\n#define GLCORE(a,b) GLE(a,b)\n\n#ifdef STB_GLEXT_DEFINE_DECLARE\n#define STB_GLEXT_DEFINE STB_GLEXT_DECLARE\n#endif\n\n#if defined(STB_GLEXT_DECLARE) && defined(STB_GLEXT_DEFINE)\n#undef STB_GLEXT_DECLARE\n#endif\n\n#if defined(STB_GLEXT_DECLARE) && !defined(STB_GLEXT_DEFINE)\n   #define GLE(a,b) extern PFNGL##b##PROC gl##a;\n\n   #ifdef __cplusplus\n   extern \"C\" {\n   #endif\n\n   extern void stbgl_initExtensions(void);\n\n   #include STB_GLEXT_DECLARE\n\n   #ifdef __cplusplus\n   };\n   #endif\n\n#else\n\n   #ifndef STB_GLEXT_DEFINE\n   #error \"Header file is screwed up somehow\"\n   #endif\n\n   #ifdef _WIN32\n   #ifndef WINGDIAPI\n   #ifndef STB__HAS_WGLPROC\n   typedef int (__stdcall *stbgl__voidfunc)(void);\n   __declspec(dllimport) stbgl__voidfunc wglGetProcAddress(char *);\n   #endif\n   #endif\n   #define STBGL__GET_FUNC(x)   wglGetProcAddress(x)\n   #endif\n\n   #ifdef GLE\n   #undef GLE\n   #endif\n\n   #define GLE(a,b)  PFNGL##b##PROC gl##a;\n   #include STB_GLEXT_DEFINE\n\n   #undef GLE\n   #define GLE(a,b) gl##a = (PFNGL##b##PROC) STBGL__GET_FUNC(\"gl\" #a );\n\n   void stbgl_initExtensions(void)\n   {\n      #include STB_GLEXT_DEFINE\n   }\n\n   #undef GLE\n\n#endif // STB_GLEXT_DECLARE\n\n#endif // STB_GLEXT_SKIP\n\n#endif // STB_GLEXT_DEFINE || STB_GLEXT_DECLARE\n"
  },
  {
    "path": "tests/caveview/stb_glprog.h",
    "content": "// stb_glprog v0.02 public domain         functions to reduce GLSL boilerplate\n// http://nothings.org/stb/stb_glprog.h   especially with GL1 + ARB extensions\n//\n// Following defines *before* including have following effects:\n//\n//     STB_GLPROG_IMPLEMENTATION\n//           creates the implementation\n//\n//     STB_GLPROG_STATIC\n//           forces the implementation to be static (private to file that creates it)\n//\n//     STB_GLPROG_ARB\n//           uses ARB extension names for GLSL functions and enumerants instead of core names\n//\n//     STB_GLPROG_ARB_DEFINE_EXTENSIONS\n//           instantiates function pointers needed, static to implementing file\n//           to avoid collisions (but will collide if implementing file also\n//           defines any; best to isolate this to its own file in this case).\n//           This will try to automatically #include glext.h, but if it's not\n//           in the default include directories you'll need to include it\n//           yourself and define the next macro.\n//\n//     STB_GLPROG_SUPPRESS_GLEXT_INCLUDE\n//           disables the automatic #include of glext.h which is normally\n//           forced by STB_GLPROG_ARB_DEFINE_EXTENSIONS\n//\n// So, e.g., sample usage on an old Windows compiler:\n//\n//     #define STB_GLPROG_IMPLEMENTATION\n//     #define STB_GLPROG_ARB_DEFINE_EXTENSIONS\n//     #include <windows.h>\n//     #include \"gl/gl.h\"\n//     #include \"stb_glprog.h\"\n//\n// Note though that the header-file version of this (when you don't define\n// STB_GLPROG_IMPLEMENTATION) still uses GLint and such, so you basically\n// can only include it in places where you're already including GL, especially\n// on Windows where including \"gl.h\" requires (some of) \"windows.h\".\n//\n// See following comment blocks for function documentation.\n//\n// Version history:\n//    2013-12-08   v0.02   slightly simplified API and reduced GL resource usage (@rygorous)\n//    2013-12-08   v0.01   initial release\n\n\n// header file section starts here\n#if !defined(INCLUDE_STB_GLPROG_H)\n#define INCLUDE_STB_GLPROG_H\n\n#ifndef STB_GLPROG_STATIC\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n\n/////////////    SHADER CREATION\n\n\n/// EASY API\n\nextern GLuint stbgl_create_program(char const **vertex_source, char const **frag_source, char const **binds, char *error, int error_buflen);\n// This function returns a compiled program or 0 if there's an error.\n// To free the created program, call stbgl_delete_program.\n//\n//     stbgl_create_program(\n//             char **vertex_source,   // NULL or one or more strings with the vertex shader source, with a final NULL\n//             char **frag_source,     // NULL or one or more strings with the fragment shader source, with a final NULL\n//             char **binds,           // NULL or zero or more strings with attribute bind names, with a final NULL\n//             char *error,            // output location where compile error message is placed\n//             int error_buflen)       // length of error output buffer\n//\n// Returns a GLuint with the GL program object handle.\n//\n// If an individual bind string is \"\", no name is bound to that slot (this\n// allows you to create binds that aren't continuous integers starting at 0).\n//\n// If the vertex shader is NULL, then fixed-function vertex pipeline\n// is used, if that's legal in your version of GL.\n//\n// If the fragment shader is NULL, then fixed-function fragment pipeline\n// is used, if that's legal in your version of GL.\n\nextern void stgbl_delete_program(GLuint program);\n// deletes a program created by stbgl_create_program or stbgl_link_program\n\n\n/// FLEXIBLE API\n\nextern GLuint stbgl_compile_shader(GLenum type, char const **sources, int num_sources, char *error, int error_buflen);\n// compiles a shader. returns the shader on success or 0 on failure.\n//\n//    type          either:  GL_VERTEX_SHADER or GL_FRAGMENT_SHADER\n//                     or    GL_VERTEX_SHADER_ARB or GL_FRAGMENT_SHADER_ARB\n//                     or    STBGL_VERTEX_SHADER or STBGL_FRAGMENT_SHADER\n//    sources       array of strings containing the shader source\n//    num_sources   number of string in sources, or -1 meaning sources is NULL-terminated\n//    error         string to output compiler error to\n//    error_buflen  length of error buffer in chars\n\nextern GLuint stbgl_link_program(GLuint vertex_shader, GLuint fragment_shader, char const **binds, int num_binds, char *error, int error_buflen);\n// links a shader. returns the linked program on success or 0 on failure.\n//\n//    vertex_shader    a compiled vertex shader from stbgl_compile_shader, or 0 for fixed-function (if legal)\n//    fragment_shader  a compiled fragment shader from stbgl_compile_shader, or 0 for fixed-function (if legal)\n//\n\nextern void stbgl_delete_shader(GLuint shader);\n// deletes a shader created by stbgl_compile_shader\n\n\n/////////////    RENDERING WITH SHADERS\n\nextern GLint stbgl_find_uniform(GLuint prog, char *uniform);\n\nextern void stbgl_find_uniforms(GLuint prog, GLint *locations, char const **uniforms, int num_uniforms);\n// Given the locations array that is num_uniforms long, fills out\n// the locations of each of those uniforms for the specified program.\n// If num_uniforms is -1, then uniforms[] must be NULL-terminated\n\n// the following functions just wrap the difference in naming between GL2+ and ARB,\n// so you don't need them unless you're using both ARB and GL2+ in the same codebase,\n// or you're relying on this lib to provide the extensions\nextern void stbglUseProgram(GLuint program);\nextern void stbglVertexAttribPointer(GLuint index,  GLint size,  GLenum type,  GLboolean normalized,  GLsizei stride,  const GLvoid * pointer);\nextern void stbglEnableVertexAttribArray(GLuint index);\nextern void stbglDisableVertexAttribArray(GLuint index);\nextern void stbglUniform1fv(GLint loc, GLsizei count, const GLfloat *v);\nextern void stbglUniform2fv(GLint loc, GLsizei count, const GLfloat *v);\nextern void stbglUniform3fv(GLint loc, GLsizei count, const GLfloat *v);\nextern void stbglUniform4fv(GLint loc, GLsizei count, const GLfloat *v);\nextern void stbglUniform1iv(GLint loc, GLsizei count, const GLint *v);\nextern void stbglUniform2iv(GLint loc, GLsizei count, const GLint *v);\nextern void stbglUniform3iv(GLint loc, GLsizei count, const GLint *v);\nextern void stbglUniform4iv(GLint loc, GLsizei count, const GLint *v);\nextern void stbglUniform1f(GLint loc, float v0);\nextern void stbglUniform2f(GLint loc, float v0, float v1);\nextern void stbglUniform3f(GLint loc, float v0, float v1, float v2);\nextern void stbglUniform4f(GLint loc, float v0, float v1, float v2, float v3);\nextern void stbglUniform1i(GLint loc, GLint v0);\nextern void stbglUniform2i(GLint loc, GLint v0, GLint v1);\nextern void stbglUniform3i(GLint loc, GLint v0, GLint v1, GLint v2);\nextern void stbglUniform4i(GLint loc, GLint v0, GLint v1, GLint v2, GLint v3);\n\n\n//////////////     END OF FUNCTIONS\n\n//////////////////////////////////////////////////////////////////////////////\n\n#ifdef __cplusplus\n}\n#endif\n#endif // STB_GLPROG_STATIC\n\n#ifdef STB_GLPROG_ARB\n#define STBGL_VERTEX_SHADER    GL_VERTEX_SHADER_ARB\n#define STBGL_FRAGMENT_SHADER  GL_FRAGMENT_SHADER_ARB\n#else\n#define STBGL_VERTEX_SHADER    GL_VERTEX_SHADER\n#define STBGL_FRAGMENT_SHADER  GL_FRAGMENT_SHADER\n#endif\n\n#endif // INCLUDE_STB_GLPROG_H\n\n\n/////////    header file section ends here\n\n\n#ifdef STB_GLPROG_IMPLEMENTATION\n#include <string.h> // strncpy\n\n#ifdef STB_GLPROG_STATIC\n#define STB_GLPROG_DECLARE static\n#else\n#define STB_GLPROG_DECLARE extern\n#endif\n\n// check if user wants this file to define the GL extensions itself\n#ifdef STB_GLPROG_ARB_DEFINE_EXTENSIONS\n#define STB_GLPROG_ARB  // make sure later code uses the extensions\n\n#ifndef STB_GLPROG_SUPPRESS_GLEXT_INCLUDE\n#include \"glext.h\"\n#endif\n\n#define STB_GLPROG_EXTENSIONS                                 \\\n   STB_GLPROG_FUNC(ATTACHOBJECT        , AttachObject        ) \\\n   STB_GLPROG_FUNC(BINDATTRIBLOCATION  , BindAttribLocation  ) \\\n   STB_GLPROG_FUNC(COMPILESHADER       , CompileShader       ) \\\n   STB_GLPROG_FUNC(CREATEPROGRAMOBJECT , CreateProgramObject ) \\\n   STB_GLPROG_FUNC(CREATESHADEROBJECT  , CreateShaderObject  ) \\\n   STB_GLPROG_FUNC(DELETEOBJECT        , DeleteObject        ) \\\n   STB_GLPROG_FUNC(DETACHOBJECT        , DetachObject        ) \\\n   STB_GLPROG_FUNC(DISABLEVERTEXATTRIBARRAY, DisableVertexAttribArray) \\\n   STB_GLPROG_FUNC(ENABLEVERTEXATTRIBARRAY,  EnableVertexAttribArray ) \\\n   STB_GLPROG_FUNC(GETATTACHEDOBJECTS  , GetAttachedObjects  ) \\\n   STB_GLPROG_FUNC(GETOBJECTPARAMETERIV, GetObjectParameteriv) \\\n   STB_GLPROG_FUNC(GETINFOLOG          , GetInfoLog          ) \\\n   STB_GLPROG_FUNC(GETUNIFORMLOCATION  , GetUniformLocation  ) \\\n   STB_GLPROG_FUNC(LINKPROGRAM         , LinkProgram         ) \\\n   STB_GLPROG_FUNC(SHADERSOURCE        , ShaderSource        ) \\\n   STB_GLPROG_FUNC(UNIFORM1F           , Uniform1f           ) \\\n   STB_GLPROG_FUNC(UNIFORM2F           , Uniform2f           ) \\\n   STB_GLPROG_FUNC(UNIFORM3F           , Uniform3f           ) \\\n   STB_GLPROG_FUNC(UNIFORM4F           , Uniform4f           ) \\\n   STB_GLPROG_FUNC(UNIFORM1I           , Uniform1i           ) \\\n   STB_GLPROG_FUNC(UNIFORM2I           , Uniform2i           ) \\\n   STB_GLPROG_FUNC(UNIFORM3I           , Uniform3i           ) \\\n   STB_GLPROG_FUNC(UNIFORM4I           , Uniform4i           ) \\\n   STB_GLPROG_FUNC(UNIFORM1FV          , Uniform1fv          ) \\\n   STB_GLPROG_FUNC(UNIFORM2FV          , Uniform2fv          ) \\\n   STB_GLPROG_FUNC(UNIFORM3FV          , Uniform3fv          ) \\\n   STB_GLPROG_FUNC(UNIFORM4FV          , Uniform4fv          ) \\\n   STB_GLPROG_FUNC(UNIFORM1IV          , Uniform1iv          ) \\\n   STB_GLPROG_FUNC(UNIFORM2IV          , Uniform2iv          ) \\\n   STB_GLPROG_FUNC(UNIFORM3IV          , Uniform3iv          ) \\\n   STB_GLPROG_FUNC(UNIFORM4IV          , Uniform4iv          ) \\\n   STB_GLPROG_FUNC(USEPROGRAMOBJECT    , UseProgramObject    ) \\\n   STB_GLPROG_FUNC(VERTEXATTRIBPOINTER , VertexAttribPointer )\n\n// define the static function pointers\n\n#define STB_GLPROG_FUNC(x,y)  static PFNGL##x##ARBPROC gl##y##ARB;\nSTB_GLPROG_EXTENSIONS\n#undef STB_GLPROG_FUNC\n\n// define the GetProcAddress\n\n#ifdef _WIN32\n#ifndef WINGDIAPI\n#ifndef STB__HAS_WGLPROC\ntypedef int (__stdcall *stbgl__voidfunc)(void);\nstatic __declspec(dllimport) stbgl__voidfunc wglGetProcAddress(char *);\n#endif\n#endif\n#define STBGL__GET_FUNC(x)   wglGetProcAddress(x)\n#else\n#error \"need to define how this platform gets extensions\"\n#endif\n\n// create a function that fills out the function pointers\n\nstatic void stb_glprog_init(void)\n{\n   static int initialized = 0; // not thread safe!\n   if (initialized) return;\n   #define STB_GLPROG_FUNC(x,y) gl##y##ARB = (PFNGL##x##ARBPROC) STBGL__GET_FUNC(\"gl\" #y \"ARB\");\n   STB_GLPROG_EXTENSIONS\n   #undef STB_GLPROG_FUNC\n}\n#undef STB_GLPROG_EXTENSIONS\n\n#else\nstatic void stb_glprog_init(void)\n{\n}\n#endif\n\n\n// define generic names for many of the gl functions or extensions for later use;\n// note that in some cases there are two functions in core and one function in ARB\n#ifdef STB_GLPROG_ARB\n#define stbglCreateShader          glCreateShaderObjectARB\n#define stbglDeleteShader          glDeleteObjectARB\n#define stbglAttachShader          glAttachObjectARB\n#define stbglDetachShader          glDetachObjectARB\n#define stbglShaderSource          glShaderSourceARB\n#define stbglCompileShader         glCompileShaderARB\n#define stbglGetShaderStatus(a,b)  glGetObjectParameterivARB(a, GL_OBJECT_COMPILE_STATUS_ARB, b)\n#define stbglGetShaderInfoLog      glGetInfoLogARB\n#define stbglCreateProgram         glCreateProgramObjectARB\n#define stbglDeleteProgram         glDeleteObjectARB\n#define stbglLinkProgram           glLinkProgramARB\n#define stbglGetProgramStatus(a,b) glGetObjectParameterivARB(a, GL_OBJECT_LINK_STATUS_ARB, b)\n#define stbglGetProgramInfoLog     glGetInfoLogARB\n#define stbglGetAttachedShaders    glGetAttachedObjectsARB\n#define stbglBindAttribLocation    glBindAttribLocationARB\n#define stbglGetUniformLocation    glGetUniformLocationARB\n#define stbgl_UseProgram           glUseProgramObjectARB\n#else\n#define stbglCreateShader          glCreateShader\n#define stbglDeleteShader          glDeleteShader\n#define stbglAttachShader          glAttachShader\n#define stbglDetachShader          glDetachShader\n#define stbglShaderSource          glShaderSource\n#define stbglCompileShader         glCompileShader\n#define stbglGetShaderStatus(a,b)  glGetShaderiv(a, GL_COMPILE_STATUS, b)\n#define stbglGetShaderInfoLog      glGetShaderInfoLog\n#define stbglCreateProgram         glCreateProgram\n#define stbglDeleteProgram         glDeleteProgram\n#define stbglLinkProgram           glLinkProgram\n#define stbglGetProgramStatus(a,b) glGetProgramiv(a, GL_LINK_STATUS, b)\n#define stbglGetProgramInfoLog     glGetProgramInfoLog\n#define stbglGetAttachedShaders    glGetAttachedShaders\n#define stbglBindAttribLocation    glBindAttribLocation\n#define stbglGetUniformLocation    glGetUniformLocation\n#define stbgl_UseProgram           glUseProgram\n#endif\n\n\n// perform a safe strcat of 3 strings, given that we can't rely on portable snprintf\n// if you need to break on error, this is the best place to place a breakpoint\nstatic void stb_glprog_error(char *error, int error_buflen, char *str1, char *str2, char *str3)\n{\n   int n = strlen(str1);\n   strncpy(error, str1, error_buflen);\n   if (n < error_buflen && str2) {\n      strncpy(error+n, str2, error_buflen - n);\n      n += strlen(str2);\n      if (n < error_buflen && str3) {\n         strncpy(error+n, str3, error_buflen - n);\n      }\n   }\n   error[error_buflen-1] = 0;\n}\n\nSTB_GLPROG_DECLARE GLuint stbgl_compile_shader(GLenum type, char const **sources, int num_sources, char *error, int error_buflen)\n{\n   char *typename = (type == STBGL_VERTEX_SHADER ? \"vertex\" : \"fragment\");\n   int len;\n   GLint result;\n   GLuint shader;\n\n   // initialize the extensions if we haven't already\n   stb_glprog_init();\n\n   // allocate\n\n   shader = stbglCreateShader(type);\n   if (!shader) {\n      stb_glprog_error(error, error_buflen, \"Couldn't allocate shader object in stbgl_compile_shader for \", typename, NULL);\n      return 0;\n   }\n\n   // compile\n\n   // if num_sources is negative, assume source is NULL-terminated and count the non-NULL ones\n   if (num_sources < 0)\n      for (num_sources = 0; sources[num_sources] != NULL; ++num_sources)\n         ;\n   stbglShaderSource(shader, num_sources, sources, NULL);\n   stbglCompileShader(shader);\n   stbglGetShaderStatus(shader, &result);\n   if (result)\n      return shader;\n\n   // errors\n\n   stb_glprog_error(error, error_buflen, \"Compile error for \", typename, \" shader: \");\n   len = strlen(error);\n   if (len < error_buflen)\n      stbglGetShaderInfoLog(shader, error_buflen-len, NULL, error+len);\n\n   stbglDeleteShader(shader);\n   return 0;\n}\n\nSTB_GLPROG_DECLARE GLuint stbgl_link_program(GLuint vertex_shader, GLuint fragment_shader, char const **binds, int num_binds, char *error, int error_buflen)\n{\n   int len;\n   GLint result;\n\n   // allocate\n\n   GLuint prog = stbglCreateProgram();\n   if (!prog) {\n      stb_glprog_error(error, error_buflen, \"Couldn't allocate program object in stbgl_link_program\", NULL, NULL);\n      return 0;\n   }\n\n   // attach\n\n   if (vertex_shader)\n      stbglAttachShader(prog, vertex_shader);\n   if (fragment_shader)\n      stbglAttachShader(prog, fragment_shader);\n\n   // attribute binds\n\n   if (binds) {\n      int i;\n      // if num_binds is negative, then it is NULL terminated\n      if (num_binds < 0)\n         for (num_binds=0; binds[num_binds]; ++num_binds)\n            ;\n      for (i=0; i < num_binds; ++i)\n         if (binds[i] && binds[i][0]) // empty binds can be NULL or \"\"\n            stbglBindAttribLocation(prog, i, binds[i]);\n   }\n\n   // link\n\n   stbglLinkProgram(prog);\n\n   // detach\n\n   if (vertex_shader)\n      stbglDetachShader(prog, vertex_shader);\n   if (fragment_shader)\n      stbglDetachShader(prog, fragment_shader);\n\n   // errors\n\n   stbglGetProgramStatus(prog, &result);\n   if (result)\n      return prog;\n\n   stb_glprog_error(error, error_buflen, \"Link error: \", NULL, NULL);\n   len = strlen(error);\n   if (len < error_buflen)\n      stbglGetProgramInfoLog(prog, error_buflen-len, NULL, error+len);\n\n   stbglDeleteProgram(prog);\n   return 0;   \n}\n\nSTB_GLPROG_DECLARE GLuint stbgl_create_program(char const **vertex_source, char const **frag_source, char const **binds, char *error, int error_buflen)\n{\n   GLuint vertex, fragment, prog=0;\n   vertex = stbgl_compile_shader(STBGL_VERTEX_SHADER, vertex_source, -1, error, error_buflen);\n   if (vertex) {\n      fragment = stbgl_compile_shader(STBGL_FRAGMENT_SHADER, frag_source, -1, error, error_buflen);\n      if (fragment)\n         prog = stbgl_link_program(vertex, fragment, binds, -1, error, error_buflen);\n      if (fragment)\n         stbglDeleteShader(fragment);\n      stbglDeleteShader(vertex);\n   }\n   return prog;\n}\n\nSTB_GLPROG_DECLARE void stbgl_delete_shader(GLuint shader)\n{\n   stbglDeleteShader(shader);\n}\n\nSTB_GLPROG_DECLARE void stgbl_delete_program(GLuint program)\n{\n   stbglDeleteProgram(program);\n}\n\nGLint stbgl_find_uniform(GLuint prog, char *uniform)\n{\n   return stbglGetUniformLocation(prog, uniform);\n}\n\nSTB_GLPROG_DECLARE void stbgl_find_uniforms(GLuint prog, GLint *locations, char const **uniforms, int num_uniforms)\n{\n   int i;\n   if (num_uniforms < 0)\n      num_uniforms = 999999;\n   for (i=0; i < num_uniforms && uniforms[i]; ++i)\n      locations[i] = stbglGetUniformLocation(prog, uniforms[i]);\n}\n\nSTB_GLPROG_DECLARE void stbglUseProgram(GLuint program)\n{\n   stbgl_UseProgram(program);\n}\n\n#ifdef STB_GLPROG_ARB\n#define STBGL_ARBIFY(name)   name##ARB\n#else\n#define STBGL_ARBIFY(name)   name\n#endif\n\nSTB_GLPROG_DECLARE void stbglVertexAttribPointer(GLuint index,  GLint size,  GLenum type,  GLboolean normalized,  GLsizei stride,  const GLvoid * pointer)\n{\n   STBGL_ARBIFY(glVertexAttribPointer)(index, size, type, normalized, stride, pointer);\n}\n\nSTB_GLPROG_DECLARE void stbglEnableVertexAttribArray (GLuint index) { STBGL_ARBIFY(glEnableVertexAttribArray )(index); }\nSTB_GLPROG_DECLARE void stbglDisableVertexAttribArray(GLuint index) { STBGL_ARBIFY(glDisableVertexAttribArray)(index); }\n\nSTB_GLPROG_DECLARE void stbglUniform1fv(GLint loc, GLsizei count, const GLfloat *v) { STBGL_ARBIFY(glUniform1fv)(loc,count,v); }\nSTB_GLPROG_DECLARE void stbglUniform2fv(GLint loc, GLsizei count, const GLfloat *v) { STBGL_ARBIFY(glUniform2fv)(loc,count,v); }\nSTB_GLPROG_DECLARE void stbglUniform3fv(GLint loc, GLsizei count, const GLfloat *v) { STBGL_ARBIFY(glUniform3fv)(loc,count,v); }\nSTB_GLPROG_DECLARE void stbglUniform4fv(GLint loc, GLsizei count, const GLfloat *v) { STBGL_ARBIFY(glUniform4fv)(loc,count,v); }\n\nSTB_GLPROG_DECLARE void stbglUniform1iv(GLint loc, GLsizei count, const GLint   *v) { STBGL_ARBIFY(glUniform1iv)(loc,count,v); }\nSTB_GLPROG_DECLARE void stbglUniform2iv(GLint loc, GLsizei count, const GLint   *v) { STBGL_ARBIFY(glUniform2iv)(loc,count,v); }\nSTB_GLPROG_DECLARE void stbglUniform3iv(GLint loc, GLsizei count, const GLint   *v) { STBGL_ARBIFY(glUniform3iv)(loc,count,v); }\nSTB_GLPROG_DECLARE void stbglUniform4iv(GLint loc, GLsizei count, const GLint   *v) { STBGL_ARBIFY(glUniform4iv)(loc,count,v); }\n\nSTB_GLPROG_DECLARE void stbglUniform1f(GLint loc, float v0)\n    { STBGL_ARBIFY(glUniform1f)(loc,v0); }\nSTB_GLPROG_DECLARE void stbglUniform2f(GLint loc, float v0, float v1)\n    { STBGL_ARBIFY(glUniform2f)(loc,v0,v1); }\nSTB_GLPROG_DECLARE void stbglUniform3f(GLint loc, float v0, float v1, float v2)\n    { STBGL_ARBIFY(glUniform3f)(loc,v0,v1,v2); }\nSTB_GLPROG_DECLARE void stbglUniform4f(GLint loc, float v0, float v1, float v2, float v3)\n    { STBGL_ARBIFY(glUniform4f)(loc,v0,v1,v2,v3); }\n\nSTB_GLPROG_DECLARE void stbglUniform1i(GLint loc, GLint v0)\n    { STBGL_ARBIFY(glUniform1i)(loc,v0); }\nSTB_GLPROG_DECLARE void stbglUniform2i(GLint loc, GLint v0, GLint v1)\n    { STBGL_ARBIFY(glUniform2i)(loc,v0,v1); }\nSTB_GLPROG_DECLARE void stbglUniform3i(GLint loc, GLint v0, GLint v1, GLint v2)\n    { STBGL_ARBIFY(glUniform3i)(loc,v0,v1,v2); }\nSTB_GLPROG_DECLARE void stbglUniform4i(GLint loc, GLint v0, GLint v1, GLint v2, GLint v3)\n    { STBGL_ARBIFY(glUniform4i)(loc,v0,v1,v2,v3); }\n\n#endif\n"
  },
  {
    "path": "tests/caveview/win32/SDL_windows_main.c",
    "content": "/*\n    SDL_windows_main.c, placed in the public domain by Sam Lantinga  4/13/98\n\n    The WinMain function -- calls your program's main() function\n*/\n#include \"SDL_config.h\"\n\n#ifdef __WIN32__\n\n//#include \"../../core/windows/SDL_windows.h\"\n\n/* Include this so we define UNICODE properly */\n#if defined(__WIN32__)\n#define WIN32_LEAN_AND_MEAN\n#define STRICT\n#ifndef UNICODE\n#define UNICODE 1\n#endif\n#undef _WIN32_WINNT\n#define _WIN32_WINNT  0x501   /* Need 0x410 for AlphaBlend() and 0x500 for EnumDisplayDevices(), 0x501 for raw input */\n#endif\n\n#include <windows.h>\n\n/* Routines to convert from UTF8 to native Windows text */\n#if UNICODE\n#define WIN_StringToUTF8(S) SDL_iconv_string(\"UTF-8\", \"UTF-16LE\", (char *)(S), (SDL_wcslen(S)+1)*sizeof(WCHAR))\n#define WIN_UTF8ToString(S) (WCHAR *)SDL_iconv_string(\"UTF-16LE\", \"UTF-8\", (char *)(S), SDL_strlen(S)+1)\n#else\n/* !!! FIXME: UTF8ToString() can just be a SDL_strdup() here. */\n#define WIN_StringToUTF8(S) SDL_iconv_string(\"UTF-8\", \"ASCII\", (char *)(S), (SDL_strlen(S)+1))\n#define WIN_UTF8ToString(S) SDL_iconv_string(\"ASCII\", \"UTF-8\", (char *)(S), SDL_strlen(S)+1)\n#endif\n\n/* Sets an error message based on a given HRESULT */\nextern int WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr);\n\n/* Sets an error message based on GetLastError(). Always return -1. */\nextern int WIN_SetError(const char *prefix);\n\n/* Wrap up the oddities of CoInitialize() into a common function. */\nextern HRESULT WIN_CoInitialize(void);\nextern void WIN_CoUninitialize(void);\n\n/* Returns SDL_TRUE if we're running on Windows Vista and newer */\nextern BOOL WIN_IsWindowsVistaOrGreater();\n\n#include <stdio.h>\n#include <stdlib.h>\n\n/* Include the SDL main definition header */\n#include \"SDL.h\"\n#include \"SDL_main.h\"\n\n#ifdef main\n#  undef main\n#endif /* main */\n\nstatic void\nUnEscapeQuotes(char *arg)\n{\n    char *last = NULL;\n\n    while (*arg) {\n        if (*arg == '\"' && (last != NULL && *last == '\\\\')) {\n            char *c_curr = arg;\n            char *c_last = last;\n\n            while (*c_curr) {\n                *c_last = *c_curr;\n                c_last = c_curr;\n                c_curr++;\n            }\n            *c_last = '\\0';\n        }\n        last = arg;\n        arg++;\n    }\n}\n\n/* Parse a command line buffer into arguments */\nstatic int\nParseCommandLine(char *cmdline, char **argv)\n{\n    char *bufp;\n    char *lastp = NULL;\n    int argc, last_argc;\n\n    argc = last_argc = 0;\n    for (bufp = cmdline; *bufp;) {\n        /* Skip leading whitespace */\n        while (SDL_isspace(*bufp)) {\n            ++bufp;\n        }\n        /* Skip over argument */\n        if (*bufp == '\"') {\n            ++bufp;\n            if (*bufp) {\n                if (argv) {\n                    argv[argc] = bufp;\n                }\n                ++argc;\n            }\n            /* Skip over word */\n            lastp = bufp;\n            while (*bufp && (*bufp != '\"' || *lastp == '\\\\')) {\n                lastp = bufp;\n                ++bufp;\n            }\n        } else {\n            if (*bufp) {\n                if (argv) {\n                    argv[argc] = bufp;\n                }\n                ++argc;\n            }\n            /* Skip over word */\n            while (*bufp && !SDL_isspace(*bufp)) {\n                ++bufp;\n            }\n        }\n        if (*bufp) {\n            if (argv) {\n                *bufp = '\\0';\n            }\n            ++bufp;\n        }\n\n        /* Strip out \\ from \\\" sequences */\n        if (argv && last_argc != argc) {\n            UnEscapeQuotes(argv[last_argc]);\n        }\n        last_argc = argc;\n    }\n    if (argv) {\n        argv[argc] = NULL;\n    }\n    return (argc);\n}\n\n/* Show an error message */\nstatic void\nShowError(const char *title, const char *message)\n{\n/* If USE_MESSAGEBOX is defined, you need to link with user32.lib */\n#ifdef USE_MESSAGEBOX\n    MessageBox(NULL, message, title, MB_ICONEXCLAMATION | MB_OK);\n#else\n    fprintf(stderr, \"%s: %s\\n\", title, message);\n#endif\n}\n\n/* Pop up an out of memory message, returns to Windows */\nstatic BOOL\nOutOfMemory(void)\n{\n    ShowError(\"Fatal Error\", \"Out of memory - aborting\");\n    return FALSE;\n}\n\n#if defined(_MSC_VER)\n/* The VC++ compiler needs main defined */\n#define console_main main\n#endif\n\n/* This is where execution begins [console apps] */\nint\nconsole_main(int argc, char *argv[])\n{\n    int status;\n\n    SDL_SetMainReady();\n\n    /* Run the application main() code */\n    status = SDL_main(argc, argv);\n\n    /* Exit cleanly, calling atexit() functions */\n    exit(status);\n\n    /* Hush little compiler, don't you cry... */\n    return 0;\n}\n\n/* This is where execution begins [windowed apps] */\nint WINAPI\nWinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)\n{\n    char **argv;\n    int argc;\n    char *cmdline;\n\n    /* Grab the command line */\n    TCHAR *text = GetCommandLine();\n#if UNICODE\n    cmdline = SDL_iconv_string(\"UTF-8\", \"UCS-2-INTERNAL\", (char *)(text), (SDL_wcslen(text)+1)*sizeof(WCHAR));\n#else\n    cmdline = SDL_strdup(text);\n#endif\n    if (cmdline == NULL) {\n        return OutOfMemory();\n    }\n\n    /* Parse it into argv and argc */\n    argc = ParseCommandLine(cmdline, NULL);\n    argv = SDL_stack_alloc(char *, argc + 1);\n    if (argv == NULL) {\n        return OutOfMemory();\n    }\n    ParseCommandLine(cmdline, argv);\n\n    /* Run the main program */\n    console_main(argc, argv);\n\n    SDL_stack_free(argv);\n\n    SDL_free(cmdline);\n\n    /* Hush little compiler, don't you cry... */\n    return 0;\n}\n\n#endif /* __WIN32__ */\n\n/* vi: set ts=4 sw=4 expandtab: */\n"
  },
  {
    "path": "tests/fuzz_main.c",
    "content": "#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n/* fuzz target entry point, works without libFuzzer */\n\nint LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);\n\nint main(int argc, char **argv)\n{\n    FILE *f;\n    char *buf = NULL;\n    long siz_buf;\n\n    if(argc < 2)\n    {\n        fprintf(stderr, \"no input file\\n\");\n        goto err;\n    }\n\n    f = fopen(argv[1], \"rb\");\n    if(f == NULL)\n    {\n        fprintf(stderr, \"error opening input file %s\\n\", argv[1]);\n        goto err;\n    }\n\n    fseek(f, 0, SEEK_END);\n\n    siz_buf = ftell(f);\n    rewind(f);\n\n    if(siz_buf < 1) goto err;\n\n    buf = (char*)malloc((size_t)siz_buf);\n    if(buf == NULL)\n    {\n        fprintf(stderr, \"malloc() failed\\n\");\n        goto err;\n    }\n\n    if(fread(buf, (size_t)siz_buf, 1, f) != 1)\n    {\n        fprintf(stderr, \"fread() failed\\n\");\n        goto err;\n    }\n\n    (void)LLVMFuzzerTestOneInput((uint8_t*)buf, (size_t)siz_buf);\n\nerr:\n    free(buf);\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/grid_reachability.c",
    "content": "#define STB_CONNECTED_COMPONENTS_IMPLEMENTATION\n#define STBCC_GRID_COUNT_X_LOG2  10\n#define STBCC_GRID_COUNT_Y_LOG2  10\n#include \"stb_connected_components.h\"\n\n#ifdef GRID_TEST\n\n#include <windows.h>\n#include <stdio.h>\n#include <direct.h>\n\n//#define STB_DEFINE\n#include \"stb.h\"\n\n//#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n//#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\ntypedef struct\n{\n   uint16 x,y;\n} point;\n\npoint leader[1024][1024];\nuint32 color[1024][1024];\n\npoint find(int x, int y)\n{\n   point p,q;\n   p = leader[y][x];\n   if (p.x == x && p.y == y)\n      return p;\n   q = find(p.x, p.y);\n   leader[y][x] = q;\n   return q;\n}\n\nvoid onion(int x1, int y1, int x2, int y2)\n{\n   point p = find(x1,y1);\n   point q = find(x2,y2);\n\n   if (p.x == q.x && p.y == q.y)\n      return;\n\n   leader[p.y][p.x] = q;\n}\n\nvoid reference(uint8 *map, int w, int h)\n{\n   int i,j;\n\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i) {\n         leader[j][i].x = i;\n         leader[j][i].y = j;\n      }\n   }\n         \n   for (j=1; j < h-1; ++j) {\n      for (i=1; i < w-1; ++i) {\n         if (map[j*w+i] == 255) {\n            if (map[(j+1)*w+i] == 255) onion(i,j, i,j+1);\n            if (map[(j)*w+i+1] == 255) onion(i,j, i+1,j);\n         }\n      }\n   }\n\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i) {\n         uint32 c = 0xff000000;\n         if (leader[j][i].x == i && leader[j][i].y == j) {\n            if (map[j*w+i] == 255)\n               c = stb_randLCG() | 0xff404040;\n         }\n         color[j][i] = c;\n      }\n   }\n\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i) {\n         if (leader[j][i].x != i || leader[j][i].y != j) {\n            point p = find(i,j);\n            color[j][i] = color[p.y][p.x];\n         }\n      }\n   }\n}\n\nvoid write_map(stbcc_grid *g, int w, int h, char *filename)\n{\n   int i,j;\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i) {\n         unsigned int c;\n         c = stbcc_get_unique_id(g,i,j);\n         c = stb_rehash_improved(c)&0xffffff;\n         if (c == STBCC_NULL_UNIQUE_ID)\n            c = 0xff000000;\n         else\n            c = (~c)^0x555555;\n         if (i % 32 == 0 || j %32 == 0) {\n            int r = (c >> 16) & 255;\n            int g = (c >> 8) & 255;\n            int b = c & 255;\n            r = (r+130)/2;\n            g = (g+130)/2;\n            b = (b+130)/2;\n            c = 0xff000000 + (r<<16) + (g<<8) + b;\n         }\n         color[j][i] = c;\n      }\n   }\n   stbi_write_png(filename, w, h, 4, color, 4*w);\n}\n\nvoid test_connected(stbcc_grid *g)\n{\n   int n = stbcc_query_grid_node_connection(g, 512, 90, 512, 871);\n   //printf(\"%d \", n);\n}\n\nstatic char *message;\nLARGE_INTEGER start;\n\nvoid start_timer(char *s)\n{\n   message = s;\n   QueryPerformanceCounter(&start);\n}\n\nvoid end_timer(void)\n{\n   LARGE_INTEGER end, freq;\n   double tm;\n\n   QueryPerformanceCounter(&end);\n   QueryPerformanceFrequency(&freq);\n\n   tm = (end.QuadPart - start.QuadPart) / (double) freq.QuadPart;\n   printf(\"%6.4lf ms: %s\\n\", tm * 1000, message);\n}\n\nextern void quicktest(void);\n\nint loc[5000][2];\nint main(int argc, char **argv)\n{\n   stbcc_grid *g;\n\n   int w,h, i,j,k=0, count=0, r;\n   uint8 *map = stbi_load(\"data/map_03.png\", &w, &h, 0, 1);\n\n   assert(map);\n   quicktest();\n\n   for (j=0; j < h; ++j)\n      for (i=0; i < w; ++i)\n         map[j*w+i] = ~map[j*w+i];\n\n   for (i=0; i < w; ++i)\n      for (j=0; j < h; ++j)\n         //map[j*w+i] = (((i+1) ^ (j+1)) >> 1) & 1 ? 255 : 0;\n         map[j*w+i] = stb_max(abs(i-w/2),abs(j-h/2)) & 1 ? 255 : 0;\n         //map[j*w+i] = (((i ^ j) >> 5) ^ (i ^ j)) & 1 ? 255 : 0;\n         //map[j*w+i] = stb_rand() & 1 ? 255 : 0;\n\n   #if 1\n   for (i=0; i < 100000; ++i)\n      map[(stb_rand()%h)*w + stb_rand()%w] ^= 255;\n   #endif\n            \n   _mkdir(\"tests/output/stbcc\");\n\n   stbi_write_png(\"tests/output/stbcc/reference.png\", w, h, 1, map, 0);\n\n   //reference(map, w, h);\n\n   g = malloc(stbcc_grid_sizeof());\n   printf(\"Size: %d\\n\", stbcc_grid_sizeof());\n\n#if 0\n   memset(map, 0, w*h);\n   stbcc_init_grid(g, map, w, h);\n   {\n      int n;\n      char **s = stb_stringfile(\"c:/x/clockwork_update.txt\", &n);\n      write_map(g, w, h, \"tests/output/stbcc/base.png\");\n      for (i=1; i < n; i += 1) {\n         int x,y,t;\n         sscanf(s[i], \"%d %d %d\", &x, &y, &t);\n         if (i == 571678)\n            write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/clockwork_good.png\", i));\n         stbcc_update_grid(g, x, y, t);\n         if (i == 571678)\n            write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/clockwork_bad.png\", i));\n         //if (i > 571648 && i <= 571712)\n            //write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/clockwork_%06d.png\", i));\n      }\n      write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/clockwork_%06d.png\", i-1));\n   }\n   return 0;\n#endif\n\n\n   start_timer(\"init\");\n   stbcc_init_grid(g, map, w, h);\n   end_timer();\n   //g = stb_file(\"c:/x/clockwork_path.bin\", 0);\n   write_map(g, w, h, \"tests/output/stbcc/base.png\");\n\n   for (i=0; i < 5000;) {\n      loc[i][0] = stb_rand() % w;\n      loc[i][1] = stb_rand() % h;\n      if (stbcc_query_grid_open(g, loc[i][0], loc[i][1]))\n         ++i;\n   }\n\n   r = 0;\n   start_timer(\"reachable\");\n   for (i=0; i < 2000; ++i) {\n      for (j=0; j < 2000; ++j) {\n         int x1 = loc[i][0], y1 = loc[i][1];\n         int x2 = loc[2000+j][0], y2 = loc[2000+j][1];\n         r += stbcc_query_grid_node_connection(g, x1,y1, x2,y2);\n      }\n   }\n   end_timer();\n   printf(\"%d reachable\\n\", r);\n\n   printf(\"Cluster size: %d,%d\\n\", STBCC__CLUSTER_SIZE_X, STBCC__CLUSTER_SIZE_Y);\n\n   #if 1\n   for (j=0; j < 10; ++j) {\n      for (i=0; i < 5000; ++i) {\n         loc[i][0] = stb_rand() % w;\n         loc[i][1] = stb_rand() % h;\n      }\n      start_timer(\"updating 2500\");\n      for (i=0; i < 2500; ++i) {\n         if (stbcc_query_grid_open(g, loc[i][0], loc[i][1]))\n            stbcc_update_grid(g, loc[i][0], loc[i][1], 1);\n         else\n            stbcc_update_grid(g, loc[i][0], loc[i][1], 0);\n      }\n      end_timer();\n      write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/update_random_%d.png\", j*i));\n   }\n   #endif\n\n   #if 0\n   start_timer(\"removing\");\n   count = 0;\n   for (i=0; i < 1800; ++i) {\n      int x,y,a,b;\n      x = stb_rand() % (w-32);\n      y = stb_rand() % (h-32);\n      \n      if (i & 1) {\n         for (a=0; a < 32; ++a)\n            for (b=0; b < 1; ++b)\n               if (stbcc_query_grid_open(g, x+a, y+b)) {\n                  stbcc_update_grid(g, x+a, y+b, 1);\n                  ++count;\n               }\n      } else {\n         for (a=0; a < 1; ++a)\n            for (b=0; b < 32; ++b)\n               if (stbcc_query_grid_open(g, x+a, y+b)) {\n                  stbcc_update_grid(g, x+a, y+b, 1);\n                  ++count;\n               }\n      }\n\n      //if (i % 100 == 0) write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/open_random_%d.png\", i+1));\n   }\n   end_timer();\n   printf(\"Removed %d grid spaces\\n\", count);\n   write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/open_random_%d.png\", i));\n\n\n   r = 0;\n   start_timer(\"reachable\");\n   for (i=0; i < 1000; ++i) {\n      for (j=0; j < 1000; ++j) {\n         int x1 = loc[i][0], y1 = loc[i][1];\n         int x2 = loc[j][0], y2 = loc[j][1];\n         r += stbcc_query_grid_node_connection(g, x1,y1, x2,y2);\n      }\n   }\n   end_timer();\n   printf(\"%d reachable\\n\", r);\n\n   start_timer(\"adding\");\n   count = 0;\n   for (i=0; i < 1800; ++i) {\n      int x,y,a,b;\n      x = stb_rand() % (w-32);\n      y = stb_rand() % (h-32);\n\n      if (i & 1) {\n         for (a=0; a < 32; ++a)\n            for (b=0; b < 1; ++b)\n               if (!stbcc_query_grid_open(g, x+a, y+b)) {\n                  stbcc_update_grid(g, x+a, y+b, 0);\n                  ++count;\n               }\n      } else {\n         for (a=0; a < 1; ++a)\n            for (b=0; b < 32; ++b)\n               if (!stbcc_query_grid_open(g, x+a, y+b)) {\n                  stbcc_update_grid(g, x+a, y+b, 0);\n                  ++count;\n               }\n      }\n\n      //if (i % 100 == 0) write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/close_random_%d.png\", i+1));\n   }\n   end_timer();\n   write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/close_random_%d.png\", i));\n   printf(\"Added %d grid spaces\\n\", count);\n   #endif\n\n\n   #if 0  // for map_02.png\n   start_timer(\"process\");\n   for (k=0; k < 20; ++k) {\n      for (j=0; j < h; ++j) {\n         int any=0;\n         for (i=0; i < w; ++i) {\n            if (map[j*w+i] > 10 && map[j*w+i] < 250) {\n               //start_timer(stb_sprintf(\"open %d,%d\", i,j));\n               stbcc_update_grid(g, i, j, 0);\n               test_connected(g);\n               //end_timer();\n               any = 1;\n            }\n         }\n         if (any) write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/open_row_%04d.png\", j));\n      }\n\n      for (j=0; j < h; ++j) {\n         int any=0;\n         for (i=0; i < w; ++i) {\n            if (map[j*w+i] > 10 && map[j*w+i] < 250) {\n               //start_timer(stb_sprintf(\"close %d,%d\", i,j));\n               stbcc_update_grid(g, i, j, 1);\n               test_connected(g);\n               //end_timer();\n               any = 1;\n            }\n         }\n         if (any) write_map(g, w, h, stb_sprintf(\"tests/output/stbcc/close_row_%04d.png\", j));\n      }\n   }\n   end_timer();\n   #endif\n\n   return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/herringbone.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"herringbone\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=herringbone - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"herringbone.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"herringbone.mak\" CFG=\"herringbone - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"herringbone - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"herringbone - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"herringbone - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"herringbone - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"herringbone___Win32_Debug\"\n# PROP BASE Intermediate_Dir \"herringbone___Win32_Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"herringbone - Win32 Release\"\n# Name \"herringbone - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\herringbone_generator.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_herringbone_wang_tile.h\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/herringbone_generator.c",
    "content": "#define STB_HERRINGBONE_WANG_TILE_IMPLEMENTATION\n#include \"stb_herringbone_wang_tile.h\"\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n//  e 12 1 1 1 1 1 1 4 4\n\nint main(int argc, char **argv)\n{\n   stbhw_config c = { 0 };\n   int w,h, num_colors,i;\n   unsigned char *data;\n\n   if (argc == 1)  goto usage;\n   if (argc  < 3)  goto error;\n\n   switch (argv[2][0]) {\n      case 'c':\n         if (argc <  8 || argc > 10)\n            goto error;\n         num_colors = 4;\n         c.is_corner = 1;\n         break;\n\n      case 'e':\n         if (argc < 10 || argc > 12)\n            goto error;\n         num_colors = 6;\n         c.is_corner = 0;\n         break;\n\n      default:\n         goto error;\n   }\n\n   c.short_side_len = atoi(argv[3]);\n   for (i=0; i < num_colors; ++i)\n      c.num_color[i] = atoi(argv[4+i]);\n\n   c.num_vary_x = 1;\n   c.num_vary_y = 1;\n\n   if (argc > 4+i)\n      c.num_vary_x = atoi(argv[4+i]);\n   if (argc > 5+i)\n      c.num_vary_y = atoi(argv[5+i]);\n\n   stbhw_get_template_size(&c, &w, &h);\n\n   data = (unsigned char *) malloc(w*h*3);\n\n   if (stbhw_make_template(&c, data, w, h, w*3))\n      stbi_write_png(argv[1], w, h, 3, data, w*3);\n   else\n      fprintf(stderr, \"Error: %s\\n\", stbhw_get_last_error());\n   return 0;\n\n error:\n   fputs(\"Invalid command-line arguments\\n\\n\", stderr);\n usage:\n   fputs(\"Usage (see source for corner & edge type definitions):\\n\\n\", stderr);\n   fputs(\"herringbone_generator {outfile} c {sidelen} {c0} {c1} {c2} {c3} [{vx} {vy}]\\n\"\n         \"     {outfile}  -- filename that template will be written to as PNG\\n\"\n         \"     {sidelen}  -- length of short side of rectangle in pixels\\n\"\n         \"     {c0}       -- number of colors for corner type 0\\n\"\n         \"     {c1}       -- number of colors for corner type 1\\n\"\n         \"     {c2}       -- number of colors for corner type 2\\n\"\n         \"     {c3}       -- number of colors for corner type 3\\n\"\n         \"     {vx}       -- number of color-duplicating variations horizontally in template\\n\"\n         \"     {vy}       -- number of color-duplicating variations vertically in template\\n\"\n         \"\\n\"\n         , stderr);\n   fputs(\"herringbone_generator {outfile} e {sidelen} {e0} {e1} {e2} {e3} {e4} {e5} [{vx} {vy}]\\n\"\n         \"     {outfile}  -- filename that template will be written to as PNG\\n\"\n         \"     {sidelen}  -- length of short side of rectangle in pixels\\n\"\n         \"     {e0}       -- number of colors for edge type 0\\n\"\n         \"     {e1}       -- number of colors for edge type 1\\n\"\n         \"     {e2}       -- number of colors for edge type 2\\n\"\n         \"     {e3}       -- number of colors for edge type 3\\n\"\n         \"     {e4}       -- number of colors for edge type 4\\n\"\n         \"     {e5}       -- number of colors for edge type 5\\n\"\n         \"     {vx}       -- number of color-duplicating variations horizontally in template\\n\"\n         \"     {vy}       -- number of color-duplicating variations vertically in template\\n\"\n         , stderr);\n   return 1;\n}\n"
  },
  {
    "path": "tests/herringbone_map.c",
    "content": "#include <stdio.h>\n\n#define STB_HBWANG_MAX_X  500\n#define STB_HBWANG_MAX_Y  500\n\n#define STB_HERRINGBONE_WANG_TILE_IMPLEMENTATION\n#include \"stb_herringbone_wang_tile.h\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\nint main(int argc, char **argv)\n{\n   if (argc < 5) {\n      fprintf(stderr, \"Usage: herringbone_map {inputfile} {output-width} {output-height} {outputfile}\\n\");\n      return 1;\n   } else {\n      char *filename = argv[1];\n      int out_w = atoi(argv[2]);\n      int out_h = atoi(argv[3]);\n      char *outfile = argv[4];\n\n      unsigned char *pixels, *out_pixels;\n      stbhw_tileset ts;\n      int w,h;\n\n      pixels = stbi_load(filename, &w, &h, 0, 3);\n      if (pixels == 0) {\n         fprintf(stderr, \"Couldn't open input file '%s'\\n\", filename);\n\t\t\texit(1);\n      }\n\n      if (!stbhw_build_tileset_from_image(&ts, pixels, w*3, w, h)) {\n         fprintf(stderr, \"Error: %s\\n\", stbhw_get_last_error());\n         return 1;\n      }\n\n      free(pixels);\n\n      #ifdef DEBUG_OUTPUT\n      {\n         int i,j,k;\n         // add blue borders to top-left edges of the tiles\n         int hstride = (ts.short_side_len*2)*3;\n         int vstride = (ts.short_side_len  )*3;\n         for (i=0; i < ts.num_h_tiles; ++i) {\n            unsigned char *pix = ts.h_tiles[i]->pixels;\n            for (j=0; j < ts.short_side_len*2; ++j)\n               for (k=0; k < 3; ++k)\n                  pix[j*3+k] = (pix[j*3+k]*0.5+100+k*75)/1.5;\n            for (j=1; j < ts.short_side_len; ++j)\n               for (k=0; k < 3; ++k)\n                  pix[j*hstride+k] = (pix[j*hstride+k]*0.5+100+k*75)/1.5;\n         }\n         for (i=0; i < ts.num_v_tiles; ++i) {\n            unsigned char *pix = ts.v_tiles[i]->pixels;\n            for (j=0; j < ts.short_side_len; ++j)\n               for (k=0; k < 3; ++k)\n                  pix[j*3+k] = (pix[j*3+k]*0.5+100+k*75)/1.5;\n            for (j=1; j < ts.short_side_len*2; ++j)\n               for (k=0; k < 3; ++k)\n                  pix[j*vstride+k] = (pix[j*vstride+k]*0.5+100+k*75)/1.5;\n         }\n      }\n      #endif\n\n      out_pixels = malloc(out_w * out_h * 3);\n\n      if (!stbhw_generate_image(&ts, NULL, out_pixels, out_w*3, out_w, out_h)) {\n         fprintf(stderr, \"Error: %s\\n\", stbhw_get_last_error());\n         return 1;\n      }\n\n      stbi_write_png(argv[4], out_w, out_h, 3, out_pixels, out_w*3);\n      free(out_pixels);\n\n      stbhw_free_tileset(&ts);\n      return 0;\n   }\n}"
  },
  {
    "path": "tests/herringbone_map.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"herringbone_map\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=herringbone_map - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"herringbone_map.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"herringbone_map.mak\" CFG=\"herringbone_map - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"herringbone_map - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"herringbone_map - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"herringbone_map - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"herringbone_map - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"herringbone_map___Win32_Debug\"\n# PROP BASE Intermediate_Dir \"herringbone_map___Win32_Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"herringbone_map - Win32 Release\"\n# Name \"herringbone_map - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\herringbone_map.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_herringbone_wang_tile.h\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/image_test.c",
    "content": "#define STBI_WINDOWS_UTF8\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#define STB_DEFINE\n#include \"stb.h\"\n\n//#define PNGSUITE_PRIMARY\n\n#if 0\nvoid test_ycbcr(void)\n{\n   STBI_SIMD_ALIGN(unsigned char, y[256]);\n   STBI_SIMD_ALIGN(unsigned char, cb[256]);\n   STBI_SIMD_ALIGN(unsigned char, cr[256]);\n   STBI_SIMD_ALIGN(unsigned char, out1[256][4]);\n   STBI_SIMD_ALIGN(unsigned char, out2[256][4]);\n\n   int i,j,k;\n   int count = 0, bigcount=0, total=0;\n\n   for (i=0; i < 256; ++i) {\n      for (j=0; j < 256; ++j) {\n         for (k=0; k < 256; ++k) {\n            y [k] = k;\n            cb[k] = j;\n            cr[k] = i;\n         }\n         stbi__YCbCr_to_RGB_row(out1[0], y, cb, cr, 256, 4);\n         stbi__YCbCr_to_RGB_sse2(out2[0], y, cb, cr, 256, 4);\n         for (k=0; k < 256; ++k) {\n            // inaccurate proxy for values outside of RGB cube\n            if (out1[k][0] == 0 || out1[k][1] == 0 || out1[k][2] == 0 || out1[k][0] == 255 || out1[k][1] == 255 || out1[k][2] == 255)\n               continue;\n            ++total;\n            if (out1[k][0] != out2[k][0] || out1[k][1] != out2[k][1] || out1[k][2] != out2[k][2]) {\n               int dist1 = abs(out1[k][0] - out2[k][0]);\n               int dist2 = abs(out1[k][1] - out2[k][1]);\n               int dist3 = abs(out1[k][2] - out2[k][2]);\n               ++count;\n               if (out1[k][1] > out2[k][1])\n                  ++bigcount;\n            }\n         }\n      }\n      printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n   }\n   printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n   static char dummy[1024];\n   if (len > 1024) len = 1024;\n   memcpy(dummy, data, len);\n}\n\nextern void image_write_test(void);\n\nint main(int argc, char **argv)\n{\n   int w,h;\n   //test_ycbcr();\n\n   image_write_test();\n\n   #if 0\n   // test hdr asserts\n   for (h=0; h < 100; h += 2)\n      for (w=0; w < 200; ++w)\n         hdr_data[h][w][0] = (float) rand(),\n         hdr_data[h][w][1] = (float) rand(),\n         hdr_data[h][w][2] = (float) rand();\n\n   stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n   #endif\n\n   if (argc > 1) {\n      int i, n;\n\n      for (i=1; i < argc; ++i) {\n         int res;\n         int w2,h2,n2;\n         unsigned char *data;\n         printf(\"%s\\n\", argv[i]);\n         res = stbi_info(argv[i], &w2, &h2, &n2);\n         data = stbi_load(argv[i], &w, &h, &n, 0); if (data) free(data); else printf(\"Failed &n\\n\");\n         data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n         data = stbi_load(argv[i], &w, &h,  0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n         data = stbi_load(argv[i], &w, &h,  0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n         data = stbi_load(argv[i], &w, &h,  0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n         data = stbi_load(argv[i], &w, &h, &n, 4);\n         assert(data);\n         assert(w == w2 && h == h2 && n == n2);\n         assert(res);\n         if (data) {\n            char fname[512];\n            stb_splitpath(fname, argv[i], STB_FILE);\n            stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n            stbi_write_bmp(stb_sprintf(\"output/%s.bmp\", fname), w, h, 4, data);\n            stbi_write_tga(stb_sprintf(\"output/%s.tga\", fname), w, h, 4, data);\n            stbi_write_png_to_func(dummy_write,0, w, h, 4, data, w*4);\n            stbi_write_bmp_to_func(dummy_write,0, w, h, 4, data);\n            stbi_write_tga_to_func(dummy_write,0, w, h, 4, data);\n            free(data);\n         } else\n            printf(\"FAILED 4\\n\");\n      }\n   } else {\n      int i;\n      #ifdef PNGSUITE_PRIMARY\n      char **files = stb_readdir_files(\"pngsuite/primary\");\n      #else\n      char **files = stb_readdir_files(\"images\");\n      #endif\n      for (i=0; i < stb_arr_len(files); ++i) {\n         int n;\n         char **failed = NULL;\n         unsigned char *data;\n         printf(\".\");\n         //printf(\"%s\\n\", files[i]);\n         data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n         data = stbi_load(files[i], &w, &h,  0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n         data = stbi_load(files[i], &w, &h,  0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");\n         data = stbi_load(files[i], &w, &h,  0, 3); if (data) free(data); else stb_arr_push(failed, \"3\");\n         data = stbi_load(files[i], &w, &h,  0, 4); if (data)           ; else stb_arr_push(failed, \"4\");\n         if (data) {\n            char fname[512];\n\n            #ifdef PNGSUITE_PRIMARY\n            int w2,h2;\n            unsigned char *data2;\n            stb_splitpath(fname, files[i], STB_FILE_EXT);\n            data2 = stbi_load(stb_sprintf(\"pngsuite/primary_check/%s\", fname), &w2, &h2, 0, 4);\n            if (!data2)\n               printf(\"FAILED: couldn't load 'pngsuite/primary_check/%s\\n\", fname);\n            else {\n               if (w != w2 || h != w2 || 0 != memcmp(data, data2, w*h*4)) {\n                  int x,y,c;\n                  if (w == w2 && h == h2)\n                     for (y=0; y < h; ++y)\n                        for (x=0; x < w; ++x)\n                           for (c=0; c < 4; ++c)\n                              assert(data[y*w*4+x*4+c] == data2[y*w*4+x*4+c]);\n                  printf(\"FAILED: %s loaded but didn't match PRIMARY_check 32-bit version\\n\", files[i]);\n               }\n               free(data2);\n            }\n            #else\n            stb_splitpath(fname, files[i], STB_FILE);\n            stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n            #endif\n            free(data);\n         }\n         if (failed) {\n            int j;\n            printf(\"FAILED: \");\n            for (j=0; j < stb_arr_len(failed); ++j)\n               printf(\"%s \", failed[j]);\n            printf(\" -- %s\\n\", files[i]);\n         }\n      }\n      printf(\"Tested %d files.\\n\", i);\n   }\n   return 0;\n}\n"
  },
  {
    "path": "tests/image_test.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"image_test\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=image_test - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"image_test.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"image_test.mak\" CFG=\"image_test - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"image_test - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"image_test - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"image_test - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /Zi /O2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"image_test - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\\image_test\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"image_test - Win32 Release\"\n# Name \"image_test - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\image_test.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\image_write_test.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_image.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_image_write.h\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/image_write_test.c",
    "content": "#ifdef __clang__\n#define STBIWDEF static inline\n#endif\n#define STB_IMAGE_WRITE_STATIC\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n// using an 'F' since it has no rotational symmetries, and 6x5\n// because it's a small, atypical size likely to trigger edge cases.\n//\n// conveniently, it's also small enough to fully fit inside a typical\n// directory listing thumbnail, which simplifies checking at a glance.\nstatic const char img6x5_template[] =\n   \".****.\"\n   \".*....\"\n   \".***..\"\n   \".*....\"\n   \".*....\";\n\nvoid image_write_test(void)\n{\n   // make a RGB version of the template image\n   // use red on blue to detect R<->B swaps\n   unsigned char img6x5_rgb[6*5*3];\n   float img6x5_rgbf[6*5*3];\n   int i;\n\n   for (i = 0; i < 6*5; i++) {\n      int on = img6x5_template[i] == '*';\n      img6x5_rgb[i*3 + 0] = on ? 255 : 0;\n      img6x5_rgb[i*3 + 1] = 0;\n      img6x5_rgb[i*3 + 2] = on ? 0 : 255;\n\n      img6x5_rgbf[i*3 + 0] = on ? 1.0f : 0.0f;\n      img6x5_rgbf[i*3 + 1] = 0.0f;\n      img6x5_rgbf[i*3 + 2] = on ? 0.0f : 1.0f;\n   }\n\n   stbi_write_png(\"output/wr6x5_regular.png\", 6, 5, 3, img6x5_rgb, 6*3);\n   stbi_write_bmp(\"output/wr6x5_regular.bmp\", 6, 5, 3, img6x5_rgb);\n   stbi_write_tga(\"output/wr6x5_regular.tga\", 6, 5, 3, img6x5_rgb);\n   stbi_write_jpg(\"output/wr6x5_regular.jpg\", 6, 5, 3, img6x5_rgb, 95);\n   stbi_write_hdr(\"output/wr6x5_regular.hdr\", 6, 5, 3, img6x5_rgbf);\n\n   stbi_flip_vertically_on_write(1);\n\n   stbi_write_png(\"output/wr6x5_flip.png\", 6, 5, 3, img6x5_rgb, 6*3);\n   stbi_write_bmp(\"output/wr6x5_flip.bmp\", 6, 5, 3, img6x5_rgb);\n   stbi_write_tga(\"output/wr6x5_flip.tga\", 6, 5, 3, img6x5_rgb);\n   stbi_write_jpg(\"output/wr6x5_flip.jpg\", 6, 5, 3, img6x5_rgb, 95);\n   stbi_write_hdr(\"output/wr6x5_flip.hdr\", 6, 5, 3, img6x5_rgbf);\n}\n\n#ifdef IWT_TEST\nint main(int argc, char **argv)\n{\n   image_write_test();\n   return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/ossfuzz.sh",
    "content": "#!/bin/bash -eu\n# This script is meant to be run by\n# https://github.com/google/oss-fuzz/blob/master/projects/stb/Dockerfile\n\n$CXX $CXXFLAGS -std=c++11 -I. -DSTBI_ONLY_PNG  \\\n    $SRC/stb/tests/stbi_read_fuzzer.c \\\n    -o $OUT/stb_png_read_fuzzer $LIB_FUZZING_ENGINE\n\n$CXX $CXXFLAGS -std=c++11 -I. \\\n    $SRC/stb/tests/stbi_read_fuzzer.c \\\n    -o $OUT/stbi_read_fuzzer $LIB_FUZZING_ENGINE\n\nfind $SRC/stb/tests/pngsuite -name \"*.png\" | \\\n     xargs zip $OUT/stb_png_read_fuzzer_seed_corpus.zip\n\ncp $SRC/stb/tests/stb_png.dict $OUT/stb_png_read_fuzzer.dict\n\ntar xvzf $SRC/stbi/jpg.tar.gz --directory $SRC/stb/tests\ntar xvzf $SRC/stbi/gif.tar.gz --directory $SRC/stb/tests\nunzip    $SRC/stbi/bmp.zip    -d $SRC/stb/tests\nunzip    $SRC/stbi/tga.zip    -d $SRC/stb/tests\n\nfind $SRC/stb/tests -name \"*.png\" -o -name \"*.jpg\" -o -name \"*.gif\" \\\n                 -o -name \"*.bmp\" -o -name \"*.tga\" -o -name \"*.TGA\" \\\n                 -o -name \"*.ppm\" -o -name \"*.pgm\" \\\n    | xargs zip $OUT/stbi_read_fuzzer_seed_corpus.zip\n\necho \"\" >> $SRC/stbi/gif.dict\ncat $SRC/stbi/gif.dict $SRC/stb/tests/stb_png.dict > $OUT/stbi_read_fuzzer.dict\n"
  },
  {
    "path": "tests/oversample/README.md",
    "content": "# Font character oversampling for rendering from atlas textures\n\nTL,DR: Run oversample.exe on a windows machine to see the\nbenefits of oversampling. It will try to use arial.ttf from the\nWindows font directory unless you type the name of a .ttf file as\na command-line argument.\n\n## Benefits of oversampling\n\nOversampling is a mechanism for improving subpixel rendering of characters.\n\nImproving subpixel has a few benefits:\n\n* With horizontal-oversampling, text can remain sharper while still being sub-pixel positioned for better kerning\n* Horizontally-oversampled text significantly reduces aliasing when text animates horizontally\n* Vertically-oversampled text significantly reduces aliasing when text animates vertically\n* Text oversampled in both directions significantly reduces aliasing when text rotates\n\n## What text oversampling is\n\nA common strategy for rendering text is to cache character bitmaps\nand reuse them. For hinted characters, every instance of a given\ncharacter is always identical, so this works fine. However, stb_truetype\ndoesn't do hinting.\n\nFor anti-aliased characters, you can actually position the characters\nwith subpixel precision, and get different bitmaps based on that positioning\nif you re-render the vector data.\n\nHowever, if you simply cache a single version of the bitmap and\ndraw it at different subpixel positions with a GPU, you will get\neither the exact same result (if you use point-sampling on the\ntexture) or linear filtering. Linear filtering will cause a sub-pixel\npositioned bitmap to blur further, causing a visible de-sharpening\nof the character. (And, since the character wasn't hinted, it was\nalready blurrier than a hinted one would be, and now it gets even\nmore blurry.)\n\nYou can avoid this by caching multiple variants of a character which\nwere rendered independently from the vector data. For example, you\nmight cache 3 versions of a char, at 0, 1/3, and 2/3rds of a pixel\nhorizontal offset, and always require characters to fall on integer\npositions vertically.\n\nWhen creating a texture atlas for use on GPUs, which support bilinear\nfiltering, there is a better approach than caching several independent\npositions, which is to allow lerping between the versions to allow\nfiner subpixel positioning. You can achieve these by interleaving\neach of the cached bitmaps, but this turns out to be mathematically\nequivalent to a simpler operation: oversampling and prefiltering the\ncharacters.\n\nSo, setting oversampling of 2x2 in stb_truetype is equivalent to caching\neach character in 4 different variations, 1 for each subpixel position\nin a 2x2 set.\n\nAn advantage of this formulation is that no changes are required to\nthe rendering code; the exact same quad-rendering code works, it just\nuses different texture coordinates. (Note this does potentially increase\ntexture bandwidth for text rendering since we end up minifying the texture\nwithout using mipmapping, but you probably are not going to be fill-bound\nby your text rendering.)\n\n## What about gamma?\n\nGamma-correction for fonts just doesn't work. This doesn't seem to make\nmuch sense -- it's physically correct, it simulates what we'd see if you\nshrunk a font down really far, right?\n\nBut you can play with it in the oversample.exe app. If you turn it on,\nwhite-on-black fonts become too thick (i.e. they become too bright), and\nblack-on-white fonts become too thin (i.e. they are insufficiently dark). There is\nno way to adjust the font's inherent thickness (i.e. by switching to\nbold) to fix this for both; making the font thicker will make white\ntext worse, and making the font thinner will make black text worse.\nObviously you could use different fonts for light and dark cases, but\nthis doesn't seem like a very good way for fonts to work.\n\nMultiple people who have experimented with this independently (me,\nFabian Giesen,and Maxim Shemanarev of Anti-Grain Geometry) have all\nconcluded that correct gamma-correction does not produce the best\nresults for fonts. Font rendering just generally looks better without\ngamma correction (or possibly with some arbitrary power stuck in\nthere, but it's not really correcting for gamma at that point). Maybe\nthis is in part a product of how we're used to fonts being on screens\nwhich has changed how we expect them to look (e.g. perhaps hinting\noversharpens them and prevents the real-world thinning you'd see in\na black-on-white text).\n\n(AGG link on text rendering, including mention of gamma:\n  http://www.antigrain.com/research/font_rasterization/ )\n\nNevertheless, even if you turn on gamma-correction, you will find that\noversampling still helps in many cases for small fonts.\n"
  },
  {
    "path": "tests/oversample/main.c",
    "content": "#pragma warning(disable:4244; disable:4305; disable:4018)\n#include <assert.h>\n#include <ctype.h>\n\n#define STB_WINMAIN\n#include \"stb_wingraph.h\"\n\n#define STB_TRUETYPE_IMPLEMENTATION\n#define STB_RECT_PACK_IMPLEMENTATION\n#include \"stb_rect_pack.h\"\n#include \"stb_truetype.h\"\n\n#ifndef WINGDIAPI\n#define CALLBACK    __stdcall\n#define WINGDIAPI   __declspec(dllimport)\n#define APIENTRY    __stdcall\n#endif\n\n#include <gl/gl.h>\n#include <gl/glu.h>\n\n#define GL_FRAMEBUFFER_SRGB_EXT           0x8DB9\n\n#define SIZE_X  1024\n#define SIZE_Y  768\n\nstbtt_packedchar chardata[6][128];\n\nint sx=SIZE_X, sy=SIZE_Y;\n\n#define BITMAP_W 512\n#define BITMAP_H 512\nunsigned char temp_bitmap[BITMAP_W][BITMAP_H];\nunsigned char ttf_buffer[1 << 25];\nGLuint font_tex;\n\nfloat scale[2] = { 24.0f, 14.0f };\n\nint sf[6] = { 0,1,2, 0,1,2 };\n\nvoid load_fonts(void)\n{\n   stbtt_pack_context pc;\n   int i;\n   FILE *f;\n   char filename[256];\n   char *win = getenv(\"windir\");\n   if (win == NULL) win = getenv(\"SystemRoot\");\n\n   f = fopen(stb_wingraph_commandline, \"rb\");\n   if (!f) {\n      if (win == NULL)\n         sprintf(filename, \"arial.ttf\", win);\n      else\n         sprintf(filename, \"%s/fonts/arial.ttf\", win);\n      f = fopen(filename, \"rb\");\n      if (!f) exit(0);\n   }\n\n   fread(ttf_buffer, 1, 1<<25, f);\n\n   stbtt_PackBegin(&pc, temp_bitmap[0], BITMAP_W, BITMAP_H, 0, 1, NULL);\n   for (i=0; i < 2; ++i) {\n      stbtt_PackSetOversampling(&pc, 1, 1);\n      stbtt_PackFontRange(&pc, ttf_buffer, 0, scale[i], 32, 95, chardata[i*3+0]+32);\n      stbtt_PackSetOversampling(&pc, 2, 2);\n      stbtt_PackFontRange(&pc, ttf_buffer, 0, scale[i], 32, 95, chardata[i*3+1]+32);\n      stbtt_PackSetOversampling(&pc, 3, 1);\n      stbtt_PackFontRange(&pc, ttf_buffer, 0, scale[i], 32, 95, chardata[i*3+2]+32);\n   }\n   stbtt_PackEnd(&pc);\n\n   glGenTextures(1, &font_tex);\n   glBindTexture(GL_TEXTURE_2D, font_tex);\n   glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, BITMAP_W, BITMAP_H, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n}\n\nint black_on_white;\n\nvoid draw_init(void)\n{\n   glDisable(GL_CULL_FACE);\n   glDisable(GL_TEXTURE_2D);\n   glDisable(GL_LIGHTING);\n   glDisable(GL_DEPTH_TEST);\n\n   glViewport(0,0,sx,sy);\n   if (black_on_white)\n      glClearColor(255,255,255,0);\n   else\n      glClearColor(0,0,0,0);\n   glClear(GL_COLOR_BUFFER_BIT);\n\n   glMatrixMode(GL_PROJECTION);\n   glLoadIdentity();\n   gluOrtho2D(0,sx,sy,0);\n   glMatrixMode(GL_MODELVIEW);\n   glLoadIdentity();\n}\n\n\nvoid drawBoxTC(float x0, float y0, float x1, float y1, float s0, float t0, float s1, float t1)\n{\n   glTexCoord2f(s0,t0); glVertex2f(x0,y0);\n   glTexCoord2f(s1,t0); glVertex2f(x1,y0);\n   glTexCoord2f(s1,t1); glVertex2f(x1,y1);\n   glTexCoord2f(s0,t1); glVertex2f(x0,y1);\n}\n\nint integer_align;\n\nvoid print(float x, float y, int font, char *text)\n{\n   glEnable(GL_TEXTURE_2D);\n   glBindTexture(GL_TEXTURE_2D, font_tex);\n   glBegin(GL_QUADS);\n   while (*text) {\n      stbtt_aligned_quad q;\n      stbtt_GetPackedQuad(chardata[font], BITMAP_W, BITMAP_H, *text++, &x, &y, &q, font ? 0 : integer_align);\n      drawBoxTC(q.x0,q.y0,q.x1,q.y1, q.s0,q.t0,q.s1,q.t1);\n   }\n   glEnd();\n}\n\nint font=3;\nint translating;\nint rotating=0;\nint srgb=0;\nfloat rotate_t, translate_t;\nint show_tex;\n\nvoid draw_world(void)\n{\n   int sfont = sf[font];\n   float x = 20;\n   glEnable(GL_BLEND);\n   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n   if (black_on_white)\n      glColor3f(0,0,0);\n   else\n      glColor3f(1,1,1);\n\n\n   print(80, 30, sfont, \"Controls:\");\n   print(100, 60, sfont, \"S: toggle font size\");\n   print(100, 85, sfont, \"O: toggle oversampling\");\n   print(100,110, sfont, \"T: toggle translation\");\n   print(100,135, sfont, \"R: toggle rotation\");\n   print(100,160, sfont, \"P: toggle pixel-snap (only non-oversampled)\");\n   print(100,185, sfont, \"G: toggle srgb gamma-correction\");\n   if (black_on_white)\n      print(100,210, sfont, \"B: toggle to white-on-black\");\n   else\n      print(100,210, sfont, \"B: toggle to black-on-white\");\n   print(100,235, sfont, \"V: view font texture\");\n\n   print(80, 300, sfont, \"Current font:\");\n\n   if (!show_tex) {\n      if (font < 3)\n         print(100, 350, sfont, \"Font height: 24 pixels\");\n      else\n         print(100, 350, sfont, \"Font height: 14 pixels\");\n   }\n\n   if (font%3==1)\n      print(100, 325, sfont, \"2x2 oversampled text at 1:1\");\n   else if (font%3 == 2)\n      print(100, 325, sfont, \"3x1 oversampled text at 1:1\");\n   else if (integer_align)\n      print(100, 325, sfont, \"1:1 text, one texel = one pixel, snapped to integer coordinates\");\n   else\n      print(100, 325, sfont, \"1:1 text, one texel = one pixel\");\n\n   if (show_tex) {\n      glBegin(GL_QUADS);\n      drawBoxTC(200,400, 200+BITMAP_W,300+BITMAP_H, 0,0,1,1);\n      glEnd();\n   } else {\n      glMatrixMode(GL_MODELVIEW);\n      glTranslatef(200,350,0);\n\n      if (translating)\n         x += fmod(translate_t*8,30);\n\n      if (rotating) {\n         glTranslatef(100,150,0);\n         glRotatef(rotate_t*2,0,0,1);\n         glTranslatef(-100,-150,0);\n      }\n      print(x,100, font, \"This is a test\");\n      print(x,130, font, \"Now is the time for all good men to come to the aid of their country.\");\n      print(x,160, font, \"The quick brown fox jumps over the lazy dog.\");\n      print(x,190, font, \"0123456789\");\n   }\n}\n\nvoid draw(void)\n{\n   draw_init();\n   draw_world();\n   stbwingraph_SwapBuffers(NULL);\n}\n\nstatic int initialized=0;\nstatic float last_dt;\n\nint move[4];\nint raw_mouse_x, raw_mouse_y;\n\nint loopmode(float dt, int real, int in_client)\n{\n   float actual_dt = dt;\n\n   if (!initialized) return 0;\n\n   rotate_t += dt;\n   translate_t += dt;\n\n//   music_sim();\n   if (!real)\n      return 0;\n\n   if (dt > 0.25) dt = 0.25;\n   if (dt < 0.01) dt = 0.01;\n\n   draw();\n\n   return 0;\n}\n\nint winproc(void *data, stbwingraph_event *e)\n{\n   switch (e->type) {\n      case STBWGE_create:\n         break;\n\n      case STBWGE_char:\n         switch(e->key) {\n            case 27:\n               stbwingraph_ShowCursor(NULL,1);\n               return STBWINGRAPH_winproc_exit;\n               break;\n            case 'o': case 'O':\n               font = (font+1) % 3 + (font/3)*3;\n               break;\n            case 's': case 'S':\n               font = (font+3) % 6;\n               break;\n            case 't': case 'T':\n               translating = !translating;\n               translate_t = 0;\n               break;\n            case 'r': case 'R':\n               rotating = !rotating;\n               rotate_t = 0;\n               break;\n            case 'p': case 'P':\n               integer_align = !integer_align;\n               break;\n            case 'g': case 'G':\n               srgb = !srgb;\n               if (srgb)\n                  glEnable(GL_FRAMEBUFFER_SRGB_EXT);\n               else\n                  glDisable(GL_FRAMEBUFFER_SRGB_EXT);\n               break;\n            case 'v': case 'V':\n               show_tex = !show_tex;\n               break;\n            case 'b': case 'B':\n               black_on_white = !black_on_white;\n               break;\n         }\n         break;\n\n      case STBWGE_mousemove:\n         raw_mouse_x = e->mx;\n         raw_mouse_y = e->my;\n         break;\n\n#if 0\n      case STBWGE_mousewheel:  do_mouse(e,0,0); break;\n      case STBWGE_leftdown:    do_mouse(e, 1,0); break;\n      case STBWGE_leftup:      do_mouse(e,-1,0); break;\n      case STBWGE_rightdown:   do_mouse(e,0, 1); break;\n      case STBWGE_rightup:     do_mouse(e,0,-1); break;\n#endif\n\n      case STBWGE_keydown:\n         if (e->key == VK_RIGHT) move[0] = 1;\n         if (e->key == VK_LEFT)  move[1] = 1;\n         if (e->key == VK_UP)    move[2] = 1;\n         if (e->key == VK_DOWN)  move[3] = 1;\n         break;\n      case STBWGE_keyup:\n         if (e->key == VK_RIGHT) move[0] = 0;\n         if (e->key == VK_LEFT)  move[1] = 0;\n         if (e->key == VK_UP)    move[2] = 0;\n         if (e->key == VK_DOWN)  move[3] = 0;\n         break;\n\n      case STBWGE_size:\n         sx = e->width;\n         sy = e->height;\n         loopmode(0,1,0);\n         break;\n\n      case STBWGE_draw:\n         if (initialized)\n            loopmode(0,1,0);\n         break;\n\n      default:\n         return STBWINGRAPH_unprocessed;\n   }\n   return 0;\n}\n\nvoid stbwingraph_main(void)\n{\n   stbwingraph_Priority(2);\n   stbwingraph_CreateWindow(1, winproc, NULL, \"tt\", SIZE_X,SIZE_Y, 0, 1, 0, 0);\n   stbwingraph_ShowCursor(NULL, 0);\n   load_fonts();\n   initialized = 1;\n   stbwingraph_MainLoop(loopmode, 0.016f);   // 30 fps = 0.33\n}\n\n"
  },
  {
    "path": "tests/oversample/oversample.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"oversample\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Application\" 0x0101\n\nCFG=oversample - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"oversample.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"oversample.mak\" CFG=\"oversample - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"oversample - Win32 Release\" (based on \"Win32 (x86) Application\")\n!MESSAGE \"oversample - Win32 Debug\" (based on \"Win32 (x86) Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nMTL=midl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"oversample - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /WX /GX /O2 /I \"c:\\sean\\prj\\stb\" /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /FD /c\n# SUBTRACT CPP /YX\n# ADD BASE MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\n# ADD MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386\n# SUBTRACT LINK32 /map /debug\n\n!ELSEIF  \"$(CFG)\" == \"oversample - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /WX /Gm /GX /Zi /Od /I \"c:\\sean\\prj\\stb\" /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /FD /GZ /c\n# ADD BASE MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\n# ADD MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib advapi32.lib winspool.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /incremental:no /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"oversample - Win32 Release\"\n# Name \"oversample - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\main.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/oversample/oversample.dsw",
    "content": "Microsoft Developer Studio Workspace File, Format Version 6.00\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\n\n###############################################################################\n\nProject: \"oversample\"=.\\oversample.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nGlobal:\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<3>\n{{{\n}}}\n\n###############################################################################\n\n"
  },
  {
    "path": "tests/oversample/stb_wingraph.h",
    "content": "// stb_wingraph.h  v0.01 - public domain windows graphics programming\n// wraps WinMain, ChoosePixelFormat, ChangeDisplayResolution, etc. for\n// doing OpenGL graphics\n//\n// in ONE source file, put '#define STB_DEFINE' before including this\n// OR put '#define STB_WINMAIN' to define a WinMain that calls stbwingraph_main(void)\n//\n// @TODO:\n//    2d rendering interface (that can be done easily in software)\n//    STB_WINGRAPH_SOFTWARE -- 2d software rendering only\n//    STB_WINGRAPH_OPENGL   -- OpenGL only\n\n\n#ifndef INCLUDE_STB_WINGRAPH_H\n#define INCLUDE_STB_WINGRAPH_H\n\n#ifdef STB_WINMAIN\n   #ifndef STB_DEFINE\n      #define STB_DEFINE\n      #define STB_WINGRAPH_DISABLE_DEFINE_AT_END\n   #endif\n#endif\n\n#ifdef STB_DEFINE\n   #pragma comment(lib, \"opengl32.lib\")\n   #pragma comment(lib, \"glu32.lib\")\n   #pragma comment(lib, \"winmm.lib\")\n   #pragma comment(lib, \"gdi32.lib\")\n   #pragma comment(lib, \"user32.lib\")\n#endif\n\n#ifdef __cplusplus\n#define STB_EXTERN extern \"C\"\n#else\n#define STB_EXTERN\n#endif\n\n#ifdef STB_DEFINE\n#ifndef _WINDOWS_\n   #ifdef APIENTRY\n   #undef APIENTRY\n   #endif\n   #ifdef WINGDIAPI\n   #undef WINGDIAPI\n   #endif\n   #define _WIN32_WINNT 0x0400  // WM_MOUSEWHEEL\n   #include <windows.h>\n#endif\n#include <stdio.h>\n#include <math.h>\n#include <time.h>\n#include <string.h>\n#include <assert.h>\n#endif\n\ntypedef void * stbwingraph_hwnd;\ntypedef void * stbwingraph_hinstance;\n\nenum\n{\n   STBWINGRAPH_unprocessed = -(1 << 24),\n   STBWINGRAPH_do_not_show,\n   STBWINGRAPH_winproc_exit,\n   STBWINGRAPH_winproc_update,\n   STBWINGRAPH_update_exit,\n   STBWINGRAPH_update_pause,\n};\n\ntypedef enum\n{\n   STBWGE__none=0,\n\n   STBWGE_create,\n   STBWGE_create_postshow,\n   STBWGE_draw,\n   STBWGE_destroy,\n   STBWGE_char,\n   STBWGE_keydown,\n   STBWGE_syskeydown,\n   STBWGE_keyup,\n   STBWGE_syskeyup,\n   STBWGE_deactivate,\n   STBWGE_activate,\n   STBWGE_size,\n\n   STBWGE_mousemove ,\n   STBWGE_leftdown  , STBWGE_leftup  ,\n   STBWGE_middledown, STBWGE_middleup,\n   STBWGE_rightdown , STBWGE_rightup ,\n   STBWGE_mousewheel,\n} stbwingraph_event_type;\n\ntypedef struct\n{\n   stbwingraph_event_type type;\n\n   // for input events (mouse, keyboard)\n   int mx,my; // mouse x & y\n   int dx,dy;\n   int shift, ctrl, alt;\n\n   // for keyboard events\n   int key;\n\n   // for STBWGE_size:\n   int width, height;\n\n   // for STBWGE_crate\n   int did_share_lists;  // if true, wglShareLists succeeded\n\n   void *handle;\n\n} stbwingraph_event;\n\ntypedef int (*stbwingraph_window_proc)(void *data, stbwingraph_event *event);\n\nextern stbwingraph_hinstance   stbwingraph_app;\nextern stbwingraph_hwnd        stbwingraph_primary_window;\nextern int                     stbwingraph_request_fullscreen;\nextern int                     stbwingraph_request_windowed;\n\nSTB_EXTERN void stbwingraph_ods(char *str, ...);\nSTB_EXTERN int stbwingraph_MessageBox(stbwingraph_hwnd win, unsigned int type,\n                                              char *caption, char *text, ...);\nSTB_EXTERN int stbwingraph_ChangeResolution(unsigned int w, unsigned int h,\n                                      unsigned int bits, int use_message_box);\nSTB_EXTERN int stbwingraph_SetPixelFormat(stbwingraph_hwnd win, int color_bits,\n            int alpha_bits, int depth_bits, int stencil_bits, int accum_bits);\nSTB_EXTERN int stbwingraph_DefineClass(void *hinstance, char *iconname);\nSTB_EXTERN void stbwingraph_SwapBuffers(void *win);\nSTB_EXTERN void stbwingraph_Priority(int n);\n\nSTB_EXTERN void stbwingraph_MakeFonts(void *window, int font_base);\nSTB_EXTERN void stbwingraph_ShowWindow(void *window);\nSTB_EXTERN void *stbwingraph_CreateWindow(int primary, stbwingraph_window_proc func, void *data, char *text, int width, int height, int fullscreen, int resizeable, int dest_alpha, int stencil);\nSTB_EXTERN void *stbwingraph_CreateWindowSimple(stbwingraph_window_proc func, int width, int height);\nSTB_EXTERN void *stbwingraph_CreateWindowSimpleFull(stbwingraph_window_proc func, int fullscreen, int ww, int wh, int fw, int fh);\nSTB_EXTERN void stbwingraph_DestroyWindow(void *window);\nSTB_EXTERN void stbwingraph_ShowCursor(void *window, int visible);\nSTB_EXTERN float stbwingraph_GetTimestep(float minimum_time);\nSTB_EXTERN void stbwingraph_SetGLWindow(void *win);\ntypedef int (*stbwingraph_update)(float timestep, int real, int in_client);\nSTB_EXTERN int stbwingraph_MainLoop(stbwingraph_update func, float mintime);\n\n#ifdef STB_DEFINE\nstbwingraph_hinstance   stbwingraph_app;\nstbwingraph_hwnd        stbwingraph_primary_window;\nint stbwingraph_request_fullscreen;\nint stbwingraph_request_windowed;\n\nvoid stbwingraph_ods(char *str, ...)\n{\n   char buffer[1024];\n   va_list v;\n   va_start(v,str);\n   vsprintf(buffer, str, v);\n   va_end(v);\n   OutputDebugString(buffer);\n}\n\nint stbwingraph_MessageBox(stbwingraph_hwnd win, unsigned int type, char *caption, char *text, ...)\n{\n   va_list v;\n   char buffer[1024];\n   va_start(v, text);\n   vsprintf(buffer, text, v);\n   va_end(v);\n   return MessageBox(win, buffer, caption, type);\n}\n\nvoid stbwingraph_Priority(int n)\n{\n   int p;\n   switch (n) {\n      case -1: p = THREAD_PRIORITY_BELOW_NORMAL; break;\n      case 0: p = THREAD_PRIORITY_NORMAL; break;\n      case 1: p = THREAD_PRIORITY_ABOVE_NORMAL; break;\n      default:\n         if (n < 0) p = THREAD_PRIORITY_LOWEST;\n         else p = THREAD_PRIORITY_HIGHEST;\n   }\n   SetThreadPriority(GetCurrentThread(), p);\n}\n\nstatic void stbwingraph_ResetResolution(void)\n{\n   ChangeDisplaySettings(NULL, 0);\n}\n\nstatic void stbwingraph_RegisterResetResolution(void)\n{\n   static int done=0;\n   if (!done) {\n      done = 1;\n      atexit(stbwingraph_ResetResolution);\n   }\n}\n\nint stbwingraph_ChangeResolution(unsigned int w, unsigned int h, unsigned int bits, int use_message_box)\n{\n   DEVMODE mode;\n   int res;\n   \n   int i, tries=0;\n   for (i=0; ; ++i) {\n      int success = EnumDisplaySettings(NULL, i, &mode);\n      if (!success) break;\n      if (mode.dmBitsPerPel == bits && mode.dmPelsWidth == w && mode.dmPelsHeight == h) {\n         ++tries;\n         success = ChangeDisplaySettings(&mode, CDS_FULLSCREEN); \n         if (success == DISP_CHANGE_SUCCESSFUL) {\n            stbwingraph_RegisterResetResolution();\n            return TRUE;\n         }\n         break;\n      }\n   }\n\n   if (!tries) {\n      if (use_message_box)\n         stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, \"The resolution %d x %d x %d-bits is not supported.\", w, h, bits);\n      return FALSE;\n   }\n\n   // we tried but failed, so try explicitly doing it without specifying refresh rate\n\n   // Win95 support logic\n   mode.dmBitsPerPel = bits; \n   mode.dmPelsWidth = w; \n   mode.dmPelsHeight = h; \n   mode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; \n\n   res = ChangeDisplaySettings(&mode, CDS_FULLSCREEN);\n\n   switch (res) {\n      case DISP_CHANGE_SUCCESSFUL:\n         stbwingraph_RegisterResetResolution();\n         return TRUE;\n\n      case DISP_CHANGE_RESTART:\n         if (use_message_box)\n            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, \"Please set your desktop to %d-bit color and then try again.\");\n         return FALSE;\n\n      case DISP_CHANGE_FAILED:\n         if (use_message_box)\n            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, \"The hardware failed to change modes.\");\n         return FALSE;\n\n      case DISP_CHANGE_BADMODE:\n         if (use_message_box)\n            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, \"The resolution %d x %d x %d-bits is not supported.\", w, h, bits);\n         return FALSE;\n\n      default:\n         if (use_message_box)\n            stbwingraph_MessageBox(stbwingraph_primary_window, MB_ICONERROR, NULL, \"An unknown error prevented a change to a %d x %d x %d-bit display.\", w, h, bits);\n         return FALSE;\n   }\n}\n\nint stbwingraph_SetPixelFormat(stbwingraph_hwnd win, int color_bits, int alpha_bits, int depth_bits, int stencil_bits, int accum_bits)\n{\n   HDC dc = GetDC(win);\n   PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd) };\n   int                   pixel_format;\n\n   pfd.nVersion = 1;\n   pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;\n   pfd.dwLayerMask = PFD_MAIN_PLANE;\n   pfd.iPixelType = PFD_TYPE_RGBA;\n   pfd.cColorBits = color_bits;\n   pfd.cAlphaBits = alpha_bits;\n   pfd.cDepthBits = depth_bits;\n   pfd.cStencilBits = stencil_bits;\n   pfd.cAccumBits = accum_bits;\n\n   pixel_format = ChoosePixelFormat(dc, &pfd);\n   if (!pixel_format) return FALSE;\n\n   if (!DescribePixelFormat(dc, pixel_format, sizeof(PIXELFORMATDESCRIPTOR), &pfd))\n      return FALSE;\n   SetPixelFormat(dc, pixel_format, &pfd);\n\n   return TRUE;\n}\n\ntypedef struct\n{\n   // app data\n   stbwingraph_window_proc func;\n   void *data;\n   // creation parameters\n   int   color, alpha, depth, stencil, accum;\n   HWND  share_window;\n   HWND  window;\n   // internal data\n   HGLRC rc;\n   HDC   dc;\n   int   hide_mouse;\n   int   in_client;\n   int   active;\n   int   did_share_lists;\n   int   mx,my; // last mouse positions\n} stbwingraph__window;\n\nstatic void stbwingraph__inclient(stbwingraph__window *win, int state)\n{\n   if (state != win->in_client) {\n      win->in_client = state;\n      if (win->hide_mouse)\n         ShowCursor(!state);\n   }\n}\n\nstatic void stbwingraph__key(stbwingraph_event *e, int type, int key, stbwingraph__window *z)\n{\n   e->type  = type;\n   e->key   = key;\n   e->shift = (GetKeyState(VK_SHIFT)   < 0);\n   e->ctrl  = (GetKeyState(VK_CONTROL) < 0);\n   e->alt   = (GetKeyState(VK_MENU)    < 0);\n   if  (z) {\n      e->mx    = z->mx;\n      e->my    = z->my;\n   } else {\n      e->mx = e->my = 0;\n   }\n   e->dx = e->dy = 0;\n}\n\nstatic void stbwingraph__mouse(stbwingraph_event *e, int type, WPARAM wparam, LPARAM lparam, int capture, void *wnd, stbwingraph__window *z)\n{\n   static int captured = 0;\n   e->type = type;\n   e->mx = (short) LOWORD(lparam);\n   e->my = (short) HIWORD(lparam);\n   if (!z || z->mx == -(1 << 30)) {\n      e->dx = e->dy = 0;\n   } else {\n      e->dx = e->mx - z->mx;\n      e->dy = e->my - z->my;\n   }\n   e->shift = (wparam & MK_SHIFT) != 0;\n   e->ctrl  = (wparam & MK_CONTROL) != 0;\n   e->alt   = (wparam & MK_ALT) != 0;\n   if (z) {\n      z->mx = e->mx;\n      z->my = e->my;\n   }\n   if (capture) {\n      if (!captured && capture == 1)\n         SetCapture(wnd);\n      captured += capture;\n      if (!captured && capture == -1)\n         ReleaseCapture();\n      if (captured < 0) captured = 0;\n   }\n}\n\nstatic void stbwingraph__mousewheel(stbwingraph_event *e, int type, WPARAM wparam, LPARAM lparam, int capture, void *wnd, stbwingraph__window *z)\n{\n   // lparam seems bogus!\n   static int captured = 0;\n   e->type = type;\n   if (z) {\n      e->mx = z->mx;\n      e->my = z->my;\n   }\n   e->dx = e->dy = 0;\n   e->shift = (wparam & MK_SHIFT) != 0;\n   e->ctrl  = (wparam & MK_CONTROL) != 0;\n   e->alt   = (GetKeyState(VK_MENU)    < 0);\n   e->key = ((int) wparam >> 16);\n}\n\nint stbwingraph_force_update;\nstatic int WINAPI stbwingraph_WinProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)\n{\n   int allow_default = TRUE;\n   stbwingraph_event e = { STBWGE__none };\n   // the following line is wrong for 64-bit windows, but VC6 doesn't have GetWindowLongPtr\n   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(wnd, GWL_USERDATA);\n\n   switch (msg) {\n\n      case WM_CREATE:\n      {\n         LPCREATESTRUCT lpcs = (LPCREATESTRUCT) lparam;\n         assert(z == NULL);\n         z = (stbwingraph__window *) lpcs->lpCreateParams;\n         SetWindowLong(wnd, GWL_USERDATA, (LONG) z);\n         z->dc = GetDC(wnd);\n         if (stbwingraph_SetPixelFormat(wnd, z->color, z->alpha, z->depth, z->stencil, z->accum)) {\n            z->rc = wglCreateContext(z->dc);\n            if (z->rc) {\n               e.type = STBWGE_create;\n               z->did_share_lists = FALSE;\n               if (z->share_window) {\n                  stbwingraph__window *y = (stbwingraph__window *) GetWindowLong(z->share_window, GWL_USERDATA);\n                  if (wglShareLists(z->rc, y->rc))\n                     z->did_share_lists = TRUE;\n               }\n               wglMakeCurrent(z->dc, z->rc);\n               return 0;\n            }\n         }\n         return -1;\n      }\n\n      case WM_PAINT: {\n         PAINTSTRUCT ps;\n         HDC hdc = BeginPaint(wnd, &ps);\n         SelectObject(hdc, GetStockObject(NULL_BRUSH));\n         e.type = STBWGE_draw;\n         e.handle = wnd;\n         z->func(z->data, &e);\n         EndPaint(wnd, &ps);\n         return 0;\n      }\n\n      case WM_DESTROY:\n         e.type = STBWGE_destroy;\n         e.handle = wnd;\n         if (z && z->func)\n            z->func(z->data, &e);\n         wglMakeCurrent(NULL, NULL) ; \n         if (z) {\n            if (z->rc) wglDeleteContext(z->rc);\n            z->dc = 0;\n            z->rc = 0;\n         }\n         if (wnd == stbwingraph_primary_window)\n            PostQuitMessage (0);\n         return 0;\n\n      case WM_CHAR:         stbwingraph__key(&e, STBWGE_char   , wparam, z); break;\n      case WM_KEYDOWN:      stbwingraph__key(&e, STBWGE_keydown, wparam, z); break;\n      case WM_KEYUP:        stbwingraph__key(&e, STBWGE_keyup  , wparam, z); break;\n\n      case WM_NCMOUSEMOVE:  stbwingraph__inclient(z,0); break;\n      case WM_MOUSEMOVE:    stbwingraph__inclient(z,1); stbwingraph__mouse(&e, STBWGE_mousemove,  wparam, lparam,0,wnd, z); break;\n      case WM_LBUTTONDOWN:  stbwingraph__mouse(&e, STBWGE_leftdown,   wparam, lparam,1,wnd, z); break;\n      case WM_MBUTTONDOWN:  stbwingraph__mouse(&e, STBWGE_middledown, wparam, lparam,1,wnd, z); break;\n      case WM_RBUTTONDOWN:  stbwingraph__mouse(&e, STBWGE_rightdown,  wparam, lparam,1,wnd, z); break;\n      case WM_LBUTTONUP:    stbwingraph__mouse(&e, STBWGE_leftup,     wparam, lparam,-1,wnd, z); break;\n      case WM_MBUTTONUP:    stbwingraph__mouse(&e, STBWGE_middleup,   wparam, lparam,-1,wnd, z); break;\n      case WM_RBUTTONUP:    stbwingraph__mouse(&e, STBWGE_rightup,    wparam, lparam,-1,wnd, z); break;\n      case WM_MOUSEWHEEL:   stbwingraph__mousewheel(&e, STBWGE_mousewheel, wparam, lparam,0,wnd, z); break;\n\n      case WM_ACTIVATE:\n         allow_default = FALSE;\n         if (LOWORD(wparam)==WA_INACTIVE ) {\n            wglMakeCurrent(z->dc, NULL);\n            e.type = STBWGE_deactivate;\n            z->active = FALSE;\n         } else {\n            wglMakeCurrent(z->dc, z->rc);\n            e.type = STBWGE_activate;\n            z->active = TRUE;\n         }\n         e.handle = wnd;\n         z->func(z->data, &e);\n         return 0;\n\n      case WM_SIZE: {\n         RECT rect;\n         allow_default = FALSE;\n         GetClientRect(wnd, &rect);\n         e.type = STBWGE_size;\n         e.width = rect.right;\n         e.height = rect.bottom;\n         e.handle = wnd;\n         z->func(z->data, &e);\n         return 0;\n      }\n\n      default:\n         return DefWindowProc (wnd, msg, wparam, lparam);\n   }\n\n   if (e.type != STBWGE__none) {\n      int n;\n      e.handle = wnd;\n      n = z->func(z->data, &e);\n      if (n == STBWINGRAPH_winproc_exit) {\n         PostQuitMessage(0);\n         n = 0;\n      }\n      if (n == STBWINGRAPH_winproc_update) {\n         stbwingraph_force_update = TRUE;\n         return 1;\n      }\n      if (n != STBWINGRAPH_unprocessed)\n         return n;\n   }\n   return DefWindowProc (wnd, msg, wparam, lparam);\n}\n\nint stbwingraph_DefineClass(HINSTANCE hInstance, char *iconname)\n{\n   WNDCLASSEX  wndclass;\n\n   stbwingraph_app = hInstance;\n\n   wndclass.cbSize        = sizeof(wndclass);\n   wndclass.style         = CS_OWNDC;\n   wndclass.lpfnWndProc   = (WNDPROC) stbwingraph_WinProc;\n   wndclass.cbClsExtra    = 0;\n   wndclass.cbWndExtra    = 0;\n   wndclass.hInstance     = hInstance;\n   wndclass.hIcon         = LoadIcon(hInstance, iconname);\n   wndclass.hCursor       = LoadCursor(NULL,IDC_ARROW);\n   wndclass.hbrBackground = GetStockObject(NULL_BRUSH);\n   wndclass.lpszMenuName  = \"zwingraph\";\n   wndclass.lpszClassName = \"zwingraph\";\n   wndclass.hIconSm       = NULL;\n\n   if (!RegisterClassEx(&wndclass))\n      return FALSE;\n   return TRUE;\n}\n\nvoid stbwingraph_ShowWindow(void *window)\n{\n   stbwingraph_event e = { STBWGE_create_postshow };\n   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(window, GWL_USERDATA);\n   ShowWindow(window, SW_SHOWNORMAL);\n   InvalidateRect(window, NULL, TRUE);\n   UpdateWindow(window);\n   e.handle = window;\n   z->func(z->data, &e);\n}\n\nvoid *stbwingraph_CreateWindow(int primary, stbwingraph_window_proc func, void *data, char *text,\n           int width, int height, int fullscreen, int resizeable, int dest_alpha, int stencil)\n{\n   HWND win;\n   DWORD dwstyle;\n   stbwingraph__window *z = (stbwingraph__window *) malloc(sizeof(*z));\n\n   if (z == NULL) return NULL;\n   memset(z, 0, sizeof(*z));\n   z->color = 24;\n   z->depth = 24;\n   z->alpha = dest_alpha;\n   z->stencil = stencil;\n   z->func = func;\n   z->data = data;\n   z->mx = -(1 << 30);\n   z->my = 0;\n\n   if (primary) {\n      if (stbwingraph_request_windowed)\n         fullscreen = FALSE;\n      else if (stbwingraph_request_fullscreen)\n         fullscreen = TRUE;\n   }\n\n   if (fullscreen) {\n      #ifdef STB_SIMPLE\n      stbwingraph_ChangeResolution(width, height, 32, 1);\n      #else\n      if (!stbwingraph_ChangeResolution(width, height, 32, 0))\n         return NULL;\n      #endif\n      dwstyle = WS_POPUP | WS_CLIPSIBLINGS;\n   } else {\n      RECT rect;\n      dwstyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;\n      if (resizeable)\n         dwstyle |= WS_SIZEBOX | WS_MAXIMIZEBOX;\n      rect.top = 0;\n      rect.left = 0;\n      rect.right = width;\n      rect.bottom = height;\n      AdjustWindowRect(&rect, dwstyle, FALSE);\n      width = rect.right - rect.left;\n      height = rect.bottom - rect.top;\n   }\n\n   win = CreateWindow(\"zwingraph\", text ? text : \"sample\", dwstyle,\n                      CW_USEDEFAULT,0, width, height,\n                      NULL, NULL, stbwingraph_app, z);\n\n   if (win == NULL) return win;\n\n   if (primary) {\n      if (stbwingraph_primary_window)\n         stbwingraph_DestroyWindow(stbwingraph_primary_window);\n      stbwingraph_primary_window = win;\n   }\n\n   {\n      stbwingraph_event e = { STBWGE_create };\n      stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(win, GWL_USERDATA);\n      z->window = win;\n      e.did_share_lists = z->did_share_lists;\n      e.handle = win;\n      if (z->func(z->data, &e) != STBWINGRAPH_do_not_show)\n         stbwingraph_ShowWindow(win);\n   }\n\n   return win;\n}\n\nvoid *stbwingraph_CreateWindowSimple(stbwingraph_window_proc func, int width, int height)\n{\n   int fullscreen = 0;\n   #ifndef _DEBUG\n   if (width ==  640 && height ==  480) fullscreen = 1;\n   if (width ==  800 && height ==  600) fullscreen = 1;\n   if (width == 1024 && height ==  768) fullscreen = 1;\n   if (width == 1280 && height == 1024) fullscreen = 1;\n   if (width == 1600 && height == 1200) fullscreen = 1;\n   //@TODO: widescreen widths\n   #endif\n   return stbwingraph_CreateWindow(1, func, NULL, NULL, width, height, fullscreen, 1, 0, 0);\n}\n\nvoid *stbwingraph_CreateWindowSimpleFull(stbwingraph_window_proc func, int fullscreen, int ww, int wh, int fw, int fh)\n{\n   if (fullscreen == -1) {\n   #ifdef _DEBUG\n      fullscreen = 0;\n   #else\n      fullscreen = 1;\n   #endif\n   }\n\n   if (fullscreen) {\n      if (fw) ww = fw;\n      if (fh) wh = fh;\n   }\n   return stbwingraph_CreateWindow(1, func, NULL, NULL, ww, wh, fullscreen, 1, 0, 0);\n}\n\nvoid stbwingraph_DestroyWindow(void *window)\n{\n   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(window, GWL_USERDATA);\n   DestroyWindow(window);\n   free(z);\n   if (stbwingraph_primary_window == window)\n      stbwingraph_primary_window = NULL;\n}\n\nvoid stbwingraph_ShowCursor(void *window, int visible)\n{\n   int hide;\n   stbwingraph__window *win;\n   if (!window)\n      window = stbwingraph_primary_window;\n   win = (stbwingraph__window *) GetWindowLong((HWND) window, GWL_USERDATA);\n   hide = !visible;\n   if (hide != win->hide_mouse) {\n      win->hide_mouse = hide;\n      if (!hide)\n         ShowCursor(TRUE);\n      else if (win->in_client)\n         ShowCursor(FALSE);\n   }\n}\n\nfloat stbwingraph_GetTimestep(float minimum_time)\n{\n   float elapsedTime;\n   double thisTime;\n   static double lastTime = -1;\n   \n   if (lastTime == -1)\n      lastTime = timeGetTime() / 1000.0 - minimum_time;\n\n   for(;;) {\n      thisTime = timeGetTime() / 1000.0;\n      elapsedTime = (float) (thisTime - lastTime);\n      if (elapsedTime >= minimum_time) {\n         lastTime = thisTime;         \n         return elapsedTime;\n      }\n      #if 1\n      Sleep(2);\n      #endif\n   }\n}\n\nvoid stbwingraph_SetGLWindow(void *win)\n{\n   stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(win, GWL_USERDATA);\n   if (z)\n      wglMakeCurrent(z->dc, z->rc);\n}\n\nvoid stbwingraph_MakeFonts(void *window, int font_base)\n{\n   wglUseFontBitmaps(GetDC(window ? window : stbwingraph_primary_window), 0, 256, font_base);\n}\n\n// returns 1 if WM_QUIT, 0 if 'func' returned 0\nint stbwingraph_MainLoop(stbwingraph_update func, float mintime)\n{\n   int needs_drawing = FALSE;\n   MSG msg;\n\n   int is_animating = TRUE;\n   if (mintime <= 0) mintime = 0.01f;\n\n   for(;;) {\n      int n;\n\n      is_animating = TRUE;\n      // wait for a message if: (a) we're animating and there's already a message\n      // or (b) we're not animating\n      if (!is_animating || PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {\n         stbwingraph_force_update = FALSE;\n         if (GetMessage(&msg, NULL, 0, 0)) {\n            TranslateMessage(&msg);\n            DispatchMessage(&msg);\n         } else {\n            return 1;   // WM_QUIT\n         }\n\n         // only force a draw for certain messages...\n         // if I don't do this, we peg at 50% for some reason... must\n         // be a bug somewhere, because we peg at 100% when rendering...\n         // very weird... looks like NVIDIA is pumping some messages\n         // through our pipeline? well, ok, I guess if we can get\n         // non-user-generated messages we have to do this\n         if (!stbwingraph_force_update) {\n            switch (msg.message) {\n               case WM_MOUSEMOVE:\n               case WM_NCMOUSEMOVE:\n                  break;\n               case WM_CHAR:         \n               case WM_KEYDOWN:      \n               case WM_KEYUP:        \n               case WM_LBUTTONDOWN:  \n               case WM_MBUTTONDOWN:  \n               case WM_RBUTTONDOWN:  \n               case WM_LBUTTONUP:    \n               case WM_MBUTTONUP:    \n               case WM_RBUTTONUP:    \n               case WM_TIMER:\n               case WM_SIZE:\n               case WM_ACTIVATE:\n                  needs_drawing = TRUE;\n                  break;\n            }\n         } else\n            needs_drawing = TRUE;\n      }\n\n      // if another message, process that first\n      // @TODO: i don't think this is working, because I can't key ahead\n      // in the SVT demo app\n      if (PeekMessage(&msg, NULL, 0,0, PM_NOREMOVE))\n         continue;\n\n      // and now call update\n      if (needs_drawing || is_animating) {\n         int real=1, in_client=1;\n         if (stbwingraph_primary_window) {\n            stbwingraph__window *z = (stbwingraph__window *) GetWindowLong(stbwingraph_primary_window, GWL_USERDATA);\n            if (z && !z->active) {\n               real = 0;\n            }\n            if (z)\n               in_client = z->in_client;\n         }\n\n         if (stbwingraph_primary_window)\n            stbwingraph_SetGLWindow(stbwingraph_primary_window);\n         n = func(stbwingraph_GetTimestep(mintime), real, in_client);\n         if (n == STBWINGRAPH_update_exit)\n            return 0; // update_quit\n\n         is_animating = (n != STBWINGRAPH_update_pause);\n\n         needs_drawing = FALSE;\n      }\n   }\n}\n\nvoid stbwingraph_SwapBuffers(void *win)\n{\n   stbwingraph__window *z;\n   if (win == NULL) win = stbwingraph_primary_window;\n   z = (stbwingraph__window *) GetWindowLong(win, GWL_USERDATA);\n   if (z && z->dc)\n      SwapBuffers(z->dc);\n}\n#endif\n\n#ifdef STB_WINMAIN    \nvoid stbwingraph_main(void);\n\nchar *stb_wingraph_commandline;\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)\n{\n   {\n      char buffer[1024];\n      // add spaces to either side of the string\n      buffer[0] = ' ';\n      strcpy(buffer+1, lpCmdLine);\n      strcat(buffer, \" \");\n      if (strstr(buffer, \" -reset \")) {\n         ChangeDisplaySettings(NULL, 0); \n         exit(0);\n      }\n      if (strstr(buffer, \" -window \") || strstr(buffer, \" -windowed \"))\n         stbwingraph_request_windowed = TRUE;\n      else if (strstr(buffer, \" -full \") || strstr(buffer, \" -fullscreen \"))\n         stbwingraph_request_fullscreen = TRUE;\n   }\n   stb_wingraph_commandline = lpCmdLine;\n\n   stbwingraph_DefineClass(hInstance, \"appicon\");\n   stbwingraph_main();\n\n   return 0;\n}\n#endif\n\n#undef STB_EXTERN\n#ifdef STB_WINGRAPH_DISABLE_DEFINE_AT_END\n#undef STB_DEFINE\n#endif\n\n#endif // INCLUDE_STB_WINGRAPH_H\n"
  },
  {
    "path": "tests/pg_test/pg_test.c",
    "content": "#define STB_DEFINE\n#include \"stb.h\"\n#define STB_PG_IMPLEMENTATION\n#include \"stb_pg.h\"\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\nstatic float *hf;\nstatic int hf_width = 10001;\nstatic int hf_height = 10001;\n\nstatic float get_height(float x, float y)\n{\n   float h00,h01,h10,h11,h0,h1;\n   int ix,iy;\n   if (x < 0) x = 0;\n   if (x > hf_width-1) x = (float) hf_width-1;\n   if (y < 0) y = 0;\n   if (y > hf_height-1) y = (float) hf_height-1;\n   ix = (int) x; x -= ix;\n   iy = (int) y; y -= iy;\n   h00 = hf[(iy+0)*hf_height+(ix+0)];\n   h10 = hf[(iy+0)*hf_height+(ix+1)];\n   h01 = hf[(iy+1)*hf_height+(ix+0)];\n   h11 = hf[(iy+1)*hf_height+(ix+1)];\n   h0 = stb_lerp(y, h00, h01);\n   h1 = stb_lerp(y, h10, h11);\n   return stb_lerp(x, h0, h1);\n}\n\nvoid stbpg_tick(float dt)\n{\n   int i=0,j=0;\n   int step = 1;\n\n   glUseProgram(0);\n\n   glClearColor(0.6f,0.7f,1.0f,1.0f);\n   glClearDepth(1.0f);\n   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n   glDepthFunc(GL_LESS);\n   glEnable(GL_DEPTH_TEST);\n#if 1\n   glEnable(GL_CULL_FACE);\n\n   glMatrixMode(GL_PROJECTION);\n   glLoadIdentity();\n   gluPerspective(60.0, 1920/1080.0f, 0.02f, 8000.0f);\n   //glOrtho(-8,8,-6,6, -100, 100);\n\n   glMatrixMode(GL_MODELVIEW);\n   glLoadIdentity();\n   glRotatef(-90, 1,0,0); // z-up\n\n   {\n      float x,y;\n      stbpg_get_mouselook(&x,&y);\n      glRotatef(-y, 1,0,0);\n      glRotatef(-x, 0,0,1);\n   }\n\n   {\n      static float cam_x = 1000;\n      static float cam_y = 1000;\n      static float cam_z = 700;\n      float x=0,y=0;\n      stbpg_get_keymove(&x,&y);\n      cam_x += x*dt*5.0f;\n      cam_y += y*dt*5.0f;\n      glTranslatef(-cam_x, -cam_y, -cam_z);\n      if (cam_x >= 0 && cam_x < hf_width && cam_y >= 0 && cam_y < hf_height)\n         cam_z = get_height(cam_x, cam_y) + 1.65f; // average eye height in meters\n   }\n\n   for (j=501; j+1 < 1500+0*hf_height; j += step) {\n      glBegin(GL_QUAD_STRIP);\n      for (i=501; i < 1500+0*hf_width; i += step) {\n         static int flip=0;\n         if (flip)\n            glColor3f(0.5,0.5,0.5);\n         else\n            glColor3f(0.4f,0.4f,0.4f);\n         flip = !flip;\n         glVertex3f((float) i, (float) j+step,hf[(j+step)*hf_width+i]);\n         glVertex3f((float) i, (float) j   ,hf[  j    *hf_width+i]);\n      }\n      glEnd();\n   }\n\n   glBegin(GL_LINES);\n      glColor3f(1,0,0); glVertex3f(10,0,0); glVertex3f(0,0,0);\n      glColor3f(0,1,0); glVertex3f(0,10,0); glVertex3f(0,0,0);\n      glColor3f(0,0,1); glVertex3f(0,0,10); glVertex3f(0,0,0);\n   glEnd();\n#endif\n}\n\nvoid stbpg_main(int argc, char **argv)\n{\n   int i,j;\n\n   #if 0\n   int w,h,c;\n   unsigned short *data = stbi_load_16(\"c:/x/ned_1m/test2.png\", &w, &h, &c, 1);\n   stb_filewrite(\"c:/x/ned_1m/x73_y428_10012_10012.bin\", data, w*h*2);\n   #else\n   unsigned short *data = stb_file(\"c:/x/ned_1m/x73_y428_10012_10012.bin\", NULL);\n   int w=10012, h = 10012;\n   #endif\n\n   hf = malloc(hf_width * hf_height * 4);\n   for (j=0; j < hf_height; ++j)\n      for (i=0; i < hf_width; ++i)\n         hf[j*hf_width+i] = data[j*w+i] / 32.0f;\n\n   stbpg_gl_compat_version(1,1);   \n   stbpg_windowed(\"terrain_edit\", 1920, 1080);\n   stbpg_run();\n\n   return;\n}\n"
  },
  {
    "path": "tests/pngsuite/PngSuite.LICENSE",
    "content": "PngSuite\n--------\n\nPermission to use, copy, modify and distribute these images for any\npurpose and without fee is hereby granted.\n\n\n(c) Willem van Schaik, 1996, 2011\n\n"
  },
  {
    "path": "tests/pngsuite/ref_results.csv",
    "content": "filename,width,height,ncomp,error,hash\npngsuite/16bit/basi0g16.png,32,32,1,,0xfc8f2f99\npngsuite/16bit/basi2c16.png,32,32,3,,0x65567ed5\npngsuite/16bit/basi4a16.png,32,32,2,,0x198cf245\npngsuite/16bit/basi6a16.png,32,32,4,,0x3016e9b5\npngsuite/16bit/basn0g16.png,32,32,1,,0xfc8f2f99\npngsuite/16bit/basn2c16.png,32,32,3,,0x65567ed5\npngsuite/16bit/basn4a16.png,32,32,2,,0x198cf245\npngsuite/16bit/basn6a16.png,32,32,4,,0x3016e9b5\npngsuite/16bit/bgai4a16.png,32,32,2,,0x198cf245\npngsuite/16bit/bgan6a16.png,32,32,4,,0x3016e9b5\npngsuite/16bit/bggn4a16.png,32,32,2,,0x198cf245\npngsuite/16bit/bgyn6a16.png,32,32,4,,0x3016e9b5\npngsuite/16bit/oi1n0g16.png,32,32,1,,0xfc8f2f99\npngsuite/16bit/oi1n2c16.png,32,32,3,,0x65567ed5\npngsuite/16bit/oi2n0g16.png,32,32,1,,0xfc8f2f99\npngsuite/16bit/oi2n2c16.png,32,32,3,,0x65567ed5\npngsuite/16bit/oi4n0g16.png,32,32,1,,0xfc8f2f99\npngsuite/16bit/oi4n2c16.png,32,32,3,,0x65567ed5\npngsuite/16bit/oi9n0g16.png,32,32,1,,0xfc8f2f99\npngsuite/16bit/oi9n2c16.png,32,32,3,,0x65567ed5\npngsuite/16bit/tbbn2c16.png,32,32,4,,0xaa9bfe44\npngsuite/16bit/tbgn2c16.png,32,32,4,,0xaa9bfe44\npngsuite/16bit/tbwn0g16.png,32,32,2,,0x075e519a\npngsuite/corrupt/xc1n0g08.png,32,32,2,bad ctype,0x00000000\npngsuite/corrupt/xc9n2c08.png,32,32,2,bad ctype,0x00000000\npngsuite/corrupt/xcrn0g04.png,32,32,2,unknown image type,0x00000000\npngsuite/corrupt/xcsn0g01.png,32,32,1,,0x43b9891f\npngsuite/corrupt/xd0n2c08.png,32,32,1,1/2/4/8/16-bit only,0x00000000\npngsuite/corrupt/xd3n2c08.png,32,32,1,1/2/4/8/16-bit only,0x00000000\npngsuite/corrupt/xd9n2c08.png,32,32,1,1/2/4/8/16-bit only,0x00000000\npngsuite/corrupt/xdtn0g01.png,32,32,1,no IDAT,0x00000000\npngsuite/corrupt/xhdn0g08.png,32,32,1,,0x414f1ca9\npngsuite/corrupt/xlfn0g04.png,32,32,1,unknown image type,0x00000000\npngsuite/corrupt/xs1n0g01.png,32,32,1,unknown image type,0x00000000\npngsuite/corrupt/xs2n0g01.png,32,32,1,unknown image type,0x00000000\npngsuite/corrupt/xs4n0g01.png,32,32,1,unknown image type,0x00000000\npngsuite/corrupt/xs7n0g01.png,32,32,1,unknown image type,0x00000000\npngsuite/iphone/iphone_basi0g01.png,32,32,4,,0x5fb33cfd\npngsuite/iphone/iphone_basi0g02.png,32,32,4,,0x5bbe95c5\npngsuite/iphone/iphone_basi3p02.png,32,32,4,,0x50ba29c5\npngsuite/iphone/iphone_bgwn6a08.png,32,32,4,,0x45d8548a\npngsuite/iphone/iphone_bgyn6a16.png,32,32,4,,0x4b2b7545\npngsuite/iphone/iphone_tbyn3p08.png,32,32,4,,0x8ea9aaaf\npngsuite/iphone/iphone_z06n2c08.png,32,32,4,,0xb5dd034b\npngsuite/primary/basi0g01.png,32,32,1,,0x43b9891f\npngsuite/primary/basi0g02.png,32,32,1,,0xaf0bb3c5\npngsuite/primary/basi0g04.png,32,32,1,,0x6fbaeb45\npngsuite/primary/basi0g08.png,32,32,1,,0x414f1ca9\npngsuite/primary/basi2c08.png,32,32,3,,0x522345c5\npngsuite/primary/basi3p01.png,32,32,3,,0x9c5b75c5\npngsuite/primary/basi3p02.png,32,32,3,,0x46f26ec5\npngsuite/primary/basi3p04.png,32,32,3,,0x35b2e4a5\npngsuite/primary/basi3p08.png,32,32,3,,0xfe066865\npngsuite/primary/basi4a08.png,32,32,2,,0x77cbbfa5\npngsuite/primary/basi6a08.png,32,32,4,,0xb472197d\npngsuite/primary/basn0g01.png,32,32,1,,0x43b9891f\npngsuite/primary/basn0g02.png,32,32,1,,0xaf0bb3c5\npngsuite/primary/basn0g04.png,32,32,1,,0x6fbaeb45\npngsuite/primary/basn0g08.png,32,32,1,,0x414f1ca9\npngsuite/primary/basn2c08.png,32,32,3,,0x522345c5\npngsuite/primary/basn3p01.png,32,32,3,,0x9c5b75c5\npngsuite/primary/basn3p02.png,32,32,3,,0x46f26ec5\npngsuite/primary/basn3p04.png,32,32,3,,0x35b2e4a5\npngsuite/primary/basn3p08.png,32,32,3,,0xfe066865\npngsuite/primary/basn4a08.png,32,32,2,,0x77cbbfa5\npngsuite/primary/basn6a08.png,32,32,4,,0xb472197d\npngsuite/primary/bgai4a08.png,32,32,2,,0x77cbbfa5\npngsuite/primary/bgan6a08.png,32,32,4,,0xb472197d\npngsuite/primary/bgbn4a08.png,32,32,2,,0x77cbbfa5\npngsuite/primary/bgwn6a08.png,32,32,4,,0xb472197d\npngsuite/primary/s01i3p01.png,1,1,3,,0xafb003b6\npngsuite/primary/s01n3p01.png,1,1,3,,0xafb003b6\npngsuite/primary/s02i3p01.png,2,2,3,,0x96f3dd85\npngsuite/primary/s02n3p01.png,2,2,3,,0x96f3dd85\npngsuite/primary/s03i3p01.png,3,3,3,,0xb0cf1241\npngsuite/primary/s03n3p01.png,3,3,3,,0xb0cf1241\npngsuite/primary/s04i3p01.png,4,4,3,,0xbfcedd75\npngsuite/primary/s04n3p01.png,4,4,3,,0xbfcedd75\npngsuite/primary/s05i3p02.png,5,5,3,,0xc322cedd\npngsuite/primary/s05n3p02.png,5,5,3,,0xc322cedd\npngsuite/primary/s06i3p02.png,6,6,3,,0x46916799\npngsuite/primary/s06n3p02.png,6,6,3,,0x46916799\npngsuite/primary/s07i3p02.png,7,7,3,,0xfdabc297\npngsuite/primary/s07n3p02.png,7,7,3,,0xfdabc297\npngsuite/primary/s08i3p02.png,8,8,3,,0x8f036d09\npngsuite/primary/s08n3p02.png,8,8,3,,0x8f036d09\npngsuite/primary/s09i3p02.png,9,9,3,,0x16a46830\npngsuite/primary/s09n3p02.png,9,9,3,,0x16a46830\npngsuite/primary/s32i3p04.png,32,32,3,,0x4bd4fbd3\npngsuite/primary/s32n3p04.png,32,32,3,,0x4bd4fbd3\npngsuite/primary/s33i3p04.png,33,33,3,,0x51aa005e\npngsuite/primary/s33n3p04.png,33,33,3,,0x51aa005e\npngsuite/primary/s34i3p04.png,34,34,3,,0x84818775\npngsuite/primary/s34n3p04.png,34,34,3,,0x84818775\npngsuite/primary/s35i3p04.png,35,35,3,,0x6359ec75\npngsuite/primary/s35n3p04.png,35,35,3,,0x6359ec75\npngsuite/primary/s36i3p04.png,36,36,3,,0xe4878065\npngsuite/primary/s36n3p04.png,36,36,3,,0xe4878065\npngsuite/primary/s37i3p04.png,37,37,3,,0x3cefc423\npngsuite/primary/s37n3p04.png,37,37,3,,0x3cefc423\npngsuite/primary/s38i3p04.png,38,38,3,,0xffc55a2b\npngsuite/primary/s38n3p04.png,38,38,3,,0xffc55a2b\npngsuite/primary/s39i3p04.png,39,39,3,,0x0c790240\npngsuite/primary/s39n3p04.png,39,39,3,,0x0c790240\npngsuite/primary/s40i3p04.png,40,40,3,,0x951a316d\npngsuite/primary/s40n3p04.png,40,40,3,,0x951a316d\npngsuite/primary/tbbn0g04.png,32,32,2,,0x9c8410ea\npngsuite/primary/tbbn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary/tbgn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary/tbrn2c08.png,32,32,4,,0xaa9bfe44\npngsuite/primary/tbwn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary/tbyn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary/tm3n3p02.png,32,32,4,,0xf59745c5\npngsuite/primary/tp0n0g08.png,32,32,1,,0xbac0864c\npngsuite/primary/tp0n2c08.png,32,32,3,,0x82687c37\npngsuite/primary/tp0n3p08.png,32,32,3,,0x61f54e37\npngsuite/primary/tp1n3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary/z00n2c08.png,32,32,3,,0x65b4a72f\npngsuite/primary/z03n2c08.png,32,32,3,,0x65b4a72f\npngsuite/primary/z06n2c08.png,32,32,3,,0x65b4a72f\npngsuite/primary/z09n2c08.png,32,32,3,,0x65b4a72f\npngsuite/primary_check/basi0g01.png,32,32,4,,0x5fb33cfd\npngsuite/primary_check/basi0g02.png,32,32,4,,0x5bbe95c5\npngsuite/primary_check/basi0g04.png,32,32,4,,0x3468b9c5\npngsuite/primary_check/basi0g08.png,32,32,4,,0x262ef46d\npngsuite/primary_check/basi2c08.png,32,32,4,,0x1fc92bc5\npngsuite/primary_check/basi3p01.png,32,32,4,,0x28a3e1c5\npngsuite/primary_check/basi3p02.png,32,32,4,,0x803be5c5\npngsuite/primary_check/basi3p04.png,32,32,4,,0xf3fc60e5\npngsuite/primary_check/basi3p08.png,32,32,4,,0x30ef4f45\npngsuite/primary_check/basi4a08.png,32,32,4,,0x23c8536d\npngsuite/primary_check/basi6a08.png,32,32,4,,0xb472197d\npngsuite/primary_check/basn0g01.png,32,32,4,,0x5fb33cfd\npngsuite/primary_check/basn0g02.png,32,32,4,,0x5bbe95c5\npngsuite/primary_check/basn0g04.png,32,32,4,,0x3468b9c5\npngsuite/primary_check/basn0g08.png,32,32,4,,0x262ef46d\npngsuite/primary_check/basn2c08.png,32,32,4,,0x1fc92bc5\npngsuite/primary_check/basn3p01.png,32,32,4,,0x28a3e1c5\npngsuite/primary_check/basn3p02.png,32,32,4,,0x803be5c5\npngsuite/primary_check/basn3p04.png,32,32,4,,0xf3fc60e5\npngsuite/primary_check/basn3p08.png,32,32,4,,0x30ef4f45\npngsuite/primary_check/basn4a08.png,32,32,4,,0x23c8536d\npngsuite/primary_check/basn6a08.png,32,32,4,,0xb472197d\npngsuite/primary_check/bgai4a08.png,32,32,4,,0x23c8536d\npngsuite/primary_check/bgan6a08.png,32,32,4,,0xb472197d\npngsuite/primary_check/bgbn4a08.png,32,32,4,,0x23c8536d\npngsuite/primary_check/bgwn6a08.png,32,32,4,,0xb472197d\npngsuite/primary_check/s01i3p01.png,1,1,4,,0xdb152beb\npngsuite/primary_check/s01n3p01.png,1,1,4,,0xdb152beb\npngsuite/primary_check/s02i3p01.png,2,2,4,,0xa344a3a5\npngsuite/primary_check/s02n3p01.png,2,2,4,,0xa344a3a5\npngsuite/primary_check/s03i3p01.png,3,3,4,,0x594d3bfa\npngsuite/primary_check/s03n3p01.png,3,3,4,,0x594d3bfa\npngsuite/primary_check/s04i3p01.png,4,4,4,,0xd59d4605\npngsuite/primary_check/s04n3p01.png,4,4,4,,0xd59d4605\npngsuite/primary_check/s05i3p02.png,5,5,4,,0x41e58366\npngsuite/primary_check/s05n3p02.png,5,5,4,,0x41e58366\npngsuite/primary_check/s06i3p02.png,6,6,4,,0xcad1a885\npngsuite/primary_check/s06n3p02.png,6,6,4,,0xcad1a885\npngsuite/primary_check/s07i3p02.png,7,7,4,,0x09184108\npngsuite/primary_check/s07n3p02.png,7,7,4,,0x09184108\npngsuite/primary_check/s08i3p02.png,8,8,4,,0x4fd11cad\npngsuite/primary_check/s08n3p02.png,8,8,4,,0x4fd11cad\npngsuite/primary_check/s09i3p02.png,9,9,4,,0xc50dbecd\npngsuite/primary_check/s09n3p02.png,9,9,4,,0xc50dbecd\npngsuite/primary_check/s32i3p04.png,32,32,4,,0x95cbb1d3\npngsuite/primary_check/s32n3p04.png,32,32,4,,0x95cbb1d3\npngsuite/primary_check/s33i3p04.png,33,33,4,,0x6649fc5b\npngsuite/primary_check/s33n3p04.png,33,33,4,,0x6649fc5b\npngsuite/primary_check/s34i3p04.png,34,34,4,,0x35b98e15\npngsuite/primary_check/s34n3p04.png,34,34,4,,0x35b98e15\npngsuite/primary_check/s35i3p04.png,35,35,4,,0xc9ddf938\npngsuite/primary_check/s35n3p04.png,35,35,4,,0xc9ddf938\npngsuite/primary_check/s36i3p04.png,36,36,4,,0x7bb4e1cd\npngsuite/primary_check/s36n3p04.png,36,36,4,,0x7bb4e1cd\npngsuite/primary_check/s37i3p04.png,37,37,4,,0xee50001c\npngsuite/primary_check/s37n3p04.png,37,37,4,,0xee50001c\npngsuite/primary_check/s38i3p04.png,38,38,4,,0x51b76813\npngsuite/primary_check/s38n3p04.png,38,38,4,,0x51b76813\npngsuite/primary_check/s39i3p04.png,39,39,4,,0x42f23327\npngsuite/primary_check/s39n3p04.png,39,39,4,,0x42f23327\npngsuite/primary_check/s40i3p04.png,40,40,4,,0xf91b6a7d\npngsuite/primary_check/s40n3p04.png,40,40,4,,0xf91b6a7d\npngsuite/primary_check/tbbn0g04.png,32,32,4,,0x8a0117a4\npngsuite/primary_check/tbbn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary_check/tbgn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary_check/tbrn2c08.png,32,32,4,,0xaa9bfe44\npngsuite/primary_check/tbwn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary_check/tbyn3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary_check/tm3n3p02.png,32,32,4,,0xf59745c5\npngsuite/primary_check/tp0n0g08.png,32,32,4,,0xd405ad2e\npngsuite/primary_check/tp0n2c08.png,32,32,4,,0x5a66ca09\npngsuite/primary_check/tp0n3p08.png,32,32,4,,0x06e81adf\npngsuite/primary_check/tp1n3p08.png,32,32,4,,0x82bf9a57\npngsuite/primary_check/z00n2c08.png,32,32,4,,0xaa698493\npngsuite/primary_check/z03n2c08.png,32,32,4,,0xaa698493\npngsuite/primary_check/z06n2c08.png,32,32,4,,0xaa698493\npngsuite/primary_check/z09n2c08.png,32,32,4,,0xaa698493\npngsuite/unused/ccwn2c08.png,32,32,3,,0xbb576418\npngsuite/unused/ccwn3p08.png,32,32,3,,0x5c4df060\npngsuite/unused/cdfn2c08.png,8,32,3,,0xe30ed48f\npngsuite/unused/cdhn2c08.png,32,8,3,,0x999321f5\npngsuite/unused/cdsn2c08.png,8,8,3,,0x7f63fa01\npngsuite/unused/cdun2c08.png,32,32,3,,0xbd325d71\npngsuite/unused/ch1n3p04.png,32,32,3,,0x35b2e4a5\npngsuite/unused/ch2n3p08.png,32,32,3,,0xfe066865\npngsuite/unused/cm0n0g04.png,32,32,1,,0xe9f53e6c\npngsuite/unused/cm7n0g04.png,32,32,1,,0xe9f53e6c\npngsuite/unused/cm9n0g04.png,32,32,1,,0xe9f53e6c\npngsuite/unused/cs3n2c16.png,32,32,3,,0x7f0fa2c5\npngsuite/unused/cs3n3p08.png,32,32,3,,0x5533bac5\npngsuite/unused/cs5n2c08.png,32,32,3,,0x8a80f8c5\npngsuite/unused/cs5n3p08.png,32,32,3,,0x8a80f8c5\npngsuite/unused/cs8n2c08.png,32,32,3,,0x7f0fa2c5\npngsuite/unused/cs8n3p08.png,32,32,3,,0x7f0fa2c5\npngsuite/unused/ct0n0g04.png,32,32,1,,0xe9f53e6c\npngsuite/unused/ct1n0g04.png,32,32,1,,0xe9f53e6c\npngsuite/unused/cten0g04.png,32,32,1,,0x1c073b45\npngsuite/unused/ctfn0g04.png,32,32,1,,0xfa9fd205\npngsuite/unused/ctgn0g04.png,32,32,1,,0xf28c8085\npngsuite/unused/cthn0g04.png,32,32,1,,0x7c039595\npngsuite/unused/ctjn0g04.png,32,32,1,,0xc520f455\npngsuite/unused/ctzn0g04.png,32,32,1,,0xe9f53e6c\npngsuite/unused/f00n0g08.png,32,32,1,,0x21db411b\npngsuite/unused/f00n2c08.png,32,32,3,,0x1f25ded0\npngsuite/unused/f01n0g08.png,32,32,1,,0x7437b32a\npngsuite/unused/f01n2c08.png,32,32,3,,0x0d4507ae\npngsuite/unused/f02n0g08.png,32,32,1,,0x6b633c7c\npngsuite/unused/f02n2c08.png,32,32,3,,0x4b278986\npngsuite/unused/f03n0g08.png,32,32,1,,0x2f31c08e\npngsuite/unused/f03n2c08.png,32,32,3,,0x843ecc7e\npngsuite/unused/f04n0g08.png,32,32,1,,0xfd3a0b73\npngsuite/unused/f04n2c08.png,32,32,3,,0x557174bc\npngsuite/unused/f99n0g04.png,32,32,1,,0xb79aa6e1\npngsuite/unused/g03n0g16.png,32,32,1,,0xecd13817\npngsuite/unused/g03n2c08.png,32,32,3,,0x242407a8\npngsuite/unused/g03n3p04.png,32,32,3,,0xe801ecc8\npngsuite/unused/g04n0g16.png,32,32,1,,0xc11bc972\npngsuite/unused/g04n2c08.png,32,32,3,,0xdf843cc4\npngsuite/unused/g04n3p04.png,32,32,3,,0x60e41f3b\npngsuite/unused/g05n0g16.png,32,32,1,,0xbe6615a5\npngsuite/unused/g05n2c08.png,32,32,3,,0x5c312116\npngsuite/unused/g05n3p04.png,32,32,3,,0x2e0fbf86\npngsuite/unused/g07n0g16.png,32,32,1,,0x2b54a398\npngsuite/unused/g07n2c08.png,32,32,3,,0xf765fb10\npngsuite/unused/g07n3p04.png,32,32,3,,0x9a8c3338\npngsuite/unused/g10n0g16.png,32,32,1,,0xb08a92e1\npngsuite/unused/g10n2c08.png,32,32,3,,0xa43f2291\npngsuite/unused/g10n3p04.png,32,32,3,,0xb733194c\npngsuite/unused/g25n0g16.png,32,32,1,,0xa6b1f5dd\npngsuite/unused/g25n2c08.png,32,32,3,,0x767aee0c\npngsuite/unused/g25n3p04.png,32,32,3,,0x4cf349a8\npngsuite/unused/pp0n2c16.png,32,32,3,,0x65567ed5\npngsuite/unused/pp0n6a08.png,32,32,4,,0x3188c645\npngsuite/unused/ps1n0g08.png,32,32,1,,0x414f1ca9\npngsuite/unused/ps1n2c16.png,32,32,3,,0x65567ed5\npngsuite/unused/ps2n0g08.png,32,32,1,,0x414f1ca9\npngsuite/unused/ps2n2c16.png,32,32,3,,0x65567ed5\n"
  },
  {
    "path": "tests/prerelease/stb_lib.h",
    "content": "/* stb_lib.h - v1.00 - http://nothings.org/stb\n   no warranty is offered or implied; use this code at your own risk\n\n ============================================================================\n   You MUST                                                                  \n                                                                             \n      #define STB_LIB_IMPLEMENTATION\n                                                                             \n   in EXACTLY _one_ C or C++ file that includes this header, BEFORE the\n   include, like this:                                                                \n                                                                             \n      #define STB_LIB_IMPLEMENTATION\n      #include \"stblib_files.h\"\n      \n   All other files should just #include \"stblib_files.h\" without the #define.\n ============================================================================\n\nLICENSE\n\n See end of file for license information.\n\nCREDITS\n\n Written by Sean Barrett.\n\n Fixes:\n  Philipp Wiesemann    Robert Nix\n  r-lyeh               blackpawn\n  github:Mojofreem     Ryan Whitworth\n  Vincent Isambart     Mike Sartain\n  Eugene Opalev        Tim Sjostrand\n  github:infatum       Dave Butler\n*/\n\n#ifndef STB_INCLUDE_STB_LIB_H\n\n#include <stdarg.h>\n\n#if defined(_WIN32) && !defined(__MINGW32__)\n   #ifndef _CRT_SECURE_NO_WARNINGS\n   #define _CRT_SECURE_NO_WARNINGS\n   #endif\n   #ifndef _CRT_NONSTDC_NO_DEPRECATE\n   #define _CRT_NONSTDC_NO_DEPRECATE\n   #endif\n   #ifndef _CRT_NON_CONFORMING_SWPRINTFS\n   #define _CRT_NON_CONFORMING_SWPRINTFS\n   #endif\n   #if !defined(_MSC_VER) || _MSC_VER > 1700\n   #include <intrin.h> // _BitScanReverse\n   #endif\n#endif\n\n#include <stdlib.h>     // stdlib could have min/max\n#include <stdio.h>      // need FILE\n#include <string.h>     // stb_define_hash needs memcpy/memset\n#include <time.h>       // stb_dirtree\n\ntypedef unsigned char stb_uchar;\ntypedef unsigned char stb_uint8;\ntypedef unsigned int  stb_uint;\ntypedef unsigned short stb_uint16;\ntypedef          short stb_int16;\ntypedef   signed char  stb_int8;\n#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)\n  typedef unsigned long  stb_uint32;\n  typedef          long  stb_int32;\n#else\n  typedef unsigned int   stb_uint32;\n  typedef          int   stb_int32;\n#endif\ntypedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];\ntypedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];\n\n#ifdef _MSC_VER\n  typedef unsigned __int64 stb_uint64;\n  typedef          __int64 stb_int64;\n  #define STB_IMM_UINT64(literalui64) (literalui64##ui64)\n#else\n  // ??\n  typedef unsigned long long stb_uint64;\n  typedef          long long stb_int64;\n  #define STB_IMM_UINT64(literalui64) (literalui64##ULL)\n#endif\ntypedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];\n\n#ifdef __cplusplus\n   #define STB_EXTERN   extern \"C\"\n#else\n   #define STB_EXTERN   extern\n#endif\n\n// check for well-known debug defines\n#if defined(DEBUG) || defined(_DEBUG) || defined(DBG)\n   #ifndef NDEBUG\n      #define STB_DEBUG\n   #endif\n#endif\n\n#ifdef STB_DEBUG\n   #include <assert.h>\n#endif\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\n   #include <assert.h>\n   #include <stdarg.h>\n   #include <stddef.h>\n   #include <ctype.h>\n   #include <math.h>\n   #ifndef _WIN32\n   #include <unistd.h>\n   #else\n   #include <io.h>      // _mktemp\n   #include <direct.h>  // _rmdir\n   #endif\n   #include <sys/types.h> // stat()/_stat()\n   #include <sys/stat.h>  // stat()/_stat()\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Miscellany\n//\n\n#ifdef _WIN32\n   #define stb_stricmp(a,b)    stricmp(a,b)\n   #define stb_strnicmp(a,b,n) strnicmp(a,b,n)\n#else\n   #define stb_stricmp(a,b)    strcasecmp(a,b)\n   #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)\n#endif\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN void stb_fatal(char *fmt, ...);\nSTB_EXTERN void stb_swap(void *p, void *q, size_t sz);\nSTB_EXTERN double stb_linear_remap(double x, double x_min, double x_max,\n                                  double out_min, double out_max);\n\n#define stb_arrcount(x)   (sizeof(x)/sizeof((x)[0]))\n#define stb_lerp(t,a,b)               ( (a) + (t) * (float) ((b)-(a)) )\n#define stb_unlerp(t,a,b)             ( ((t) - (a)) / (float) ((b) - (a)) )\n\n#endif\n\n\n#ifdef STB_LIB_IMPLEMENTATION\nvoid stb_fatal(char *s, ...)\n{\n   va_list a;\n   va_start(a,s);\n   fputs(\"Fatal error: \", stderr);\n   vfprintf(stderr, s, a);\n   va_end(a);\n   fputs(\"\\n\", stderr);\n   #ifdef STB_DEBUG\n   #ifdef _MSC_VER\n   #ifndef _WIN64\n   __asm int 3;   // trap to debugger!\n   #else\n   __debugbreak();\n   #endif\n   #else\n   __builtin_trap();\n   #endif\n   #endif\n   exit(1);\n}\n\ntypedef struct { char d[4]; } stb__4;\ntypedef struct { char d[8]; } stb__8;\n\n// optimize the small cases, though you shouldn't be calling this for those!\nvoid stb_swap(void *p, void *q, size_t sz)\n{\n   char buffer[256];\n   if (p == q) return;\n   if (sz == 4) {\n      stb__4 temp    = * ( stb__4 *) p;\n      * (stb__4 *) p = * ( stb__4 *) q;\n      * (stb__4 *) q = temp;\n      return;\n   } else if (sz == 8) {\n      stb__8 temp    = * ( stb__8 *) p;\n      * (stb__8 *) p = * ( stb__8 *) q;\n      * (stb__8 *) q = temp;\n      return;\n   }\n\n   while (sz > sizeof(buffer)) {\n      stb_swap(p, q, sizeof(buffer));\n      p = (char *) p + sizeof(buffer);\n      q = (char *) q + sizeof(buffer);\n      sz -= sizeof(buffer);\n   }\n\n   memcpy(buffer, p     , sz);\n   memcpy(p     , q     , sz);\n   memcpy(q     , buffer, sz);\n}\n\n#ifdef stb_linear_remap\n#undef stb_linear_remap\n#endif\n\ndouble stb_linear_remap(double x, double x_min, double x_max,\n                                  double out_min, double out_max)\n{\n   return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);\n}\n\n#define stb_linear_remap(t,a,b,c,d)   stb_lerp(stb_unlerp(t,a,b),c,d)\n#endif // STB_LIB_IMPLEMENTATION\n\n#ifndef STB_INCLUDE_STB_LIB_H\n// avoid unnecessary function call, but define function so its address can be taken\n#ifndef stb_linear_remap\n#define stb_linear_remap(t,a,b,c,d)   stb_lerp(stb_unlerp(t,a,b),c,d)\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//     cross-platform snprintf because they keep changing that,\n//     and with old compilers without vararg macros we can't write\n//     a macro wrapper to fix it up\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN int  stb_snprintf(char *s, size_t n, const char *fmt, ...);\nSTB_EXTERN int  stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);\nSTB_EXTERN char *stb_sprintf(const char *fmt, ...);\n#endif\n\n#ifdef STB_LIB_IMPLEMENTATION\n\nint stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)\n{\n   int res;\n   #ifdef _WIN32\n   // Could use \"_vsnprintf_s(s, n, _TRUNCATE, fmt, v)\" ?\n   res = _vsnprintf(s,n,fmt,v);\n   #else\n   res = vsnprintf(s,n,fmt,v);\n   #endif\n   if (n) s[n-1] = 0;\n   // Unix returns length output would require, Windows returns negative when truncated.\n   return (res >= (int) n || res < 0) ? -1 : res;\n}\n\nint stb_snprintf(char *s, size_t n, const char *fmt, ...)\n{\n   int res;\n   va_list v;\n   va_start(v,fmt);\n   res = stb_vsnprintf(s, n, fmt, v);\n   va_end(v);\n   return res;\n}\n\nchar *stb_sprintf(const char *fmt, ...)\n{\n   static char buffer[1024];\n   va_list v;\n   va_start(v,fmt);\n   stb_vsnprintf(buffer,1024,fmt,v);\n   va_end(v);\n   return buffer;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                         Windows UTF8 filename handling\n//\n// Windows stupidly treats 8-bit filenames as some dopey code page,\n// rather than utf-8. If we want to use utf8 filenames, we have to\n// convert them to WCHAR explicitly and call WCHAR versions of the\n// file functions. So, ok, we do.\n\n\n#ifndef STB_INCLUDE_STB_LIB_H\n#ifdef _WIN32\n   #define stb__fopen(x,y)    _wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))\n   #define stb__windows(x,y)  x\n#else\n   #define stb__fopen(x,y)    fopen(x,y)\n   #define stb__windows(x,y)  y\n#endif\n\n\ntypedef unsigned short stb__wchar;\n\nSTB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, char *str, int n);\nSTB_EXTERN char       * stb_to_utf8  (char *buffer, stb__wchar *str, int n);\n\nSTB_EXTERN stb__wchar *stb__from_utf8(char *str);\nSTB_EXTERN stb__wchar *stb__from_utf8_alt(char *str);\nSTB_EXTERN char *stb__to_utf8(stb__wchar *str);\n#endif\n\n#ifdef STB_LIB_IMPLEMENTATION\nstb__wchar * stb_from_utf8(stb__wchar *buffer, char *ostr, int n)\n{\n   unsigned char *str = (unsigned char *) ostr;\n   stb_uint32 c;\n   int i=0;\n   --n;\n   while (*str) {\n      if (i >= n)\n         return NULL;\n      if (!(*str & 0x80))\n         buffer[i++] = *str++;\n      else if ((*str & 0xe0) == 0xc0) {\n         if (*str < 0xc2) return NULL;\n         c = (*str++ & 0x1f) << 6;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         buffer[i++] = c + (*str++ & 0x3f);\n      } else if ((*str & 0xf0) == 0xe0) {\n         if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;\n         if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below\n         c = (*str++ & 0x0f) << 12;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f) << 6;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         buffer[i++] = c + (*str++ & 0x3f);\n      } else if ((*str & 0xf8) == 0xf0) {\n         if (*str > 0xf4) return NULL;\n         if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;\n         if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below\n         c = (*str++ & 0x07) << 18;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f) << 12;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f) << 6;\n         if ((*str & 0xc0) != 0x80) return NULL;\n         c += (*str++ & 0x3f);\n         // utf-8 encodings of values used in surrogate pairs are invalid\n         if ((c & 0xFFFFF800) == 0xD800) return NULL;\n         if (c >= 0x10000) {\n            c -= 0x10000;\n            if (i + 2 > n) return NULL;\n            buffer[i++] = 0xD800 | (0x3ff & (c >> 10));\n            buffer[i++] = 0xDC00 | (0x3ff & (c      ));\n         }\n      } else\n         return NULL;\n   }\n   buffer[i] = 0;\n   return buffer;\n}\n\nchar * stb_to_utf8(char *buffer, stb__wchar *str, int n)\n{\n   int i=0;\n   --n;\n   while (*str) {\n      if (*str < 0x80) {\n         if (i+1 > n) return NULL;\n         buffer[i++] = (char) *str++;\n      } else if (*str < 0x800) {\n         if (i+2 > n) return NULL;\n         buffer[i++] = 0xc0 + (*str >> 6);\n         buffer[i++] = 0x80 + (*str & 0x3f);\n         str += 1;\n      } else if (*str >= 0xd800 && *str < 0xdc00) {\n         stb_uint32 c;\n         if (i+4 > n) return NULL;\n         c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;\n         buffer[i++] = 0xf0 + (c >> 18);\n         buffer[i++] = 0x80 + ((c >> 12) & 0x3f);\n         buffer[i++] = 0x80 + ((c >>  6) & 0x3f);\n         buffer[i++] = 0x80 + ((c      ) & 0x3f);\n         str += 2;\n      } else if (*str >= 0xdc00 && *str < 0xe000) {\n         return NULL;\n      } else {\n         if (i+3 > n) return NULL;\n         buffer[i++] = 0xe0 + (*str >> 12);\n         buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);\n         buffer[i++] = 0x80 + ((*str     ) & 0x3f);\n         str += 1;\n      }\n   }\n   buffer[i] = 0;\n   return buffer;\n}\n\nstb__wchar *stb__from_utf8(char *str)\n{\n   static stb__wchar buffer[4096];\n   return stb_from_utf8(buffer, str, 4096);\n}\n\nstb__wchar *stb__from_utf8_alt(char *str)\n{\n   static stb__wchar buffer[4096];\n   return stb_from_utf8(buffer, str, 4096);\n}\n\nchar *stb__to_utf8(stb__wchar *str)\n{\n   static char buffer[4096];\n   return stb_to_utf8(buffer, str, 4096);\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                            qsort Compare Routines\n//                              NOT THREAD SAFE\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_ucharcmp(int offset))(const void *a, const void *b);\nSTB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);\n#endif\n\n#ifdef STB_LIB_IMPLEMENTATION\nstatic int stb__intcmpoffset, stb__ucharcmpoffset, stb__strcmpoffset;\nstatic int stb__floatcmpoffset, stb__doublecmpoffset, stb__charcmpoffset;\n\nint stb__intcmp(const void *a, const void *b)\n{\n   const int p = *(const int *) ((const char *) a + stb__intcmpoffset);\n   const int q = *(const int *) ((const char *) b + stb__intcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__ucharcmp(const void *a, const void *b)\n{\n   const int p = *(const unsigned char *) ((const char *) a + stb__ucharcmpoffset);\n   const int q = *(const unsigned char *) ((const char *) b + stb__ucharcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__charcmp(const void *a, const void *b)\n{\n   const int p = *(const char *) ((const char *) a + stb__ucharcmpoffset);\n   const int q = *(const char *) ((const char *) b + stb__ucharcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__floatcmp(const void *a, const void *b)\n{\n   const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);\n   const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__doublecmp(const void *a, const void *b)\n{\n   const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);\n   const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);\n   return p < q ? -1 : p > q;\n}\n\nint stb__qsort_strcmp(const void *a, const void *b)\n{\n   const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);\n   const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);\n   return strcmp(p,q);\n}\n\nint stb__qsort_stricmp(const void *a, const void *b)\n{\n   const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);\n   const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);\n   return stb_stricmp(p,q);\n}\n\nint (*stb_intcmp(int offset))(const void *, const void *)\n{\n   stb__intcmpoffset = offset;\n   return &stb__intcmp;\n}\n\nint (*stb_ucharcmp(int offset))(const void *, const void *)\n{\n   stb__ucharcmpoffset = offset;\n   return &stb__ucharcmp;\n}\n\nint (*stb_charcmp(int offset))(const void *, const void *)\n{\n   stb__charcmpoffset = offset;\n   return &stb__ucharcmp;\n}\n\nint (*stb_qsort_strcmp(int offset))(const void *, const void *)\n{\n   stb__strcmpoffset = offset;\n   return &stb__qsort_strcmp;\n}\n\nint (*stb_qsort_stricmp(int offset))(const void *, const void *)\n{\n   stb__strcmpoffset = offset;\n   return &stb__qsort_stricmp;\n}\n\nint (*stb_floatcmp(int offset))(const void *, const void *)\n{\n   stb__floatcmpoffset = offset;\n   return &stb__floatcmp;\n}\n\nint (*stb_doublecmp(int offset))(const void *, const void *)\n{\n   stb__doublecmpoffset = offset;\n   return &stb__doublecmp;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                           String Processing\n//\n\n#ifndef STB_INCLUDE_STB_LIB_H\n#define stb_prefixi(s,t)  (0==stb_strnicmp((s),(t),strlen(t)))\n\nenum stb_splitpath_flag\n{\n   STB_PATH = 1,\n   STB_FILE = 2,\n   STB_EXT  = 4,\n   STB_PATH_FILE = STB_PATH + STB_FILE,\n   STB_FILE_EXT  = STB_FILE + STB_EXT,\n   STB_EXT_NO_PERIOD = 8,\n};\n\nSTB_EXTERN char * stb_skipwhite(char *s);\nSTB_EXTERN char * stb_trimwhite(char *s);\nSTB_EXTERN char * stb_skipnewline(char *s);\nSTB_EXTERN char * stb_strncpy(char *s, char *t, int n);\nSTB_EXTERN char * stb_substr(char *t, int n);\nSTB_EXTERN char * stb_duplower(char *s);\nSTB_EXTERN void   stb_tolower (char *s);\nSTB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);\nSTB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);\nSTB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);\nSTB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);\nSTB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);\nSTB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);\nSTB_EXTERN void   stb_replaceinplace(char *s, char *find, char *replace);\nSTB_EXTERN char * stb_splitpath(char *output, char *src, int flag);\nSTB_EXTERN char * stb_splitpathdup(char *src, int flag);\nSTB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);\nSTB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);\nSTB_EXTERN void   stb_fixpath(char *path);\nSTB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);\nSTB_EXTERN int    stb_suffix (char *s, char *t);\nSTB_EXTERN int    stb_suffixi(char *s, char *t);\nSTB_EXTERN int    stb_prefix (char *s, char *t);\nSTB_EXTERN char * stb_strichr(char *s, char t);\nSTB_EXTERN char * stb_stristr(char *s, char *t);\nSTB_EXTERN int    stb_prefix_count(char *s, char *t);\nSTB_EXTERN const char * stb_plural(int n);  // \"s\" or \"\"\nSTB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);\n\nSTB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);\nSTB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);\nSTB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);\nSTB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);\n// with 'quoted', allow delimiters to appear inside quotation marks, and don't\n// strip whitespace inside them (and we delete the quotation marks unless they\n// appear back to back, in which case they're considered escaped)\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\n#include <ctype.h>\n\nsize_t stb_strscpy(char *d, const char *s, size_t n)\n{\n   size_t len = strlen(s);\n   if (len >= n) {\n      if (n) d[0] = 0;\n      return 0;\n   }\n   strcpy(d,s);\n   return len + 1;\n}\n\nconst char *stb_plural(int n)\n{\n   return n == 1 ? \"\" : \"s\";\n}\n\nint stb_prefix(char *s, char *t)\n{\n   while (*t)\n      if (*s++ != *t++)\n         return 0;\n   return 1;\n}\n\nint stb_prefix_count(char *s, char *t)\n{\n   int c=0;\n   while (*t) {\n      if (*s++ != *t++)\n         break;\n      ++c;\n   }\n   return c;\n}\n\nint stb_suffix(char *s, char *t)\n{\n   size_t n = strlen(s);\n   size_t m = strlen(t);\n   if (m <= n)\n      return 0 == strcmp(s+n-m, t);\n   else\n      return 0;\n}\n\nint stb_suffixi(char *s, char *t)\n{\n   size_t n = strlen(s);\n   size_t m = strlen(t);\n   if (m <= n)\n      return 0 == stb_stricmp(s+n-m, t);\n   else\n      return 0;\n}\n\n// originally I was using this table so that I could create known sentinel\n// values--e.g. change whitetable[0] to be true if I was scanning for whitespace,\n// and false if I was scanning for nonwhite. I don't appear to be using that\n// functionality anymore (I do for tokentable, though), so just replace it\n// with isspace()\nchar *stb_skipwhite(char *s)\n{\n   while (isspace((unsigned char) *s)) ++s;\n   return s;\n}\n\nchar *stb_skipnewline(char *s)\n{\n   if (s[0] == '\\r' || s[0] == '\\n') {\n      if (s[0]+s[1] == '\\r' + '\\n') ++s;\n      ++s;\n   }\n   return s;\n}\n\nchar *stb_trimwhite(char *s)\n{\n   int i,n;\n   s = stb_skipwhite(s);\n   n = (int) strlen(s);\n   for (i=n-1; i >= 0; --i)\n      if (!isspace(s[i]))\n         break;\n   s[i+1] = 0;\n   return s;\n}\n\nchar *stb_strncpy(char *s, char *t, int n)\n{\n   strncpy(s,t,n);\n   s[n-1] = 0;\n   return s;\n}\n\nchar *stb_substr(char *t, int n)\n{\n   char *a;\n   int z = (int) strlen(t);\n   if (z < n) n = z;\n   a = (char *) malloc(n+1);\n   strncpy(a,t,n);\n   a[n] = 0;\n   return a;\n}\n\nchar *stb_duplower(char *s)\n{\n   char *p = strdup(s), *q = p;\n   while (*q) {\n      *q = tolower(*q);\n      ++q;\n   }\n   return p;\n}\n\nvoid stb_tolower(char *s)\n{\n   while (*s) {\n      *s = tolower(*s);\n      ++s;\n   }\n}\n\nchar *stb_strchr2(char *s, char x, char y)\n{\n   for(; *s; ++s)\n      if (*s == x || *s == y)\n         return s;\n   return NULL;\n}\n\nchar *stb_strrchr2(char *s, char x, char y)\n{\n   char *r = NULL;\n   for(; *s; ++s)\n      if (*s == x || *s == y)\n         r = s;\n   return r;\n}\n\nchar *stb_strichr(char *s, char t)\n{\n   if (tolower(t) == toupper(t))\n      return strchr(s,t);\n   return stb_strchr2(s, (char) tolower(t), (char) toupper(t));\n}\n\nchar *stb_stristr(char *s, char *t)\n{\n   size_t n = strlen(t);\n   char *z;\n   if (n==0) return s;\n   while ((z = stb_strichr(s, *t)) != NULL) {\n      if (0==stb_strnicmp(z, t, n))\n         return z;\n      s = z+1;\n   }\n   return NULL;\n}\n\nstatic char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert)\n{\n   if (invert) {\n      while (*src && strchr(delimit, *src) != NULL) {\n         *output++ = *src++;\n      }\n   } else {\n      while (*src && strchr(delimit, *src) == NULL) {\n         *output++ = *src++;\n      }\n   }\n   *output = 0;\n   if (keep)\n      return src;\n   else\n      return *src ? src+1 : src;\n}\n\nchar *stb_strtok(char *output, char *src, char *delimit)\n{\n   return stb_strtok_raw(output, src, delimit, 0, 0);\n}\n\nchar *stb_strtok_keep(char *output, char *src, char *delimit)\n{\n   return stb_strtok_raw(output, src, delimit, 1, 0);\n}\n\nchar *stb_strtok_invert(char *output, char *src, char *delimit)\n{\n   return stb_strtok_raw(output, src, delimit, 1,1);\n}\n\nstatic char **stb_tokens_raw(char *src_, char *delimit, int *count,\n                             int stripwhite, int allow_empty, char *start, char *end)\n{\n   int nested = 0;\n   unsigned char *src = (unsigned char *) src_;\n   static char stb_tokentable[256]; // rely on static initializion to 0\n   static char stable[256],etable[256];\n   char *out;\n   char **result;\n   int num=0;\n   unsigned char *s;\n\n   s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 1;\n   if (start) {\n      s = (unsigned char *) start;         while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) etable[*s++] = 1;\n   }\n   stable[0] = 1;\n\n   // two passes through: the first time, counting how many\n   s = (unsigned char *) src;\n   while (*s) {\n      // state: just found delimiter\n      // skip further delimiters\n      if (!allow_empty) {\n         stb_tokentable[0] = 0;\n         while (stb_tokentable[*s])\n            ++s;\n         if (!*s) break;\n      }\n      ++num;\n      // skip further non-delimiters\n      stb_tokentable[0] = 1;\n      if (stripwhite == 2) { // quoted strings\n         while (!stb_tokentable[*s]) {\n            if (*s != '\"')\n               ++s;\n            else {\n               ++s;\n               if (*s == '\"')\n                  ++s;   // \"\" -> \", not start a string\n               else {\n                  // begin a string\n                  while (*s) {\n                     if (s[0] == '\"') {\n                        if (s[1] == '\"') s += 2; // \"\" -> \"\n                        else { ++s; break; } // terminating \"\n                     } else\n                        ++s;\n                  }\n               }\n            }\n         }\n      } else \n         while (nested || !stb_tokentable[*s]) {\n            if (stable[*s]) {\n               if (!*s) break;\n               if (end ? etable[*s] : nested)\n                  --nested;\n               else\n                  ++nested;\n            }\n            ++s;\n         }\n      if (allow_empty) {\n         if (*s) ++s;\n      }\n   }\n   // now num has the actual count... malloc our output structure\n   // need space for all the strings: strings won't be any longer than\n   // original input, since for every '\\0' there's at least one delimiter\n   result = (char **) malloc(sizeof(*result) * (num+1) + (s-src+1));\n   if (result == NULL) return result;\n   out = (char *) (result + (num+1));\n   // second pass: copy out the data\n   s = (unsigned char *) src;\n   num = 0;\n   nested = 0;\n   while (*s) {\n      char *last_nonwhite;\n      // state: just found delimiter\n      // skip further delimiters\n      if (!allow_empty) {\n         stb_tokentable[0] = 0;\n         if (stripwhite)\n            while (stb_tokentable[*s] || isspace(*s))\n               ++s;\n         else\n            while (stb_tokentable[*s])\n               ++s;\n      } else if (stripwhite) {\n         while (isspace(*s)) ++s;\n      }\n      if (!*s) break;\n      // we're past any leading delimiters and whitespace\n      result[num] = out;\n      ++num;\n      // copy non-delimiters\n      stb_tokentable[0] = 1;\n      last_nonwhite = out-1;\n      if (stripwhite == 2) {\n         while (!stb_tokentable[*s]) {\n            if (*s != '\"') {\n               if (!isspace(*s)) last_nonwhite = out;\n               *out++ = *s++;\n            } else {\n               ++s;\n               if (*s == '\"') {\n                  if (!isspace(*s)) last_nonwhite = out;\n                  *out++ = *s++; // \"\" -> \", not start string\n               } else {\n                  // begin a quoted string\n                  while (*s) {\n                     if (s[0] == '\"') {\n                        if (s[1] == '\"') { *out++ = *s; s += 2; }\n                        else { ++s; break; } // terminating \"\n                     } else\n                        *out++ = *s++;\n                  }\n                  last_nonwhite = out-1; // all in quotes counts as non-white\n               }\n            }\n         }\n      } else {\n         while (nested || !stb_tokentable[*s]) {\n            if (!isspace(*s)) last_nonwhite = out;\n            if (stable[*s]) {\n               if (!*s) break;\n               if (end ? etable[*s] : nested)\n                  --nested;\n               else\n                  ++nested;\n            }\n            *out++ = *s++;\n         }\n      }\n\n      if (stripwhite) // rewind to last non-whitespace char\n         out = last_nonwhite+1;\n      *out++ = '\\0';\n\n      if (*s) ++s; // skip delimiter\n   }\n   s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 0;\n   if (start) {\n      s = (unsigned char *) start;         while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) stable[*s++] = 1;\n      s = (unsigned char *) end;   if (s)  while (*s) etable[*s++] = 1;\n   }\n   if (count != NULL) *count = num;\n   result[num] = 0;\n   return result;\n}\n\nchar **stb_tokens(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,0,0,0,0);\n}\n\nchar **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out)\n{\n   return stb_tokens_raw(src,delimit,count,0,0,nest_in,nest_out);\n}\n\nchar **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out)\n{\n   return stb_tokens_raw(src,delimit,count,0,1,nest_in,nest_out);\n}\n\nchar **stb_tokens_allowempty(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,0,1,0,0);\n}\n\nchar **stb_tokens_stripwhite(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,1,1,0,0);\n}\n\nchar **stb_tokens_quoted(char *src, char *delimit, int *count)\n{\n   return stb_tokens_raw(src,delimit,count,2,1,0,0);\n}\n\nchar *stb_dupreplace(char *src, char *find, char *replace)\n{\n   size_t len_find = strlen(find);\n   size_t len_replace = strlen(replace);\n   int count = 0;\n\n   char *s,*p,*q;\n\n   s = strstr(src, find);\n   if (s == NULL) return strdup(src);\n   do {\n      ++count;\n      s = strstr(s + len_find, find);\n   } while (s != NULL);\n\n   p = (char *)  malloc(strlen(src) + count * (len_replace - len_find) + 1);\n   if (p == NULL) return p;\n   q = p;\n   s = src;\n   for (;;) {\n      char *t = strstr(s, find);\n      if (t == NULL) {\n         strcpy(q,s);\n         assert(strlen(p) == strlen(src) + count*(len_replace-len_find));\n         return p;\n      }\n      memcpy(q, s, t-s);\n      q += t-s;\n      memcpy(q, replace, len_replace);\n      q += len_replace;\n      s = t + len_find;\n   }\n}\n\nvoid stb_replaceinplace(char *src, char *find, char *replace)\n{\n   size_t len_find = strlen(find);\n   size_t len_replace = strlen(replace);\n   int delta;\n\n   char *s,*p,*q;\n\n   delta = len_replace - len_find;\n   assert(delta <= 0);\n   if (delta > 0) return;\n\n   p = strstr(src, find);\n   if (p == NULL) return;\n\n   s = q = p;\n   while (*s) {\n      memcpy(q, replace, len_replace);\n      p += len_find;\n      q += len_replace;\n      s = strstr(p, find);\n      if (s == NULL) s = p + strlen(p);\n      memmove(q, p, s-p);\n      q += s-p;\n      p = s;\n   }\n   *q = 0;\n}\n\nvoid stb_fixpath(char *path)\n{\n   for(; *path; ++path)\n      if (*path == '\\\\')\n         *path = '/';\n}\n\nvoid stb__add_section(char *buffer, char *data, int curlen, int newlen)\n{\n   if (newlen < curlen) {\n      int z1 = newlen >> 1, z2 = newlen-z1;\n      memcpy(buffer, data, z1-1);\n      buffer[z1-1] = '.';\n      buffer[z1-0] = '.';\n      memcpy(buffer+z1+1, data+curlen-z2+1, z2-1);\n   } else\n      memcpy(buffer, data, curlen);\n}\n\nchar * stb_shorten_path_readable(char *path, int len)\n{\n   static char buffer[1024];\n   int n = strlen(path),n1,n2,r1,r2;\n   char *s;\n   if (n <= len) return path;\n   if (len > 1024) return path;\n   s = stb_strrchr2(path, '/', '\\\\');\n   if (s) {\n      n1 = s - path + 1;\n      n2 = n - n1;\n      ++s;\n   } else {\n      n1 = 0;\n      n2 = n;\n      s = path;\n   }\n   // now we need to reduce r1 and r2 so that they fit in len\n   if (n1 < len>>1) {\n      r1 = n1;\n      r2 = len - r1;\n   } else if (n2 < len >> 1) {\n      r2 = n2;\n      r1 = len - r2;\n   } else {\n      r1 = n1 * len / n;\n      r2 = n2 * len / n;\n      if (r1 < len>>2) r1 = len>>2, r2 = len-r1;\n      if (r2 < len>>2) r2 = len>>2, r1 = len-r2;\n   }\n   assert(r1 <= n1 && r2 <= n2);\n   if (n1)\n      stb__add_section(buffer, path, n1, r1);\n   stb__add_section(buffer+r1, s, n2, r2);\n   buffer[len] = 0;\n   return buffer;\n}\n\nstatic char *stb__splitpath_raw(char *buffer, char *path, int flag)\n{\n   int len=0,x,y, n = (int) strlen(path), f1,f2;\n   char *s = stb_strrchr2(path, '/', '\\\\');\n   char *t = strrchr(path, '.');\n   if (s && t && t < s) t = NULL;\n   if (s) ++s;\n\n   if (flag == STB_EXT_NO_PERIOD)\n      flag |= STB_EXT;\n\n   if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL;\n\n   f1 = s == NULL ? 0 : s-path; // start of filename\n   f2 = t == NULL ? n : t-path; // just past end of filename\n\n   if (flag & STB_PATH) {\n      x = 0; if (f1 == 0 && flag == STB_PATH) len=2;\n   } else if (flag & STB_FILE) {\n      x = f1;\n   } else {\n      x = f2;\n      if (flag & STB_EXT_NO_PERIOD)\n         if (buffer[x] == '.')\n            ++x;\n   }\n\n   if (flag & STB_EXT)\n      y = n;\n   else if (flag & STB_FILE)\n      y = f2;\n   else\n      y = f1;\n\n   if (buffer == NULL) {\n      buffer = (char *) malloc(y-x + len + 1);\n      if (!buffer) return NULL;\n   }\n\n   if (len) { strcpy(buffer, \"./\"); return buffer; }\n   strncpy(buffer, path+x, y-x);\n   buffer[y-x] = 0;\n   return buffer;\n}\n\nchar *stb_splitpath(char *output, char *src, int flag)\n{\n   return stb__splitpath_raw(output, src, flag);\n}\n\nchar *stb_splitpathdup(char *src, int flag)\n{\n   return stb__splitpath_raw(NULL, src, flag);\n}\n\nchar *stb_replacedir(char *output, char *src, char *dir)\n{\n   char buffer[4096];\n   stb_splitpath(buffer, src, STB_FILE | STB_EXT);\n   if (dir)\n      sprintf(output, \"%s/%s\", dir, buffer);\n   else\n      strcpy(output, buffer);\n   return output;\n}\n\nchar *stb_replaceext(char *output, char *src, char *ext)\n{\n   char buffer[4096];\n   stb_splitpath(buffer, src, STB_PATH | STB_FILE);\n   if (ext)\n      sprintf(output, \"%s.%s\", buffer, ext[0] == '.' ? ext+1 : ext);\n   else\n      strcpy(output, buffer);\n   return output;\n}\n#endif\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                                stb_arr\n//\n//  An stb_arr is directly useable as a pointer (use the actual type in your\n//  definition), but when it resizes, it returns a new pointer and you can't\n//  use the old one, so you have to be careful to copy-in-out as necessary.\n//\n//  Use a NULL pointer as a 0-length array.\n//\n//     float *my_array = NULL, *temp;\n//\n//     // add elements on the end one at a time\n//     stb_arr_push(my_array, 0.0f);\n//     stb_arr_push(my_array, 1.0f);\n//     stb_arr_push(my_array, 2.0f);\n//\n//     assert(my_array[1] == 2.0f);\n//\n//     // add an uninitialized element at the end, then assign it\n//     *stb_arr_add(my_array) = 3.0f;\n//\n//     // add three uninitialized elements at the end\n//     temp = stb_arr_addn(my_array,3);\n//     temp[0] = 4.0f;\n//     temp[1] = 5.0f;\n//     temp[2] = 6.0f;\n//\n//     assert(my_array[5] == 5.0f);\n//\n//     // remove the last one\n//     stb_arr_pop(my_array);\n//\n//     assert(stb_arr_len(my_array) == 6);\n\n\n#ifndef STB_INCLUDE_STB_LIB_H\n\n// simple functions written on top of other functions\n#define stb_arr_empty(a)       (  stb_arr_len(a) == 0 )\n#define stb_arr_add(a)         (  stb_arr_addn((a),1) )\n#define stb_arr_push(a,v)      ( *stb_arr_add(a)=(v)  )\n\ntypedef struct\n{\n   int len, limit;\n   unsigned int signature;\n   unsigned int padding; // make it a multiple of 16 so preserve alignment mod 16\n} stb__arr;\n\n#define stb_arr_signature      0x51bada7b  // ends with 0123 in decimal\n\n// access the header block stored before the data\n#define stb_arrhead(a)         /*lint --e(826)*/ (((stb__arr *) (a)) - 1)\n#define stb_arrhead2(a)        /*lint --e(826)*/ (((stb__arr *) (a)) - 1)\n\n#ifdef STB_DEBUG\n#define stb_arr_check(a)       assert(!a || stb_arrhead(a)->signature == stb_arr_signature)\n#define stb_arr_check2(a)      assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)\n#else\n#define stb_arr_check(a)       ((void) 0)\n#define stb_arr_check2(a)      ((void) 0)\n#endif\n\n// ARRAY LENGTH\n\n// get the array length; special case if pointer is NULL\n#define stb_arr_len(a)         (a ? stb_arrhead(a)->len : 0)\n#define stb_arr_len2(a)        ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0)\n#define stb_arr_lastn(a)       (stb_arr_len(a)-1)\n\n// check whether a given index is valid -- tests 0 <= i < stb_arr_len(a) \n#define stb_arr_valid(a,i)     (a ? (int) (i) < stb_arrhead(a)->len : 0)\n\n// change the array length so is is exactly N entries long, creating\n// uninitialized entries as needed\n#define stb_arr_setlen(a,n)  \\\n            (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n)))\n\n// change the array length so that N is a valid index (that is, so\n// it is at least N entries long), creating uninitialized entries as needed\n#define stb_arr_makevalid(a,n)  \\\n            (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a))\n\n// remove the last element of the array, returning it\n#define stb_arr_pop(a)         ((stb_arr_check(a), (a))[--stb_arrhead(a)->len])\n\n// access the last element in the array\n#define stb_arr_last(a)        ((stb_arr_check(a), (a))[stb_arr_len(a)-1])\n\n// is iterator at end of list?\n#define stb_arr_end(a,i)       ((i) >= &(a)[stb_arr_len(a)])\n\n// (internal) change the allocated length of the array\n#define stb_arr__grow(a,n)     (stb_arr_check(a), stb_arrhead(a)->len += (n))\n\n// add N new uninitialized elements to the end of the array\n#define stb_arr__addn(a,n)     /*lint --e(826)*/ \\\n                               ((stb_arr_len(a)+(n) > stb_arrcurmax(a))      \\\n                                 ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \\\n                                 : ((stb_arr__grow(a,n), 0)))\n\n// add N new uninitialized elements to the end of the array, and return\n// a pointer to the first new one\n#define stb_arr_addn(a,n)      (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n))\n\n// add N new uninitialized elements starting at index 'i'\n#define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), i, n))\n\n// insert an element at i\n#define stb_arr_insert(a,i,v)  (stb__arr_insertn((void **) &(a), sizeof(*a), i, 1), ((a)[i] = v))\n\n// delete N elements from the middle starting at index 'i'\n#define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), i, n))\n\n// delete the i'th element\n#define stb_arr_delete(a,i)   stb_arr_deleten(a,i,1)\n\n// delete the i'th element, swapping down from the end\n#define stb_arr_fastdelete(a,i)  \\\n   (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a))\n\n\n// ARRAY STORAGE\n\n// get the array maximum storage; special case if NULL\n#define stb_arrcurmax(a)       (a ? stb_arrhead(a)->limit : 0)\n#define stb_arrcurmax2(a)      (a ? stb_arrhead2(a)->limit : 0)\n\n// set the maxlength of the array to n in anticipation of further growth\n#define stb_arr_setsize(a,n)   (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n))\n\n// make sure maxlength is large enough for at least N new allocations\n#define stb_arr_atleast(a,n)   (stb_arr_len(a)+(n) > stb_arrcurmax(a)      \\\n                                 ? stb_arr_setsize((a), (n)) : 0)\n\n// make a copy of a given array (copies contents via 'memcpy'!)\n#define stb_arr_copy(a)        stb__arr_copy(a, sizeof((a)[0]))\n\n// compute the storage needed to store all the elements of the array\n#define stb_arr_storage(a)     (stb_arr_len(a) * sizeof((a)[0]))\n\n#define stb_arr_for(v,arr)     for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v))\n\n// IMPLEMENTATION\n\nSTB_EXTERN void stb_arr_free_(void **p);\nSTB_EXTERN void *stb__arr_copy_(void *p, int elem_size);\nSTB_EXTERN void stb__arr_setsize_(void **p, int size, int limit);\nSTB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen);\nSTB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen);\nSTB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n);\nSTB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n);\n\n#define stb_arr_free(p)            stb_arr_free_((void **) &(p))\n\n#ifndef STBLIB_MALLOC_WRAPPER // @Todo\n  #define stb__arr_setsize         stb__arr_setsize_\n  #define stb__arr_setlen          stb__arr_setlen_\n  #define stb__arr_addlen          stb__arr_addlen_\n  #define stb__arr_deleten         stb__arr_deleten_\n  #define stb__arr_insertn         stb__arr_insertn_\n  #define stb__arr_copy            stb__arr_copy_\n#else\n  #define stb__arr_addlen(p,s,n)    stb__arr_addlen_(p,s,n,__FILE__,__LINE__)\n  #define stb__arr_setlen(p,s,n)    stb__arr_setlen_(p,s,n,__FILE__,__LINE__)\n  #define stb__arr_setsize(p,s,n)   stb__arr_setsize_(p,s,n,__FILE__,__LINE__)\n  #define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__)\n  #define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__)\n  #define stb__arr_copy(p,s)        stb__arr_copy_(p,s,__FILE__,__LINE__)\n#endif\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\nvoid stb_arr_malloc(void **target, void *context)\n{\n   stb__arr *q = (stb__arr *) malloc(sizeof(*q));\n   q->len = q->limit = 0;\n   q->signature = stb_arr_signature;\n   *target = (void *) (q+1);\n}\n\nstatic void * stb__arr_malloc(int size)\n{\n   return malloc(size);\n}\n\nvoid * stb__arr_copy_(void *p, int elem_size)\n{\n   stb__arr *q;\n   if (p == NULL) return p;\n   q = (stb__arr *) malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit);\n   stb_arr_check2(p);\n   memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len);\n   return q+1;\n}\n\nvoid stb_arr_free_(void **pp)\n{\n   void *p = *pp;\n   stb_arr_check2(p);\n   if (p) {\n      stb__arr *q = stb_arrhead2(p);\n      free(q);\n   }\n   *pp = NULL;\n}\n\nstatic void stb__arrsize_(void **pp, int size, int limit, int len)\n{\n   void *p = *pp;\n   stb__arr *a;\n   stb_arr_check2(p);\n   if (p == NULL) {\n      if (len == 0 && size == 0) return;\n      a = (stb__arr *) stb__arr_malloc(sizeof(*a) + size*limit);\n      a->limit = limit;\n      a->len   = len;\n      a->signature = stb_arr_signature;\n   } else {\n      a = stb_arrhead2(p);\n      a->len = len;\n      if (a->limit < limit) {\n         void *p;\n         if (a->limit >= 4 && limit < a->limit * 2)\n            limit = a->limit * 2;\n         p = realloc(a, sizeof(*a) + limit*size);\n         if (p) {\n            a = (stb__arr *) p;\n            a->limit = limit;\n         } else {\n            // throw an error!\n         }\n      }\n   }\n   a->len = a->len < a->limit ? a->len : a->limit;\n   *pp = a+1;\n}\n\nvoid stb__arr_setsize_(void **pp, int size, int limit)\n{\n   void *p = *pp;\n   stb_arr_check2(p);\n   stb__arrsize_(pp, size, limit, stb_arr_len2(p));\n}\n\nvoid stb__arr_setlen_(void **pp, int size, int newlen)\n{\n   void *p = *pp;\n   stb_arr_check2(p);\n   if (stb_arrcurmax2(p) < newlen || p == NULL) {\n      stb__arrsize_(pp, size, newlen, newlen);\n   } else {\n      stb_arrhead2(p)->len = newlen;\n   }\n}\n\nvoid stb__arr_addlen_(void **p, int size, int addlen)\n{\n   stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen);\n}\n\nvoid stb__arr_insertn_(void **pp, int size, int i, int n)\n{\n   void *p = *pp;\n   if (n) {\n      int z;\n\n      if (p == NULL) {\n         stb__arr_addlen_(pp, size, n);\n         return;\n      }\n\n      z = stb_arr_len2(p);\n      stb__arr_addlen_(&p, size, n);\n      memmove((char *) p + (i+n)*size, (char *) p + i*size, size * (z-i));\n   }\n   *pp = p;\n}\n\nvoid stb__arr_deleten_(void **pp, int size, int i, int n)\n{\n   void *p = *pp;\n   if (n) {\n      memmove((char *) p + i*size, (char *) p + (i+n)*size, size * (stb_arr_len2(p)-(i+n)));\n      stb_arrhead2(p)->len -= n;\n   }\n   *pp = p;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                               Hashing\n//\n//      typical use for this is to make a power-of-two hash table.\n//\n//      let N = size of table (2^n)\n//      let H = stb_hash(str)\n//      let S = stb_rehash(H) | 1\n//\n//      then hash probe sequence P(i) for i=0..N-1\n//         P(i) = (H + S*i) & (N-1)\n//\n//      the idea is that H has 32 bits of hash information, but the\n//      table has only, say, 2^20 entries so only uses 20 of the bits.\n//      then by rehashing the original H we get 2^12 different probe\n//      sequences for a given initial probe location. (So it's optimal\n//      for 64K tables and its optimality decreases past that.)\n//\n//      ok, so I've added something that generates _two separate_\n//      32-bit hashes simultaneously which should scale better to\n//      very large tables.\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN unsigned int stb_hash(char *str);\nSTB_EXTERN unsigned int stb_hashptr(void *p);\nSTB_EXTERN unsigned int stb_hashlen(char *str, int len);\nSTB_EXTERN unsigned int stb_rehash_improved(unsigned int v);\nSTB_EXTERN unsigned int stb_hash_fast(void *p, int len);\nSTB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr);\nSTB_EXTERN unsigned int stb_hash_number(unsigned int hash);\n\n#define stb_rehash(x)  ((x) + ((x) >> 6) + ((x) >> 19))\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\nunsigned int stb_hash(char *str)\n{\n   unsigned int hash = 0;\n   while (*str)\n      hash = (hash << 7) + (hash >> 25) + *str++;\n   return hash + (hash >> 16);\n}\n\nunsigned int stb_hashlen(char *str, int len)\n{\n   unsigned int hash = 0;\n   while (len-- > 0 && *str)\n      hash = (hash << 7) + (hash >> 25) + *str++;\n   return hash + (hash >> 16);\n}\n\nunsigned int stb_hashptr(void *p)\n{\n    unsigned int x = (unsigned int)(size_t) p;\n\n   // typically lacking in low bits and high bits\n   x = stb_rehash(x);\n   x += x << 16;\n\n   // pearson's shuffle\n   x ^= x << 3;\n   x += x >> 5;\n   x ^= x << 2;\n   x += x >> 15;\n   x ^= x << 10;\n   return stb_rehash(x);\n}\n\nunsigned int stb_rehash_improved(unsigned int v)\n{\n   return stb_hashptr((void *)(size_t) v);\n}\n\nunsigned int stb_hash2(char *str, unsigned int *hash2_ptr)\n{\n   unsigned int hash1 = 0x3141592c;\n   unsigned int hash2 = 0x77f044ed;\n   while (*str) {\n      hash1 = (hash1 << 7) + (hash1 >> 25) + *str;\n      hash2 = (hash2 << 11) + (hash2 >> 21) + *str;\n      ++str;\n   }\n   *hash2_ptr = hash2 + (hash1 >> 16);\n   return       hash1 + (hash2 >> 16);\n}\n\n// Paul Hsieh hash\n#define stb__get16_slow(p) ((p)[0] + ((p)[1] << 8))\n#if defined(_MSC_VER)\n   #define stb__get16(p) (*((unsigned short *) (p)))\n#else\n   #define stb__get16(p) stb__get16_slow(p)\n#endif\n\nunsigned int stb_hash_fast(void *p, int len)\n{\n   unsigned char *q = (unsigned char *) p;\n   unsigned int hash = len;\n\n   if (len <= 0 || q == NULL) return 0;\n\n   /* Main loop */\n    if (((int)(size_t) q & 1) == 0) {\n      for (;len > 3; len -= 4) {\n         unsigned int val;\n         hash +=  stb__get16(q);\n         val   = (stb__get16(q+2) << 11);\n         hash  = (hash << 16) ^ hash ^ val;\n         q    += 4;\n         hash += hash >> 11;\n      }\n   } else {\n      for (;len > 3; len -= 4) {\n         unsigned int val;\n         hash +=  stb__get16_slow(q);\n         val   = (stb__get16_slow(q+2) << 11);\n         hash  = (hash << 16) ^ hash ^ val;\n         q    += 4;\n         hash += hash >> 11;\n      }\n   }\n\n   /* Handle end cases */\n   switch (len) {\n      case 3: hash += stb__get16_slow(q);\n              hash ^= hash << 16;\n              hash ^= q[2] << 18;\n              hash += hash >> 11;\n              break;\n      case 2: hash += stb__get16_slow(q);\n              hash ^= hash << 11;\n              hash += hash >> 17;\n              break;\n      case 1: hash += q[0];\n              hash ^= hash << 10;\n              hash += hash >> 1;\n              break;\n      case 0: break;\n   }\n\n   /* Force \"avalanching\" of final 127 bits */\n   hash ^= hash << 3;\n   hash += hash >> 5;\n   hash ^= hash << 4;\n   hash += hash >> 17;\n   hash ^= hash << 25;\n   hash += hash >> 6;\n\n   return hash;\n}\n\nunsigned int stb_hash_number(unsigned int hash)\n{\n   hash ^= hash << 3;\n   hash += hash >> 5;\n   hash ^= hash << 4;\n   hash += hash >> 17;\n   hash ^= hash << 25;\n   hash += hash >> 6;\n   return hash;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                     Instantiated data structures\n//\n// This is an attempt to implement a templated data structure.\n//\n// Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE)\n//     TYPE     -- will define a structure type containing the hash table\n//     N        -- the name, will prefix functions named:\n//                        N create\n//                        N destroy\n//                        N get\n//                        N set, N add, N update,\n//                        N remove\n//     KEY      -- the type of the key. 'x == y' must be valid\n//       K1,K2  -- keys never used by the app, used as flags in the hashtable\n//       HASH   -- a piece of code ending with 'return' that hashes key 'k'\n//     VALUE    -- the type of the value. 'x = y' must be valid\n//\n//  Note that stb_define_hash_base can be used to define more sophisticated\n//  hash tables, e.g. those that make copies of the key or use special\n//  comparisons (e.g. strcmp).\n\n#define STB_(prefix,name)     stb__##prefix##name\n#define STB__(prefix,name)    prefix##name\n#define STB__use(x)           x\n#define STB__skip(x)\n\n#define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \\\n   typedef struct stb__st_##TYPE TYPE;\\\n   PREFIX int STB__(N, init)(TYPE *h, int count);\\\n   PREFIX int STB__(N, memory_usage)(TYPE *h);\\\n   PREFIX TYPE * STB__(N, create)(void);\\\n   PREFIX TYPE * STB__(N, copy)(TYPE *h);\\\n   PREFIX void STB__(N, destroy)(TYPE *h);\\\n   PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\\\n   PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\\\n   PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\\\n   PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\\\n   PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\\\n   PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v);\n\n#define STB_nocopy(x)        (x)\n#define STB_nodelete(x)      0\n#define STB_nofields         \n#define STB_nonullvalue(x)\n#define STB_nullvalue(x)     x\n#define STB_safecompare(x)   x\n#define STB_nosafe(x)\n#define STB_noprefix\n\n#ifdef __GNUC__\n#define STB__nogcc(x)\n#else\n#define STB__nogcc(x)  x\n#endif\n\n#define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR,             \\\n                             KEY,EMPTY,DEL,COPY,DISPOSE,SAFE,                 \\\n                             VCOMPARE,CCOMPARE,HASH,                          \\\n                             VALUE,HASVNULL,VNULL)                            \\\n                                                                              \\\ntypedef struct                                                                \\\n{                                                                             \\\n   KEY   k;                                                                   \\\n   VALUE v;                                                                   \\\n} STB_(N,_hashpair);                                                          \\\n                                                                              \\\nSTB__nogcc( typedef struct stb__st_##TYPE TYPE;  )                            \\\nstruct stb__st_##TYPE {                                                       \\\n   FIELDS                                                                     \\\n   STB_(N,_hashpair) *table;                                                  \\\n   unsigned int mask;                                                         \\\n   int count, limit;                                                          \\\n   int deleted;                                                               \\\n                                                                              \\\n   int delete_threshhold;                                                     \\\n   int grow_threshhold;                                                       \\\n   int shrink_threshhold;                                                     \\\n   unsigned char alloced, has_empty, has_del;                                 \\\n   VALUE ev; VALUE dv;                                                        \\\n};                                                                            \\\n                                                                              \\\nstatic unsigned int STB_(N, hash)(KEY k)                                      \\\n{                                                                             \\\n   HASH                                                                       \\\n}                                                                             \\\n                                                                              \\\nPREFIX int STB__(N, init)(TYPE *h, int count)                                        \\\n{                                                                             \\\n   int i;                                                                     \\\n   if (count < 4) count = 4;                                                  \\\n   h->limit = count;                                                          \\\n   h->count = 0;                                                              \\\n   h->mask  = count-1;                                                        \\\n   h->deleted = 0;                                                            \\\n   h->grow_threshhold = (int) (count * LOAD_FACTOR);                          \\\n   h->has_empty = h->has_del = 0;                                             \\\n   h->alloced = 0;                                                            \\\n   if (count <= 64)                                                           \\\n      h->shrink_threshhold = 0;                                               \\\n   else                                                                       \\\n      h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25));              \\\n   h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2);                  \\\n   h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count);       \\\n   if (h->table == NULL) return 0;                                            \\\n   /* ideally this gets turned into a memset32 automatically */               \\\n   for (i=0; i < count; ++i)                                                  \\\n      h->table[i].k = EMPTY;                                                  \\\n   return 1;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX int STB__(N, memory_usage)(TYPE *h)                                           \\\n{                                                                             \\\n   return sizeof(*h) + h->limit * sizeof(h->table[0]);                        \\\n}                                                                             \\\n                                                                              \\\nPREFIX TYPE * STB__(N, create)(void)                                                 \\\n{                                                                             \\\n   TYPE *h = (TYPE *) malloc(sizeof(*h));                                     \\\n   if (h) {                                                                   \\\n      if (STB__(N, init)(h, 16))                                              \\\n         h->alloced = 1;                                                      \\\n      else { free(h); h=NULL; }                                               \\\n   }                                                                          \\\n   return h;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX void STB__(N, destroy)(TYPE *a)                                               \\\n{                                                                             \\\n   int i;                                                                     \\\n   for (i=0; i < a->limit; ++i)                                               \\\n      if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL))    \\\n         DISPOSE(a->table[i].k);                                              \\\n   free(a->table);                                                            \\\n   if (a->alloced)                                                            \\\n      free(a);                                                                \\\n}                                                                             \\\n                                                                              \\\nstatic void STB_(N, rehash)(TYPE *a, int count);                              \\\n                                                                              \\\nPREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v)                               \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask, s;                                           \\\n   if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\\\n   if (CCOMPARE(k,DEL)) { if (a->has_del  ) *v = a->dv; return a->has_del;   }\\\n   if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \\\n   SAFE(if (!CCOMPARE(a->table[n].k,DEL)))                                    \\\n   if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; }            \\\n   s = stb_rehash(h) | 1;                                                     \\\n   for(;;) {                                                                  \\\n      n = (n + s) & a->mask;                                                  \\\n      if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                            \\\n      SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;)                        \\\n      if (VCOMPARE(a->table[n].k,k))                                           \\\n         { *v = a->table[n].v; return 1; }                                    \\\n   }                                                                          \\\n}                                                                             \\\n                                                                              \\\nHASVNULL(                                                                     \\\n   PREFIX VALUE STB__(N,get)(TYPE *a, KEY k)                                         \\\n   {                                                                          \\\n      VALUE v;                                                                \\\n      if (STB__(N,get_flag)(a,k,&v)) return v;                                \\\n      else                           return VNULL;                            \\\n   }                                                                          \\\n)                                                                             \\\n                                                                              \\\nPREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout)                                \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask, s;                                           \\\n   if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0;                          \\\n   if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \\\n   SAFE(if (!CCOMPARE(a->table[n].k,DEL)))                                    \\\n   if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; }         \\\n   s = stb_rehash(h) | 1;                                                     \\\n   for(;;) {                                                                  \\\n      n = (n + s) & a->mask;                                                  \\\n      if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                            \\\n      SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;)                        \\\n      if (VCOMPARE(a->table[n].k,k))                                          \\\n         { *kout = a->table[n].k; return 1; }                                 \\\n   }                                                                          \\\n}                                                                             \\\n                                                                              \\\nstatic int STB_(N,addset)(TYPE *a, KEY k, VALUE v,                            \\\n                             int allow_new, int allow_old, int copy)          \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask;                                              \\\n   int b = -1;                                                                \\\n   if (CCOMPARE(k,EMPTY)) {                                                   \\\n      if (a->has_empty ? allow_old : allow_new) {                             \\\n          n=a->has_empty; a->ev = v; a->has_empty = 1; return !n;             \\\n      } else return 0;                                                        \\\n   }                                                                          \\\n   if (CCOMPARE(k,DEL)) {                                                     \\\n      if (a->has_del ? allow_old : allow_new) {                               \\\n          n=a->has_del; a->dv = v; a->has_del = 1; return !n;                 \\\n      } else return 0;                                                        \\\n   }                                                                          \\\n   if (!CCOMPARE(a->table[n].k, EMPTY)) {                                     \\\n      unsigned int s;                                                         \\\n      if (CCOMPARE(a->table[n].k, DEL))                                       \\\n         b = n;                                                               \\\n      else if (VCOMPARE(a->table[n].k,k)) {                                   \\\n         if (allow_old)                                                       \\\n            a->table[n].v = v;                                                \\\n         return !allow_new;                                                   \\\n      }                                                                       \\\n      s = stb_rehash(h) | 1;                                                  \\\n      for(;;) {                                                               \\\n         n = (n + s) & a->mask;                                               \\\n         if (CCOMPARE(a->table[n].k, EMPTY)) break;                           \\\n         if (CCOMPARE(a->table[n].k, DEL)) {                                  \\\n            if (b < 0) b = n;                                                 \\\n         } else if (VCOMPARE(a->table[n].k,k)) {                              \\\n            if (allow_old)                                                    \\\n               a->table[n].v = v;                                             \\\n            return !allow_new;                                                \\\n         }                                                                    \\\n      }                                                                       \\\n   }                                                                          \\\n   if (!allow_new) return 0;                                                  \\\n   if (b < 0) b = n; else --a->deleted;                                       \\\n   a->table[b].k = copy ? COPY(k) : k;                                        \\\n   a->table[b].v = v;                                                         \\\n   ++a->count;                                                                \\\n   if (a->count > a->grow_threshhold)                                         \\\n      STB_(N,rehash)(a, a->limit*2);                                          \\\n   return 1;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\\\nPREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\\\nPREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\\\n                                                                              \\\nPREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v)                                \\\n{                                                                             \\\n   unsigned int h = STB_(N, hash)(k);                                         \\\n   unsigned int n = h & a->mask, s;                                           \\\n   if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \\\n   if (CCOMPARE(k,DEL))   { if (a->has_del  ) { if(v)*v = a->dv; a->has_del  =0; return 1; } return 0; } \\\n   if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \\\n   if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) {     \\\n      s = stb_rehash(h) | 1;                                                  \\\n      for(;;) {                                                               \\\n         n = (n + s) & a->mask;                                               \\\n         if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                         \\\n         SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;)                    \\\n         if (VCOMPARE(a->table[n].k,k)) break;                                 \\\n      }                                                                       \\\n   }                                                                          \\\n   DISPOSE(a->table[n].k);                                                    \\\n   a->table[n].k = DEL;                                                       \\\n   --a->count;                                                                \\\n   ++a->deleted;                                                              \\\n   if (v != NULL)                                                             \\\n      *v = a->table[n].v;                                                     \\\n   if (a->count < a->shrink_threshhold)                                       \\\n      STB_(N, rehash)(a, a->limit >> 1);                                      \\\n   else if (a->deleted > a->delete_threshhold)                                \\\n      STB_(N, rehash)(a, a->limit);                                           \\\n   return 1;                                                                  \\\n}                                                                             \\\n                                                                              \\\nPREFIX TYPE * STB__(NC, copy)(TYPE *a)                                        \\\n{                                                                             \\\n   int i;                                                                     \\\n   TYPE *h = (TYPE *) malloc(sizeof(*h));                                     \\\n   if (!h) return NULL;                                                       \\\n   if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; }                \\\n   h->count = a->count;                                                       \\\n   h->deleted = a->deleted;                                                   \\\n   h->alloced = 1;                                                            \\\n   h->ev = a->ev; h->dv = a->dv;                                              \\\n   h->has_empty = a->has_empty; h->has_del = a->has_del;                      \\\n   memcpy(h->table, a->table, h->limit * sizeof(h->table[0]));                \\\n   for (i=0; i < a->limit; ++i)                                               \\\n      if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL))     \\\n         h->table[i].k = COPY(h->table[i].k);                                 \\\n   return h;                                                                  \\\n}                                                                             \\\n                                                                              \\\nstatic void STB_(N, rehash)(TYPE *a, int count)                               \\\n{                                                                             \\\n   int i;                                                                     \\\n   TYPE b;                                                                    \\\n   STB__(N, init)(&b, count);                                                 \\\n   for (i=0; i < a->limit; ++i)                                               \\\n      if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL))     \\\n         STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0);              \\\n   free(a->table);                                                            \\\n   a->table = b.table;                                                        \\\n   a->mask = b.mask;                                                          \\\n   a->count = b.count;                                                        \\\n   a->limit = b.limit;                                                        \\\n   a->deleted = b.deleted;                                                    \\\n   a->delete_threshhold = b.delete_threshhold;                                \\\n   a->grow_threshhold = b.grow_threshhold;                                    \\\n   a->shrink_threshhold = b.shrink_threshhold;                                \\\n}\n\n#define STB_equal(a,b)  ((a) == (b))\n\n#define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE)                      \\\n   stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f,              \\\n              KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe,               \\\n              STB_equal,STB_equal,HASH,                                       \\\n              VALUE,STB_nonullvalue,0)\n\n#define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL)          \\\n   stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f,              \\\n              KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe,               \\\n              STB_equal,STB_equal,HASH,                                       \\\n              VALUE,STB_nullvalue,VNULL)\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                        stb_ptrmap\n//\n// An stb_ptrmap data structure is an O(1) hash table between pointers. One\n// application is to let you store \"extra\" data associated with pointers,\n// which is why it was originally called stb_extra.\n\n#ifndef STB_INCLUDE_STB_LIB_H\nstb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *)\nstb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32)\n\nSTB_EXTERN void        stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *));\nSTB_EXTERN stb_ptrmap *stb_ptrmap_new(void);\n\nSTB_EXTERN stb_idict * stb_idict_new_size(unsigned int size);\nSTB_EXTERN void        stb_idict_remove_all(stb_idict *e);\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\n\n#define STB_EMPTY ((void *) 2)\n#define STB_EDEL  ((void *) 6)\n\nstb_define_hash_base(STB_noprefix,stb_ptrmap, STB_nofields, stb_ptrmap_,stb_ptrmap_,0.85f,\n              void *,STB_EMPTY,STB_EDEL,STB_nocopy,STB_nodelete,STB_nosafe,\n              STB_equal,STB_equal,return stb_hashptr(k);,\n              void *,STB_nullvalue,NULL)\n\nstb_ptrmap *stb_ptrmap_new(void)\n{\n   return stb_ptrmap_create();\n}\n\nvoid stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *))\n{\n   int i;\n   if (free_func)\n      for (i=0; i < e->limit; ++i)\n         if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) {\n            if (free_func == free)\n               free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate\n            else\n               free_func(e->table[i].v);\n         }\n   stb_ptrmap_destroy(e);\n}\n\n// extra fields needed for stua_dict\n#define STB_IEMPTY  ((int) 1)\n#define STB_IDEL    ((int) 3)\nstb_define_hash_base(STB_noprefix, stb_idict, STB_nofields, stb_idict_,stb_idict_,0.85f,\n              stb_int32,STB_IEMPTY,STB_IDEL,STB_nocopy,STB_nodelete,STB_nosafe,\n              STB_equal,STB_equal,\n              return stb_rehash_improved(k);,stb_int32,STB_nonullvalue,0)\n\nstb_idict * stb_idict_new_size(unsigned int size)\n{\n   stb_idict *e = (stb_idict *) malloc(sizeof(*e));\n   if (e) {\n      // round up to power of 2\n      while ((size & (size-1)) != 0) // while more than 1 bit is set\n         size += (size & ~(size-1)); // add the lowest set bit\n      stb_idict_init(e, size);\n      e->alloced = 1;\n   }\n   return e;\n}\n\nvoid stb_idict_remove_all(stb_idict *e)\n{\n   int n;\n   for (n=0; n < e->limit; ++n)\n      e->table[n].k = STB_IEMPTY;\n   e->has_empty = e->has_del = 0;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                  SDICT: Hash Table for Strings (symbol table)\n//\n//           if \"use_arena=1\", then strings will be copied\n//           into blocks and never freed until the sdict is freed;\n//           otherwise they're malloc()ed and free()d on the fly. \n//           (specify use_arena=1 if you never stb_sdict_remove)\n\n#ifndef STB_INCLUDE_STB_LIB_H\nstb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *)\n\nSTB_EXTERN stb_sdict * stb_sdict_new(void);\nSTB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*); \nSTB_EXTERN void        stb_sdict_delete(stb_sdict *);\nSTB_EXTERN void *      stb_sdict_change(stb_sdict *, char *str, void *p);\nSTB_EXTERN int         stb_sdict_count(stb_sdict *d);\n\nSTB_EXTERN int         stb_sdict_internal_limit(stb_sdict *d);\nSTB_EXTERN char *      stb_sdict_internal_key(stb_sdict *d, int n);\nSTB_EXTERN void *      stb_sdict_internal_value(stb_sdict *d, int n);\n\n#define stb_sdict_for(d,i,q,z)                                          \\\n   for(i=0; i < stb_sdict_internal_limit(d) ? (q=stb_sdict_internal_key(d,i),z=stb_sdict_internal_value(d,i),1) : 0; ++i)    \\\n      if (q==NULL||q==(void *) 1);else   // reversed makes macro friendly\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\n\n// if in same translation unit, for speed, don't call accessors\n#undef stb_sdict_for\n#define stb_sdict_for(d,i,q,z)                                          \\\n   for(i=0; i < (d)->limit ? (q=(d)->table[i].k,z=(d)->table[i].v,1) : 0; ++i)    \\\n      if (q==NULL||q==(void *) 1);else   // reversed makes macro friendly\n\n//#define STB_DEL ((void *) 1)\n#define STB_SDEL  ((char *) 1)\n\nstb_define_hash_base(STB_noprefix, stb_sdict, STB_nofields, stb_sdict_,stb_sdictinternal_, 0.85f,\n        char *, NULL, STB_SDEL, strdup, free,\n                        STB_safecompare, !strcmp, STB_equal, return stb_hash(k);,\n        void *, STB_nullvalue, NULL)\n\nint stb_sdict_count(stb_sdict *a)\n{\n   return a->count;\n}\n\nint stb_sdict_internal_limit(stb_sdict *a)\n{\n   return a->limit;\n}\nchar* stb_sdict_internal_key(stb_sdict *a, int n)\n{\n   return a->table[n].k;\n}\nvoid* stb_sdict_internal_value(stb_sdict *a, int n)\n{\n   return a->table[n].v;\n}\n\nstb_sdict * stb_sdict_new(void)\n{\n   stb_sdict *d = stb_sdict_create();\n   if (d == NULL) return NULL;\n   return d;\n}\n\nstb_sdict* stb_sdict_copy(stb_sdict *old)\n{\n   return stb_sdictinternal_copy(old);\n} \n\nvoid stb_sdict_delete(stb_sdict *d)\n{\n   stb_sdict_destroy(d);\n}\n\nvoid * stb_sdict_change(stb_sdict *d, char *str, void *p)\n{\n   void *q = stb_sdict_get(d, str);\n   stb_sdict_set(d, str, p);\n   return q;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                             File Processing\n//\n\n#ifndef STB_INCLUDE_STB_LIB_H\n#ifdef _MSC_VER\n  #define stb_rename(x,y)   _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))\n  #define stb_mktemp   _mktemp\n#else\n  #define stb_mktemp   mktemp\n  #define stb_rename   rename\n#endif\n\n#define stb_filec    (char *) stb_file\n#define stb_fileu    (unsigned char *) stb_file\nSTB_EXTERN void *  stb_file(char *filename, size_t *length);\nSTB_EXTERN size_t  stb_filelen(FILE *f);\nSTB_EXTERN int     stb_filewrite(char *filename, void *data, size_t length);\nSTB_EXTERN int     stb_filewritestr(char *filename, char *data);\nSTB_EXTERN char ** stb_stringfile(char *filename, int *len);\nSTB_EXTERN char *  stb_fgets(char *buffer, int buflen, FILE *f);\nSTB_EXTERN char *  stb_fgets_malloc(FILE *f);\nSTB_EXTERN int     stb_fexists(char *filename);\nSTB_EXTERN int     stb_fcmp(char *s1, char *s2);\nSTB_EXTERN int     stb_feq(char *s1, char *s2);\nSTB_EXTERN time_t  stb_ftimestamp(char *filename);\nSTB_EXTERN int     stb_fullpath(char *abs, int abs_size, char *rel);\n\nSTB_EXTERN int     stb_copyfile(char *src, char *dest);\nSTB_EXTERN int     stb_fread(void *data, size_t len, size_t count, void *f);\nSTB_EXTERN int     stb_fwrite(void *data, size_t len, size_t count, void *f);\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\n#if defined(_MSC_VER) || defined(__MINGW32__)\n   #define stb__stat   _stat\n#else\n   #define stb__stat   stat\n#endif\n\nint stb_fexists(char *filename)\n{\n   struct stb__stat buf;\n   return stb__windows(\n             _wstat((const wchar_t *)stb__from_utf8(filename), &buf),\n               stat(filename,&buf)\n          ) == 0;\n}\n\ntime_t stb_ftimestamp(char *filename)\n{\n   struct stb__stat buf;\n   if (stb__windows(\n             _wstat((const wchar_t *)stb__from_utf8(filename), &buf),\n               stat(filename,&buf)\n          ) == 0)\n   {\n      return buf.st_mtime;\n   } else {\n      return 0;\n   }\n}\n\nsize_t  stb_filelen(FILE *f)\n{\n   size_t len, pos;\n   pos = ftell(f);\n   fseek(f, 0, SEEK_END);\n   len = ftell(f);\n   fseek(f, pos, SEEK_SET);\n   return len;\n}\n\nvoid *stb_file(char *filename, size_t *length)\n{\n   FILE *f = stb__fopen(filename, \"rb\");\n   char *buffer;\n   size_t len, len2;\n   if (!f) return NULL;\n   len = stb_filelen(f);\n   buffer = (char *) malloc(len+2); // nul + extra\n   len2 = fread(buffer, 1, len, f);\n   if (len2 == len) {\n      if (length) *length = len;\n      buffer[len] = 0;\n   } else {\n      free(buffer);\n      buffer = NULL;\n   }\n   fclose(f);\n   return buffer;\n}\n\nint stb_filewrite(char *filename, void *data, size_t length)\n{\n   FILE *f = stb__fopen(filename, \"wb\");\n   if (f) {\n      unsigned char *data_ptr = (unsigned char *) data;\n      size_t remaining = length;\n      while (remaining > 0) {\n         size_t len2 = remaining > 65536 ? 65536 : remaining;\n         size_t len3 = fwrite(data_ptr, 1, len2, f);\n         if (len2 != len3) {\n            fprintf(stderr, \"Failed while writing %s\\n\", filename);\n            break;\n         }\n         remaining -= len2;\n         data_ptr += len2;\n      }\n      fclose(f);\n   }\n   return f != NULL;\n}\n\nint stb_filewritestr(char *filename, char *data)\n{\n   return stb_filewrite(filename, data, strlen(data));\n}\n\nchar ** stb_stringfile(char *filename, int *plen)\n{\n   FILE *f = stb__fopen(filename, \"rb\");\n   char *buffer, **list=NULL, *s;\n   size_t len, count, i;\n\n   if (!f) return NULL;\n   len = stb_filelen(f);\n   buffer = (char *) malloc(len+1);\n   len = fread(buffer, 1, len, f);\n   buffer[len] = 0;\n   fclose(f);\n\n   // two passes through: first time count lines, second time set them\n   for (i=0; i < 2; ++i) {\n      s = buffer;\n      if (i == 1)\n         list[0] = s;\n      count = 1;\n      while (*s) {\n         if (*s == '\\n' || *s == '\\r') {\n            // detect if both cr & lf are together\n            int crlf = (s[0] + s[1]) == ('\\n' + '\\r');\n            if (i == 1) *s = 0;\n            if (crlf) ++s;\n            if (s[1]) {  // it's not over yet\n               if (i == 1) list[count] = s+1;\n               ++count;\n            }\n         }\n         ++s;\n      }\n      if (i == 0) {\n         list = (char **) malloc(sizeof(*list) * (count+1) + len+1);\n         if (!list) return NULL;\n         list[count] = 0;\n         // recopy the file so there's just a single allocation to free\n         memcpy(&list[count+1], buffer, len+1);\n         free(buffer);\n         buffer = (char *) &list[count+1];\n         if (plen) *plen = count;\n      }\n   }\n   return list;\n}\n\nchar * stb_fgets(char *buffer, int buflen, FILE *f)\n{\n   char *p;\n   buffer[0] = 0;\n   p = fgets(buffer, buflen, f);\n   if (p) {\n      int n = strlen(p)-1;\n      if (n >= 0)\n         if (p[n] == '\\n')\n            p[n] = 0;\n   }\n   return p;\n}\n\nchar * stb_fgets_malloc(FILE *f)\n{\n   // avoid reallocing for small strings\n   char quick_buffer[800];\n   quick_buffer[sizeof(quick_buffer)-2] = 0;\n   if (!fgets(quick_buffer, sizeof(quick_buffer), f))\n      return NULL;\n\n   if (quick_buffer[sizeof(quick_buffer)-2] == 0) {\n      int n = strlen(quick_buffer);\n      if (n > 0 && quick_buffer[n-1] == '\\n')\n         quick_buffer[n-1] = 0;\n      return strdup(quick_buffer);\n   } else {\n      char *p;\n      char *a = strdup(quick_buffer);\n      int len = sizeof(quick_buffer)-1;\n\n      while (!feof(f)) {\n         if (a[len-1] == '\\n') break;\n         a = (char *) realloc(a, len*2);\n         p = &a[len];\n         p[len-2] = 0;\n         if (!fgets(p, len, f))\n            break;\n         if (p[len-2] == 0) {\n            len += strlen(p);\n            break;\n         }\n         len = len + (len-1);\n      }\n      if (a[len-1] == '\\n')\n         a[len-1] = 0;\n      return a;\n   }\n}\n\nint stb_fullpath(char *abs, int abs_size, char *rel)\n{\n   #ifdef _MSC_VER\n   return _fullpath(abs, rel, abs_size) != NULL;\n   #else\n   if (rel[0] == '/' || rel[0] == '~') {\n      if ((int) strlen(rel) >= abs_size)\n         return 0;\n      strcpy(abs,rel);\n      return 1;\n   } else {\n      int n;\n      getcwd(abs, abs_size);\n      n = strlen(abs);\n      if (n+(int) strlen(rel)+2 <= abs_size) {\n         abs[n] = '/';\n         strcpy(abs+n+1, rel);\n         return 1;\n      } else {\n         return 0;\n      }\n   }\n   #endif\n}\n\nstatic int stb_fcmp_core(FILE *f, FILE *g)\n{\n   char buf1[1024],buf2[1024];\n   int n1,n2, res=0;\n\n   while (1) {\n      n1 = fread(buf1, 1, sizeof(buf1), f);\n      n2 = fread(buf2, 1, sizeof(buf2), g);\n      res = memcmp(buf1,buf2,n1 < n2 ? n1 : n2);\n      if (res)\n         break;\n      if (n1 != n2) {\n         res = n1 < n2 ? -1 : 1;\n         break;\n      }\n      if (n1 == 0)\n         break;\n   }\n\n   fclose(f);\n   fclose(g);\n   return res;\n}\n\nint stb_fcmp(char *s1, char *s2)\n{\n   FILE *f = stb__fopen(s1, \"rb\");\n   FILE *g = stb__fopen(s2, \"rb\");\n\n   if (f == NULL || g == NULL) {\n      if (f) fclose(f);\n      if (g) {\n         fclose(g);\n         return 1;\n      }\n      return f != NULL;\n   }\n\n   return stb_fcmp_core(f,g);\n}\n\nint stb_feq(char *s1, char *s2)\n{\n   FILE *f = stb__fopen(s1, \"rb\");\n   FILE *g = stb__fopen(s2, \"rb\");\n\n   if (f == NULL || g == NULL) {\n      if (f) fclose(f);\n      if (g) fclose(g);\n      return f == g;\n   }\n\n   // feq is faster because it shortcuts if they're different length\n   if (stb_filelen(f) != stb_filelen(g)) {\n      fclose(f);\n      fclose(g);\n      return 0;\n   }\n\n   return !stb_fcmp_core(f,g);\n}\n\nint stb_copyfile(char *src, char *dest)\n{\n   char raw_buffer[1024];\n   char *buffer;\n   int buf_size = 65536;\n\n   FILE *f, *g;\n\n   // if file already exists at destination, do nothing\n   if (stb_feq(src, dest)) return 1;\n\n   // open file\n   f = stb__fopen(src, \"rb\");\n   if (f == NULL) return 0;\n\n   // open file for writing\n   g = stb__fopen(dest, \"wb\");\n   if (g == NULL) {\n      fclose(f);\n      return 0;\n   }\n\n   buffer = (char *) malloc(buf_size);\n   if (buffer == NULL) {\n      buffer = raw_buffer;\n      buf_size = sizeof(raw_buffer);\n   }\n\n   while (!feof(f)) {\n      int n = fread(buffer, 1, buf_size, f);\n      if (n != 0)\n         fwrite(buffer, 1, n, g);\n   }\n\n   fclose(f);\n   if (buffer != raw_buffer)\n      free(buffer);\n\n   fclose(g);\n   return 1;\n}\n\n#define stb_fgetc(f)    ((unsigned char) fgetc(f))\n\n#if 0\n// strip the trailing '/' or '\\\\' from a directory so we can refer to it\n// as a file for _stat()\nchar *stb_strip_final_slash(char *t)\n{\n   if (t[0]) {\n      char *z = t + strlen(t) - 1;\n      // *z is the last character\n      if (*z == '\\\\' || *z == '/')\n         if (z != t+2 || t[1] != ':') // but don't strip it if it's e.g. \"c:/\"\n            *z = 0;\n      if (*z == '\\\\')\n         *z = '/'; // canonicalize to make sure it matches db\n   }\n   return t;\n}\n\nchar *stb_strip_final_slash_regardless(char *t)\n{\n   if (t[0]) {\n      char *z = t + strlen(t) - 1;\n      // *z is the last character\n      if (*z == '\\\\' || *z == '/')\n         *z = 0;\n      if (*z == '\\\\')\n         *z = '/'; // canonicalize to make sure it matches db\n   }\n   return t;\n}\n#endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                 Portable directory reading\n//\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN char **stb_readdir_files  (char *dir);\nSTB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild);\nSTB_EXTERN char **stb_readdir_subdirs(char *dir);\nSTB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild);\nSTB_EXTERN void   stb_readdir_free   (char **files);\nSTB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec);\nSTB_EXTERN void stb_delete_directory_recursive(char *dir);\n\n// forward declare for implementation\nSTB_EXTERN int stb_wildmatchi(char *expr, char *candidate);\n#endif // STB_INCLUDE_STB_LIB_H\n\n\n#ifdef STB_LIB_IMPLEMENTATION\n\n#ifdef _MSC_VER\n#include <io.h>\n#else\n#include <unistd.h>\n#include <dirent.h>\n#endif\n\nvoid stb_readdir_free(char **files)\n{\n   char **f2 = files;\n   int i;\n   for (i=0; i < stb_arr_len(f2); ++i)\n      free(f2[i]);\n   stb_arr_free(f2);\n}\n\nstatic int isdotdirname(char *name)\n{\n   if (name[0] == '.')\n      return (name[1] == '.') ? !name[2] : !name[1];\n   return 0;\n}\n\nstatic char **readdir_raw(char *dir, int return_subdirs, char *mask)\n{\n   char **results = NULL;\n   char buffer[4096], with_slash[4096];\n   size_t n;\n\n   #ifdef _MSC_VER\n      stb__wchar *ws;\n      struct _wfinddata_t data;\n   #ifdef _WIN64\n      const intptr_t none = -1;\n      intptr_t z;\n   #else\n      const long none = -1;\n      long z;\n   #endif\n   #else // !_MSC_VER\n      const DIR *none = NULL;\n      DIR *z;\n   #endif\n\n   n = stb_strscpy(buffer,dir,sizeof(buffer));\n   if (!n || n >= sizeof(buffer))\n      return NULL;\n   stb_fixpath(buffer);\n   n--;\n\n   if (n > 0 && (buffer[n-1] != '/')) {\n      buffer[n++] = '/';\n   }\n   buffer[n] = 0;\n   if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))\n      return NULL;\n\n   #ifdef _MSC_VER\n      if (!stb_strscpy(buffer+n,\"*.*\",sizeof(buffer)-n))\n         return NULL;\n      ws = stb__from_utf8(buffer);\n      z = _wfindfirst((const wchar_t *)ws, &data);\n   #else\n      z = opendir(dir);\n   #endif\n\n   if (z != none) {\n      int nonempty = 1;\n      #ifndef _MSC_VER\n      struct dirent *data = readdir(z);\n      nonempty = (data != NULL);\n      #endif\n\n      if (nonempty) {\n\n         do {\n            int is_subdir;\n            #ifdef _MSC_VER\n            char *name = stb__to_utf8((stb__wchar *)data.name);\n            if (name == NULL) {\n               fprintf(stderr, \"%s to convert '%S' to %s!\\n\", \"Unable\", data.name, \"utf8\");\n               continue;\n            }\n            is_subdir = !!(data.attrib & _A_SUBDIR);\n            #else\n            char *name = data->d_name;\n            if (!stb_strscpy(buffer+n,name,sizeof(buffer)-n))\n               break;\n            // Could follow DT_LNK, but would need to check for recursive links.\n            is_subdir = !!(data->d_type & DT_DIR);\n            #endif\n\n            if (is_subdir == return_subdirs) {\n               if (!is_subdir || !isdotdirname(name)) {\n                  if (!mask || stb_wildmatchi(mask, name)) {\n                     char buffer[4096],*p=buffer;\n                     if ( stb_snprintf(buffer, sizeof(buffer), \"%s%s\", with_slash, name) < 0 )\n                        break;\n                     if (buffer[0] == '.' && buffer[1] == '/')\n                        p = buffer+2;\n                     stb_arr_push(results, strdup(p));\n                  }\n               }\n            }\n         }\n         #ifdef _MSC_VER\n         while (0 == _wfindnext(z, &data));\n         #else\n         while ((data = readdir(z)) != NULL);\n         #endif\n      }\n      #ifdef _MSC_VER\n         _findclose(z);\n      #else\n         closedir(z);\n      #endif\n   }\n   return results;\n}\n\nchar **stb_readdir_files  (char *dir) { return readdir_raw(dir, 0, NULL); }\nchar **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); }\nchar **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); }\nchar **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); }\n\nint stb__rec_max=0x7fffffff;\nstatic char **stb_readdir_rec(char **sofar, char *dir, char *filespec)\n{\n   char **files;\n   char ** dirs;\n   char **p;\n\n   if (stb_arr_len(sofar) >= stb__rec_max) return sofar;\n\n   files = stb_readdir_files_mask(dir, filespec);\n   stb_arr_for(p, files) {\n      stb_arr_push(sofar, strdup(*p));\n      if (stb_arr_len(sofar) >= stb__rec_max) break;\n   }\n   stb_readdir_free(files);\n   if (stb_arr_len(sofar) >= stb__rec_max) return sofar;\n\n   dirs = stb_readdir_subdirs(dir);\n   stb_arr_for(p, dirs)\n      sofar = stb_readdir_rec(sofar, *p, filespec);\n   stb_readdir_free(dirs);\n   return sofar;\n}\n\nchar **stb_readdir_recursive(char *dir, char *filespec)\n{\n   return stb_readdir_rec(NULL, dir, filespec);\n}\n\nvoid stb_delete_directory_recursive(char *dir)\n{\n   char **list = stb_readdir_subdirs(dir);\n   int i;\n   for (i=0; i < stb_arr_len(list); ++i)\n      stb_delete_directory_recursive(list[i]);\n   stb_arr_free(list);\n   list = stb_readdir_files(dir);\n   for (i=0; i < stb_arr_len(list); ++i)\n      if (!remove(list[i])) {\n         // on windows, try again after making it writeable; don't ALWAYS\n         // do this first since that would be slow in the normal case\n         #ifdef _MSC_VER\n         _chmod(list[i], _S_IWRITE);\n         remove(list[i]);\n         #endif\n      }\n   stb_arr_free(list);\n   stb__windows(_rmdir,rmdir)(dir);\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//                 Checksums: CRC-32, ADLER32, SHA-1\n//\n//    CRC-32 and ADLER32 allow streaming blocks\n//    SHA-1 requires either a complete buffer, max size 2^32 - 73\n//          or it can checksum directly from a file, max 2^61\n\n#ifndef STB_INCLUDE_STB_LIB_H\n#define STB_ADLER32_SEED   1\n#define STB_CRC32_SEED     0    // note that we logical NOT this in the code\n\nSTB_EXTERN stb_uint stb_adler32    (stb_uint adler32,  stb_uchar *buffer, stb_uint buflen);\nSTB_EXTERN stb_uint stb_crc32_block(stb_uint crc32  ,  stb_uchar *buffer, stb_uint buflen);\nSTB_EXTERN stb_uint stb_crc32      (                   stb_uchar *buffer, stb_uint buflen);\n\nSTB_EXTERN void stb_sha1(    unsigned char output[20], stb_uchar *buffer, unsigned int len);\nSTB_EXTERN int stb_sha1_file(unsigned char output[20], char *file);\n#endif //  STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\nstb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len)\n{\n   static stb_uint crc_table[256];\n   stb_uint i,j,s;\n   crc = ~crc;\n\n   if (crc_table[1] == 0)\n      for(i=0; i < 256; i++) {\n         for (s=i, j=0; j < 8; ++j)\n            s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0);\n         crc_table[i] = s;\n      }\n   for (i=0; i < len; ++i)\n      crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];\n   return ~crc;\n}\n\nstb_uint stb_crc32(unsigned char *buffer, stb_uint len)\n{\n   return stb_crc32_block(0, buffer, len);\n}\n\nstb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)\n{\n   const unsigned long ADLER_MOD = 65521;\n   unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;\n   unsigned long blocklen, i;\n\n   blocklen = buflen % 5552;\n   while (buflen) {\n      for (i=0; i + 7 < blocklen; i += 8) {\n         s1 += buffer[0], s2 += s1;\n         s1 += buffer[1], s2 += s1;\n         s1 += buffer[2], s2 += s1;\n         s1 += buffer[3], s2 += s1;\n         s1 += buffer[4], s2 += s1;\n         s1 += buffer[5], s2 += s1;\n         s1 += buffer[6], s2 += s1;\n         s1 += buffer[7], s2 += s1;\n\n         buffer += 8;\n      }\n\n      for (; i < blocklen; ++i)\n         s1 += *buffer++, s2 += s1;\n\n      s1 %= ADLER_MOD, s2 %= ADLER_MOD;\n      buflen -= blocklen;\n      blocklen = 5552;\n   }\n   return (s2 << 16) + s1;\n}\n\n#define stb__big32(c)    (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])\nstatic void stb__sha1(stb_uchar *chunk, stb_uint h[5])\n{\n   int i;\n   stb_uint a,b,c,d,e;\n   stb_uint w[80];\n\n   for (i=0; i < 16; ++i)\n      w[i] = stb__big32(&chunk[i*4]);\n   for (i=16; i < 80; ++i) {\n      stb_uint t;\n      t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];\n      w[i] = (t + t) | (t >> 31);\n   }\n\n   a = h[0];\n   b = h[1];\n   c = h[2];\n   d = h[3];\n   e = h[4];\n\n   #define STB__SHA1(k,f)                                            \\\n   {                                                                 \\\n      stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i];  \\\n      e = d;                                                       \\\n      d = c;                                                     \\\n      c = (b << 30) + (b >> 2);                               \\\n      b = a;                                              \\\n      a = temp;                                    \\\n   }\n\n   i=0;\n   for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d))       );\n   for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d               );\n   for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );\n   for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d               );\n\n   #undef STB__SHA1\n\n   h[0] += a;\n   h[1] += b;\n   h[2] += c;\n   h[3] += d;\n   h[4] += e;\n}\n\nvoid stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len)\n{\n   unsigned char final_block[128];\n   stb_uint end_start, final_len, j;\n   int i;\n\n   stb_uint h[5];\n\n   h[0] = 0x67452301;\n   h[1] = 0xefcdab89;\n   h[2] = 0x98badcfe;\n   h[3] = 0x10325476;\n   h[4] = 0xc3d2e1f0;\n\n   // we need to write padding to the last one or two\n   // blocks, so build those first into 'final_block'\n\n   // we have to write one special byte, plus the 8-byte length\n\n   // compute the block where the data runs out\n   end_start = len & ~63;\n\n   // compute the earliest we can encode the length\n   if (((len+9) & ~63) == end_start) {\n      // it all fits in one block, so fill a second-to-last block\n      end_start -= 64;\n   }\n\n   final_len = end_start + 128;\n\n   // now we need to copy the data in\n   assert(end_start + 128 >= len+9);\n   assert(end_start < len || len < 64-9);\n\n   j = 0;\n   if (end_start > len)\n      j = (stb_uint) - (int) end_start;\n\n   for (; end_start + j < len; ++j)\n      final_block[j] = buffer[end_start + j];\n   final_block[j++] = 0x80;\n   while (j < 128-5) // 5 byte length, so write 4 extra padding bytes\n      final_block[j++] = 0;\n   // big-endian size\n   final_block[j++] = len >> 29;\n   final_block[j++] = len >> 21;\n   final_block[j++] = len >> 13;\n   final_block[j++] = len >>  5;\n   final_block[j++] = len <<  3;\n   assert(j == 128 && end_start + j == final_len);\n\n   for (j=0; j < final_len; j += 64) { // 512-bit chunks\n      if (j+64 >= end_start+64)\n         stb__sha1(&final_block[j - end_start], h);\n      else\n         stb__sha1(&buffer[j], h);\n   }\n\n   for (i=0; i < 5; ++i) {\n      output[i*4 + 0] = h[i] >> 24;\n      output[i*4 + 1] = h[i] >> 16;\n      output[i*4 + 2] = h[i] >>  8;\n      output[i*4 + 3] = h[i] >>  0;\n   }\n}\n\nint stb_sha1_file(stb_uchar output[20], char *file)\n{\n   int i;\n   stb_uint64 length=0;\n   unsigned char buffer[128];\n\n   FILE *f = stb__fopen(file, \"rb\");\n   stb_uint h[5];\n\n   if (f == NULL) return 0; // file not found\n\n   h[0] = 0x67452301;\n   h[1] = 0xefcdab89;\n   h[2] = 0x98badcfe;\n   h[3] = 0x10325476;\n   h[4] = 0xc3d2e1f0;\n\n   for(;;) {\n      int n = fread(buffer, 1, 64, f);\n      if (n == 64) {\n         stb__sha1(buffer, h);\n         length += n;\n      } else {\n         int block = 64;\n\n         length += n;\n\n         buffer[n++] = 0x80;\n\n         // if there isn't enough room for the length, double the block\n         if (n + 8 > 64) \n            block = 128;\n\n         // pad to end\n         memset(buffer+n, 0, block-8-n);\n\n         i = block - 8;\n         buffer[i++] = (stb_uchar) (length >> 53);\n         buffer[i++] = (stb_uchar) (length >> 45);\n         buffer[i++] = (stb_uchar) (length >> 37);\n         buffer[i++] = (stb_uchar) (length >> 29);\n         buffer[i++] = (stb_uchar) (length >> 21);\n         buffer[i++] = (stb_uchar) (length >> 13);\n         buffer[i++] = (stb_uchar) (length >>  5);\n         buffer[i++] = (stb_uchar) (length <<  3);\n         assert(i == block);\n         stb__sha1(buffer, h);\n         if (block == 128)\n            stb__sha1(buffer+64, h);\n         else\n            assert(block == 64);\n         break;\n      }\n   }\n   fclose(f);\n\n   for (i=0; i < 5; ++i) {\n      output[i*4 + 0] = h[i] >> 24;\n      output[i*4 + 1] = h[i] >> 16;\n      output[i*4 + 2] = h[i] >>  8;\n      output[i*4 + 3] = h[i] >>  0;\n   }\n\n   return 1;\n}\n#endif // STB_LIB_IMPLEMENTATION\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//               Random Numbers via Meresenne Twister or LCG\n//\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN unsigned long stb_srandLCG(unsigned long seed);\nSTB_EXTERN unsigned long stb_randLCG(void);\nSTB_EXTERN double        stb_frandLCG(void);\n\nSTB_EXTERN void          stb_srand(unsigned long seed);\nSTB_EXTERN unsigned long stb_rand(void);\nSTB_EXTERN double        stb_frand(void);\nSTB_EXTERN void          stb_shuffle(void *p, size_t n, size_t sz,\n                                        unsigned long seed);\nSTB_EXTERN void stb_reverse(void *p, size_t n, size_t sz);\n\nSTB_EXTERN unsigned long stb_randLCG_explicit(unsigned long seed);\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\nunsigned long stb_randLCG_explicit(unsigned long seed)\n{\n   return seed * 2147001325 + 715136305;\n}\n\nstatic unsigned long stb__rand_seed=0;\n\nunsigned long stb_srandLCG(unsigned long seed)\n{\n   unsigned long previous = stb__rand_seed;\n   stb__rand_seed = seed;\n   return previous;\n}\n\nunsigned long stb_randLCG(void)\n{\n   stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator\n   // shuffle non-random bits to the middle, and xor to decorrelate with seed\n   return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16));\n}\n\ndouble stb_frandLCG(void)\n{\n   return stb_randLCG() / ((double) (1 << 16) * (1 << 16));\n}\n\nvoid stb_shuffle(void *p, size_t n, size_t sz, unsigned long seed)\n{\n   char *a;\n   unsigned long old_seed;\n   int i;\n   if (seed)\n      old_seed = stb_srandLCG(seed);\n   a = (char *) p + (n-1) * sz;\n\n   for (i=n; i > 1; --i) {\n      int j = stb_randLCG() % i;\n      stb_swap(a, (char *) p + j * sz, sz);\n      a -= sz;\n   }\n   if (seed)\n      stb_srandLCG(old_seed);\n}\n\nvoid stb_reverse(void *p, size_t n, size_t sz)\n{\n   int i,j = n-1;\n   for (i=0; i < j; ++i,--j) {\n      stb_swap((char *) p + i * sz, (char *) p + j * sz, sz);\n   }\n}\n\n// public domain Mersenne Twister by Michael Brundage\n#define STB__MT_LEN       624\n\nint stb__mt_index = STB__MT_LEN*sizeof(unsigned long)+1;\nunsigned long stb__mt_buffer[STB__MT_LEN];\n\nvoid stb_srand(unsigned long seed)\n{\n   int i;\n   unsigned long old = stb_srandLCG(seed);\n   for (i = 0; i < STB__MT_LEN; i++)\n      stb__mt_buffer[i] = stb_randLCG();\n   stb_srandLCG(old);\n   stb__mt_index = STB__MT_LEN*sizeof(unsigned long);\n}\n\n#define STB__MT_IA           397\n#define STB__MT_IB           (STB__MT_LEN - STB__MT_IA)\n#define STB__UPPER_MASK      0x80000000\n#define STB__LOWER_MASK      0x7FFFFFFF\n#define STB__MATRIX_A        0x9908B0DF\n#define STB__TWIST(b,i,j)    ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK)\n#define STB__MAGIC(s)        (((s)&1)*STB__MATRIX_A)\n\nunsigned long stb_rand()\n{\n   unsigned long * b = stb__mt_buffer;\n   int idx = stb__mt_index;\n   unsigned long s,r;\n   int i;\n\t\n   if (idx >= STB__MT_LEN*sizeof(unsigned long)) {\n      if (idx > STB__MT_LEN*sizeof(unsigned long))\n         stb_srand(0);\n      idx = 0;\n      i = 0;\n      for (; i < STB__MT_IB; i++) {\n         s = STB__TWIST(b, i, i+1);\n         b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s);\n      }\n      for (; i < STB__MT_LEN-1; i++) {\n         s = STB__TWIST(b, i, i+1);\n         b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s);\n      }\n      \n      s = STB__TWIST(b, STB__MT_LEN-1, 0);\n      b[STB__MT_LEN-1] = b[STB__MT_IA-1] ^ (s >> 1) ^ STB__MAGIC(s);\n   }\n   stb__mt_index = idx + sizeof(unsigned long);\n   \n   r = *(unsigned long *)((unsigned char *)b + idx);\n   \n   r ^= (r >> 11);\n   r ^= (r << 7) & 0x9D2C5680;\n   r ^= (r << 15) & 0xEFC60000;\n   r ^= (r >> 18);\n   \n   return r;\n}\n\ndouble stb_frand(void)\n{\n   return stb_rand() / ((double) (1 << 16) * (1 << 16));\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n//\n//      wildcards and regexping\n//\n\n#ifndef STB_INCLUDE_STB_LIB_H\nSTB_EXTERN int stb_wildmatch (char *expr, char *candidate);\nSTB_EXTERN int stb_wildmatchi(char *expr, char *candidate);\nSTB_EXTERN int stb_wildfind  (char *expr, char *candidate);\nSTB_EXTERN int stb_wildfindi (char *expr, char *candidate);\n#endif // STB_INCLUDE_STB_LIB_H\n\n#ifdef STB_LIB_IMPLEMENTATION\nstatic int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive)\n{\n   int i;\n   if (insensitive) {\n      for (i=0; i < qlen; ++i)\n         if (qstring[i] == '?') {\n            if (!candidate[i]) return 0;\n         } else\n            if (tolower(qstring[i]) != tolower(candidate[i]))\n               return 0;\n   } else {\n      for (i=0; i < qlen; ++i)\n         if (qstring[i] == '?') {\n            if (!candidate[i]) return 0;\n         } else\n            if (qstring[i] != candidate[i])\n               return 0;\n   }\n   return 1;\n}\n\nstatic int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive)\n{\n   char c;\n\n   int offset=0;\n   while (*qstring == '?') {\n      ++qstring;\n      --qlen;\n      ++candidate;\n      if (qlen == 0) return 0;\n      if (*candidate == 0) return -1;\n   }\n\n   c = *qstring++;\n   --qlen;\n   if (insensitive) c = tolower(c);\n\n   while (candidate[offset]) {\n      if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset]))\n         if (stb__match_qstring(candidate+offset+1, qstring, qlen, insensitive))\n            return offset;\n      ++offset;\n   }\n\n   return -1;\n}\n\nint stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive)\n{\n   int where=0;\n   int start = -1;\n   \n   if (!search) {\n      // parse to first '*'\n      if (*expr != '*')\n         start = 0;\n      while (*expr != '*') {\n         if (!*expr)\n            return *candidate == 0 ? 0 : -1;\n         if (*expr == '?') {\n            if (!*candidate) return -1;\n         } else {\n            if (insensitive) {\n               if (tolower(*candidate) != tolower(*expr))\n                  return -1;\n            } else \n               if (*candidate != *expr)\n                  return -1;\n         }\n         ++candidate, ++expr, ++where;\n      }\n   } else {\n      // 0-length search string\n      if (!*expr)\n         return 0;\n   }\n\n   assert(search || *expr == '*');\n   if (!search)\n      ++expr;\n\n   // implicit '*' at this point\n      \n   while (*expr) {\n      int o=0;\n      // combine redundant * characters\n      while (expr[0] == '*') ++expr;\n\n      // ok, at this point, expr[-1] == '*',\n      // and expr[0] != '*'\n\n      if (!expr[0]) return start >= 0 ? start : 0;\n\n      // now find next '*'\n      o = 0;\n      while (expr[o] != '*') {\n         if (expr[o] == 0)\n            break;\n         ++o;\n      }\n      // if no '*', scan to end, then match at end\n      if (expr[o] == 0 && !search) {\n         int z;\n         for (z=0; z < o; ++z)\n            if (candidate[z] == 0)\n               return -1;\n         while (candidate[z])\n            ++z;\n         // ok, now check if they match\n         if (stb__match_qstring(candidate+z-o, expr, o, insensitive))\n            return start >= 0 ? start : 0;\n         return -1; \n      } else {\n         // if yes '*', then do stb__find_qmatch on the intervening chars\n         int n = stb__find_qstring(candidate, expr, o, insensitive);\n         if (n < 0)\n            return -1;\n         if (start < 0)\n            start = where + n;\n         expr += o;\n         candidate += n+o;\n      }\n\n      if (*expr == 0) {\n         assert(search);\n         return start;\n      }\n\n      assert(*expr == '*');\n      ++expr;\n   }\n\n   return start >= 0 ? start : 0;\n}\n\nint stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive)\n{\n   char buffer[256];\n   // handle multiple search strings\n   char *s = strchr(expr, ';');\n   char *last = expr;\n   while (s) {\n      int z;\n      // need to allow for non-writeable strings... assume they're small\n      if (s - last < 256) {\n         stb_strncpy(buffer, last, s-last+1);\n         z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);\n      } else {\n         *s = 0;\n         z = stb__wildmatch_raw2(last, candidate, search, insensitive);\n         *s = ';';\n      }\n      if (z >= 0) return z;\n      last = s+1;\n      s = strchr(last, ';');\n   }\n   return stb__wildmatch_raw2(last, candidate, search, insensitive);\n}\n\nint stb_wildmatch(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 0,0) >= 0;\n}\n\nint stb_wildmatchi(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 0,1) >= 0;\n}\n\nint stb_wildfind(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 1,0);\n}\n\nint stb_wildfindi(char *expr, char *candidate)\n{\n   return stb__wildmatch_raw(expr, candidate, 1,1);\n}\n\n#undef STB_LIB_IMPLEMENTATION\n#endif // STB_LIB_IMPLEMENTATION\n\n#ifndef STB_INCLUDE_STB_LIB_H\n#define STB_INCLUDE_STB_LIB_H\n#undef STB_EXTERN\n#endif\n\n/*\n------------------------------------------------------------------------------\nThis software is available under 2 licenses -- choose whichever you prefer.\n------------------------------------------------------------------------------\nALTERNATIVE A - MIT License\nCopyright (c) 2017 Sean Barrett\nPermission is hereby granted, free of charge, to any person obtaining a copy of \nthis software and associated documentation files (the \"Software\"), to deal in \nthe Software without restriction, including without limitation the rights to \nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies \nof the Software, and to permit persons to whom the Software is furnished to do \nso, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all \ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \nSOFTWARE.\n------------------------------------------------------------------------------\nALTERNATIVE B - Public Domain (www.unlicense.org)\nThis is free and unencumbered software released into the public domain.\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this \nsoftware, either in source code form or as a compiled binary, for any purpose, \ncommercial or non-commercial, and by any means.\nIn jurisdictions that recognize copyright laws, the author or authors of this \nsoftware dedicate any and all copyright interest in the software to the public \ndomain. We make this dedication for the benefit of the public at large and to \nthe detriment of our heirs and successors. We intend this dedication to be an \novert act of relinquishment in perpetuity of all present and future rights to \nthis software under copyright law.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN \nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION \nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n------------------------------------------------------------------------------\n*/\n"
  },
  {
    "path": "tests/resample_test.cpp",
    "content": "#define _CRT_SECURE_NO_WARNINGS\n#include <stdlib.h>\n#include <stdio.h>\n\n#if defined(_WIN32) && _MSC_VER > 1200\n#define STBIR_ASSERT(x) \\\n\tif (!(x)) {         \\\n\t\t__debugbreak();  \\\n\t} else\n#else\n#include <assert.h>\n#define STBIR_ASSERT(x) assert(x)\n#endif\n\n#define STBIR_MALLOC stbir_malloc\n#define STBIR_FREE stbir_free\n\nclass stbir_context {\npublic:\n\tstbir_context()\n\t{\n\t\tsize = 1000000;\n\t\tmemory = malloc(size);\n\t}\n\n\t~stbir_context()\n\t{\n\t\tfree(memory);\n\t}\n\n\tsize_t size;\n\tvoid* memory;\n} g_context;\n\nvoid* stbir_malloc(size_t size, void* context)\n{\n\tif (!context)\n\t\treturn malloc(size);\n\n\tstbir_context* real_context = (stbir_context*)context;\n\tif (size > real_context->size)\n\t\treturn 0;\n\n\treturn real_context->memory;\n}\n\nvoid stbir_free(void* memory, void* context)\n{\n\tif (!context)\n\t\tfree(memory);\n}\n\n//#include <stdio.h>\nvoid stbir_progress(float p)\n{\n\t//printf(\"%f\\n\", p);\n\tSTBIR_ASSERT(p >= 0 && p <= 1);\n}\n\n#ifdef __clang__\n#define STBIRDEF static inline\n#endif\n\n#define STBIR_PROGRESS_REPORT stbir_progress\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#define STB_IMAGE_RESIZE_STATIC\n#include \"stb_image_resize2.h\"\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#ifdef _WIN32\n#include <sys/timeb.h>\n#include <direct.h>\n#define mkdir(a, b) _mkdir(a)\n#else\n#include <sys/stat.h>\n#endif\n\n#define MT_SIZE 624\nstatic size_t g_aiMT[MT_SIZE];\nstatic size_t g_iMTI = 0;\n\n// Mersenne Twister implementation from Wikipedia.\n// Avoiding use of the system rand() to be sure that our tests generate the same test data on any system.\nvoid mtsrand(size_t iSeed)\n{\n\tg_aiMT[0] = iSeed;\n\tfor (size_t i = 1; i < MT_SIZE; i++)\n\t{\n\t\tsize_t inner1 = g_aiMT[i - 1];\n\t\tsize_t inner2 = (g_aiMT[i - 1] >> 30);\n\t\tsize_t inner = inner1 ^ inner2;\n\t\tg_aiMT[i] = (0x6c078965 * inner) + i;\n\t}\n\n\tg_iMTI = 0;\n}\n\nsize_t mtrand()\n{\n\tif (g_iMTI == 0)\n\t{\n\t\tfor (size_t i = 0; i < MT_SIZE; i++)\n\t\t{\n\t\t\tsize_t y = (0x80000000 & (g_aiMT[i])) + (0x7fffffff & (g_aiMT[(i + 1) % MT_SIZE]));\n\t\t\tg_aiMT[i] = g_aiMT[(i + 397) % MT_SIZE] ^ (y >> 1);\n\t\t\tif ((y % 2) == 1)\n\t\t\t\tg_aiMT[i] = g_aiMT[i] ^ 0x9908b0df;\n\t\t}\n\t}\n\n\tsize_t y = g_aiMT[g_iMTI];\n\ty = y ^ (y >> 11);\n\ty = y ^ ((y << 7) & (0x9d2c5680));\n\ty = y ^ ((y << 15) & (0xefc60000));\n\ty = y ^ (y >> 18);\n\n\tg_iMTI = (g_iMTI + 1) % MT_SIZE;\n\n\treturn y;\n}\n\n\ninline float mtfrand()\n{\n\tconst int ninenine = 999999;\n\treturn (float)(mtrand() % ninenine)/ninenine;\n}\n\nvoid resizer(int argc, char **argv)\n{\n\tunsigned char* input_pixels;\n\tunsigned char* output_pixels;\n\tint w, h;\n\tint n;\n\tint out_w, out_h;\n\tinput_pixels = stbi_load(argv[1], &w, &h, &n, 0);\n\tout_w = w*3;\n\tout_h = h*3;\n\toutput_pixels = (unsigned char*) malloc(out_w*out_h*n);\n\t//stbir_resize_uint8_srgb(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, n, -1,0);\n\tstbir_resize_uint8_linear(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, (stbir_pixel_layout) n);\n\tstbi_write_png(\"output.png\", out_w, out_h, n, output_pixels, 0);\n\texit(0);\n}\n\nvoid performance(int argc, char **argv)\n{\n\tunsigned char* input_pixels;\n\tunsigned char* output_pixels;\n\tint w, h, count;\n\tint n, i;\n\tint out_w, out_h, srgb=1;\n\tinput_pixels = stbi_load(argv[1], &w, &h, &n, 0);\n    #if 0\n    out_w = w/4; out_h = h/4; count=100; // 1\n    #elif 0\n\tout_w = w*2; out_h = h/4; count=20; // 2   // note this is structured pessimily, would be much faster to downsample vertically first\n    #elif 0\n    out_w = w/4; out_h = h*2; count=50; // 3\n    #elif 0\n    out_w = w*3; out_h = h*3; count=2; srgb=0; // 4\n    #else\n    out_w = w*3; out_h = h*3; count=2; // 5   // this is dominated by linear->sRGB conversion\n    #endif\n\n\toutput_pixels = (unsigned char*) malloc(out_w*out_h*n);\n    for (i=0; i < count; ++i)\n        if (srgb)\n\t        stbir_resize_uint8_srgb(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, (stbir_pixel_layout) n);\n        else\n\t        stbir_resize_uint8_linear(input_pixels, w, h, 0, output_pixels, out_w, out_h, 0, (stbir_pixel_layout) n);\n\texit(0);\n}\n\nvoid test_suite(int argc, char **argv);\n\nint main(int argc, char** argv)\n{\n\t//resizer(argc, argv);\n    //performance(argc, argv);\n\n\ttest_suite(argc, argv);\n\treturn 0;\n}\n\n#if 0\nvoid resize_image(const char* filename, float width_percent, float height_percent, stbir_filter filter, stbir_edge edge, stbir_colorspace colorspace, const char* output_filename)\n{\n\tint w, h, n;\n\n\tunsigned char* input_data = stbi_load(filename, &w, &h, &n, 0);\n\tif (!input_data)\n\t{\n\t\tprintf(\"Input image could not be loaded\\n\");\n\t\treturn;\n\t}\n\n\tint out_w = (int)(w * width_percent);\n\tint out_h = (int)(h * height_percent);\n\n\tunsigned char* output_data = (unsigned char*)malloc(out_w * out_h * n);\n\n\tstbir_resize(input_data, w, h, 0, output_data, out_w, out_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, edge, edge, filter, filter, colorspace, &g_context);\n\n\tstbi_image_free(input_data);\n\n\tstbi_write_png(output_filename, out_w, out_h, n, output_data, 0);\n\n\tfree(output_data);\n}\n\ntemplate <typename F, typename T>\nvoid convert_image(const F* input, T* output, int length)\n{\n\tdouble f = (pow(2.0, 8.0 * sizeof(T)) - 1) / (pow(2.0, 8.0 * sizeof(F)) - 1);\n\tfor (int i = 0; i < length; i++)\n\t\toutput[i] = (T)(((double)input[i]) * f);\n}\n\ntemplate <typename T>\nvoid test_format(const char* file, float width_percent, float height_percent, stbir_datatype type, stbir_colorspace colorspace)\n{\n\tint w, h, n;\n\tunsigned char* input_data = stbi_load(file, &w, &h, &n, 0);\n\n\tif (input_data == NULL)\n\t\treturn;\n\n\n\tint new_w = (int)(w * width_percent);\n\tint new_h = (int)(h * height_percent);\n\n\tT* T_data = (T*)malloc(w * h * n * sizeof(T));\n    memset(T_data, 0, w*h*n*sizeof(T));\n\tconvert_image<unsigned char, T>(input_data, T_data, w * h * n);\n\n\tT* output_data = (T*)malloc(new_w * new_h * n * sizeof(T));\n\n\tstbir_resize(T_data, w, h, 0, output_data, new_w, new_h, 0, type, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, colorspace, &g_context);\n\n\tfree(T_data);\n\tstbi_image_free(input_data);\n\n\tunsigned char* char_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(char));\n\tconvert_image<T, unsigned char>(output_data, char_data, new_w * new_h * n);\n\n\tchar output[200];\n\tsprintf(output, \"test-output/type-%d-%d-%d-%d-%s\", type, colorspace, new_w, new_h, file);\n\tstbi_write_png(output, new_w, new_h, n, char_data, 0);\n\n\tfree(char_data);\n\tfree(output_data);\n}\n\nvoid convert_image_float(const unsigned char* input, float* output, int length)\n{\n\tfor (int i = 0; i < length; i++)\n\t\toutput[i] = ((float)input[i])/255;\n}\n\nvoid convert_image_float(const float* input, unsigned char* output, int length)\n{\n\tfor (int i = 0; i < length; i++)\n\t\toutput[i] = (unsigned char)(stbir__saturate(input[i]) * 255);\n}\n\nvoid test_float(const char* file, float width_percent, float height_percent, stbir_datatype type, stbir_colorspace colorspace)\n{\n\tint w, h, n;\n\tunsigned char* input_data = stbi_load(file, &w, &h, &n, 0);\n\n\tif (input_data == NULL)\n\t\treturn;\n\n\tint new_w = (int)(w * width_percent);\n\tint new_h = (int)(h * height_percent);\n\n\tfloat* T_data = (float*)malloc(w * h * n * sizeof(float));\n\tconvert_image_float(input_data, T_data, w * h * n);\n\n\tfloat* output_data = (float*)malloc(new_w * new_h * n * sizeof(float));\n\n\tstbir_resize_float_generic(T_data, w, h, 0, output_data, new_w, new_h, 0, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, colorspace, &g_context);\n\n\tfree(T_data);\n\tstbi_image_free(input_data);\n\n\tunsigned char* char_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(char));\n\tconvert_image_float(output_data, char_data, new_w * new_h * n);\n\n\tchar output[200];\n\tsprintf(output, \"test-output/type-%d-%d-%d-%d-%s\", type, colorspace, new_w, new_h, file);\n\tstbi_write_png(output, new_w, new_h, n, char_data, 0);\n\n\tfree(char_data);\n\tfree(output_data);\n}\n\nvoid test_channels(const char* file, float width_percent, float height_percent, int channels)\n{\n\tint w, h, n;\n\tunsigned char* input_data = stbi_load(file, &w, &h, &n, 0);\n\n\tif (input_data == NULL)\n\t\treturn;\n\n\tint new_w = (int)(w * width_percent);\n\tint new_h = (int)(h * height_percent);\n\n\tunsigned char* channels_data = (unsigned char*)malloc(w * h * channels * sizeof(unsigned char));\n\n\tfor (int i = 0; i < w * h; i++)\n\t{\n\t\tint input_position = i * n;\n\t\tint output_position = i * channels;\n\n\t\tfor (int c = 0; c < channels; c++)\n\t\t\tchannels_data[output_position + c] = input_data[input_position + stbir__min(c, n)];\n\t}\n\n\tunsigned char* output_data = (unsigned char*)malloc(new_w * new_h * channels * sizeof(unsigned char));\n\n\tstbir_resize_uint8_srgb(channels_data, w, h, 0, output_data, new_w, new_h, 0, channels, STBIR_ALPHA_CHANNEL_NONE, 0);\n\n\tfree(channels_data);\n\tstbi_image_free(input_data);\n\n\tchar output[200];\n\tsprintf(output, \"test-output/channels-%d-%d-%d-%s\", channels, new_w, new_h, file);\n\tstbi_write_png(output, new_w, new_h, channels, output_data, 0);\n\n\tfree(output_data);\n}\n\nvoid test_subpixel(const char* file, float width_percent, float height_percent, float s1, float t1)\n{\n\tint w, h, n;\n\tunsigned char* input_data = stbi_load(file, &w, &h, &n, 0);\n\n\tif (input_data == NULL)\n\t\treturn;\n\n\ts1 = ((float)w - 1 + s1)/w;\n\tt1 = ((float)h - 1 + t1)/h;\n\n\tint new_w = (int)(w * width_percent);\n\tint new_h = (int)(h * height_percent);\n\n\tunsigned char* output_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(unsigned char));\n\n\tstbir_resize_region(input_data, w, h, 0, output_data, new_w, new_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0, 0, s1, t1);\n\n\tstbi_image_free(input_data);\n\n\tchar output[200];\n\tsprintf(output, \"test-output/subpixel-%d-%d-%f-%f-%s\", new_w, new_h, s1, t1, file);\n\tstbi_write_png(output, new_w, new_h, n, output_data, 0);\n\n\tfree(output_data);\n}\n\nvoid test_subpixel_region(const char* file, float width_percent, float height_percent, float s0, float t0, float s1, float t1)\n{\n\tint w, h, n;\n\tunsigned char* input_data = stbi_load(file, &w, &h, &n, 0);\n\n\tif (input_data == NULL)\n\t\treturn;\n\n\tint new_w = (int)(w * width_percent);\n\tint new_h = (int)(h * height_percent);\n\n\tunsigned char* output_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(unsigned char));\n\n\tstbir_resize_region(input_data, w, h, 0, output_data, new_w, new_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, s0, t0, s1, t1);\n\n\tstbi_image_free(input_data);\n\n\tchar output[200];\n\tsprintf(output, \"test-output/subpixel-region-%d-%d-%f-%f-%f-%f-%s\", new_w, new_h, s0, t0, s1, t1, file);\n\tstbi_write_png(output, new_w, new_h, n, output_data, 0);\n\n\tfree(output_data);\n}\n\nvoid test_subpixel_command(const char* file, float width_percent, float height_percent, float x_scale, float y_scale, float x_offset, float y_offset)\n{\n\tint w, h, n;\n\tunsigned char* input_data = stbi_load(file, &w, &h, &n, 0);\n\n\tif (input_data == NULL)\n\t\treturn;\n\n\tint new_w = (int)(w * width_percent);\n\tint new_h = (int)(h * height_percent);\n\n\tunsigned char* output_data = (unsigned char*)malloc(new_w * new_h * n * sizeof(unsigned char));\n\n\tstbir_resize_subpixel(input_data, w, h, 0, output_data, new_w, new_h, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, x_scale, y_scale, x_offset, y_offset);\n\n\tstbi_image_free(input_data);\n\n\tchar output[200];\n\tsprintf(output, \"test-output/subpixel-command-%d-%d-%f-%f-%f-%f-%s\", new_w, new_h, x_scale, y_scale, x_offset, y_offset, file);\n\tstbi_write_png(output, new_w, new_h, n, output_data, 0);\n\n\tfree(output_data);\n}\n\nunsigned int* pixel(unsigned int* buffer, int x, int y, int c, int w, int n)\n{\n\treturn &buffer[y*w*n + x*n + c];\n}\n\nvoid test_premul()\n{\n\tunsigned int input[2 * 2 * 4];\n\tunsigned int output[1 * 1 * 4];\n\tunsigned int output2[2 * 2 * 4];\n\n\tmemset(input, 0, sizeof(input));\n\n\t// First a test to make sure premul is working properly.\n\n\t// Top left - solid red\n\t*pixel(input, 0, 0, 0, 2, 4) = 255;\n\t*pixel(input, 0, 0, 3, 2, 4) = 255;\n\n\t// Bottom left - solid red\n\t*pixel(input, 0, 1, 0, 2, 4) = 255;\n\t*pixel(input, 0, 1, 3, 2, 4) = 255;\n\n\t// Top right - transparent green\n\t*pixel(input, 1, 0, 1, 2, 4) = 255;\n\t*pixel(input, 1, 0, 3, 2, 4) = 25;\n\n\t// Bottom right - transparent green\n\t*pixel(input, 1, 1, 1, 2, 4) = 255;\n\t*pixel(input, 1, 1, 3, 2, 4) = 25;\n\n\tstbir_resize(input, 2, 2, 0, output, 1, 1, 0, STBIR_TYPE_UINT32, 4, 3, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, &g_context);\n\n\tfloat r = (float)255 / 4294967296;\n\tfloat g = (float)255 / 4294967296;\n\tfloat ra = (float)255 / 4294967296;\n\tfloat ga = (float)25 / 4294967296;\n\tfloat a = (ra + ga) / 2;\n\n\tSTBIR_ASSERT(output[0] == (unsigned int)(r * ra / 2 / a * 4294967296 + 0.5f)); // 232\n\tSTBIR_ASSERT(output[1] == (unsigned int)(g * ga / 2 / a * 4294967296 + 0.5f)); // 23\n\tSTBIR_ASSERT(output[2] == 0);\n\tSTBIR_ASSERT(output[3] == (unsigned int)(a * 4294967296 + 0.5f)); // 140\n\n\t// Now a test to make sure it doesn't clobber existing values.\n\n\t// Top right - completely transparent green\n\t*pixel(input, 1, 0, 1, 2, 4) = 255;\n\t*pixel(input, 1, 0, 3, 2, 4) = 0;\n\n\t// Bottom right - completely transparent green\n\t*pixel(input, 1, 1, 1, 2, 4) = 255;\n\t*pixel(input, 1, 1, 3, 2, 4) = 0;\n\n\tstbir_resize(input, 2, 2, 0, output2, 2, 2, 0, STBIR_TYPE_UINT32, 4, 3, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, &g_context);\n\n\tSTBIR_ASSERT(*pixel(output2, 0, 0, 0, 2, 4) == 255);\n\tSTBIR_ASSERT(*pixel(output2, 0, 0, 1, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 0, 0, 2, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 0, 0, 3, 2, 4) == 255);\n\n\tSTBIR_ASSERT(*pixel(output2, 0, 1, 0, 2, 4) == 255);\n\tSTBIR_ASSERT(*pixel(output2, 0, 1, 1, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 0, 1, 2, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 0, 1, 3, 2, 4) == 255);\n\n\tSTBIR_ASSERT(*pixel(output2, 1, 0, 0, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 1, 0, 1, 2, 4) == 255);\n\tSTBIR_ASSERT(*pixel(output2, 1, 0, 2, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 1, 0, 3, 2, 4) == 0);\n\n\tSTBIR_ASSERT(*pixel(output2, 1, 1, 0, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 1, 1, 1, 2, 4) == 255);\n\tSTBIR_ASSERT(*pixel(output2, 1, 1, 2, 2, 4) == 0);\n\tSTBIR_ASSERT(*pixel(output2, 1, 1, 3, 2, 4) == 0);\n}\n\n// test that splitting a pow-2 image into tiles produces identical results\nvoid test_subpixel_1()\n{\n\tunsigned char image[8 * 8];\n\n\tmtsrand(0);\n\n\tfor (int i = 0; i < sizeof(image); i++)\n\t\timage[i] = mtrand() & 255;\n\n\tunsigned char output_data[16 * 16];\n\n\tstbir_resize_region(image, 8, 8, 0, output_data, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0, 0, 1, 1);\n\n\tunsigned char output_left[8 * 16];\n\tunsigned char output_right[8 * 16];\n\n\tstbir_resize_region(image, 8, 8, 0, output_left, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0, 0, 0.5f, 1);\n\tstbir_resize_region(image, 8, 8, 0, output_right, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0.5f, 0, 1, 1);\n\n\tfor (int x = 0; x < 8; x++)\n\t{\n\t\tfor (int y = 0; y < 16; y++)\n\t\t{\n\t\t\tSTBIR_ASSERT(output_data[y * 16 + x] == output_left[y * 8 + x]);\n\t\t\tSTBIR_ASSERT(output_data[y * 16 + x + 8] == output_right[y * 8 + x]);\n\t\t}\n\t}\n\n\tstbir_resize_subpixel(image, 8, 8, 0, output_left, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 2, 2, 0, 0);\n\tstbir_resize_subpixel(image, 8, 8, 0, output_right, 8, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 2, 2, 8, 0);\n\n\t{for (int x = 0; x < 8; x++)\n\t{\n\t\tfor (int y = 0; y < 16; y++)\n\t\t{\n\t\t\tSTBIR_ASSERT(output_data[y * 16 + x] == output_left[y * 8 + x]);\n\t\t\tSTBIR_ASSERT(output_data[y * 16 + x + 8] == output_right[y * 8 + x]);\n\t\t}\n\t}}\n}\n\n// test that replicating an image and using a subtile of it produces same results as wraparound\nvoid test_subpixel_2()\n{\n\tunsigned char image[8 * 8];\n\n\tmtsrand(0);\n\n\tfor (int i = 0; i < sizeof(image); i++)\n\t\timage[i] = mtrand() & 255;\n\n\tunsigned char large_image[32 * 32];\n\n\tfor (int x = 0; x < 8; x++)\n\t{\n\t\tfor (int y = 0; y < 8; y++)\n\t\t{\n\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 4; j++)\n\t\t\t\t\tlarge_image[j*4*8*8 + i*8 + y*4*8 + x] = image[y*8 + x];\n\t\t\t}\n\t\t}\n\t}\n\n\tunsigned char output_data_1[16 * 16];\n\tunsigned char output_data_2[16 * 16];\n\n\tstbir_resize(image, 8, 8, 0, output_data_1, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_WRAP, STBIR_EDGE_WRAP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context);\n\tstbir_resize_region(large_image, 32, 32, 0, output_data_2, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_WRAP, STBIR_EDGE_WRAP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 0.25f, 0.25f, 0.5f, 0.5f);\n\n\t{for (int x = 0; x < 16; x++)\n\t{\n\t\tfor (int y = 0; y < 16; y++)\n\t\t\tSTBIR_ASSERT(output_data_1[y * 16 + x] == output_data_2[y * 16 + x]);\n\t}}\n\n\tstbir_resize_subpixel(large_image, 32, 32, 0, output_data_2, 16, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_WRAP, STBIR_EDGE_WRAP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context, 2, 2, 16, 16);\n\n\t{for (int x = 0; x < 16; x++)\n\t{\n\t\tfor (int y = 0; y < 16; y++)\n\t\t\tSTBIR_ASSERT(output_data_1[y * 16 + x] == output_data_2[y * 16 + x]);\n\t}}\n}\n\n// test that 0,0,1,1 subpixel produces same result as no-rect\nvoid test_subpixel_3()\n{\n\tunsigned char image[8 * 8];\n\n\tmtsrand(0);\n\n\tfor (int i = 0; i < sizeof(image); i++)\n\t\timage[i] = mtrand() & 255;\n\n\tunsigned char output_data_1[32 * 32];\n\tunsigned char output_data_2[32 * 32];\n\n\tstbir_resize_region(image, 8, 8, 0, output_data_1, 32, 32, 0, STBIR_TYPE_UINT8, 1, 0, STBIR_ALPHA_CHANNEL_NONE, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_LINEAR, NULL, 0, 0, 1, 1);\n\tstbir_resize_uint8(image, 8, 8, 0, output_data_2, 32, 32, 0, 1);\n\n\tfor (int x = 0; x < 32; x++)\n\t{\n\t\tfor (int y = 0; y < 32; y++)\n\t\t\tSTBIR_ASSERT(output_data_1[y * 32 + x] == output_data_2[y * 32 + x]);\n\t}\n\n\tstbir_resize_subpixel(image, 8, 8, 0, output_data_1, 32, 32, 0, STBIR_TYPE_UINT8, 1, 0, STBIR_ALPHA_CHANNEL_NONE, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_LINEAR, NULL, 4, 4, 0, 0);\n\n\t{for (int x = 0; x < 32; x++)\n\t{\n\t\tfor (int y = 0; y < 32; y++)\n\t\t\tSTBIR_ASSERT(output_data_1[y * 32 + x] == output_data_2[y * 32 + x]);\n\t}}\n}\n\n// test that 1:1 resample using s,t=0,0,1,1 with bilinear produces original image\nvoid test_subpixel_4()\n{\n\tunsigned char image[8 * 8];\n\n\tmtsrand(0);\n\n\tfor (int i = 0; i < sizeof(image); i++)\n\t\timage[i] = mtrand() & 255;\n\n\tunsigned char output[8 * 8];\n\n\tstbir_resize_region(image, 8, 8, 0, output, 8, 8, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_TRIANGLE, STBIR_FILTER_TRIANGLE, STBIR_COLORSPACE_LINEAR, &g_context, 0, 0, 1, 1);\n\tSTBIR_ASSERT(memcmp(image, output, 8 * 8) == 0);\n\n\tstbir_resize_subpixel(image, 8, 8, 0, output, 8, 8, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_TRIANGLE, STBIR_FILTER_TRIANGLE, STBIR_COLORSPACE_LINEAR, &g_context, 1, 1, 0, 0);\n\tSTBIR_ASSERT(memcmp(image, output, 8 * 8) == 0);\n}\n\nstatic unsigned int  image88_int[8][8];\nstatic unsigned char image88 [8][8];\nstatic unsigned char output88[8][8];\nstatic unsigned char output44[4][4];\nstatic unsigned char output22[2][2];\nstatic unsigned char output11[1][1];\n\nvoid resample_88(stbir_filter filter)\n{\n\tstbir_resize_uint8_generic(image88[0],8,8,0, output88[0],8,8,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);\n\tstbir_resize_uint8_generic(image88[0],8,8,0, output44[0],4,4,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);\n\tstbir_resize_uint8_generic(image88[0],8,8,0, output22[0],2,2,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);\n\tstbir_resize_uint8_generic(image88[0],8,8,0, output11[0],1,1,0, 1,-1,0, STBIR_EDGE_CLAMP, filter, STBIR_COLORSPACE_LINEAR, NULL);\n}\n\nvoid verify_box(void)\n{\n\tint i,j,t;\n\n\tresample_88(STBIR_FILTER_BOX);\n\n\tfor (i=0; i < sizeof(image88); ++i)\n\t\tSTBIR_ASSERT(image88[0][i] == output88[0][i]);\n\n\tt = 0;\n\tfor (j=0; j < 4; ++j)\n\t\tfor (i=0; i < 4; ++i) {\n\t\t\tint n = image88[j*2+0][i*2+0]\n\t\t\t      + image88[j*2+0][i*2+1]\n\t\t\t\t  + image88[j*2+1][i*2+0]\n\t\t\t\t  + image88[j*2+1][i*2+1];\n\t\t\tSTBIR_ASSERT(output44[j][i] == ((n+2)>>2) || output44[j][i] == ((n+1)>>2)); // can't guarantee exact rounding due to numerical precision\n\t\t\tt += n;\n\t\t}\n\tSTBIR_ASSERT(output11[0][0] == ((t+32)>>6) || output11[0][0] == ((t+31)>>6)); // can't guarantee exact rounding due to numerical precision\n}\n\nvoid verify_filter_normalized(stbir_filter filter, int output_size, unsigned int value)\n{\n\tint i, j;\n\tunsigned int output[64];\n\n\tstbir_resize(image88_int[0], 8, 8, 0, output, output_size, output_size, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, filter, filter, STBIR_COLORSPACE_LINEAR, NULL);\n\n\tfor (j = 0; j < output_size; ++j)\n\t\tfor (i = 0; i < output_size; ++i)\n\t\t\tSTBIR_ASSERT(value == output[j*output_size + i]);\n}\n\nfloat round2(float f)\n{\n\treturn (float) floor(f+0.5f); // round() isn't C standard pre-C99\n}\n\nvoid test_filters(void)\n{\n\tint i,j;\n\n\tmtsrand(0);\n\n\tfor (i=0; i < sizeof(image88); ++i)\n\t\timage88[0][i] = mtrand() & 255;\n\tverify_box();\n\n\tfor (i=0; i < sizeof(image88); ++i)\n\t\timage88[0][i] = 0;\n\timage88[4][4] = 255;\n\tverify_box();\n\n\tfor (j=0; j < 8; ++j)\n\t\tfor (i=0; i < 8; ++i)\n\t\t\timage88[j][i] = (j^i)&1 ? 255 : 0;\n\tverify_box();\n\n\tfor (j=0; j < 8; ++j)\n\t\tfor (i=0; i < 8; ++i)\n\t\t\timage88[j][i] = i&2 ? 255 : 0;\n\tverify_box();\n\n\tint value = 64;\n\n\tfor (j = 0; j < 8; ++j)\n\t\tfor (i = 0; i < 8; ++i)\n\t\t\timage88_int[j][i] = value;\n\n\tverify_filter_normalized(STBIR_FILTER_BOX, 8, value);\n\tverify_filter_normalized(STBIR_FILTER_TRIANGLE, 8, value);\n\tverify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 8, value);\n\tverify_filter_normalized(STBIR_FILTER_CATMULLROM, 8, value);\n\tverify_filter_normalized(STBIR_FILTER_MITCHELL, 8, value);\n\n\tverify_filter_normalized(STBIR_FILTER_BOX, 4, value);\n\tverify_filter_normalized(STBIR_FILTER_TRIANGLE, 4, value);\n\tverify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 4, value);\n\tverify_filter_normalized(STBIR_FILTER_CATMULLROM, 4, value);\n\tverify_filter_normalized(STBIR_FILTER_MITCHELL, 4, value);\n\n\tverify_filter_normalized(STBIR_FILTER_BOX, 2, value);\n\tverify_filter_normalized(STBIR_FILTER_TRIANGLE, 2, value);\n\tverify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 2, value);\n\tverify_filter_normalized(STBIR_FILTER_CATMULLROM, 2, value);\n\tverify_filter_normalized(STBIR_FILTER_MITCHELL, 2, value);\n\n\tverify_filter_normalized(STBIR_FILTER_BOX, 1, value);\n\tverify_filter_normalized(STBIR_FILTER_TRIANGLE, 1, value);\n\tverify_filter_normalized(STBIR_FILTER_CUBICBSPLINE, 1, value);\n\tverify_filter_normalized(STBIR_FILTER_CATMULLROM, 1, value);\n\tverify_filter_normalized(STBIR_FILTER_MITCHELL, 1, value);\n\n\t{\n\t\t// This test is designed to produce coefficients that are very badly denormalized.\n\t\tunsigned int v = 556;\n\n\t\tunsigned int input[100 * 100];\n\t\tunsigned int output[11 * 11];\n\n\t\tfor (j = 0; j < 100 * 100; ++j)\n\t\t\tinput[j] = v;\n\n\t\tstbir_resize(input, 100, 100, 0, output, 11, 11, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_TRIANGLE, STBIR_FILTER_TRIANGLE, STBIR_COLORSPACE_LINEAR, NULL);\n\n\t\tfor (j = 0; j < 11 * 11; ++j)\n\t\t\tSTBIR_ASSERT(v == output[j]);\n\t}\n\n\t{\n\t\t// Now test the trapezoid filter for downsampling.\n\t\tunsigned int input[3 * 1];\n\t\tunsigned int output[2 * 1];\n\n\t\tinput[0] = 0;\n\t\tinput[1] = 255;\n\t\tinput[2] = 127;\n\n\t\tstbir_resize(input, 3, 1, 0, output, 2, 1, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);\n\n\t\tSTBIR_ASSERT(output[0] == (unsigned int)round2((float)(input[0] * 2 + input[1]) / 3));\n\t\tSTBIR_ASSERT(output[1] == (unsigned int)round2((float)(input[2] * 2 + input[1]) / 3));\n\n\t\tstbir_resize(input, 1, 3, 0, output, 1, 2, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);\n\n\t\tSTBIR_ASSERT(output[0] == (unsigned int)round2((float)(input[0] * 2 + input[1]) / 3));\n\t\tSTBIR_ASSERT(output[1] == (unsigned int)round2((float)(input[2] * 2 + input[1]) / 3));\n\t}\n\n\t{\n\t\t// Now test the trapezoid filter for upsampling.\n\t\tunsigned int input[2 * 1];\n\t\tunsigned int output[3 * 1];\n\n\t\tinput[0] = 0;\n\t\tinput[1] = 255;\n\n\t\tstbir_resize(input, 2, 1, 0, output, 3, 1, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);\n\n\t\tSTBIR_ASSERT(output[0] == input[0]);\n\t\tSTBIR_ASSERT(output[1] == (input[0] + input[1]) / 2);\n\t\tSTBIR_ASSERT(output[2] == input[1]);\n\n\t\tstbir_resize(input, 1, 2, 0, output, 1, 3, 0, STBIR_TYPE_UINT32, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);\n\n\t\tSTBIR_ASSERT(output[0] == input[0]);\n\t\tSTBIR_ASSERT(output[1] == (input[0] + input[1]) / 2);\n\t\tSTBIR_ASSERT(output[2] == input[1]);\n\t}\n\n\t// checkerboard\n\t{\n\t\tunsigned char input[64][64];\n\t\tunsigned char output[16][16];\n\t\tint i,j;\n\t\tfor (j=0; j < 64; ++j)\n\t\t\tfor (i=0; i < 64; ++i)\n\t\t\t\tinput[j][i] = (i^j)&1 ? 255 : 0;\n\t\tstbir_resize_uint8_generic(input[0], 64, 64, 0, output[0],16,16,0, 1,-1,0,STBIR_EDGE_WRAP,STBIR_FILTER_DEFAULT,STBIR_COLORSPACE_LINEAR,0);\n\t\tfor (j=0; j < 16; ++j)\n\t\t\tfor (i=0; i < 16; ++i)\n\t\t\t\tSTBIR_ASSERT(output[j][i] == 128);\n\t\tstbir_resize_uint8_srgb_edgemode(input[0], 64, 64, 0, output[0],16,16,0, 1,-1,0,STBIR_EDGE_WRAP);\n\t\tfor (j=0; j < 16; ++j)\n\t\t\tfor (i=0; i < 16; ++i)\n\t\t\t\tSTBIR_ASSERT(output[j][i] == 188);\n\n\n\t}\n\n\t{\n\t\t// Test trapezoid box filter\n\t\tunsigned char input[2 * 1];\n\t\tunsigned char output[127 * 1];\n\n\t\tinput[0] = 0;\n\t\tinput[1] = 255;\n\n\t\tstbir_resize(input, 2, 1, 0, output, 127, 1, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);\n\t\tSTBIR_ASSERT(output[0] == 0);\n\t\tSTBIR_ASSERT(output[127 / 2 - 1] == 0);\n\t\tSTBIR_ASSERT(output[127 / 2] == 128);\n\t\tSTBIR_ASSERT(output[127 / 2 + 1] == 255);\n\t\tSTBIR_ASSERT(output[126] == 255);\n\t\tstbi_write_png(\"test-output/trapezoid-upsample-horizontal.png\", 127, 1, 1, output, 0);\n\n\t\tstbir_resize(input, 1, 2, 0, output, 1, 127, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_BOX, STBIR_COLORSPACE_LINEAR, NULL);\n\t\tSTBIR_ASSERT(output[0] == 0);\n\t\tSTBIR_ASSERT(output[127 / 2 - 1] == 0);\n\t\tSTBIR_ASSERT(output[127 / 2] == 128);\n\t\tSTBIR_ASSERT(output[127 / 2 + 1] == 255);\n\t\tSTBIR_ASSERT(output[126] == 255);\n\t\tstbi_write_png(\"test-output/trapezoid-upsample-vertical.png\", 1, 127, 1, output, 0);\n\t}\n}\n\n#define UMAX32   4294967295U\n\nstatic void write32(const char *filename, stbir_uint32 *output, int w, int h)\n{\n    stbir_uint8 *data = (stbir_uint8*) malloc(w*h*3);\n    for (int i=0; i < w*h*3; ++i)\n        data[i] = output[i]>>24;\n    stbi_write_png(filename, w, h, 3, data, 0);\n    free(data);\n}\n\nstatic void test_32(void)\n{\n    int w=100,h=120,x,y, out_w,out_h;\n    stbir_uint32 *input  = (stbir_uint32*) malloc(4 * 3 * w * h);\n    stbir_uint32 *output = (stbir_uint32*) malloc(4 * 3 * 3*w * 3*h);\n    for (y=0; y < h; ++y) {\n        for (x=0; x < w; ++x) {\n            input[y*3*w + x*3 + 0] = x * ( UMAX32/w );\n            input[y*3*w + x*3 + 1] = y * ( UMAX32/h );\n            input[y*3*w + x*3 + 2] = UMAX32/2;\n        }\n    }\n    out_w = w*33/16;\n    out_h = h*33/16;\n    stbir_resize(input,w,h,0,output,out_w,out_h,0,STBIR_TYPE_UINT32,3,-1,0,STBIR_EDGE_CLAMP,STBIR_EDGE_CLAMP,STBIR_FILTER_DEFAULT,STBIR_FILTER_DEFAULT,STBIR_COLORSPACE_LINEAR,NULL);\n    write32(\"test-output/seantest_1.png\", output,out_w,out_h);\n\n    out_w = w*16/33;\n    out_h = h*16/33;\n    stbir_resize(input,w,h,0,output,out_w,out_h,0,STBIR_TYPE_UINT32,3,-1,0,STBIR_EDGE_CLAMP,STBIR_EDGE_CLAMP,STBIR_FILTER_DEFAULT,STBIR_FILTER_DEFAULT,STBIR_COLORSPACE_LINEAR,NULL);\n    write32(\"test-output/seantest_2.png\", output,out_w,out_h);\n}\n\n\nvoid test_suite(int argc, char **argv)\n{\n\tint i;\n\tconst char *barbara;\n\n\tmkdir(\"test-output\", 777);\n\n\tif (argc > 1)\n\t\tbarbara = argv[1];\n\telse\n\t\tbarbara = \"barbara.png\";\n\n\t// check what cases we need normalization for\n#if 1\n\t{\n\t\tfloat x, y;\n\t\tfor (x = -1; x < 1; x += 0.05f) {\n\t\t\tfloat sums[5] = { 0 };\n\t\t\tfloat o;\n\t\t\tfor (o = -5; o <= 5; ++o) {\n\t\t\t\tsums[0] += stbir__filter_mitchell(x + o, 1);\n\t\t\t\tsums[1] += stbir__filter_catmullrom(x + o, 1);\n\t\t\t\tsums[2] += stbir__filter_cubic(x + o, 1);\n\t\t\t\tsums[3] += stbir__filter_triangle(x + o, 1);\n\t\t\t\tsums[4] += stbir__filter_trapezoid(x + o, 0.5f);\n\t\t\t}\n\t\t\tfor (i = 0; i < 5; ++i)\n\t\t\t\tSTBIR_ASSERT(sums[i] >= 1.0 - 0.001 && sums[i] <= 1.0 + 0.001);\n\t\t}\n\n#if 1\t\n\t\tfor (y = 0.11f; y < 1; y += 0.01f) {  // Step\n\t\t\tfor (x = -1; x < 1; x += 0.05f) { // Phase\n\t\t\t\tfloat sums[5] = { 0 };\n\t\t\t\tfloat o;\n\t\t\t\tfor (o = -5; o <= 5; o += y) {\n\t\t\t\t\tsums[0] += y * stbir__filter_mitchell(x + o, 1);\n\t\t\t\t\tsums[1] += y * stbir__filter_catmullrom(x + o, 1);\n\t\t\t\t\tsums[2] += y * stbir__filter_cubic(x + o, 1);\n\t\t\t\t\tsums[4] += y * stbir__filter_trapezoid(x + o, 0.5f);\n\t\t\t\t\tsums[3] += y * stbir__filter_triangle(x + o, 1);\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < 3; ++i)\n\t\t\t\t\tSTBIR_ASSERT(sums[i] >= 1.0 - 0.0170 && sums[i] <= 1.0 + 0.0170);\n\t\t\t}\n\t\t}\n#endif\n\t}\n#endif\n\n#if 0 // linear_to_srgb_uchar table\n\tfor (i=0; i < 256; ++i) {\n\t\tfloat f = stbir__srgb_to_linear((i-0.5f)/255.0f);\n\t\tprintf(\"%9d, \", (int) ((f) * (1<<28)));\n\t\tif ((i & 7) == 7)\n\t\t\tprintf(\"\\n\");\n\t}\n#endif\n\n\t// old tests that hacky fix worked on - test that\n\t// every uint8 maps to itself\n\tfor (i = 0; i < 256; i++) {\n\t\tfloat f = stbir__srgb_to_linear(float(i) / 255);\n\t\tint n = stbir__linear_to_srgb_uchar(f);\n\t\tSTBIR_ASSERT(n == i);\n\t}\n\n\t// new tests that hacky fix failed for - test that\n\t// values adjacent to uint8 round to nearest uint8\n\tfor (i = 0; i < 256; i++) {\n\t\tfor (float y = -0.42f; y <= 0.42f; y += 0.01f) {\n\t\t\tfloat f = stbir__srgb_to_linear((i+y) / 255.0f);\n\t\t\tint n = stbir__linear_to_srgb_uchar(f);\n\t\t\tSTBIR_ASSERT(n == i);\n\t\t}\n\t}\n\n\ttest_filters();\n\n\ttest_subpixel_1();\n\ttest_subpixel_2();\n\ttest_subpixel_3();\n\ttest_subpixel_4();\n\n\ttest_premul();\n\n\ttest_32();\n\n\t// Some tests to make sure errors don't pop up with strange filter/dimension combinations.\n\tstbir_resize(image88, 8, 8, 0, output88, 4, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context);\n\tstbir_resize(image88, 8, 8, 0, output88, 4, 16, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_BOX, STBIR_COLORSPACE_SRGB, &g_context);\n\tstbir_resize(image88, 8, 8, 0, output88, 16, 4, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_BOX, STBIR_FILTER_CATMULLROM, STBIR_COLORSPACE_SRGB, &g_context);\n\tstbir_resize(image88, 8, 8, 0, output88, 16, 4, 0, STBIR_TYPE_UINT8, 1, STBIR_ALPHA_CHANNEL_NONE, 0, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_FILTER_CATMULLROM, STBIR_FILTER_BOX, STBIR_COLORSPACE_SRGB, &g_context);\n\n\tint barbara_width, barbara_height, barbara_channels;\n\tstbi_image_free(stbi_load(barbara, &barbara_width, &barbara_height, &barbara_channels, 0));\n\n\tint res = 10;\n\t// Downscaling\n\t{for (int i = 0; i <= res; i++)\n\t{\n\t\tfloat t = (float)i/res;\n\t\tfloat scale = 0.5;\n\t\tfloat out_scale = 2.0f/3;\n\t\tfloat x_shift = (barbara_width*out_scale - barbara_width*scale) * t;\n\t\tfloat y_shift = (barbara_height*out_scale - barbara_height*scale) * t;\n\n\t\ttest_subpixel_command(barbara, scale, scale, out_scale, out_scale, x_shift, y_shift);\n\t}}\n\n\t// Upscaling\n\t{for (int i = 0; i <= res; i++)\n\t{\n\t\tfloat t = (float)i/res;\n\t\tfloat scale = 2;\n\t\tfloat out_scale = 3;\n\t\tfloat x_shift = (barbara_width*out_scale - barbara_width*scale) * t;\n\t\tfloat y_shift = (barbara_height*out_scale - barbara_height*scale) * t;\n\n\t\ttest_subpixel_command(barbara, scale, scale, out_scale, out_scale, x_shift, y_shift);\n\t}}\n\n\t// Downscaling\n\t{for (int i = 0; i <= res; i++)\n\t{\n\t\tfloat t = (float)i/res / 2;\n\t\ttest_subpixel_region(barbara, 0.25f, 0.25f, t, t, t+0.5f, t+0.5f);\n\t}}\n\n\t// No scaling\n\t{for (int i = 0; i <= res; i++)\n\t{\n\t\tfloat t = (float)i/res / 2;\n\t\ttest_subpixel_region(barbara, 0.5f, 0.5f, t, t, t+0.5f, t+0.5f);\n\t}}\n\n\t// Upscaling\n\t{for (int i = 0; i <= res; i++)\n\t{\n\t\tfloat t = (float)i/res / 2;\n\t\ttest_subpixel_region(barbara, 1, 1, t, t, t+0.5f, t+0.5f);\n\t}}\n\n\t{for (i = 0; i < 10; i++)\n\t\ttest_subpixel(barbara, 0.5f, 0.5f, (float)i / 10, 1);\n   }\n\n\t{for (i = 0; i < 10; i++)\n\t\ttest_subpixel(barbara, 0.5f, 0.5f, 1, (float)i / 10);\n   }\n\n\t{for (i = 0; i < 10; i++)\n\t\ttest_subpixel(barbara, 2, 2, (float)i / 10, 1);\n   }\n\n\t{for (i = 0; i < 10; i++)\n\t\ttest_subpixel(barbara, 2, 2, 1, (float)i / 10);\n   }\n\n\t// Channels test\n\ttest_channels(barbara, 0.5f, 0.5f, 1);\n\ttest_channels(barbara, 0.5f, 0.5f, 2);\n\ttest_channels(barbara, 0.5f, 0.5f, 3);\n\ttest_channels(barbara, 0.5f, 0.5f, 4);\n\n\ttest_channels(barbara, 2, 2, 1);\n\ttest_channels(barbara, 2, 2, 2);\n\ttest_channels(barbara, 2, 2, 3);\n\ttest_channels(barbara, 2, 2, 4);\n\n\t// filter tests\n\tresize_image(barbara, 2, 2, STBIR_FILTER_BOX         , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-upsample-nearest.png\");\n\tresize_image(barbara, 2, 2, STBIR_FILTER_TRIANGLE    , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-upsample-bilinear.png\");\n\tresize_image(barbara, 2, 2, STBIR_FILTER_CUBICBSPLINE, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-upsample-bicubic.png\");\n\tresize_image(barbara, 2, 2, STBIR_FILTER_CATMULLROM  , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-upsample-catmullrom.png\");\n\tresize_image(barbara, 2, 2, STBIR_FILTER_MITCHELL    , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-upsample-mitchell.png\");\n\n\tresize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_BOX         , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-downsample-nearest.png\");\n\tresize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_TRIANGLE    , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-downsample-bilinear.png\");\n\tresize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_CUBICBSPLINE, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-downsample-bicubic.png\");\n\tresize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_CATMULLROM  , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-downsample-catmullrom.png\");\n\tresize_image(barbara, 0.5f, 0.5f, STBIR_FILTER_MITCHELL    , STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, \"test-output/barbara-downsample-mitchell.png\");\n\n\t{for (i = 10; i < 100; i++)\n\t{\n\t\tchar outname[200];\n\t\tsprintf(outname, \"test-output/barbara-width-%d.jpg\", i);\n\t\tresize_image(barbara, (float)i / 100, 1, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);\n\t}}\n\n\t{for (i = 110; i < 500; i += 10)\n\t{\n\t\tchar outname[200];\n\t\tsprintf(outname, \"test-output/barbara-width-%d.jpg\", i);\n\t\tresize_image(barbara, (float)i / 100, 1, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);\n\t}}\n\n\t{for (i = 10; i < 100; i++)\n\t{\n\t\tchar outname[200];\n\t\tsprintf(outname, \"test-output/barbara-height-%d.jpg\", i);\n\t\tresize_image(barbara, 1, (float)i / 100, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);\n\t}}\n\n\t{for (i = 110; i < 500; i += 10)\n\t{\n\t\tchar outname[200];\n\t\tsprintf(outname, \"test-output/barbara-height-%d.jpg\", i);\n\t\tresize_image(barbara, 1, (float)i / 100, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);\n\t}}\n\n\t{for (i = 50; i < 200; i += 10)\n\t{\n\t\tchar outname[200];\n\t\tsprintf(outname, \"test-output/barbara-width-height-%d.jpg\", i);\n\t\tresize_image(barbara, 100 / (float)i, (float)i / 100, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB, outname);\n\t}}\n\n\ttest_format<unsigned short>(barbara, 0.5, 2.0, STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB);\n\ttest_format<unsigned short>(barbara, 0.5, 2.0, STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR);\n\ttest_format<unsigned short>(barbara, 2.0, 0.5, STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB);\n\ttest_format<unsigned short>(barbara, 2.0, 0.5, STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR);\n\n\ttest_format<unsigned int>(barbara, 0.5, 2.0, STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB);\n\ttest_format<unsigned int>(barbara, 0.5, 2.0, STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR);\n\ttest_format<unsigned int>(barbara, 2.0, 0.5, STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB);\n\ttest_format<unsigned int>(barbara, 2.0, 0.5, STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR);\n\n\ttest_float(barbara, 0.5, 2.0, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB);\n\ttest_float(barbara, 0.5, 2.0, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR);\n\ttest_float(barbara, 2.0, 0.5, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB);\n\ttest_float(barbara, 2.0, 0.5, STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR);\n\n\t// Edge behavior tests\n\tresize_image(\"hgradient.png\", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR, \"test-output/hgradient-clamp.png\");\n\tresize_image(\"hgradient.png\", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_WRAP, STBIR_COLORSPACE_LINEAR, \"test-output/hgradient-wrap.png\");\n\n\tresize_image(\"vgradient.png\", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR, \"test-output/vgradient-clamp.png\");\n\tresize_image(\"vgradient.png\", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_WRAP, STBIR_COLORSPACE_LINEAR, \"test-output/vgradient-wrap.png\");\n\n\tresize_image(\"1px-border.png\", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_LINEAR, \"test-output/1px-border-reflect.png\");\n\tresize_image(\"1px-border.png\", 2, 2, STBIR_FILTER_CATMULLROM, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR, \"test-output/1px-border-clamp.png\");\n\n\t// sRGB tests\n\tresize_image(\"gamma_colors.jpg\", .5f, .5f, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_SRGB, \"test-output/gamma_colors.jpg\");\n\tresize_image(\"gamma_2.2.jpg\", .5f, .5f, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_SRGB, \"test-output/gamma_2.2.jpg\");\n\tresize_image(\"gamma_dalai_lama_gray.jpg\", .5f, .5f, STBIR_FILTER_CATMULLROM, STBIR_EDGE_REFLECT, STBIR_COLORSPACE_SRGB, \"test-output/gamma_dalai_lama_gray.jpg\");\n}\n#endif\nvoid test_suite(int argc, char **argv)\n{\n}\n"
  },
  {
    "path": "tests/resample_test_c.c",
    "content": "#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#define STB_IMAGE_RESIZE_STATIC\n#include \"stb_image_resize.h\"\n\n// Just to make sure it will build properly with a c compiler\n\nint main() {\n}\n"
  },
  {
    "path": "tests/resize.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"resize\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=resize - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"resize.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"resize.mak\" CFG=\"resize - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"resize - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"resize - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"resize - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /G6 /W3 /GX /Z7 /O2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"resize - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /WX /Gm /GX /ZI /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"resize - Win32 Release\"\n# Name \"resize - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\resample_test.cpp\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_image_resize2.h\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/sdf/sdf_test.c",
    "content": "#define STB_DEFINE\n#include \"stb.h\"\n\n#define STB_TRUETYPE_IMPLEMENTATION\n#include \"stb_truetype.h\"\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n// used both to compute SDF and in 'shader'\nfloat sdf_size = 32.0;          // the larger this is, the better large font sizes look\nfloat pixel_dist_scale = 64.0;  // trades off precision w/ ability to handle *smaller* sizes\nint onedge_value = 128;\nint padding = 3; // not used in shader\n\ntypedef struct\n{\n   float advance;\n   signed char xoff;\n   signed char yoff;\n   unsigned char w,h;\n   unsigned char *data;\n} fontchar;\n\nfontchar fdata[128];\n\n#define BITMAP_W  1200\n#define BITMAP_H  800\nunsigned char bitmap[BITMAP_H][BITMAP_W][3];\n\nchar *sample = \"This is goofy text, size %d!\";\nchar *small_sample = \"This is goofy text, size %d! Really needs in-shader supersampling to look good.\";\n\nvoid blend_pixel(int x, int y, int color, float alpha)\n{\n   int i;\n   for (i=0; i < 3; ++i)\n      bitmap[y][x][i] = (unsigned char) (stb_lerp(alpha, bitmap[y][x][i], color)+0.5); // round\n}\n\nvoid draw_char(float px, float py, char c, float relative_scale)\n{\n   int x,y;\n   fontchar *fc = &fdata[c];\n   float fx0 = px + fc->xoff*relative_scale;\n   float fy0 = py + fc->yoff*relative_scale;\n   float fx1 = fx0 + fc->w*relative_scale;\n   float fy1 = fy0 + fc->h*relative_scale;\n   int ix0 = (int) floor(fx0);\n   int iy0 = (int) floor(fy0);\n   int ix1 = (int) ceil(fx1);\n   int iy1 = (int) ceil(fy1);\n   // clamp to viewport\n   if (ix0 < 0) ix0 = 0;\n   if (iy0 < 0) iy0 = 0;\n   if (ix1 > BITMAP_W) ix1 = BITMAP_W;\n   if (iy1 > BITMAP_H) iy1 = BITMAP_H;\n\n   for (y=iy0; y < iy1; ++y) {\n      for (x=ix0; x < ix1; ++x) {\n         float sdf_dist, pix_dist;\n         float bmx = stb_linear_remap(x, fx0, fx1, 0, fc->w);\n         float bmy = stb_linear_remap(y, fy0, fy1, 0, fc->h);\n         int v00,v01,v10,v11;\n         float v0,v1,v;\n         int sx0 = (int) bmx;\n         int sx1 = sx0+1;\n         int sy0 = (int) bmy;\n         int sy1 = sy0+1;\n         // compute lerp weights\n         bmx = bmx - sx0;\n         bmy = bmy - sy0;\n         // clamp to edge\n         sx0 = stb_clamp(sx0, 0, fc->w-1);\n         sx1 = stb_clamp(sx1, 0, fc->w-1);\n         sy0 = stb_clamp(sy0, 0, fc->h-1);\n         sy1 = stb_clamp(sy1, 0, fc->h-1);\n         // bilinear texture sample\n         v00 = fc->data[sy0*fc->w+sx0];\n         v01 = fc->data[sy0*fc->w+sx1];\n         v10 = fc->data[sy1*fc->w+sx0];\n         v11 = fc->data[sy1*fc->w+sx1];\n         v0 = stb_lerp(bmx,v00,v01);\n         v1 = stb_lerp(bmx,v10,v11);\n         v  = stb_lerp(bmy,v0 ,v1 );\n         #if 0\n         // non-anti-aliased\n         if (v > onedge_value)\n            blend_pixel(x,y,0,1.0);\n         #else\n         // Following math can be greatly simplified\n\n         // convert distance in SDF value to distance in SDF bitmap\n         sdf_dist = stb_linear_remap(v, onedge_value, onedge_value+pixel_dist_scale, 0, 1);\n         // convert distance in SDF bitmap to distance in output bitmap\n         pix_dist = sdf_dist * relative_scale;\n         // anti-alias by mapping 1/2 pixel around contour from 0..1 alpha\n         v = stb_linear_remap(pix_dist, -0.5f, 0.5f, 0, 1);\n         if (v > 1) v = 1;\n         if (v > 0)\n            blend_pixel(x,y,0,v);\n         #endif\n      }\n   }\n}\n\n\nvoid print_text(float x, float y, char *text, float scale)\n{\n   int i;\n   for (i=0; text[i]; ++i) {\n      if (fdata[text[i]].data)\n         draw_char(x,y,text[i],scale);\n      x += fdata[text[i]].advance * scale;\n   }\n}\n\nint main(int argc, char **argv)\n{\n   int ch;\n   float scale, ypos;\n   stbtt_fontinfo font;\n   void *data = stb_file(\"c:/windows/fonts/times.ttf\", NULL);\n   stbtt_InitFont(&font, data, 0);\n\n   scale = stbtt_ScaleForPixelHeight(&font, sdf_size);\n\n   for (ch=32; ch < 127; ++ch) {\n      fontchar fc;\n      int xoff,yoff,w,h, advance;\n      fc.data = stbtt_GetCodepointSDF(&font, scale, ch, padding, onedge_value, pixel_dist_scale, &w, &h, &xoff, &yoff);\n      fc.xoff = xoff;\n      fc.yoff = yoff;\n      fc.w = w;\n      fc.h = h;\n      stbtt_GetCodepointHMetrics(&font, ch, &advance, NULL);\n      fc.advance = advance * scale;\n      fdata[ch] = fc;\n   }\n\n   ypos = 60;\n   memset(bitmap, 255, sizeof(bitmap));\n   print_text(400, ypos+30, stb_sprintf(\"sdf bitmap height %d\", (int) sdf_size), 30/sdf_size);\n   ypos += 80;\n   for (scale = 8.0; scale < 120.0; scale *= 1.33f) {\n      print_text(80, ypos+scale, stb_sprintf(scale == 8.0 ? small_sample : sample, (int) scale), scale / sdf_size);\n      ypos += scale*1.05f + 20;\n   }\n\n   stbi_write_png(\"sdf_test.png\", BITMAP_W, BITMAP_H, 3, bitmap, 0);\n   return 0;\n}\n"
  },
  {
    "path": "tests/stb.c",
    "content": "/*\n * Unit tests for \"stb.h\"\n */\n\n#define _CRT_SECURE_NO_WARNINGS\n//#include <windows.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n#include <assert.h>\n#include <stdlib.h>\n\n#ifdef _WIN32\n#include <crtdbg.h>\n#endif\n\n//#define STB_FASTMALLOC\n#ifdef _DEBUG\n#define STB_MALLOC_WRAPPER_DEBUG\n#endif\n#ifndef _M_AMD64\n#define STB_NPTR\n#endif\n#define STB_DEFINE\n#include \"stb.h\"\n\n//#include \"stb_file.h\"\n//#include \"stb_pixel32.h\"\n\n//#define DEBUG_BLOCK\n#ifdef DEBUG_BLOCK\n#include <conio.h>\n#endif\n\n#ifdef STB_FASTMALLOC\n#error \"can't use FASTMALLOC with threads\"\n#endif\n\nint count;\nvoid c(int truth, char *error)\n{\n   if (!truth) {\n      fprintf(stderr, \"Test failed: %s\\n\", error);\n      ++count;\n   }\n}\n\n\n#if 0\nvoid show(void)\n{\n   #ifdef _WIN32\n   SYSTEM_INFO x;\n   GetSystemInfo(&x);\n   printf(\"%d\\n\", x.dwPageSize);\n   #endif\n}\n#endif\n\nvoid test_classes(void)\n{\n   unsigned char size_base[32], size_shift[32];\n   int class_to_pages[256];\n   int class_to_size[256], cl;\n   int lg, size, wasted_pages;\n   int kAlignShift = 3;\n   int kAlignment = 1 << kAlignShift;\n   int kMaxSize = 8 * 4096;\n   int kPageShift = 12;\n   int kPageSize = (1 << kPageShift);\n  int next_class = 1;\n  int alignshift = kAlignShift;\n  int last_lg = -1;\n\n  for (lg = 0; lg < kAlignShift; lg++) {\n    size_base[lg] = 1;\n    size_shift[lg] = kAlignShift;\n  }\n\n  for (size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {\n    int lg = stb_log2_floor(size);\n    if (lg > last_lg) {\n      // Increase alignment every so often.\n      //\n      // Since we double the alignment every time size doubles and\n      // size >= 128, this means that space wasted due to alignment is\n      // at most 16/128 i.e., 12.5%.  Plus we cap the alignment at 256\n      // bytes, so the space wasted as a percentage starts falling for\n      // sizes > 2K.\n      if ((lg >= 7) && (alignshift < 8)) {\n        alignshift++;\n      }\n      size_base[lg] = next_class - ((size-1) >> alignshift);\n      size_shift[lg] = alignshift;\n    }\n\n    class_to_size[next_class] = size;\n    last_lg = lg;\n\n    next_class++;\n  }\n\n  // Initialize the number of pages we should allocate to split into\n  // small objects for a given class.\n  wasted_pages = 0;\n  for (cl = 1; cl < next_class; cl++) {\n    // Allocate enough pages so leftover is less than 1/8 of total.\n    // This bounds wasted space to at most 12.5%.\n    size_t psize = kPageSize;\n    const size_t s = class_to_size[cl];\n    while ((psize % s) > (psize >> 3)) {\n      psize += kPageSize;\n    }\n    class_to_pages[cl] = (int) (psize >> kPageShift);\n    wasted_pages += (int) psize;\n  }\n\n  printf(\"TCMalloc can waste as much as %d memory on one-shot allocations\\n\", wasted_pages);\n\n\n  return;\n}\n\n#ifdef STB_STUA\nvoid test_script(void)\n{\n   stua_run_script(\n      \"var g = (2+3)*5 + 3*(2+1) + ((7)); \\n\"\n      \"func sprint(x) _print(x) _print(' ') x end;\\n\"\n      \"func foo(y) var q = func(x) sprint(x) end; q end;\\n \"\n      \"var z=foo(5); z(77);\\n\"\n      \"func counter(z) func(x) z=z+1 end end\\n\"\n      \"var q=counter(0), p=counter(5);\\n\"\n      \"sprint(q()) sprint(p()) sprint(q()) sprint(p()) sprint(q()) sprint(p())\\n\"\n      \"var x=2222;\\n\"\n      \"if 1 == 2 then 3333 else 4444 end; => x; sprint(x);\\n\"\n      \"var x1 = sprint(1.5e3);  \\n\"\n      \"var x2 = sprint(.5);  \\n\"\n      \"var x3 = sprint(1.);  \\n\"\n      \"var x4 = sprint(1.e3);  \\n\"\n      \"var x5 = sprint(1e3);  \\n\"\n      \"var x6 = sprint(0.5e3);  \\n\"\n      \"var x7 = sprint(.5e3);  \\n\"\n      \" func sum(x,y) x+y end                                       \\n\"\n      \" func sumfunc(a) sum+{x=a} end                               \\n\"\n      \" var q = sumfunc(3) \\n\"\n      \" var p = sumfunc(20) \\n\"\n      \" var d = sprint(q(5)) - sprint(q(8)) \\n\"\n      \" var e = sprint(p(5)) - sprint(p(8)) \\n\"\n      \" func test3(x)       \\n\"\n      \"    sprint(x)         \\n\"\n      \"    x = x+3          \\n\"\n      \"    sprint(x)         \\n\"\n      \"    x+5              \\n\"\n      \" end                 \\n\"\n      \" var y = test3(4);   \\n\"\n      \" func fib(x)         \\n\"\n      \"    if x < 3 then    \\n\"\n      \"       1             \\n\"\n      \"    else             \\n\"\n      \"      fib(x-1) + fib(x-2); \\n\"\n      \"    end              \\n\"\n      \" end                 \\n\"\n      \"                     \\n\"\n      \" func fib2(x)        \\n\"\n      \"    var a=1          \\n\"\n      \"    var b=1          \\n\"\n      \"    sprint(a)        \\n\"\n      \"    sprint(b)        \\n\"\n      \"    while x > 2 do   \\n\"\n      \"       var c=a+b     \\n\"\n      \"       a=b           \\n\"\n      \"       b=c           \\n\"\n      \"       sprint(b)     \\n\"\n      \"       x=x-1         \\n\"\n      \"    end              \\n\"\n      \"    b                \\n\"\n      \" end                 \\n\"\n      \"                                                             \\n\"\n      \" func assign(z)                                              \\n\"\n      \"    var y = { 'this', 'is', 'a', 'lame', 'day', 'to', 'die'} \\n\"\n      \"    y[3] = z                                                 \\n\"\n      \"    var i = 0                                                \\n\"\n      \"    while y[i] != nil do                                     \\n\"\n      \"       sprint(y[i])                                          \\n\"\n      \"       i = i+1                                               \\n\"\n      \"    end                                                      \\n\"\n      \" end                                                         \\n\"\n      \"                                                             \\n\"\n      \" sprint(fib(12)); \\n\"\n      \" assign(\\\"good\\\"); \\n\"\n      \" fib2(20); \\n\"\n      \" sprint('ok'); \\n\"\n      \" sprint(-5); \\n\"\n      \" // final comment with no newline\"\n   );\n}\n#endif\n\n#ifdef STB_THREADS\nextern void __stdcall Sleep(unsigned long);\n\nvoid * thread_1(void *x)\n{\n   Sleep(80);\n   printf(\"thread 1\\n\"); fflush(stdout);\n   return (void *) 2;\n}\n\nvoid * thread_2(void *y)\n{\n   stb_work(thread_1, NULL, y);\n   Sleep(50);\n   printf(\"thread 2\\n\"); fflush(stdout);\n   return (void *) 3;\n}\n\nstb_semaphore stest;\nstb_mutex mutex;\nvolatile int tc1, tc2;\n\nvoid *thread_3(void *p)\n{\n   stb_mutex_begin(mutex);\n   ++tc1;\n   stb_mutex_end(mutex);\n   stb_sem_waitfor(stest);\n   stb_mutex_begin(mutex);\n   ++tc2;\n   stb_mutex_end(mutex);\n   return NULL;\n}\n\nvoid test_threads(void)\n{\n   volatile int a=0,b=0;\n   //stb_work_numthreads(2);\n   stb_work(thread_2, (void *) &a, (void *) &b);\n   while (a==0 || b==0) {\n      Sleep(10);\n      //printf(\"a=%d b=%d\\n\", a, b);\n   }\n   c(a==2 && b == 3, \"stb_thread\");\n   stb_work_numthreads(4);\n   stest = stb_sem_new(8);\n   mutex = stb_mutex_new();\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   while (tc1 < 4)\n      Sleep(10);\n   c(tc1 == 4, \"stb_work 1\");\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   Sleep(40);\n   while (tc1 != 8 || tc2 != 8)\n      Sleep(10);\n   c(tc1 == 8 && tc2 == 8, \"stb_work 2\");\n   stb_work_numthreads(2);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   stb_work(thread_3, NULL, NULL);\n   while (tc1 < 10)\n      Sleep(10);\n   c(tc1 == 10, \"stb_work 1\");\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n   stb_sem_release(stest);\n\n   Sleep(100);\n   stb_sem_delete(stest);\n   stb_mutex_delete(mutex);\n}\n#else\nvoid test_threads(void)\n{\n}\n#endif\n\nvoid *thread4(void *p)\n{\n   return NULL;\n}\n\n#ifdef STB_THREADS\nstb_threadqueue *tq;\nstb_sync synch;\nstb_mutex msum;\n\nvolatile int thread_sum;\n\nvoid *consume1(void *p)\n{\n   volatile int *q = (volatile int *) p;\n   for(;;) {\n      int z;\n      stb_threadq_get_block(tq, &z);\n      stb_mutex_begin(msum);\n      thread_sum += z;\n      *q += z;\n      stb_mutex_end(msum);\n      stb_sync_reach(synch);\n   }      \n}\n\nvoid test_threads2(void)\n{\n   int array[256],i,n=0;\n   volatile int which[4];\n   synch = stb_sync_new();\n   stb_sync_set_target(synch,2);\n   stb_work_reach(thread4, NULL, NULL, synch);\n   stb_sync_reach_and_wait(synch);\n   printf(\"ok\\n\");\n\n   tq = stb_threadq_new(4, 1, TRUE,TRUE);\n   msum = stb_mutex_new();\n   thread_sum = 0;\n   stb_sync_set_target(synch, 65);\n   for (i=0; i < 4; ++i) {\n      which[i] = 0;\n      stb_create_thread(consume1, (int *) &which[i]);\n   }\n   for (i=1; i <= 64; ++i) {\n      array[i] = i;\n      n += i;\n      stb_threadq_add_block(tq, &array[i]);\n   }\n   stb_sync_reach_and_wait(synch);\n   stb_barrier();\n   c(thread_sum == n, \"stb_threadq 1\");\n   c(which[0] + which[1] + which[2] + which[3] == n, \"stb_threadq 2\");\n   printf(\"(Distribution: %d %d %d %d)\\n\", which[0], which[1], which[2], which[3]);\n\n   stb_sync_delete(synch);\n   stb_threadq_delete(tq);\n   stb_mutex_delete(msum);\n}\n#else\nvoid test_threads2(void)\n{\n}\n#endif\n\nchar tc[] = \"testing compression test quick test voila woohoo what the hell\";\n\nunsigned char storage1[1 << 23];\nint test_compression(unsigned char *buffer, int length)\n{\n   unsigned char *storage2;\n   int c_len = stb_compress(storage1, buffer, length);\n   int dc_len;\n   printf(\"Compressed %d to %d\\n\", length, c_len);\n   dc_len = stb_decompress_length(storage1);\n   storage2 = malloc(dc_len);\n   dc_len = stb_decompress(storage2, storage1, c_len);\n   if (dc_len != length) { free(storage2); return -1; }\n   if (memcmp(buffer, storage2, length) != 0) { free(storage2); return -1; }\n   free(storage2);\n   return c_len;\n}\n\n#if 0\nint test_en_compression(char *buffer, int length)\n{\n   int c_len = stb_en_compress(storage1, buffer, length);\n   int dc_len;\n   printf(\"Encompressed %d to %d\\n\", length, c_len);\n   dc_len = stb_en_decompress(storage2, storage1, c_len);\n   if (dc_len != length) return -1;\n   if (memcmp(buffer, storage2, length) != 0) return -1;\n   return c_len;\n}\n#endif\n\n#define STR_x \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n#define STR_y \"yyyyyyyyyyyyyyyyyy\"\n\n#define STR_xy STR_x STR_y\n#define STR_xyyxy STR_xy STR_y STR_xy\n\n#define STR_1 \"testing\"\n#define STR_2 STR_xyyxy STR_xy STR_xyyxy STR_xyyxy STR_xy STR_xyyxy\n#define STR_3 \"buh\"\n\nchar buffer[] = STR_1 \"\\r\\n\" STR_2 STR_2 STR_2 \"\\n\" STR_3;\nchar str1[] = STR_1;\nchar str2[] = STR_2 STR_2 STR_2;\nchar str3[] = STR_3;\n\nint sum(short *s)\n{\n   int i,total=0;\n   for (i=0; i < stb_arr_len(s); ++i)\n      total += s[i];\n   return total;\n}\n\nstb_uint stb_adler32_old(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)\n{\n   const stb_uint ADLER_MOD = 65521;\n   stb_uint s1 = adler32 & 0xffff;\n   stb_uint s2 = adler32 >> 16;\n\n   while (buflen-- > 0) { // NOTE: much faster implementations are possible!\n      s1 += *buffer++; if (s1 > ADLER_MOD) s1 -= ADLER_MOD;\n      s2 += s1       ; if (s2 > ADLER_MOD) s2 -= ADLER_MOD;\n   }\n   return (s2 << 16) + s1;\n}\n\nint sample_test[3][5] =\n{\n   { 1,2,3,4,5 },\n   { 6,7,8,9,10, },\n   { 11,12,13,14,15 },\n};\n\ntypedef struct { unsigned short x,y,z; } struct1;\ntypedef struct { double a; int x,y,z; } struct2;\n\nchar *args_raw[] = { \"foo\", \"-dxrf\", \"bar\", \"-ts\" };\nchar *args[8];\n\nvoid do_compressor(int,char**);\nvoid test_sha1(void);\n\nint alloc_num, alloc_size;\nvoid dumpfunc(void *ptr, int sz, char *file, int line)\n{\n   printf(\"%p (%6d)  -- %3d:%s\\n\", ptr, sz, line, file);\n   alloc_size += sz;\n   alloc_num  += 1;\n}\n\nchar *expects(stb_matcher *m, char *s, int result, int len, char *str)\n{\n   int res2,len2=0;\n   res2 = stb_lex(m, s, &len2);\n   c(result == res2 && len == len2, str);\n   return s + len;\n}\n\nvoid test_lex(void)\n{\n   stb_matcher *m = stb_lex_matcher();\n   //         tok_en5 .3 20.1 20. .20 .1\n   char *s = \"tok_en5.3 20.1 20. .20.1\";\n\n   stb_lex_item(m, \"[a-zA-Z_][a-zA-Z0-9_]*\", 1   );\n   stb_lex_item(m, \"[0-9]*\\\\.?[0-9]*\"      , 2   );\n   stb_lex_item(m, \"[\\r\\n\\t ]+\"            , 3   );\n   stb_lex_item(m, \".\"                     , -99 );\n   s=expects(m,s,1,7, \"stb_lex 1\");\n   s=expects(m,s,2,2, \"stb_lex 2\");\n   s=expects(m,s,3,1, \"stb_lex 3\");\n   s=expects(m,s,2,4, \"stb_lex 4\");\n   s=expects(m,s,3,1, \"stb_lex 5\");\n   s=expects(m,s,2,3, \"stb_lex 6\");\n   s=expects(m,s,3,1, \"stb_lex 7\");\n   s=expects(m,s,2,3, \"stb_lex 8\");\n   s=expects(m,s,2,2, \"stb_lex 9\");\n   s=expects(m,s,0,0, \"stb_lex 10\");\n   stb_matcher_free(m);\n}\n\ntypedef struct Btest\n{\n   struct Btest stb_bst_fields(btest_);\n   int v;\n} Btest;\n\nstb_bst(Btest, btest_, BT2,bt2,v, int, a - b)\n\nvoid bst_test(void)\n{\n   Btest *root = NULL, *t;\n   int items[500], sorted[500];\n   int i,j,z;\n   for (z=0; z < 10; ++z) {\n      for (i=0; i < 500; ++i)\n         items[i] = stb_rand() & 0xfffffff;\n\n      // check for collisions, and retrry if so\n      memcpy(sorted, items, sizeof(sorted));\n      qsort(sorted, 500, sizeof(sorted[0]), stb_intcmp(0));\n      for (i=1; i < 500; ++i)\n         if (sorted[i-1] == sorted[i])\n            break;\n      if (i != 500) { --z; break; }\n\n      for (i=0; i < 500; ++i)  {\n         t = malloc(sizeof(*t));\n         t->v = items[i];\n         root = btest_insert(root, t);\n         #ifdef STB_DEBUG\n         btest__validate(root,1);\n         #endif\n         for (j=0; j <= i; ++j)\n            c(btest_find(root, items[j]) != NULL, \"stb_bst 1\");\n         for (   ; j < 500; ++j)\n            c(btest_find(root, items[j]) == NULL, \"stb_bst 2\");\n      }\n\n      t = btest_first(root);\n      for (i=0; i < 500; ++i)\n         t = btest_next(root,t);\n      c(t == NULL, \"stb_bst 5\");\n      t = btest_last(root);\n      for (i=0; i < 500; ++i)\n         t = btest_prev(root,t);\n      c(t == NULL, \"stb_bst 6\");\n\n      memcpy(sorted, items, sizeof(sorted));\n      qsort(sorted, 500, sizeof(sorted[0]), stb_intcmp(0));\n      t = btest_first(root);\n      for (i=0; i < 500; ++i) {\n         assert(t->v == sorted[i]);\n         t = btest_next(root, t);\n      }\n      assert(t == NULL);\n\n      if (z==1)\n         stb_reverse(items, 500, sizeof(items[0]));\n      else if (z)\n         stb_shuffle(items, 500, sizeof(items[0]), stb_rand());\n\n      for (i=0; i < 500; ++i)  {\n         t = btest_find(root, items[i]);\n         assert(t != NULL);\n         root = btest_remove(root, t);\n         c(btest_find(root, items[i]) == NULL, \"stb_bst 5\");\n         #ifdef STB_DEBUG\n         btest__validate(root, 1);\n         #endif\n         for (j=0; j <= i; ++j)\n            c(btest_find(root, items[j]) == NULL, \"stb_bst 3\");\n         for (   ; j < 500; ++j)\n            c(btest_find(root, items[j]) != NULL, \"stb_bst 4\");\n         free(t);\n      }\n   }\n}\n\nextern void stu_uninit(void);\n\nstb_define_sort(sort_int, int, *a < *b)\n\nstb_rand_define(prime_rand, 1)\nvoid test_packed_floats(void);\nvoid test_parser_generator(void);\n\nvoid rec_print(stb_dirtree2 *d, int depth)\n{\n   int i;\n   for (i=0; i < depth; ++i) printf(\"  \");\n   printf(\"%s (%d)\\n\", d->relpath, stb_arr_len(d->files));\n   for (i=0; i < stb_arr_len(d->subdirs); ++i)\n      rec_print(d->subdirs[i], depth+1);\n   d->weight = (float) stb_arr_len(d->files);\n}\n\n#ifdef MAIN_TEST\nint main(int argc, char **argv)\n{\n   char *z;\n   stb__wchar buffer7[1024],buffer9[1024];\n   char buffer8[4096];\n   FILE *f;\n   char *p1 = \"foo/bar\\\\baz/test.xyz\";\n   char *p2 = \"foo/.bar\";\n   char *p3 = \"foo.bar\";\n   char *p4 = \"foo/bar\";\n   char *wildcards[] = { \"*foo*\", \"*bar\", \"baz\", \"*1*2*3*\", \"*/CVS/repository\", \"*oof*\" };\n   char **s;\n   char buf[256], *p;\n   int n,len2,*q,i;\n   stb_matcher *mt=NULL;\n\n   if (argc > 1) {\n      do_compressor(argc,argv);\n      return 0;\n   }\n   test_classes();\n   //show();\n\n   //stb_malloc_check_counter(2,2);\n   //_CrtSetBreakAlloc(10398);\n\n   stbprint(\"Checking {!if} the {$fancy} print function {#works}?  - should\\n\");\n   stbprint(\"                                                      - align\\n\");\n   stbprint(\"But {#3this}} {one}}                                  - shouldn't\\n\");\n\n   #if 0\n   {\n      int i;\n      char **s = stb_readdir_recursive(\"/sean\", NULL);\n      stb_dirtree *d = stb_dirtree_from_files_relative(\"\", s, stb_arr_len(s));\n      stb_dirtree **e;\n      rec_print(d, 0);\n      e = stb_summarize_tree(d,12,4);\n      for (i=0; i < stb_arr_len(e); ++i) {\n         printf(\"%s\\n\", e[i]->fullpath);\n      }\n      stb_arr_free(e);\n\n      stb_fatal(\"foo\");\n   }\n   #endif\n\n   stb_(\"Started stb.c\");\n   test_threads2();\n   test_threads();\n\n   for (i=0; i < 1023 && 5+77*i < 0xd800; ++i)\n      buffer7[i] = 5+77*i;\n   buffer7[i++] = 0xd801;\n   buffer7[i++] = 0xdc02;\n   buffer7[i++] = 0xdbff;\n   buffer7[i++] = 0xdfff;\n   buffer7[i] = 0;\n   p = stb_to_utf8(buffer8, buffer7, sizeof(buffer8));\n   c(p != NULL, \"stb_to_utf8\");\n   if (p != NULL) {\n      stb_from_utf8(buffer9, buffer8, sizeof(buffer9)/2);\n      c(!memcmp(buffer7, buffer9, i*2), \"stb_from_utf8\");\n   }\n\n   z = \"foo.*[bd]ak?r\";\n   c( stb_regex(z, \"muggle man food is barfy\") == 1, \"stb_regex 1\");\n   c( stb_regex(\"foo.*bar\", \"muggle man food is farfy\") == 0, \"stb_regex 2\");\n   c( stb_regex(\"[^a-zA-Z]foo[^a-zA-Z]\", \"dfoobar xfood\") == 0, \"stb_regex 3\");\n   c( stb_regex(z, \"muman foob is bakrfy\") == 1, \"stb_regex 4\");\n   z = \"foo.*[bd]bk?r\";\n   c( stb_regex(z, \"muman foob is bakrfy\") == 0, \"stb_regex 5\");\n   c( stb_regex(z, \"muman foob is bbkrfy\") == 1, \"stb_regex 6\");\n\n   stb_regex(NULL,NULL);\n\n   #if 0\n   test_parser_generator();\n   stb_wrapper_listall(dumpfunc);\n   if (alloc_num) \n      printf(\"Memory still in use: %d allocations of %d bytes.\\n\", alloc_num, alloc_size);\n   #endif\n\n   test_script();\n   p = stb_file(\"sieve.stua\", NULL);\n   if (p) {\n      stua_run_script(p);      \n      free(p);\n   }\n   stua_uninit();\n\n   //stb_wrapper_listall(dumpfunc);\n   printf(\"Memory still in use: %d allocations of %d bytes.\\n\", alloc_num, alloc_size);\n\n   c(stb_alloc_count_alloc == stb_alloc_count_free, \"stb_alloc 0\");\n\n   bst_test();\n\n   c(stb_alloc_count_alloc == stb_alloc_count_free, \"stb_alloc 0\");\n\n#if 0\n   // stb_block\n   {\n      int inuse=0, freespace=0;\n      int *x = malloc(10000*sizeof(*x));\n      stb_block *b = stb_block_new(1, 10000);\n      #define BLOCK_COUNT  1000\n      int *p = malloc(sizeof(*p) * BLOCK_COUNT);\n      int *l = malloc(sizeof(*l) * BLOCK_COUNT);\n      int i, n, k = 0;\n\n      memset(x, 0, 10000 * sizeof(*x));\n\n      n = 0;\n      while (n < BLOCK_COUNT && k < 1000) {\n         l[n] = 16 + (rand() & 31);\n         p[n] = stb_block_alloc(b, l[n], 0);\n         if (p[n] == 0)\n            break;\n         inuse += l[n];\n\n         freespace = 0;\n         for (i=0; i < b->len; ++i)\n            freespace += b->freelist[i].len;\n         assert(freespace + inuse == 9999);\n\n         for (i=0; i < l[n]; ++i)\n            x[ p[n]+i ] = p[n];\n         ++n;\n\n         if (k > 20) {\n            int sz;\n            i = (stb_rand() % n);\n            sz = l[i];\n            stb_block_free(b, p[i], sz);\n            inuse -= sz;\n            p[i] = p[n-1];\n            l[i] = l[n-1];\n            --n;\n\n            freespace = 0;\n            for (i=0; i < b->len; ++i)\n               freespace += b->freelist[i].len;\n            assert(freespace + inuse == 9999);\n         }\n\n\n         ++k;\n\n         // validate\n         if ((k % 50) == 0) {\n            int j;\n            for (j=0; j < n; ++j) {\n               for (i=0; i < l[j]; ++i)\n                  assert(x[ p[j]+i ] == p[j]);\n            }\n         }\n\n         if ((k % 200) == 0) {\n            stb_block_compact_freelist(b);\n         }\n      }\n\n      for (i=0; i < n; ++i)\n         stb_block_free(b, p[i], l[i]);\n\n      stb_block_destroy(b);\n      free(p);\n      free(l);\n      free(x);\n   }\n\n   blockfile_test();\n#endif\n\n   mt = stb_lex_matcher();\n   for (i=0; i < 5; ++i)\n      stb_lex_item_wild(mt, wildcards[i], i+1);\n\n   c(1==stb_lex(mt, \"this is a foo in the middle\",NULL), \"stb_matcher_match 1\");\n   c(0==stb_lex(mt, \"this is a bar in the middle\",NULL), \"stb_matcher_match 2\");\n   c(0==stb_lex(mt, \"this is a baz in the middle\",NULL), \"stb_matcher_match 3\");\n   c(2==stb_lex(mt, \"this is a bar\",NULL), \"stb_matcher_match 4\");\n   c(0==stb_lex(mt, \"this is a baz\",NULL), \"stb_matcher_match 5\");\n   c(3==stb_lex(mt, \"baz\",NULL), \"stb_matcher_match 6\");\n   c(4==stb_lex(mt, \"1_2_3_4\",NULL), \"stb_matcher_match 7\");\n   c(0==stb_lex(mt, \"1  3  3 3 3  2 \",NULL), \"stb_matcher_match 8\");\n   c(4==stb_lex(mt, \"1  3  3 3 2  3 \",NULL), \"stb_matcher_match 9\");\n   c(5==stb_lex(mt, \"C:/sean/prj/old/gdmag/mipmap/hqp/adol-c/CVS/Repository\",NULL), \"stb_matcher_match 10\");\n   stb_matcher_free(mt);\n\n   {\n      #define SSIZE  500000\n      static int arr[SSIZE],arr2[SSIZE];\n      int i,good;\n      for (i=0; i < SSIZE; ++i)\n         arr2[i] = stb_rand();\n      memcpy(arr,arr2,sizeof(arr));\n      printf(\"stb_define_sort:\\n\");\n      sort_int(arr, SSIZE);\n      good = 1;\n      for (i=0; i+1 < SSIZE; ++i)\n         if (arr[i] > arr[i+1])\n            good = 0;\n      c(good, \"stb_define_sort\");\n      printf(\"qsort:\\n\");\n      qsort(arr2, SSIZE, sizeof(arr2[0]), stb_intcmp(0));\n      printf(\"done\\n\");\n      // check for bugs\n      memset(arr, 0, sizeof(arr[0]) * 1000);\n      sort_int(arr, 1000);\n   }\n\n\n   c(stb_alloc_count_alloc == stb_alloc_count_free, \"stb_alloc -2\");\n\n   c( stb_is_prime( 2), \"stb_is_prime 1\");\n   c( stb_is_prime( 3), \"stb_is_prime 2\");\n   c( stb_is_prime( 5), \"stb_is_prime 3\");\n   c( stb_is_prime( 7), \"stb_is_prime 4\");\n   c(!stb_is_prime( 9), \"stb_is_prime 5\");\n   c( stb_is_prime(11), \"stb_is_prime 6\");\n   c(!stb_is_prime(25), \"stb_is_prime 7\");\n   c(!stb_is_prime(27), \"stb_is_prime 8\");\n   c( stb_is_prime(29), \"stb_is_prime 9\");\n   c( stb_is_prime(31), \"stb_is_prime a\");\n   c(!stb_is_prime(33), \"stb_is_prime b\");\n   c(!stb_is_prime(35), \"stb_is_prime c\");\n   c(!stb_is_prime(36), \"stb_is_prime d\");\n\n   for (n=7; n < 64; n += 3) {\n      int i;\n      stb_perfect s;\n      unsigned int *p = malloc(n * sizeof(*p));\n      for (i=0; i < n; ++i)\n         p[i] = i*i;\n      c(stb_perfect_create(&s, p, n), \"stb_perfect_hash 1\");\n      stb_perfect_destroy(&s);\n      for (i=0; i < n; ++i)\n         p[i] = stb_rand();\n      c(stb_perfect_create(&s, p, n), \"stb_perfect_hash 2\");\n      stb_perfect_destroy(&s);\n      for (i=0; i < n; ++i)\n         p[i] = (0x80000000 >> stb_log2_ceil(n>>1)) * i;\n      c(stb_perfect_create(&s, p, n), \"stb_perfect_hash 2\");\n      stb_perfect_destroy(&s);\n      for (i=0; i < n; ++i)\n         p[i] = (int) malloc(1024);\n      c(stb_perfect_create(&s, p, n), \"stb_perfect_hash 3\");\n      stb_perfect_destroy(&s);\n      for (i=0; i < n; ++i)\n         free((void *) p[i]);\n      free(p);\n   }\n   printf(\"Maximum attempts required to find perfect hash: %d\\n\",\n         stb_perfect_hash_max_failures);\n\n   p = \"abcdefghijklmnopqrstuvwxyz\";\n   c(stb_ischar('c', p), \"stb_ischar 1\");\n   c(stb_ischar('x', p), \"stb_ischar 2\");\n   c(!stb_ischar('#', p), \"stb_ischar 3\");\n   c(!stb_ischar('X', p), \"stb_ischar 4\");\n   p = \"0123456789\";\n   c(!stb_ischar('c', p), \"stb_ischar 5\");\n   c(!stb_ischar('x', p), \"stb_ischar 6\");\n   c(!stb_ischar('#', p), \"stb_ischar 7\");\n   c(!stb_ischar('X', p), \"stb_ischar 8\");\n   p = \"#####\";\n   c(!stb_ischar('c', p), \"stb_ischar a\");\n   c(!stb_ischar('x', p), \"stb_ischar b\");\n   c(stb_ischar('#', p), \"stb_ischar c\");\n   c(!stb_ischar('X', p), \"stb_ischar d\");\n   p = \"xXyY\";\n   c(!stb_ischar('c', p), \"stb_ischar e\");\n   c(stb_ischar('x', p), \"stb_ischar f\");\n   c(!stb_ischar('#', p), \"stb_ischar g\");\n   c(stb_ischar('X', p), \"stb_ischar h\");\n\n   c(stb_alloc_count_alloc == stb_alloc_count_free, \"stb_alloc 1\");\n\n   q = stb_wordwrapalloc(15, \"How now brown cow. Testinglishously. Okey dokey\");\n   // How now brown\n   // cow. Testinglis\n   // hously. Okey\n   // dokey\n   c(stb_arr_len(q) ==  8, \"stb_wordwrap 8\");\n   c(q[2] == 14 && q[3] == 15, \"stb_wordwrap 9\");\n   c(q[4] == 29 && q[5] == 12, \"stb_wordwrap 10\");\n   stb_arr_free(q);\n\n   q = stb_wordwrapalloc(20, \"How now brown cow. Testinglishously. Okey dokey\");\n   // How now brown cow.\n   // Testinglishously.\n   // Okey dokey\n   c(stb_arr_len(q) ==  6, \"stb_wordwrap 1\");\n   c(q[0] ==  0 && q[1] == 18, \"stb_wordwrap 2\");\n   c(q[2] == 19 && q[3] == 17, \"stb_wordwrap 3\");\n   c(q[4] == 37 && q[5] == 10, \"stb_wordwrap 4\");\n   stb_arr_free(q);\n\n   q = stb_wordwrapalloc(12, \"How now brown cow. Testinglishously. Okey dokey\");\n   // How now\n   // brown cow.\n   // Testinglisho\n   // usly. Okey\n   // dokey\n   c(stb_arr_len(q) ==  10, \"stb_wordwrap 5\");\n   c(q[4] == 19 && q[5] == 12, \"stb_wordwrap 6\");\n   c(q[6] == 31 && q[3] == 10, \"stb_wordwrap 7\");\n   stb_arr_free(q);\n\n   //test_script();\n\n   //test_packed_floats();\n\n   c(stb_alloc_count_alloc == stb_alloc_count_free, \"stb_alloc 0\");\n   if (stb_alloc_count_alloc != stb_alloc_count_free) {\n      printf(\"%d allocs, %d frees\\n\", stb_alloc_count_alloc, stb_alloc_count_free);\n   }\n   test_lex();\n\n   mt = stb_regex_matcher(\".*foo.*bar.*\");\n   c(stb_matcher_match(mt, \"foobarx\")                == 1, \"stb_matcher_match 1\");\n   c(stb_matcher_match(mt, \"foobar\")                 == 1, \"stb_matcher_match 2\");\n   c(stb_matcher_match(mt, \"foo bar\")                == 1, \"stb_matcher_match 3\");\n   c(stb_matcher_match(mt, \"fo foo ba ba bar ba\")    == 1, \"stb_matcher_match 4\");\n   c(stb_matcher_match(mt, \"fo oo oo ba ba bar foo\") == 0, \"stb_matcher_match 5\");\n   stb_free(mt);\n\n   mt = stb_regex_matcher(\".*foo.?bar.*\");\n   c(stb_matcher_match(mt, \"abfoobarx\")                == 1, \"stb_matcher_match 6\");\n   c(stb_matcher_match(mt, \"abfoobar\")                 == 1, \"stb_matcher_match 7\");\n   c(stb_matcher_match(mt, \"abfoo bar\")                == 1, \"stb_matcher_match 8\");\n   c(stb_matcher_match(mt, \"abfoo  bar\")               == 0, \"stb_matcher_match 9\");\n   c(stb_matcher_match(mt, \"abfo foo ba ba bar ba\")    == 0, \"stb_matcher_match 10\");\n   c(stb_matcher_match(mt, \"abfo oo oo ba ba bar foo\") == 0, \"stb_matcher_match 11\");\n   stb_free(mt);\n\n   mt = stb_regex_matcher(\".*m((foo|bar)*baz)m.*\");\n   c(stb_matcher_match(mt, \"abfoobarx\")                == 0, \"stb_matcher_match 12\");\n   c(stb_matcher_match(mt, \"a mfoofoofoobazm d\")       == 1, \"stb_matcher_match 13\");\n   c(stb_matcher_match(mt, \"a mfoobarbazfoom d\")       == 0, \"stb_matcher_match 14\");\n   c(stb_matcher_match(mt, \"a mbarbarfoobarbazm d\")    == 1, \"stb_matcher_match 15\");\n   c(stb_matcher_match(mt, \"a mfoobarfoo bazm d\")      == 0, \"stb_matcher_match 16\");\n   c(stb_matcher_match(mt, \"a mm foobarfoobarfoobar \") == 0, \"stb_matcher_match 17\");\n   stb_free(mt);\n\n   mt = stb_regex_matcher(\"f*|z\");\n   c(stb_matcher_match(mt, \"fz\")       == 0, \"stb_matcher_match 0a\");\n   c(stb_matcher_match(mt, \"ff\")       == 1, \"stb_matcher_match 0b\");\n   c(stb_matcher_match(mt, \"z\")        == 1, \"stb_matcher_match 0c\");\n   stb_free(mt);\n\n   mt = stb_regex_matcher(\"m(f|z*)n\");\n   c(stb_matcher_match(mt, \"mfzn\")     == 0, \"stb_matcher_match 0d\");\n   c(stb_matcher_match(mt, \"mffn\")     == 0, \"stb_matcher_match 0e\");\n   c(stb_matcher_match(mt, \"mzn\")      == 1, \"stb_matcher_match 0f\");\n   c(stb_matcher_match(mt, \"mn\")       == 1, \"stb_matcher_match 0g\");\n   c(stb_matcher_match(mt, \"mzfn\")     == 0, \"stb_matcher_match 0f\");\n\n   c(stb_matcher_find(mt, \"manmanmannnnnnnmmmmmmmmm       \") == 0, \"stb_matcher_find 1\");\n   c(stb_matcher_find(mt, \"manmanmannnnnnnmmmmmmmmm       \") == 0, \"stb_matcher_find 2\");\n   c(stb_matcher_find(mt, \"manmanmannnnnnnmmmmmmmmmffzzz  \") == 0, \"stb_matcher_find 3\");\n   c(stb_matcher_find(mt, \"manmanmannnnnnnmmmmmmmmmnfzzz  \") == 1, \"stb_matcher_find 4\");\n   c(stb_matcher_find(mt, \"mmmfn aanmannnnnnnmmmmmm fzzz  \") == 1, \"stb_matcher_find 5\");\n   c(stb_matcher_find(mt, \"mmmzzn anmannnnnnnmmmmmm fzzz  \") == 1, \"stb_matcher_find 6\");\n   c(stb_matcher_find(mt, \"mm anmannnnnnnmmmmmm fzmzznzz  \") == 1, \"stb_matcher_find 7\");\n   c(stb_matcher_find(mt, \"mm anmannnnnnnmmmmmm fzmzzfnzz \") == 0, \"stb_matcher_find 8\");\n   c(stb_matcher_find(mt, \"manmfnmannnnnnnmmmmmmmmmffzzz  \") == 1, \"stb_matcher_find 9\");\n   stb_free(mt);\n\n   mt = stb_regex_matcher(\".*m((foo|bar)*|baz)m.*\");\n   c(stb_matcher_match(mt, \"abfoobarx\")                == 0, \"stb_matcher_match 18\");\n   c(stb_matcher_match(mt, \"a mfoofoofoobazm d\")       == 0, \"stb_matcher_match 19\");\n   c(stb_matcher_match(mt, \"a mfoobarbazfoom d\")       == 0, \"stb_matcher_match 20\");\n   c(stb_matcher_match(mt, \"a mbazm d\")                == 1, \"stb_matcher_match 21\");\n   c(stb_matcher_match(mt, \"a mfoobarfoom d\")          == 1, \"stb_matcher_match 22\");\n   c(stb_matcher_match(mt, \"a mm foobarfoobarfoobar \") == 1, \"stb_matcher_match 23\");\n   stb_free(mt);\n\n   mt = stb_regex_matcher(\"[a-fA-F]..[^]a-zA-Z]\");\n   c(stb_matcher_match(mt, \"Axx1\")                     == 1, \"stb_matcher_match 24\");\n   c(stb_matcher_match(mt, \"Fxx1\")                     == 1, \"stb_matcher_match 25\");\n   c(stb_matcher_match(mt, \"Bxx]\")                     == 0, \"stb_matcher_match 26\");\n   c(stb_matcher_match(mt, \"Cxxz\")                     == 0, \"stb_matcher_match 27\");\n   c(stb_matcher_match(mt, \"gxx[\")                     == 0, \"stb_matcher_match 28\");\n   c(stb_matcher_match(mt, \"-xx0\")                     == 0, \"stb_matcher_match 29\");\n   stb_free(mt);\n\n   c(stb_wildmatch(\"foo*bar\", \"foobarx\")    == 0, \"stb_wildmatch 0a\");\n   c(stb_wildmatch(\"foo*bar\", \"foobar\")     == 1, \"stb_wildmatch 1a\");\n   c(stb_wildmatch(\"foo*bar\", \"foo bar\")    == 1, \"stb_wildmatch 2a\");\n   c(stb_wildmatch(\"foo*bar\", \"fo foo ba ba bar ba\") == 0, \"stb_wildmatch 3a\");\n   c(stb_wildmatch(\"foo*bar\", \"fo oo oo ba ba ar foo\") == 0, \"stb_wildmatch 4a\");\n\n   c(stb_wildmatch(\"*foo*bar*\", \"foobar\")     == 1, \"stb_wildmatch 1b\");\n   c(stb_wildmatch(\"*foo*bar*\", \"foo bar\")    == 1, \"stb_wildmatch 2b\");\n   c(stb_wildmatch(\"*foo*bar*\", \"fo foo ba ba bar ba\") == 1, \"stb_wildmatch 3b\");\n   c(stb_wildmatch(\"*foo*bar*\", \"fo oo oo ba ba ar foo\") == 0, \"stb_wildmatch 4b\");\n\n   c(stb_wildmatch(\"foo*bar*\", \"foobarx\")     == 1, \"stb_wildmatch 1c\");\n   c(stb_wildmatch(\"foo*bar*\", \"foobabar\")    == 1, \"stb_wildmatch 2c\");\n   c(stb_wildmatch(\"foo*bar*\", \"fo foo ba ba bar ba\") == 0, \"stb_wildmatch 3c\");\n   c(stb_wildmatch(\"foo*bar*\", \"fo oo oo ba ba ar foo\") == 0, \"stb_wildmatch 4c\");\n\n   c(stb_wildmatch(\"*foo*bar\", \"foobar\")     == 1, \"stb_wildmatch 1d\");\n   c(stb_wildmatch(\"*foo*bar\", \"foo bar\")    == 1, \"stb_wildmatch 2d\");\n   c(stb_wildmatch(\"*foo*bar\", \"fo foo ba ba bar ba\") == 0, \"stb_wildmatch 3d\");\n   c(stb_wildmatch(\"*foo*bar\", \"fo oo oo ba ba ar foo\") == 0, \"stb_wildmatch 4d\");\n\n   c(stb_wildfind(\"foo*bar\", \"xyfoobarx\")    == 2, \"stb_wildfind 0a\");\n   c(stb_wildfind(\"foo*bar\", \"aaafoobar\")    == 3, \"stb_wildfind 1a\");\n   c(stb_wildfind(\"foo*bar\", \"foo bar\")      == 0, \"stb_wildfind 2a\");\n   c(stb_wildfind(\"foo*bar\", \"fo foo ba ba bar ba\") == 3, \"stb_wildfind 3a\");\n   c(stb_wildfind(\"foo*bar\", \"fo oo oo ba ba ar foo\") == -1, \"stb_wildfind 4a\");\n\n   c(stb_wildmatch(\"*foo*;*bar*\", \"foobar\")  == 1, \"stb_wildmatch 1e\");\n   c(stb_wildmatch(\"*foo*;*bar*\", \"afooa\")  == 1, \"stb_wildmatch 2e\");\n   c(stb_wildmatch(\"*foo*;*bar*\", \"abara\")  == 1, \"stb_wildmatch 3e\");\n   c(stb_wildmatch(\"*foo*;*bar*\", \"abaza\")  == 0, \"stb_wildmatch 4e\");\n   c(stb_wildmatch(\"*foo*;*bar*\", \"foboar\")  == 0, \"stb_wildmatch 5e\");\n\n   test_sha1();\n\n   n = sizeof(args_raw)/sizeof(args_raw[0]);\n   memcpy(args, args_raw, sizeof(args_raw));\n   s = stb_getopt(&n, args);\n   c(n >= 1 && !strcmp(args[1], \"bar\" ), \"stb_getopt 1\");\n   c(stb_arr_len(s) >= 2 && !strcmp(s[2]   , \"r\"   ), \"stb_getopt 2\");\n   stb_getopt_free(s);\n\n   n = sizeof(args_raw)/sizeof(args_raw[0]);\n   memcpy(args, args_raw, sizeof(args_raw));\n   s = stb_getopt_param(&n, args, \"f\");\n   c(stb_arr_len(s) >= 3 && !strcmp(s[3]   , \"fbar\"), \"stb_getopt 3\");\n   stb_getopt_free(s);\n\n   n = sizeof(args_raw)/sizeof(args_raw[0]);\n   memcpy(args, args_raw, sizeof(args_raw));\n   s = stb_getopt_param(&n, args, \"x\");\n   c(stb_arr_len(s) >= 2 && !strcmp(s[1]   , \"xrf\" ), \"stb_getopt 4\");\n   stb_getopt_free(s);\n\n   n = sizeof(args_raw)/sizeof(args_raw[0]);\n   memcpy(args, args_raw, sizeof(args_raw));\n   s = stb_getopt_param(&n, args, \"s\");\n   c(s == NULL && n == 0     , \"stb_getopt 5\");\n   stb_getopt_free(s);\n\n#if 0\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3, -1, -1) ==  1, \"stb_csample_int 1\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3,  1, -3) ==  2, \"stb_csample_int 2\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3, 12, -2) ==  5, \"stb_csample_int 3\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3, 15,  1) == 10, \"stb_csample_int 4\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3,  5,  4) == 15, \"stb_csample_int 5\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3,  3,  3) == 14, \"stb_csample_int 6\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3, -2,  5) == 11, \"stb_csample_int 7\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3, -7,  0) ==  1, \"stb_csample_int 8\");\n   c(*stb_csample_int(sample_test[0], 1, 5, 5, 3,  2,  1) ==  8, \"stb_csample_int 9\");\n#endif\n\n   c(!strcmp(stb_splitpath(buf, p1, STB_PATH      ), \"foo/bar\\\\baz/\"), \"stb_splitpath 1\");\n   c(!strcmp(stb_splitpath(buf, p1, STB_FILE      ), \"test\"), \"stb_splitpath 2\");\n   c(!strcmp(stb_splitpath(buf, p1, STB_EXT       ), \".xyz\"), \"stb_splitpath 3\");\n   c(!strcmp(stb_splitpath(buf, p1, STB_PATH_FILE ), \"foo/bar\\\\baz/test\"), \"stb_splitpath 4\");\n   c(!strcmp(stb_splitpath(buf, p1, STB_FILE_EXT  ), \"test.xyz\"), \"stb_splitpath 5\");\n\n   c(!strcmp(stb_splitpath(buf, p2, STB_PATH      ), \"foo/\"), \"stb_splitpath 6\");\n   c(!strcmp(stb_splitpath(buf, p2, STB_FILE      ), \"\"), \"stb_splitpath 7\");\n   c(!strcmp(stb_splitpath(buf, p2, STB_EXT       ), \".bar\"), \"stb_splitpath 8\");\n   c(!strcmp(stb_splitpath(buf, p2, STB_PATH_FILE ), \"foo/\"), \"stb_splitpath 9\");\n   c(!strcmp(stb_splitpath(buf, p2, STB_FILE_EXT  ), \".bar\"), \"stb_splitpath 10\");\n\n   c(!strcmp(stb_splitpath(buf, p3, STB_PATH      ), \"./\"), \"stb_splitpath 11\");\n   c(!strcmp(stb_splitpath(buf, p3, STB_FILE      ), \"foo\"), \"stb_splitpath 12\");\n   c(!strcmp(stb_splitpath(buf, p3, STB_EXT       ), \".bar\"), \"stb_splitpath 13\");\n   c(!strcmp(stb_splitpath(buf, p3, STB_PATH_FILE ), \"foo\"), \"stb_splitpath 14\");\n\n   c(!strcmp(stb_splitpath(buf, p4, STB_PATH      ), \"foo/\"), \"stb_splitpath 16\");\n   c(!strcmp(stb_splitpath(buf, p4, STB_FILE      ), \"bar\"), \"stb_splitpath 17\");\n   c(!strcmp(stb_splitpath(buf, p4, STB_EXT       ), \"\"), \"stb_splitpath 18\");\n   c(!strcmp(stb_splitpath(buf, p4, STB_PATH_FILE ), \"foo/bar\"), \"stb_splitpath 19\");\n   c(!strcmp(stb_splitpath(buf, p4, STB_FILE_EXT  ), \"bar\"), \"stb_splitpath 20\");\n\n   c(!strcmp(p=stb_dupreplace(\"testfootffooo foo fox\", \"foo\", \"brap\"), \"testbraptfbrapo brap fox\"), \"stb_dupreplace 1\"); free(p);\n   c(!strcmp(p=stb_dupreplace(\"testfootffooo foo fox\", \"foo\", \"\"    ), \"testtfo  fox\"            ), \"stb_dupreplace 2\"); free(p);\n   c(!strcmp(p=stb_dupreplace(\"abacab\", \"a\", \"aba\"),                   \"abababacabab\"            ), \"stb_dupreplace 3\"); free(p);\n\n\n#if 0\n   m = stb_mml_parse(\"<a><b><c>x</c><d>y</d></b><e>&lt;&amp;f&gt;</e></a>\");\n   c(m != NULL, \"stb_mml_parse 1\");\n   if (m) {\n      c(!strcmp(m->child[0]->child[0]->child[1]->tag, \"d\"), \"stb_mml_parse 2\");\n      c(!strcmp(m->child[0]->child[1]->leaf_data, \"<&f>\"), \"stb_mml_parse 3\");\n   }\n   if (m)\n      stb_mml_free(m);\n   c(stb_alloc_count_alloc == stb_alloc_count_free, \"stb_alloc 1\");\n   if (stb_alloc_count_alloc != stb_alloc_count_free) {\n      printf(\"%d allocs, %d frees\\n\", stb_alloc_count_alloc, stb_alloc_count_free);\n   }\n#endif\n\n   c(stb_linear_remap(3.0f,0,8,1,2) == 1.375, \"stb_linear_remap()\");\n\n   c(stb_bitreverse(0x1248fec8) == 0x137f1248, \"stb_bitreverse() 1\");\n   c(stb_bitreverse8(0x4e) == 0x72, \"stb_bitreverse8() 1\");\n   c(stb_bitreverse8(0x31) == 0x8c, \"stb_bitreverse8() 2\");\n   for (n=1; n < 255; ++n) {\n      unsigned int m = stb_bitreverse8((uint8) n);\n      c(stb_bitreverse8((uint8) m) == (unsigned int) n, \"stb_bitreverse8() 3\");\n   }\n\n   for (n=2; n <= 31; ++n) {\n      c(stb_is_pow2   ((1 << n)  ) == 1  , \"stb_is_pow2() 1\");\n      c(stb_is_pow2   ((1 << n)+1) == 0  , \"stb_is_pow2() 2\");\n      c(stb_is_pow2   ((1 << n)-1) == 0  , \"stb_is_pow2() 3\");\n\n      c(stb_log2_floor((1 << n)  ) == n  , \"stb_log2_floor() 1\");\n      c(stb_log2_floor((1 << n)+1) == n  , \"stb_log2_floor() 2\");\n      c(stb_log2_floor((1 << n)-1) == n-1, \"stb_log2_floor() 3\");\n\n      c(stb_log2_ceil ((1 << n)  ) == n  , \"stb_log2_ceil() 1\");\n      c(stb_log2_ceil ((1 << n)+1) == n+1, \"stb_log2_ceil() 2\");\n      c(stb_log2_ceil ((1 << n)-1) == n  , \"stb_log2_ceil() 3\");\n\n      c(stb_bitreverse(1 << n) == 1U << (31-n), \"stb_bitreverse() 2\");\n   }\n\n   c(stb_log2_floor(0) == -1, \"stb_log2_floor() 4\");\n   c(stb_log2_ceil (0) == -1, \"stb_log2_ceil () 4\");\n\n   c(stb_log2_floor(-1) == 31, \"stb_log2_floor() 5\");\n   c(stb_log2_ceil (-1) == 32, \"stb_log2_ceil () 5\");\n\n   c(stb_bitcount(0xffffffff) == 32, \"stb_bitcount() 1\");\n   c(stb_bitcount(0xaaaaaaaa) == 16, \"stb_bitcount() 2\");\n   c(stb_bitcount(0x55555555) == 16, \"stb_bitcount() 3\");\n   c(stb_bitcount(0x00000000) ==  0, \"stb_bitcount() 4\");\n\n   c(stb_lowbit8(0xf0) == 4, \"stb_lowbit8 1\");\n   c(stb_lowbit8(0x10) == 4, \"stb_lowbit8 2\");\n   c(stb_lowbit8(0xf3) == 0, \"stb_lowbit8 3\");\n   c(stb_lowbit8(0xf8) == 3, \"stb_lowbit8 4\");\n   c(stb_lowbit8(0x60) == 5, \"stb_lowbit8 5\");\n\n   for (n=0; n < sizeof(buf); ++n)\n      buf[n] = 0;\n\n   for (n = 0; n < 200000; ++n) {\n      unsigned int k = stb_rand();\n      int i,z=0;\n      for (i=0; i < 32; ++i)\n         if (k & (1 << i)) ++z;\n      c(stb_bitcount(k) == z, \"stb_bitcount() 5\");\n\n      buf[k >> 24] = 1;\n\n      if (k != 0) {\n         if (stb_is_pow2(k)) {\n            c(stb_log2_floor(k) == stb_log2_ceil(k), \"stb_is_pow2() 1\");\n            c(k == 1U << stb_log2_floor(k), \"stb_is_pow2() 2\");\n         } else {\n            c(stb_log2_floor(k) == stb_log2_ceil(k)-1, \"stb_is_pow2() 3\");\n         }\n      }\n\n      c(stb_bitreverse(stb_bitreverse(n)) == (uint32) n, \"stb_bitreverse() 3\");\n   }\n\n   // make sure reasonable coverage from stb_rand()\n   for (n=0; n < sizeof(buf); ++n)\n      c(buf[n] != 0, \"stb_rand()\");\n\n   for (n=0; n < sizeof(buf); ++n)\n      buf[n] = 0;\n\n   for (n=0; n < 60000; ++n) {\n      float z = (float) stb_frand();\n      int n = (int) (z * sizeof(buf));\n      c(z >= 0 && z < 1, \"stb_frand() 1\");\n      c(n >= 0 && n < sizeof(buf), \"stb_frand() 2\");\n      buf[n] = 1;\n   }\n\n   // make sure reasonable coverage from stb_frand(),\n   // e.g. that the range remap isn't incorrect\n   for (n=0; n < sizeof(buf); ++n)\n      c(buf[n] != 0, \"stb_frand()\");\n         \n\n   // stb_arr\n   {\n      short *s = NULL;\n\n      c(sum(s) == 0, \"stb_arr 1\");\n\n      stb_arr_add(s); s[0] = 3;\n      stb_arr_push(s,7);\n\n      c( stb_arr_valid(s,1), \"stb_arr 2\");\n      c(!stb_arr_valid(s,2), \"stb_arr 3\");\n\n      // force a realloc\n      stb_arr_push(s,0);\n      stb_arr_push(s,0);\n      stb_arr_push(s,0);\n      stb_arr_push(s,0);\n\n      c(sum(s) == 10, \"stb_arr 4\");\n      stb_arr_push(s,0);\n      s[0] = 1; s[1] = 5; s[2] = 20;\n      c(sum(s) == 26, \"stb_arr 5\");\n      stb_arr_setlen(s,2);\n      c(sum(s) == 6, \"stb_arr 6\");\n      stb_arr_setlen(s,1);\n      c(sum(s) == 1, \"stb_arr 7\");\n      stb_arr_setlen(s,0);\n      c(sum(s) == 0, \"stb_arr 8\");\n\n      stb_arr_push(s,3);\n      stb_arr_push(s,4);\n      stb_arr_push(s,5);\n      stb_arr_push(s,6);\n      stb_arr_push(s,7);\n      stb_arr_deleten(s,1,3);\n      c(stb_arr_len(s)==2 && sum(s) == 10, \"stb_arr_9\");\n\n      stb_arr_push(s,2);\n      // 3 7 2\n      stb_arr_insertn(s,2,2);\n      // 3 7 x x 2\n      s[2] = 5;\n      s[3] = 6;\n      c(s[0]==3 && s[1] == 7 && s[2] == 5 && s[3] == 6 && s[4] == 2, \"stb_arr 10\");\n      stb_arr_free(s);\n   }\n\n   #if 1\n   f= stb_fopen(\"data/stb.test\", \"wb\");\n   fwrite(buffer, 1, sizeof(buffer)-1, f);\n   stb_fclose(f, stb_keep_yes);\n   #ifndef WIN32\n   sleep(1);  // andLinux has some synchronization problem here\n   #endif\n   #else\n   f= fopen(\"data/stb.test\", \"wb\");\n   fwrite(buffer, 1, sizeof(buffer)-1, f);\n   fclose(f);\n   #endif\n   if (!stb_fexists(\"data/stb.test\")) {\n      fprintf(stderr, \"Error: couldn't open file just written, or stb_fexists() is broken.\\n\");\n   }\n\n   f = fopen(\"data/stb.test\", \"rb\");\n   // f = NULL; // test stb_fatal()\n   if (!f) { stb_fatal(\"Error: couldn't open file just written\\n\"); }\n   else {\n      char temp[4];\n      int len1 = stb_filelen(f), len2;\n      int n1,n2;\n      if (fread(temp,1,4,f) == 0) {\n         int n = ferror(f);\n         if (n) { stb_fatal(\"Error reading from stream: %d\", n); }\n         if (feof(f)) stb_fatal(\"Weird, read 0 bytes and hit eof\");\n         stb_fatal(\"Read 0, but neither feof nor ferror is true\");\n      }\n      fclose(f);\n      p = stb_file(\"data/stb.test\", &len2);\n      if (p == NULL) stb_fatal(\"Error: stb_file() failed\");\n      c(len1 == sizeof(buffer)-1, \"stb_filelen()\");\n      c(len2 == sizeof(buffer)-1, \"stb_file():n\");\n      c(memcmp(p, buffer, sizeof(buffer)-1) == 0, \"stb_file()\");\n      c(strcmp(p, buffer)==0, \"stb_file() terminated\");\n      free(p);\n\n      s = stb_stringfile(\"data/stb.test\", &n1);\n      c(n1 == 3, \"stb_stringfile():n\");\n      n2 = 0;\n      while (s[n2]) ++n2;\n      c(n1 == n2, \"stb_stringfile():n length matches the non-NULL strings\");\n      if (n2 == 3) {\n         c(strcmp(s[0],str1)==0, \"stb_stringfile()[0]\");\n         c(strcmp(s[1],str2)==0, \"stb_stringfile()[1]\");\n         c(strcmp(s[2],str3)==0, \"stb_stringfile()[2] (no terminating newlines)\");\n      }\n      free(s);\n\n      f = fopen(\"data/stb.test\", \"rb\");\n      stb_fgets(buf, sizeof(buf), f);\n      //c(strcmp(buf, str1)==0, \"stb_fgets()\");\n      p = stb_fgets_malloc(f);\n      n1 = strlen(p);\n      n2 = strlen(str2);\n      c(strcmp(p, str2)==0, \"stb_fgets_malloc()\");\n      free(p);\n      stb_fgets(buf, sizeof(buf), f);\n      c(strcmp(buf, str3)==0, \"stb_fgets()3\");\n   }\n\n   c( stb_prefix(\"foobar\", \"foo\"), \"stb_prefix() 1\");\n   c(!stb_prefix(\"foo\", \"foobar\"), \"stb_prefix() 2\");\n   c( stb_prefix(\"foob\", \"foob\" ), \"stb_prefix() 3\");\n\n   stb_strncpy(buf, \"foobar\", 6);  c(strcmp(buf,\"fooba\" )==0, \"stb_strncpy() 1\");\n   stb_strncpy(buf, \"foobar\", 8);  c(strcmp(buf,\"foobar\")==0, \"stb_strncpy() 2\");\n\n   c(!strcmp(p=stb_duplower(\"FooBar\"), \"foobar\"), \"stb_duplower()\"); free(p);\n   strcpy(buf, \"FooBar\");\n   stb_tolower(buf);\n   c(!strcmp(buf, \"foobar\"), \"stb_tolower()\");\n\n   p = stb_strtok(buf, \"foo=ba*r\", \"#=*\");\n   c(!strcmp(buf, \"foo\" ), \"stb_strtok() 1\");\n   c(!strcmp(p  , \"ba*r\"), \"stb_strtok() 2\");\n   p = stb_strtok(buf, \"foobar\", \"#=*\");\n   c(*p == 0, \"stb_strtok() 3\");\n\n   c(!strcmp(stb_skipwhite(\" \\t\\n foo\"), \"foo\"), \"stb_skipwhite()\");\n\n   s = stb_tokens(\"foo == ba*r\", \"#=*\", NULL);\n   c(!strcmp(s[0], \"foo \"), \"stb_tokens() 1\");\n   c(!strcmp(s[1], \" ba\"),  \"stb_tokens() 2\");\n   c(!strcmp(s[2], \"r\"),    \"stb_tokens() 3\");\n   c(s[3] == 0,             \"stb_tokens() 4\");\n   free(s);\n\n   s = stb_tokens_allowempty(\"foo == ba*r\", \"#=*\", NULL);\n   c(!strcmp(s[0], \"foo \"), \"stb_tokens_allowempty() 1\");\n   c(!strcmp(s[1], \"\"    ), \"stb_tokens_allowempty() 2\");\n   c(!strcmp(s[2], \" ba\"),  \"stb_tokens_allowempty() 3\");\n   c(!strcmp(s[3], \"r\"),    \"stb_tokens_allowempty() 4\");\n   c(s[4] == 0,             \"stb_tokens_allowempty() 5\");\n   free(s);\n\n   s = stb_tokens_stripwhite(\"foo == ba*r\", \"#=*\", NULL);\n   c(!strcmp(s[0], \"foo\"),  \"stb_tokens_stripwhite() 1\");\n   c(!strcmp(s[1], \"\"   ),  \"stb_tokens_stripwhite() 2\");\n   c(!strcmp(s[2], \"ba\"),   \"stb_tokens_stripwhite() 3\");\n   c(!strcmp(s[3], \"r\"),    \"stb_tokens_stripwhite() 4\");\n   c(s[4] == 0,             \"stb_tokens_stripwhite() 5\");\n   free(s);\n\n   s = stb_tokens_quoted(\"foo =\\\"=\\\" ba*\\\"\\\"r \\\" foo\\\" bah    \", \"#=*\", NULL);\n   c(!strcmp(s[0], \"foo\"),  \"stb_tokens_quoted() 1\");\n   c(!strcmp(s[1], \"= ba\"), \"stb_tokens_quoted() 2\");\n   c(!strcmp(s[2], \"\\\"r  foo bah\"),  \"stb_tokens_quoted() 3\");\n   c(s[3] == 0,             \"stb_tokens_quoted() 4\");\n   free(s);\n\n\n   p = stb_file(\"stb.h\", &len2);\n   if (p) {\n      uint32 z = stb_adler32_old(1, p, len2);\n      uint32 x = stb_adler32    (1, p, len2);\n      c(z == x, \"stb_adler32() 1\");\n      memset(p,0xff,len2);\n      z = stb_adler32_old((65520<<16) + 65520, p, len2);\n      x = stb_adler32    ((65520<<16) + 65520, p, len2);\n      c(z == x, \"stb_adler32() 2\");\n      free(p);\n   }\n\n   //   stb_hheap\n   {\n      #define HHEAP_COUNT  100000\n      void **p = malloc(sizeof(*p) * HHEAP_COUNT);\n      int i, j;\n      #if 0\n      stb_hheap *h2, *h = stb_newhheap(sizeof(struct1),0);\n\n      for (i=0; i < HHEAP_COUNT; ++i)\n         p[i] = stb_halloc(h);\n      stb_shuffle(p, HHEAP_COUNT, sizeof(*p), stb_rand());\n      for (i=0; i < HHEAP_COUNT; ++i)\n         stb_hfree(p[i]);\n\n      c(h->num_alloc == 0, \"stb_hheap 1\");\n      stb_delhheap(h);\n\n      h = stb_newhheap(sizeof(struct1),0);\n      h2 = stb_newhheap(sizeof(struct2),8);\n\n      for (i=0; i < HHEAP_COUNT; ++i) {\n         if (i & 1)\n            p[i] = stb_halloc(h);\n         else {\n            p[i] = stb_halloc(h2);\n            c((((int) p[i]) & 4) == 0, \"stb_hheap 2\");\n         }\n      }\n\n      stb_shuffle(p, HHEAP_COUNT, sizeof(*p), stb_rand());\n      for (i=0; i < HHEAP_COUNT; ++i)\n         stb_hfree(p[i]);\n\n      c(h->num_alloc == 0, \"stb_hheap 3\");\n      c(h2->num_alloc == 0, \"stb_hheap 4\");\n\n      stb_delhheap(h);\n      stb_delhheap(h2);\n      #else\n      for (i=0; i < HHEAP_COUNT; ++i)\n         p[i] = malloc(32);\n      stb_shuffle(p, HHEAP_COUNT, sizeof(*p), stb_rand());\n      for (i=0; i < HHEAP_COUNT; ++i)\n         free(p[i]);\n      #endif\n\n      // now use the same array of pointers to do pointer set operations\n      for (j=100; j < HHEAP_COUNT; j += 25000) {\n         stb_ps *ps = NULL;\n         for (i=0; i < j; ++i)\n            ps = stb_ps_add(ps, p[i]);\n\n         for (i=0; i < HHEAP_COUNT; ++i)\n            c(stb_ps_find(ps, p[i]) == (i < j), \"stb_ps 1\");\n         c(stb_ps_count(ps) == j, \"stb_ps 1b\");\n\n         for (i=j; i < HHEAP_COUNT; ++i)\n            ps = stb_ps_add(ps, p[i]);\n\n         for (i=0; i < j; ++i)\n            ps = stb_ps_remove(ps, p[i]);\n\n         for (i=0; i < HHEAP_COUNT; ++i)\n            c(stb_ps_find(ps, p[i]) == !(i < j), \"stb_ps 2\");\n\n         stb_ps_delete(ps);\n      }\n\n      #define HHEAP_COUNT2   100\n      // now use the same array of pointers to do pointer set operations\n      for (j=1; j < 40; ++j) {\n         stb_ps *ps = NULL;\n         for (i=0; i < j; ++i)\n            ps = stb_ps_add(ps, p[i]);\n\n         for (i=0; i < HHEAP_COUNT2; ++i)\n            c(stb_ps_find(ps, p[i]) == (i < j), \"stb_ps 3\");\n         c(stb_ps_count(ps) == j, \"stb_ps 3b\");\n\n         for (i=j; i < HHEAP_COUNT2; ++i)\n            ps = stb_ps_add(ps, p[i]);\n\n         for (i=0; i < j; ++i)\n            ps = stb_ps_remove(ps, p[i]);\n\n         for (i=0; i < HHEAP_COUNT2; ++i)\n            c(stb_ps_find(ps, p[i]) == !(i < j), \"stb_ps 4\");\n\n         stb_ps_delete(ps);\n      }\n\n      free(p);\n   }\n\n\n   n = test_compression(tc, sizeof(tc));\n   c(n >= 0, \"stb_compress()/stb_decompress() 1\");\n\n   p = stb_file(\"stb.h\", &len2);\n   if (p) {\n      FILE *f = fopen(\"data/stb_h.z\", \"wb\");\n      if (stb_compress_stream_start(f)) {\n         int i;\n         void *q;\n         int len3;\n\n         for (i=0; i < len2; ) {\n            int n = stb_rand() % 10;\n            if (n <= 6) n = 1 + stb_rand()%16;\n            else if (n <= 8) n = 20 + stb_rand() % 1000;\n            else n = 15000;\n            if (i + n > len2) n = len2 - i;\n            stb_write(p + i, n);\n            i += n;\n         }\n         stb_compress_stream_end(1);\n\n         q = stb_decompress_fromfile(\"data/stb_h.z\", &len3);\n         c(len3 == len2, \"stb_compress_stream 2\");\n         if (len2 == len3)\n            c(!memcmp(p,q,len2), \"stb_compress_stream 3\");\n         if (q) free(q);\n      } else {\n         c(0, \"stb_compress_stream 1\");\n      }\n\n      free(p);\n      stb_compress_window(65536*4);\n   }\n\n   p = stb_file(\"stb.h\", &len2);\n   if (p) {\n      n = test_compression(p, len2);\n      c(n >= 0, \"stb_compress()/stb_decompress() 2\");\n      #if 0\n      n = test_en_compression(p, len2);\n      c(n >= 0, \"stb_en_compress()/stb_en_decompress() 2\");\n      #endif\n      free(p);\n   } else {\n      fprintf(stderr, \"No stb.h to compression test.\\n\");\n   }\n\n   p = stb_file(\"data/test.bmp\", &len2);\n   if (p) {\n      n = test_compression(p, len2);\n      c(n == 106141, \"stb_compress()/stb_decompress() 4\");\n      #if 0\n      n = test_en_compression(p, len2);\n      c(n >= 0, \"stb_en_compress()/stb_en_decompress() 4\");\n      #endif\n      free(p);\n   }\n\n   // the hardcoded compressed lengths being verified _could_\n   // change if you changed the compressor parameters; but pure\n   // performance optimizations shouldn't change them\n   p = stb_file(\"data/cantrbry.zip\", &len2);\n   if (p) {\n      n = test_compression(p, len2);\n      c(n == 642787, \"stb_compress()/stb_decompress() 3\");\n      #if 0\n      n = test_en_compression(p, len2);\n      c(n >= 0, \"stb_en_compress()/stb_en_decompress() 3\");\n      #endif\n      free(p);\n   }\n\n   p = stb_file(\"data/bible.txt\", &len2);\n   if (p) {\n      n = test_compression(p, len2);\n      c(n == 2022520, \"stb_compress()/stb_decompress() 4\");\n      #if 0\n      n = test_en_compression(p, len2);\n      c(n >= 0, \"stb_en_compress()/stb_en_decompress() 4\");\n      #endif\n      free(p);\n   }\n\n   {\n      int len = 1 << 25, o=0; // 32MB\n      char *buffer = malloc(len);\n      int i;\n      for (i=0; i < 8192; ++i)\n         buffer[o++] = (char) stb_rand();\n      for (i=0; i < (1 << 15); ++i)\n         buffer[o++] = 1;\n      for (i=0; i < 64; ++i)\n         buffer[o++] = buffer[i];\n      for (i=0; i < (1 << 21); ++i)\n         buffer[o++] = 2;\n      for (i=0; i < 64; ++i)\n         buffer[o++] = buffer[i];\n      for (i=0; i < (1 << 21); ++i)\n         buffer[o++] = 3;\n      for (i=0; i < 8192; ++i)\n         buffer[o++] = buffer[i];\n      for (i=0; i < (1 << 21); ++i)\n         buffer[o++] = 4;\n      assert(o < len);\n      stb_compress_window(1 << 24);\n      i = test_compression(buffer, len);\n      c(n >= 0, \"stb_compress() 6\");\n      free(buffer);\n   }\n\n   #ifdef STB_THREADS\n   stb_thread_cleanup();\n   #endif\n   stb_ischar(0,NULL);\n   stb_wrapper_listall(dumpfunc);\n   printf(\"Memory still in use: %d allocations of %d bytes.\\n\", alloc_num, alloc_size);\n\n   // force some memory checking\n   for (n=1; n < 20; ++n)\n      malloc(1 << n);\n\n   printf(\"Finished stb.c with %d errors.\\n\", count);\n\n   #ifdef _MSC_VER\n   if (count)\n      __asm int 3;\n   #endif\n\n   return 0;\n}\n\n#endif\n\n\n\n\n\n// NIST test vectors\n\nstruct\n{\n   int length;\n   char *message;\n   char *digest;\n} sha1_tests[] =\n{\n{   24,\n\"616263\",\n\"a9993e364706816aba3e25717850c26c9cd0d89d\",\n},{\n   1304,\n\"ec29561244ede706b6eb30a1c371d74450a105c3f9735f7fa9fe38cf67f304a5736a106e\"\n\"92e17139a6813b1c81a4f3d3fb9546ab4296fa9f722826c066869edacd73b25480351858\"\n\"13e22634a9da44000d95a281ff9f264ecce0a931222162d021cca28db5f3c2aa24945ab1\"\n\"e31cb413ae29810fd794cad5dfaf29ec43cb38d198fe4ae1da2359780221405bd6712a53\"\n\"05da4b1b737fce7cd21c0eb7728d08235a9011\",\n\"970111c4e77bcc88cc20459c02b69b4aa8f58217\",\n},{\n   2096,\n\"5fc2c3f6a7e79dc94be526e5166a238899d54927ce470018fbfd668fd9dd97cbf64e2c91\"\n\"584d01da63be3cc9fdff8adfefc3ac728e1e335b9cdc87f069172e323d094b47fa1e652a\"\n\"fe4d6aa147a9f46fda33cacb65f3aa12234746b9007a8c85fe982afed7815221e43dba55\"\n\"3d8fe8a022cdac1b99eeeea359e5a9d2e72e382dffa6d19f359f4f27dc3434cd27daeeda\"\n\"8e38594873398678065fbb23665aba9309d946135da0e4a4afdadff14db18e85e71dd93c\"\n\"3bf9faf7f25c8194c4269b1ee3d9934097ab990025d9c3aaf63d5109f52335dd3959d38a\"\n\"e485050e4bbb6235574fc0102be8f7a306d6e8de6ba6becf80f37415b57f9898a5824e77\"\n\"414197422be3d36a6080\",\n   \"0423dc76a8791107d14e13f5265b343f24cc0f19\",\n},{\n   2888,\n\"0f865f46a8f3aed2da18482aa09a8f390dc9da07d51d1bd10fe0bf5f3928d5927d08733d\"\n\"32075535a6d1c8ac1b2dc6ba0f2f633dc1af68e3f0fa3d85e6c60cb7b56c239dc1519a00\"\n\"7ea536a07b518ecca02a6c31b46b76f021620ef3fc6976804018380e5ab9c558ebfc5cb1\"\n\"c9ed2d974722bf8ab6398f1f2b82fa5083f85c16a5767a3a07271d67743f00850ce8ec42\"\n\"8c7f22f1cf01f99895c0c844845b06a06cecb0c6cf83eb55a1d4ebc44c2c13f6f7aa5e0e\"\n\"08abfd84e7864279057abc471ee4a45dbbb5774afa24e51791a0eada11093b88681fe30b\"\n\"aa3b2e94113dc63342c51ca5d1a6096d0897b626e42cb91761058008f746f35465465540\"\n\"ad8c6b8b60f7e1461b3ce9e6529625984cb8c7d46f07f735be067588a0117f23e34ff578\"\n\"00e2bbe9a1605fde6087fb15d22c5d3ac47566b8c448b0cee40373e5ba6eaa21abee7136\"\n\"6afbb27dbbd300477d70c371e7b8963812f5ed4fb784fb2f3bd1d3afe883cdd47ef32bea\"\n\"ea\",\n   \"6692a71d73e00f27df976bc56df4970650d90e45\",\n},{\n   3680,\n\"4893f1c763625f2c6ce53aacf28026f14b3cd8687e1a1d3b60a81e80fcd1e2b038f9145a\"\n\"b64a0718f948f7c3c9ac92e3d86fb669a5257da1a18c776291653688338210a3242120f1\"\n\"01788e8acc9110db9258b1554bf3d26602516ea93606a25a7f566c0c758fb39ecd9d876b\"\n\"c5d8abc1c3205095382c2474cb1f8bbdb45c2c0e659cb0fc703ec607a5de6bcc7a28687d\"\n\"b1ee1c8f34797bb2441d5706d210df8c2d7d65dbded36414d063c117b52a51f7a4eb9cac\"\n\"0782e008b47459ed5acac0bc1f20121087f992ad985511b33c866d18e63f585478ee5a5e\"\n\"654b19d81231d98683ae3f0533565aba43dce408d7e3c4c6be11d8f05165f29c9dcb2030\"\n\"c4ee31d3a04e7421aa92c3231a1fc07e50e95fea7389a5e65891afaba51cf55e36a9d089\"\n\"bf293accb356d5d06547307d6e41456d4ed146a056179971c56521c83109bf922866186e\"\n\"184a99a96c7bb96df8937e35970e438412a2b8d744cf2ad87cb605d4232e976f9f151697\"\n\"76e4e5b6b786132c966b25fc56d815c56c819af5e159aa39f8a93d38115f5580cda93bc0\"\n\"73c30b39920e726fe861b72483a3f886269ab7a8eefe952f35d25c4eb7f443f4f3f26e43\"\n\"d51fb54591e6a6dad25fcdf5142033084e5624bdd51435e77dea86b8\",\n   \"dc5859dd5163c4354d5d577b855fa98e37f04384\",\n},{\n   4472,\n\"cf494c18a4e17bf03910631471bca5ba7edea8b9a63381e3463517961749848eb03abefd\"\n\"4ce676dece3740860255f57c261a558aa9c7f11432f549a9e4ce31d8e17c79450ce2ccfc\"\n\"148ad904aedfb138219d7052088520495355dadd90f72e6f69f9c6176d3d45f113f275b7\"\n\"fbc2a295784d41384cd7d629b23d1459a22e45fd5097ec9bf65fa965d3555ec77367903c\"\n\"32141065fc24da5c56963d46a2da3c279e4035fb2fb1c0025d9dda5b9e3443d457d92401\"\n\"a0d3f58b48469ecb1862dc975cdbe75ca099526db8b0329b03928206f084c633c04eef5e\"\n\"8e377f118d30edf592504be9d2802651ec78aeb02aea167a03fc3e23e5fc907c324f283f\"\n\"89ab37e84687a9c74ccf055402db95c29ba2c8d79b2bd4fa96459f8e3b78e07e923b8119\"\n\"8267492196ecb71e01c331f8df245ec5bdf8d0e05c91e63bb299f0f6324895304dda721d\"\n\"39410458f117c87b7dd6a0ee734b79fcbe482b2c9e9aa0cef03a39d4b0c86de3bc34b4aa\"\n\"dabfa373fd2258f7c40c187744d237080762382f547a36adb117839ca72f8ebbc5a20a07\"\n\"e86f4c8bb923f5787698d278f6db0040e76e54645bb0f97083995b34b9aa445fc4244550\"\n\"58795828dd00c32471ec402a307f5aa1b37b1a86d6dae3bcbfbe9ba41cab0beeabf489af\"\n\"0073d4b3837d3f14b815120bc3602d072b5aeefcdec655fe756b660eba7dcf34675acbce\"\n\"317746270599424b9248791a0780449c1eabbb9459cc1e588bfd74df9b1b711c85c09d8a\"\n\"a171b309281947e8f4b6ac438753158f4f36fa\",\n   \"4c17926feb6e87f5bca7890d8a5cde744f231dab\",\n},{\n   5264,\n\"8236153781bd2f1b81ffe0def1beb46f5a70191142926651503f1b3bb1016acdb9e7f7ac\"\n\"ced8dd168226f118ff664a01a8800116fd023587bfba52a2558393476f5fc69ce9c65001\"\n\"f23e70476d2cc81c97ea19caeb194e224339bcb23f77a83feac5096f9b3090c51a6ee6d2\"\n\"04b735aa71d7e996d380b80822e4dfd43683af9c7442498cacbea64842dfda238cb09992\"\n\"7c6efae07fdf7b23a4e4456e0152b24853fe0d5de4179974b2b9d4a1cdbefcbc01d8d311\"\n\"b5dda059136176ea698ab82acf20dd490be47130b1235cb48f8a6710473cfc923e222d94\"\n\"b582f9ae36d4ca2a32d141b8e8cc36638845fbc499bce17698c3fecae2572dbbd4705524\"\n\"30d7ef30c238c2124478f1f780483839b4fb73d63a9460206824a5b6b65315b21e3c2f24\"\n\"c97ee7c0e78faad3df549c7ca8ef241876d9aafe9a309f6da352bec2caaa92ee8dca3928\"\n\"99ba67dfed90aef33d41fc2494b765cb3e2422c8e595dabbfaca217757453fb322a13203\"\n\"f425f6073a9903e2dc5818ee1da737afc345f0057744e3a56e1681c949eb12273a3bfc20\"\n\"699e423b96e44bd1ff62e50a848a890809bfe1611c6787d3d741103308f849a790f9c015\"\n\"098286dbacfc34c1718b2c2b77e32194a75dda37954a320fa68764027852855a7e5b5274\"\n\"eb1e2cbcd27161d98b59ad245822015f48af82a45c0ed59be94f9af03d9736048570d6e3\"\n\"ef63b1770bc98dfb77de84b1bb1708d872b625d9ab9b06c18e5dbbf34399391f0f8aa26e\"\n\"c0dac7ff4cb8ec97b52bcb942fa6db2385dcd1b3b9d567aaeb425d567b0ebe267235651a\"\n\"1ed9bf78fd93d3c1dd077fe340bb04b00529c58f45124b717c168d07e9826e33376988bc\"\n\"5cf62845c2009980a4dfa69fbc7e5a0b1bb20a5958ca967aec68eb31dd8fccca9afcd30a\"\n\"26bab26279f1bf6724ff\",\n   \"11863b483809ef88413ca9b0084ac4a5390640af\",\n},{\n   6056,\n\"31ec3c3636618c7141441294fde7e72366a407fa7ec6a64a41a7c8dfda150ca417fac868\"\n\"1b3c5be253e3bff3ab7a5e2c01b72790d95ee09b5362be835b4d33bd20e307c3c702aa15\"\n\"60cdc97d190a1f98b1c78e9230446e31d60d25155167f73e33ed20cea27b2010514b57ba\"\n\"b05ed16f601e6388ea41f714b0f0241d2429022e37623c11156f66dd0fa59131d8401dba\"\n\"f502cffb6f1d234dcb53e4243b5cf9951688821586a524848123a06afa76ab8058bcfa72\"\n\"27a09ce30d7e8cb100c8877bb7a81b615ee6010b8e0daced7cc922c971940b757a9107de\"\n\"60b8454dda3452e902092e7e06faa57c20aadc43c8012b9d28d12a8cd0ba0f47ab4b377f\"\n\"316902e6dff5e4f2e4a9b9de1e4359f344e66d0565bd814091e15a25d67d89cf6e30407b\"\n\"36b2654762bbe53a6f204b855a3f9108109e351825cf9080c89764c5f74fb4afef89d804\"\n\"e7f7d097fd89d98171d63eaf11bd719df44c5a606be0efea358e058af2c265b2da2623fd\"\n\"afc62b70f0711d0150625b55672060cea6a253c590b7db1427a536d8a51085756d1e6ada\"\n\"41d9d506b5d51bcae41249d16123b7df7190e056777a70feaf7d9f051fdbbe45cbd60fc6\"\n\"295dda84d4ebbd7284ad44be3ee3ba57c8883ead603519b8ad434e3bf630734a9243c00a\"\n\"a07366b8f88621ec6176111f0418c66b20ff9a93009f43432aaea899dad0f4e3ae72e9ab\"\n\"a3f678f140118eb7117230c357a5caa0fe36c4e6cf1957bbe7499f9a68b0f1536e476e53\"\n\"457ed826d9dea53a6ded52e69052faaa4d3927b9a3f9e8b435f424b941bf2d9cd6849874\"\n\"42a44d5acaa0da6d9f390d1a0dd6c19af427f8bb7c082ae405a8dd535dea76aa360b4faa\"\n\"d786093e113424bb75b8cc66c41af637a7b2acdca048a501417919cf9c5cd3b2fa668860\"\n\"d08b6717eea6f125fa1b0bae1dbb52aafce8ae2deaf92aeb5be003fb9c09fedbc286ffb5\"\n\"e16ad8e07e725faa46ebc35500cf205fc03250075ddc050c263814b8d16d141db4ca289f\"\n\"386719b28a09a8e5934722202beb3429899b016dfeb972fee487cdd8d18f8a681042624f\"\n\"51\",\n   \"f43937922444421042f76756fbed0338b354516f\",\n},{\n   6848,\n\"21b9a9686ec200456c414f2e6963e2d59e8b57e654eced3d4b57fe565b51c9045c697566\"\n\"44c953178f0a64a6e44d1b46f58763c6a71ce4c373b0821c0b3927a64159c32125ec916b\"\n\"6edd9bf41c3d80725b9675d6a97c8a7e3b662fac9dbcf6379a319a805b5341a8d360fe00\"\n\"5a5c9ac1976094fea43566d66d220aee5901bd1f2d98036b2d27eb36843e94b2e5d1f09c\"\n\"738ec826de6e0034cf8b1dca873104c5c33704cae290177d491d65f307c50a69b5c81936\"\n\"a050e1fe2b4a6f296e73549323b6a885c3b54ee5eca67aa90660719126b590163203909e\"\n\"470608f157f033f017bcf48518bf17d63380dabe2bc9ac7d8efe34aedcae957aeb68f10c\"\n\"8ad02c4465f1f2b029d5fbb8e8538d18be294394b54b0ee6e67a79fce11731604f3ac4f8\"\n\"d6ffa9ef3d2081f3d1c99ca107a7bf3d624324a7978ec38af0bcd0d7ee568572328b212b\"\n\"9dc831efb7880e3f4d6ca7e25f8e80d73913fb8edfffd758ae4df61b4140634a92f49314\"\n\"6138ebdcdaa083ea72d52a601230aa6f77874dcad9479f5bcac3763662cc30cb99823c5f\"\n\"f469dcbd64c028286b0e579580fd3a17b56b099b97bf62d555798f7a250e08b0e4f238c3\"\n\"fcf684198bd48a68c208a6268be2bb416eda3011b523388bce8357b7f26122640420461a\"\n\"bcabcb5004519adfa2d43db718bce7d0c8f1b4645c89315c65df1f0842e5741244bba3b5\"\n\"10801d2a446818635d0e8ffcd80c8a6f97ca9f878793b91780ee18eb6c2b99ffac3c38ef\"\n\"b7c6d3af0478317c2b9c421247eba8209ea677f984e2398c7c243696a12df2164417f602\"\n\"d7a1d33809c865b73397550ff33fe116166ae0ddbccd00e2b6fc538733830ac39c328018\"\n\"bcb87ac52474ad3cce8780d6002e14c6734f814cb551632bcc31965c1cd23d048b9509a4\"\n\"e22ab88f76a6dba209d5dd2febd1413a64d32be8574a22341f2a14e4bd879abb35627ef1\"\n\"35c37be0f80843006a7cc7158d2bb2a71bf536b36de20ca09bb5b674e5c408485106e6fa\"\n\"966e4f2139779b46f6010051615b5b41cda12d206d48e436b9f75d7e1398a656abb0087a\"\n\"a0eb453368fc1ecc71a31846080f804d7b67ad6a7aa48579c3a1435eff7577f4e6004d46\"\n\"aac4130293f6f62ae6d50c0d0c3b9876f0728923a94843785966a27555dd3ce68602e7d9\"\n\"0f7c7c552f9bda4969ec2dc3e30a70620db6300e822a93e633ab9a7a\",\n   \"5d4d18b24b877092188a44be4f2e80ab1d41e795\",\n},{\n   7640,\n\"1c87f48f4409c3682e2cf34c63286dd52701b6c14e08669851a6dc8fa15530ad3bef692c\"\n\"7d2bf02238644561069df19bdec3bccae5311fce877afc58c7628d08d32d9bd2dc1df0a6\"\n\"24360e505944219d211f33bff62e9ff2342ac86070240a420ccaf14908e6a93c1b27b6e2\"\n\"0324e522199e83692805cc4c7f3ea66f45a490a50d4dd558aa8e052c45c1a5dfad452674\"\n\"edc7149024c09024913f004ceee90577ff3eaec96a1eebbdc98b440ffeb0cad9c6224efc\"\n\"9267d2c192b53dc012fb53010926e362ef9d4238d00df9399f6cbb9acc389a7418007a6c\"\n\"a926c59359e3608b548bdeece213f4e581d02d273781dffe26905ec161956f6dfe1c008d\"\n\"6da8165d08f8062eea88e80c055b499f6ff8204ffdb303ab132d9b0cba1e5675f3525bbe\"\n\"4cf2c3f2b00506f58336b36aefd865d37827f2fad7d1e59105b52f1596ea19f848037dfe\"\n\"dc9136e824ead5505e2995d4c0769276548835430667f333fc77375125b29c1b1535602c\"\n\"10fe161864f49a98fc274ae7335a736be6bf0a98cd019d120b87881103f86c0a6efadd8c\"\n\"aa405b6855c384141b4f8751cc42dc0cb2913382210baaa84fe242ca66679472d815c08b\"\n\"f3d1a7c6b5705a3de17ad157522de1eb90c568a8a1fbcbb422cca293967bb14bfdd91bc5\"\n\"a9c4d2774dee524057e08f937f3e2bd8a04ced0fc7b16fb78a7b16ee9c6447d99e53d846\"\n\"3726c59066af25c317fc5c01f5dc9125809e63a55f1cd7bdf7f995ca3c2655f4c7ab940f\"\n\"2aa48bc3808961eb48b3a03c731ce627bb67dd0037206c5f2c442fc72704258548c6a9db\"\n\"e16da45e40da009dc8b2600347620eff8361346116b550087cb9e2ba6b1d6753622e8b22\"\n\"85589b90a8e93902aa17530104455699a1829efef153327639b2ae722d5680fec035575c\"\n\"3b48d9ec8c8e9550e15338cc76b203f3ab597c805a8c6482676deabc997a1e4ba857a889\"\n\"97ceba32431443c53d4d662dd5532aa177b373c93bf93122b72ed7a3189e0fa171dfabf0\"\n\"520edf4b9d5caef595c9a3a13830c190cf84bcf9c3596aadb2a674fbc2c951d135cb7525\"\n\"3ee6c59313444f48440a381e4b95f5086403beb19ff640603394931f15d36b1cc9f3924f\"\n\"794c965d4449bfbdd8b543194335bdf70616dc986b49582019ac2bf8e68cfd71ec67e0aa\"\n\"dff63db39e6a0ef207f74ec6108fae6b13f08a1e6ae01b813cb7ee40961f95f5be189c49\"\n\"c43fbf5c594f5968e4e820a1d38f105f2ff7a57e747e4d059ffb1d0788b7c3c772b9bc1f\"\n\"e147c723aca999015230d22c917730b935e902092f83e0a8e6db9a75d2626e0346e67e40\"\n\"8d5b815439dab8ccb8ea23f828fff6916c4047\",\n   \"32e0f5d40ceec1fbe45ddd151c76c0b3fef1c938\",\n},{\n   8432,\n\"084f04f8d44b333dca539ad2f45f1d94065fbb1d86d2ccf32f9486fe98f7c64011160ec0\"\n\"cd66c9c7478ed74fde7945b9c2a95cbe14cedea849978cc2d0c8eb0df48d4834030dfac2\"\n\"b043e793b6094a88be76b37f836a4f833467693f1aa331b97a5bbc3dbd694d96ce19d385\"\n\"c439b26bc16fc64919d0a5eab7ad255fbdb01fac6b2872c142a24aac69b9a20c4f2f07c9\"\n\"923c9f0220256b479c11c90903193d4e8f9e70a9dbdf796a49ca5c12a113d00afa844694\"\n\"de942601a93a5c2532031308ad63c0ded048633935f50a7e000e9695c1efc1e59c426080\"\n\"a7d1e69a93982a408f1f6a4769078f82f6e2b238b548e0d4af271adfa15aa02c5d7d7052\"\n\"6e00095ffb7b74cbee4185ab54385f2707e8362e8bd1596937026f6d95e700340b6338ce\"\n\"ba1ee854a621ce1e17a016354016200b1f98846aa46254ab15b7a128b1e840f494b2cdc9\"\n\"daccf14107c1e149a7fc27d33121a5cc31a4d74ea6945816a9b7a83850dc2c11d26d767e\"\n\"ec44c74b83bfd2ef8a17c37626ed80be10262fe63cf9f804b8460c16d62ae63c8dd0d124\"\n\"1d8aaac5f220e750cb68d8631b162d80afd6b9bf929875bf2e2bc8e2b30e05babd8336be\"\n\"31e41842673a66a68f0c5acd4d7572d0a77970f42199a4da26a56df6aad2fe420e0d5e34\"\n\"448eb2ed33afbfb35dffaba1bf92039df89c038bae3e11c02ea08aba5240c10ea88a45a1\"\n\"d0a8631b269bec99a28b39a3fc5b6b5d1381f7018f15638cc5274ab8dc56a62b2e9e4fee\"\n\"f172be20170b17ec72ff67b81c15299f165810222f6a001a281b5df1153a891206aca89e\"\n\"e7baa761a5af7c0493a3af840b9219e358b1ec1dd301f35d4d241b71ad70337bda42f0ea\"\n\"dc9434a93ed28f96b6ea073608a314a7272fefd69d030cf22ee6e520b848fa705ed6160f\"\n\"e54bd3bf5e89608506e882a16aced9c3cf80657cd03749f34977ced9749caa9f52b683e6\"\n\"4d96af371b293ef4e5053a8ea9422df9dd8be45d5574730f660e79bf4cbaa5f3c93a79b4\"\n\"0f0e4e86e0fd999ef4f26c509b0940c7a3eaf1f87c560ad89aff43cd1b9d4863aa3ebc41\"\n\"a3dd7e5b77372b6953dae497fc7f517efe99e553052e645e8be6a3aeb362900c75ce712d\"\n\"fcba712c4c25583728db9a883302939655ef118d603e13fcf421d0cea0f8fb7c49224681\"\n\"d013250defa7d4fd64b69b0b52e95142e4cc1fb6332486716a82a3b02818b25025ccd283\"\n\"198b07c7d9e08519c3c52c655db94f423912b9dc1c95f2315e44be819477e7ff6d2e3ccd\"\n\"daa6da27722aaadf142c2b09ce9472f7fd586f68b64d71fc653decebb4397bf7af30219f\"\n\"25c1d496514e3c73b952b8aa57f4a2bbf7dcd4a9e0456aaeb653ca2d9fa7e2e8a532b173\"\n\"5c4609e9c4f393dd70901393e898ed704db8e9b03b253357f333a66aba24495e7c3d1ad1\"\n\"b5200b7892554b59532ac63af3bdef590b57bd5df4fbf38d2b3fa540fa5bf89455802963\"\n\"036bd173fe3967ed1b7d\",\n   \"ee976e4ad3cad933b283649eff9ffdb41fcccb18\",\n},{\n   9224,\n\"bd8320703d0cac96a96aeefa3abf0f757456bf42b3e56f62070fc03e412d3b8f4e4e427b\"\n\"c47c4600bb423b96de6b4910c20bc5c476c45feb5b429d4b35088813836fa5060ceb26db\"\n\"bb9162e4acd683ef879a7e6a0d6549caf0f0482de8e7083d03ed2f583de1b3ef505f4b2c\"\n\"cd8a23d86c09d47ba05093c56f21a82c815223d777d0cabb7ee4550423b5deb6690f9394\"\n\"1862ae41590ea7a580dda79229d141a786215d75f77e74e1db9a03c9a7eb39eb35adf302\"\n\"5e26eb31ca2d2ca507edca77d9e7cfcfd136784f2117a2afafa87fa468f08d07d720c933\"\n\"f61820af442d260d172a0a113494ca169d33a3aeaacdcc895b356398ed85a871aba769f6\"\n\"071abd31e9f2f5834721d0fef6f6ee0fc0e38760b6835dfcc7dbefb592e1f0c3793af7ad\"\n\"f748786d3364f3cfd5686b1a18711af220e3637d8fad08c553ce9d5dc1183d48e8337b16\"\n\"1fe69b50e1920316dbffec07425b5d616a805a699576590e0939f5c965bce6c7342d314a\"\n\"c37b9c4d30166567c4f633f182de4d6b00e20a1c762789f915eaa1c89ac31b85222b1f05\"\n\"403dedd94db9ce75ff4e49923d1999d032695fa0a1c595617830c3c9a7ab758732fcec26\"\n\"85ae14350959b6a5f423ef726587e186b055a8daf6fa8fdefa02841b2fdbca1616dcee78\"\n\"c685fc6dcc09f24a36097572eba3c37a3eabe98bc23836085f63ef71a54b4488615d83b2\"\n\"6ed28c9fce78852df9b6cf8a75ca3899a7567298e91bc4ffdd04ffab0066b43b8286a4bb\"\n\"555c78808496b252c6e0e4d153631f11f68baf88630e052acc2af5d2af2e22e4f23bb630\"\n\"314c561a577455f86b6727bcad3c19d3e271404dec30af3d9dd0ed63cd9fa708aadfa12a\"\n\"500ef2d99a6b71e137b56ba90036975b88004b45f577ef800f0fb3cf97577dc9da37253b\"\n\"8675e5c8bb7e0bd26564f19eca232fb25f280f82e014424c9fbdd1411d7556e5d7906bb8\"\n\"62206316ba03385cd820c54c82ed35b36735bc486b1885d84053eba036c1ebfb5422d93d\"\n\"a71c53deda7f74db07cd4959cdfa898ba37080d76b564d344b124dd7b80cd70ed3b52a6c\"\n\"f9c9a32695d134bd39eb11ddeecdac86c808e469bd8a7995b667c452e7d9a54d5c85bcf6\"\n\"d5ffdc27d491bc06f438f02c7cf018073431587c78ba08d18a8daccb2d3b26136f612ade\"\n\"c673f3cd5eb83412b29652d55a10d0d6238d0b5365db272c917349450aff062c36191cfc\"\n\"d45660819083f89cd42ecae9e26934a020cafeb9b2b68d544edf59574c0ca159fd195dbf\"\n\"3e3e74244d942fffdbd4ed7f626219bab88b5a07e50b09a832d3e8ad82091114e54f2c35\"\n\"6b48e55e36589ebad3ac6077cb7b1827748b00670df65bbf0a2e65caad3f8a97d654d64e\"\n\"1c7dad171cafbc37110d2f7ca66524dc08fe60593e914128bd95f41137bfe819b5ca835f\"\n\"e5741344b5c907ce20a35f4f48726141c6398e753ed9d46d3692050628c78859d5014fe4\"\n\"dd3708e58d4d9807f8dac540492e32fa579491717ad4145c9efc24cf95605660b2e09b89\"\n\"9369b74d3ebff41e707917ff314d93e6ac8dfd643ef2c087cd9912005b4b2681da01a369\"\n\"42a756a3e22123cbf38c429373c6a8663130c24b24b2690b000013960b1c46a32d1d5397\"\n\"47\",\n   \"2df09b10933afedfcd3f2532dfd29e7cb6213859\",\n},{\n   10016,\n\"7a94978bec7f5034b12c96b86498068db28cd2726b676f54d81d8d7350804cc106bead8a\"\n\"252b465a1f413b1c41e5697f8cece49ec0dea4dfb9fa7b1bfe7a4a00981875b420d094bb\"\n\"1ce86c1b8c2e1dbebf819c176b926409fdec69042e324e71d7a8d75006f5a11f512811fe\"\n\"6af88a12f450e327950b18994dfc3f740631beda6c78bca5fe23d54e6509120e05cd1842\"\n\"d3639f1466cf26585030e5b4aefe0404fe900afc31e1980f0193579085342f1803c1ba27\"\n\"0568f80eaf92440c4f2186b736f6ab9dc7b7522ccdcfc8cf12b6375a2d721aa89b5ef482\"\n\"112a42c31123aebabcb485d0e72d6b6b70c44e12d2da98d1f87fa9df4f37847e1ffec823\"\n\"1b8be3d737d282ddb9cc4b95937acfa0f028ba450def4d134a7d0fc88119bf7296e18cd4\"\n\"4f56890b661b5b72ddfa34c29228067e13caf08eb3b7fd29de800df9a9ae137aad4a81a4\"\n\"16a301c9f74b66c0e163e243b3187996b36eb569de3d9c007d78df91f9b554eef0eaa663\"\n\"88754ce20460b75d95e2d0747229a1502a5652cf39ca58e1daa0e9321d7ab3093981cd70\"\n\"23a7ee956030dd70177028a66ad619ad0629e631f91228b7c5db8e81b276d3b168c1edb1\"\n\"bc0888d1cbcbb23245c2d8e40c1ff14bfe13f9c70e93a1939a5c45eef9351e795374b9e1\"\n\"b5c3a7bd642477ba7233e1f590ab44a8232c53099a3c0a6ffe8be8b7ca7b58e6fedf700f\"\n\"6f03dd7861ee1ef857e3f1a32a2e0baa591d0c7ca04cb231cc254d29cda873f00d68f465\"\n\"00d6101cfdc2e8004c1f333d8007325d06ffe6b0ff7b80f24ba51928e65aa3cb78752028\"\n\"27511207b089328bb60264595a2cebfc0b84d9899f5eca7ea3e1d2f0f053b4e67f975500\"\n\"7ff3705ca4178ab9c15b29dd99494135f35befbcec05691d91f6361cad9c9a32e0e65577\"\n\"f14d8dc66515081b51d09e3f6c25eea868cf519a83e80c935968cae6fce949a646ad53c5\"\n\"6ee1f07dda23daef3443310bc04670afedb1a0132a04cb64fa84b4af4b3dc501044849cd\"\n\"dd4adb8d733d1eac9c73afa4f7d75864c87787f4033ffe5ba707cbc14dd17bd1014b8b61\"\n\"509c1f55a25cf6c0cbe49e4ddcc9e4de3fa38f7203134e4c7404ee52ef30d0b3f4e69bcc\"\n\"7d0b2e4d8e60d9970e02cc69d537cfbc066734eb9f690a174e0194ca87a6fadad3883d91\"\n\"6bd1700a052b26deee832701590d67e6f78938eac7c4beef3061a3474dd90dd588c1cd6e\"\n\"6a4cda85b110fd08a30dcd85a3ebde910283366a17a100db920885600db7578be46bcfa6\"\n\"4765ba9a8d6d5010cb1766d5a645e48365ed785e4b1d8c7c233c76291c92ef89d70bc77f\"\n\"bf37d7ce9996367e5b13b08242ce73971f1e0c6ff2d7920fb9c821768a888a7fe0734908\"\n\"33efb854cbf482aed5cb594fb715ec82a110130664164db488666d6198279006c1aa521f\"\n\"9cf04250476c934eba0914fd586f62d6c5825b8cf82cd7ef915d93106c506ea6760fd8b0\"\n\"bf39875cd1036b28417de54783173446026330ef701c3a6e5b6873b2025a2c1666bb9e41\"\n\"a40adb4a81c1052047dabe2ad092df2ae06d6d67b87ac90be7d826ca647940c4da264cad\"\n\"43c32a2bb8d5e27f87414e6887561444a80ed879ce91af13e0fbd6af1b5fa497ad0cbd2e\"\n\"7f0f898f52f9e4710de2174e55ad07c45f8ead3b02cac6c811becc51e72324f2439099a0\"\n\"5740090c1b165ecae7dec0b341d60a88f46d7ad8624aac231a90c93fad61fcfbbea12503\"\n\"59fcd203862a6b0f1d71ac43db6c58a6b60c2c546edc12dd658998e8\",\n   \"f32e70862a16e3e8b199e9d81a9949d66f812cad\",\n},{\n   10808,\n\"88dd7f273acbe799219c23184782ac0b07bade2bc46b4f8adbd25ed3d59c0fd3e2931638\"\n\"837d31998641bbb7374c7f03d533ca60439ac4290054ff7659cc519bdda3dff2129a7bdb\"\n\"66b3300068931ade382b7b813c970c8e15469187d25cb04b635403dc50ea6c65ab38a97c\"\n\"431f28a41ae81c16192bd0c103f03b8fa815d6ea5bf0aa7fa534ad413b194eb12eb74f5d\"\n\"62b3d3a7411eb8c8b09a261542bf6880acbdfb617a42e577009e482992253712f8d4c8bd\"\n\"1c386bad068c7aa10a22111640041f0c35dabd0de00ebf6cd82f89cbc49325df12419278\"\n\"ec0d5ebb670577b2fe0c3e0840c5dd0dc5b3da00669eed8ead380f968b00d42f4967faec\"\n\"c131425fce1f7edb01cbec7e96d3c26fa6390a659e0ab069ef3edadc07e077bb816f1b22\"\n\"98830a0fe2b393693bb79f41feca89577c5230e0a6c34b860dc1fdb10d85aa054481082c\"\n\"494779d59ba798fcd817116c3059b7831857d0364352b354ce3b960fbb61a1b8a04d47ca\"\n\"a0ead52a9bea4bada2646cdbaec211f391dac22f2c5b8748e36bfc3d4e8ea45131ca7f52\"\n\"af09df21babe776fcecbb5c5dfa352c790ab27b9a5e74242bbd23970368dbefd7c3c74d1\"\n\"61ae01c7e13c65b415f38aa660f51b69ea1c9a504fe1ad31987cb9b26a4db2c37d7b326c\"\n\"50dbc8c91b13925306ff0e6098532dee7282a99c3ddf99f9e1024301f76e31e58271870b\"\n\"d94b9356e892a6a798d422a48c7fd5b80efe855a4925cc93b8cf27badec5498338e2b538\"\n\"70758b45d3e7a2fa059ed88df320a65e0a7cf87fa7e63b74cea1b7371e221f8004726642\"\n\"30d4d57945a85b23d58f248c8cd06ccfabfa969ab8cb78317451fab60e4fdfa796e2e2a8\"\n\"b46405839a91266d37e8d38bae545fb4060c357923b86d62f5d59d7bef5af20fbb9c7fb4\"\n\"2c6fd487748ed3b9973dbf4b1f2c9615129fa10d21cc49c622842c37c01670be71715765\"\n\"a98814634efbdee66bf3420f284dbd3efafc8a9117a8b9a72d9b81aa53ded78c409f3f90\"\n\"bad6e30d5229e26f4f0cea7ee82c09e3b60ec0e768f35a7fb9007b869f9bfc49c518f648\"\n\"3c951d3b6e22505453266ec4e7fe6a80dbe6a2458a1d6cd93044f2955607412091009c7d\"\n\"6cd81648a3b0603c92bfdff9ec3c0104b07ed2105962ca7c56ede91cb932073c337665e2\"\n\"409387549f9a46da05bc21c5126bd4b084bc2c06ab1019c51df30581aa4464ab92978c13\"\n\"f6d7c7ac8d30a78f982b9a43181bbe3c3eb9f7a1230b3e53b98a3c2a028317827fbe8cf6\"\n\"ec5e3e6b2a084d517d472b25f72fab3a34415bba488f14e7f621cfa72396ba40890e8c60\"\n\"b04815601a0819c9bebc5e18b95e04be3f9c156bd7375d8cc8a97c13ce0a3976123419fa\"\n\"592631317ca638c1182be06886f9663d0e8e6839573df8f52219eeb5381482a6a1681a64\"\n\"173660bfbb6d98bf06ee31e601ee99b4b99b5671ed0253260b3077ed5b977c6a79b4ff9a\"\n\"08efd3cba5c39bec1a1e9807d40bbf0c988e0fd071cf2155ed7b014c88683cd869783a95\"\n\"4cbfced9c0e80c3a92d45b508985cbbc533ba868c0dc4f112e99400345cf7524e42bf234\"\n\"5a129e53da4051c429af2ef09aba33ae3c820ec1529132a203bd2b81534f2e865265f55c\"\n\"9395caf0e0d3e1762c95eaaec935e765dc963b3e0d0a04b28373ab560fa9ba5ca71ced5d\"\n\"17bb8b56f314f6f0d0bc8104b3f1835eca7eaac15adf912cf9a6945cfd1de392342dd596\"\n\"d67e7ffcb7e086a6c1ea318aa2e0c2b5c2da079078232c637de0d317a1f26640bc1dac5b\"\n\"e8699b53edc86e4bfdfaf797a2ae350bf4ea29790face675c4d2e85b8f37a694c91f6a14\"\n\"1fd561274392ee6ee1a14424d5c134a69bcb4333079400f03615952fc4c99bf03f5733a8\"\n\"dc71524269fc5c648371f5f3098314d9d10258\",\n   \"08632c75676571a5db5971f5d99cb8de6bf1792a\",\n},{\n   11600,\n\"85d43615942fcaa449329fd1fe9efb17545eb252cac752228f1e9d90955a3cf4e72cb116\"\n\"3c3d8e93ccb7e4826206ff58b3e05009ee82ab70943db3f18a32925d6d5aed1525c91673\"\n\"bd33846571af815b09bb236466807d935b5816a8be8e9becbe65d05d765bcc0bc3ae66c2\"\n\"5320ebe9fff712aa5b4931548b76b0fd58f6be6b83554435587b1725873172e130e1a3ca\"\n\"3d9d0425f4632d79cca0683780f266a0633230e4f3b25f87b0c390092f7b13c66ab5e31b\"\n\"5a58dbcac8dd26a0600bf85507057bb36e870dfae76da8847875a1a52e4596d5b4b0a211\"\n\"2435d27e1dc8dd5016d60feaf2838746d436a2983457b72e3357059b2bf1e9148bb0551a\"\n\"e2b27d5a39abd3d1a62c36331e26668e8baabc2a1ef218b5e7a51a9ca35795bcd54f403a\"\n\"188eafafb30d82896e45ddaea4f418629a1fb76a0f539c7114317bac1e2a8fba5a868bce\"\n\"40abd40f6b9ced3fa8c0329b4de5ca03cc84d75b8746ef31e6c8d0a0a79b4f747690928e\"\n\"be327f8bbe9374a0df4c39c845bf3322a49fda9455b36db5a9d6e4ea7d4326cf0e0f7cd8\"\n\"0ff74538f95cec01a38c188d1243221e9272ccc1053e30787c4cf697043cca6fc3730d2a\"\n\"431ecbf60d73ee667a3ab114c68d578c66dc1c659b346cb148c053980190353f6499bfef\"\n\"acfd1d73838d6dc1188c74dd72b690fb0481eee481a3fd9af1d4233f05d5ae33a7b10d7d\"\n\"d643406cb1f88d7dd1d77580dcbee6f757eeb2bfbcc940f2cddb820b2718264b1a64115c\"\n\"b85909352c44b13d4e70bbb374a8594d8af7f41f65b221bf54b8d1a7f8f9c7da563550cb\"\n\"2b062e7a7f21d5e07dd9da8d82e5a89074627597551c745718094c2eb316ca077526d27f\"\n\"9a589c461d891dc7cd1bc20ba3f464da53c97924219c87a0f683dfb3b3ac8793c59e78ac\"\n\"fac109439221ac599a6fd8d2754946d6bcba60784805f7958c9e34ff287ad1dbbc888848\"\n\"fa80cc4200dbb8c5e4224535906cbffdd0237a77a906c10ced740f9c0ce7821f2dbf8c8d\"\n\"7d41ecfcc7dfdc0846b98c78b765d01fb1eb15ff39149ab592e5dd1152665304bba85bbf\"\n\"4705751985aaaf31245361554d561a2337e3daeef58a826492fd886d5f18ef568c1e772e\"\n\"f6461170407695e3254eb7bf0c683811ddde5960140d959114998f08bdb24a104095987d\"\n\"3255d590e0dbd41ae32b1ae4f4ea4a4f011de1388034231e034756870c9f2d9f23788723\"\n\"27055a7de2b5e931dfb53e7780b6d4294bf094e08567025b026db9203b681565a1d52f30\"\n\"318d0ebe49471b22ba5fd62e1ed6c8966c99b853c9062246a1ace51ef7523c7bf93bef53\"\n\"d8a9cb96d6a04f0da1eca888df66e0380a72525a7ecc6115d08569a66248f6ba34e2341b\"\n\"fd01a78f7b3c1cfe0754e0d26cba2fa3f951ef14d5749ff8933b8aba06fa40fb570b467c\"\n\"54ce0d3f0bed21e998e5a36b3bc2f9e1ae29c4bab59c121af6fad67c0b45959cd6a86194\"\n\"14b90b4535fb95f86ca7e64502acc135eff4f8a3abe9dde84238fab7a7d402454a3f07ad\"\n\"ec05ec94b2891e0879037fae6acaa31dcecf3f85236ade946f5ad69ad4077beb65099285\"\n\"38ee09f2bc38e5704da67b5006b5e39cd765aafcd740c7dadb99d0c547126e1324610fcb\"\n\"7353dac2c110e803fca2b17485b1c4b78690bc4f867e6f043b2568889f67985a465a48eb\"\n\"ee915200589e915756d4968d26529c3ffe3dbe70e84c682ad08a0c68db571634fbb0210d\"\n\"c1b16b8b725886465c8c51f36a5e27d0f78e5643e051d3bddd512ce511f6bdf3dfe42759\"\n\"00c5fea9d248c2b3f36911ed0ff41a19f6445521f251724657ea8f795b3ead0928a1657f\"\n\"308dd7c7c1e7e490d9849df43becfa5cc25ed09ef614fd69ddc7e5e3147623901d647876\"\n\"fb60077ffc48c51ed7d02b35f6802e3715fc708a0c88b82fe9cba0a442d38d09ca5ae483\"\n\"21487bdef1794e7636bf7457dd2b51a391880c34d229438347e5fec8555fe263f08ba87b\"\n\"b16dcde529248a477628067d13d0cb3bf51776f4d39fb3fbc5f669e91019323e40360e4b\"\n\"78b6584f077bf9e03b66\",\n   \"ab7213f6becb980d40dc89fbda0ca39f225a2d33\",\n},{\n   12392,\n\"7ae3ca60b3a96be914d24980fb5652eb68451fed5fa47abe8e771db8301fbd5331e64753\"\n\"93d96a4010d6551701e5c23f7ecb33bec7dd7bade21381e9865d410c383a139cb4863082\"\n\"8e9372bd197c5b5788b6599853e8487bddfd395e537772fdd706b6a1de59c695d63427da\"\n\"0dc3261bce2e1ae3cd6de90ec45ecd7e5f14580f5672b6ccd8f9336330dffcd6a3612a74\"\n\"975afc08fb136450e25dc6b071ddfc28fca89d846c107fd2e4bd7a19a4ff6f482d62896d\"\n\"a583c3277e23ab5e537a653112cdf2306043b3cc39f5280bd744fe81d66f497b95650e7d\"\n\"dfd704efcb929b13e00c3e3a7d3cd53878af8f1506d9de05dba9c39a92604b394ea25acb\"\n\"a2cda7b4ae8b08098ba3f0fdea15359df76517be84377f33631c844313ac335aa0d590fe\"\n\"c472d805521f0905d44ca40d7391b292184105acd142c083761c1a038c4f5ed869ea3696\"\n\"99592a37817f64cb4205b66be1f1de6fa47a08e1bf1a94312fe61a29e71bab242af95a7b\"\n\"38d4fb412c682b30256d91e2a46b634535d02b495240cbdb842cbe17cba6a2b94073f3d5\"\n\"f9621ac92ddda66f98bed997216466b4bb0579d58945f8d7450808d9e285d4f1709d8a1d\"\n\"416aa57d4a1a72bfcbfecdda33de2cff3e90e0cc60c897c4663224fc5bbe8316a83c1773\"\n\"802837a57bc7e9238173ed41ea32fe5fe38e546014a16d5e80700d9bac7a84bb03902f31\"\n\"79e641f86f6bc383d656daf69801499633fb367ea7593195934c72bc9bf9624c0c845ebf\"\n\"c36eb7ad4b22fdfb45ca7d4f0d6708c69a21f6eaa6db6bde0f0bd9dc7ec9c6e24626d0a7\"\n\"8fbeeed4b391f871e80e6a9d207165832d4ff689296f9bca15dc03c7c0381659ea5335eb\"\n\"aafdc3e50d18e46b00f1844870d09c25afcdb0ff1ae69dd8f94f91aca6095ba6f2b6e594\"\n\"c4acfe9903485d21b684e31a6acc2162d40e1a7bb8114a860a07e76f5265666555f2418d\"\n\"f11ef8f7499656d12215f5da8d7d041ac72648d15d7661ad93b24f3f071334b0921d5bb0\"\n\"6f2c7ab09f5034518b5ae21cec379373e87d51c77d44a70c2337606aadeb9036716fd920\"\n\"a824e7ae18ce3de9f0ec3456f3454027d8c476b3f1854b240c309f6f9786fa8a073915d9\"\n\"7a019ce99aec3260c5f6b6346cd9c41cb9267f4475958e45289965548238c6b9f91a8784\"\n\"b4e0957ba8b73956012c9a2fc3428434b1c1679f6ed2a3e8e2c90238df428622046f668e\"\n\"e2b053f55e64ffd45600e05a885e3264af573bacee93d23d72a0222b5442ac80bc0a8b79\"\n\"4c2afcf3bc881d20c111f57e3450b50a703f3db1fc5de2076a006f3b7eed694b93269874\"\n\"3b03c2ed2684bad445e69a692e744c7ac3a04f1e0e52b7a6708076d1fbffdb3f1c995828\"\n\"7d5f884e29407030f2db06811092efd80ae08da9daec39744c5ecd3ca771663b8f4968d4\"\n\"2a88c2c9821c73ae2a5a4d9e2551f82c03583b9c4dea775423b4748d24eb604e8ee3159b\"\n\"a6de9bea5b22eed6264e011734ed02b2c74ce06dda890b8604ed7ba49e7bf30e28c9871b\"\n\"e90f5cead67eaf52b5d3181c822b10701219b28ef6f6bebfa278e38acf863e2a1d4b1e40\"\n\"fd8a0ac6ce31054446301046148bf10dc3ae3385e2026e7762bdc8003ffebc4263191a59\"\n\"c72f4f90db03e7d52808506b33bfe1dfa53f1a3daa152e83974fbe56cfd4e8f4e7f7806a\"\n\"084b9d0795b858100eced0b5355a72446f37779d6c67ade60a627b8077ae1f3996b03bc3\"\n\"a5c290651c8609f0d879fbf578cbab35086e1159dd6ddbe3bf7fb5654edcc8f09e4f80d0\"\n\"258c9376d7c53fb68f78d333b18b70170d9a11070790c956f5744c78c986b1baf08b7631\"\n\"7a65c5f07ae6f57eb0e65488659324d29709e3735623d0426e90aa8c4629bb080881150c\"\n\"02be1c004da84414ac001c2eb6138c26388f5a36d594f3acef0e69e2cb43b870efa84da0\"\n\"cff9c923a9880202aed64ad76260f53c45bb1584b3e388a909d13586094b924680006a1d\"\n\"25d4dd36c579a8ec9d3fa63c082d977a5a5021440b5314b51850f2daa6e6af6ae88cb5b1\"\n\"44242bceb1d4771e641101f8abfc3a9b19f2de64e35e76458ad22072ba57925d73015de5\"\n\"66c66fcaa28fdc656f90de967ad51afd331e246d74ed469d63dd7d219935c59984bd9629\"\n\"09d1af296eb3121d782650e7d038063bab5fa854aac77de5ffebeb53d263f521e3fc02ac\"\n\"70\",\n   \"b0e15d39025f5263e3efa255c1868d4a37041382\",\n},{\n   13184,\n\"fa922061131282d91217a9ff07463843ae34ff7f8c28b6d93b23f1ea031d5020aa92f660\"\n\"8c3d3df0ee24a8958fd41af880ee454e36e26438defb2de8f09c018607c967d2f0e8b80a\"\n\"00c91c0eabe5b4c253e319b45e6106ff8bf0516f866020e5ba3f59fd669c5aeff310ebb3\"\n\"85007069d01c64f72d2b02f4ec0b45c5ecf313056afcb52b17e08b666d01fecc42adb5b4\"\n\"9ea00c60cacac2e0a953f1324bdd44aec00964a22a3cb33916a33da10d74ec6c6577fb37\"\n\"5dc6ac8a6ad13e00cba419a8636d4daac8383a2e98fe90790cde7b59cfaa17c410a52abc\"\n\"d68b127593d2fcbafd30578d195d890e981ae09e6772cb4382404a4e09f1a33c958b57db\"\n\"ccee54ae335b6c91443206a0c100135647b844f226417a1f70317fd350d9f3789d81894a\"\n\"aff4730072401aaeb8b713ead4394e2e64b6917d6eee2549af7bd0952f12035719065320\"\n\"ca0d2dfe2847c6a2357c52bee4a676b12bafff66597bd479aa29299c1896f63a7523a85a\"\n\"b7b916c5930ab66b4d191103cefc74f2f7e0e96e354f65e355ae43959a0af1880d14ea9d\"\n\"1569e4fd47174aba7f5decb430b3f6baf80a1ef27855227b62487250d3602970e423423c\"\n\"7ca90920685bcf75adfbe2a61ce5bd9228947b32f567927cb1a5bd8727c03aef91d6367b\"\n\"ae7d86fd15c0977ac965a88b0d7236037aefb8d24eec8d2a07c633e031a7b9147c4c7714\"\n\"110bfc7e261448a5d0f73c3619664e1c533c81a0acbf95d502227a33f84f0b8249e3f9fa\"\n\"5c7905a8192b7313fc56bb20679e81333d32c797ac5162204a0eaa0e64507635921c485b\"\n\"8f17c4e2484667a733197529e2a833eed83c57229b11bd820b5a5b78f1867787dbc217ea\"\n\"28bfba785fb545cbc5a840a12eea428213e1aaa4e50a900ba13efcf4a5345574c2481c5d\"\n\"927ada610bba567a55630c89d905db3d9b67fe36c9cc3d6a947664c83e69f51c74711a33\"\n\"df66dd3ff6af9b7c1605b614d4798b4192b9a4b1508f2e2ec5aaad7eaea1ee8867353db9\"\n\"b8d7d9a6f16aa5f339492073238c979082879aee7f94ac4be8133eaacbaedfb044e2ad4e\"\n\"93ba0fa071dea615a5cd80d1d2678f4f93ae5a4bc9cdf3df345a29ec41d8febb23805ce4\"\n\"2541036f3f05c63ae736f79a29802045fad9f370cabf843458c1b636ca41f387fd7821c9\"\n\"1abbd1946afcb9186b936403233f28a5b467595131a6bc07b0873e51a08de66b5d7709a6\"\n\"02c1bd0e7f6e8f4beb0579c51bda0e0c738ef876fcd9a40ab7873c9c31c1d63a588eebc7\"\n\"8d9a0ae6fa35cd1a269e0d2bc68252cbd7c08d79e96f0aa6be22a016136a2b8abe9d3c9c\"\n\"f9d60eeafe3dbc76d489b24d68c36167df4c38cf2b21cf03dc5e659e39018c3490f1237e\"\n\"ca3f85b742ab0045d86a899c4126ad60a147cbc95b71814c274d6478668df41eb32acfb4\"\n\"bbf024fb4e3d6be0b60653a0471afc3037ab67dcb00a2b2e24b26911e1880136e56106b7\"\n\"f3c570fbe6f311d94624cb001914ff96fbbf481f71686aa17be0850568058fc1ee8900b4\"\n\"7af5cf51c5ed9e00a8b532c131f42513f6b8df14a9bbc2e9ede5a560681184d41a147552\"\n\"edfbdef98d95e6a7793229d25ba9b0b395a020aa1c0731de89e662246d59ec22e5d8f4b4\"\n\"6fbc048efcffbc234744c5c66417070f9c751c81788f04691ccb1a09d60c46f6f73375bf\"\n\"e2e646cf6290069541a8dfe216374c925e94d06ece72e851e81d3e8acd011f82526c2f9f\"\n\"55955c6752dc10e93153ab58627e30fa2c573e4042954337982eec1f741be058c85bad86\"\n\"bf3a02ed96d3201dadd48bd4de8105200dfcbcc400c3c3dd717abfc562ebe338b14b1eb5\"\n\"ecbe9227661e49c58bf8233770d813faafc78b05711135adcc4ce4c65095ca0bdc1debc0\"\n\"b6e5d195dbc582ce94b3afa14a422edf9b69abd7ae869a78c3a26fb50ef7122ec5af8d0c\"\n\"78ef082ca114f8817c3d93b31809870caea2eb9533fa767c2954efb9ba07e4f1077e9f9b\"\n\"be845661eabea2c91079321477a7c167c7234528d63d6aabbe723e0e337b2e61138a310a\"\n\"3fd04368aa4215b7af9d0334a8a74681bcb86b4af87a0329a1ed9dc7c9aef14521785eda\"\n\"0eeb97bdff8c9945fd0ee04e84d0dae091a69c0bfcdcd4150878fed839c0db6565fc1fed\"\n\"0e7d6ae2efde7a59d58a9fb3b07e6f7cea51ba93f771c18b2eafa252d7fe171085776052\"\n\"a6a17e6858f0a20b7e8be54413523989bf20a028a84d9ce98b78e6ee0b8362df49de5344\"\n\"b409cc322354672a21ea383e870d047551a3af71aaf2f44f49a859cf001e61b592dd036f\"\n\"c6625bf7b91ea0fb78c1563cceb8c4345bf4a9fbe6ee2b6bf5e81083\",\n   \"8b6d59106f04300cb57c7c961945cd77f3536b0a\",\n},{\n   13976,\n\"162cca41155de90f6e4b76a34261be6666ef65bdb92b5831b47604ce42e0c6c8d2eda265\"\n\"ab9a3716809bf2e745e7831a41768d0f6349a268d9ac6e6adfb832a5d51b75d7951cf60e\"\n\"03d9e40de6d351f1f6ade5143531cf32839401ca6dfb9dc7473daa607aeb0c3d1e8eb3db\"\n\"cc2f1231ad1dd394d7eac9d8dab726b895b1ee774fdcabc8031063ecfa41c71a9f03ad23\"\n\"904cc056f17c76a1059c43faffe30dfd157fdfd7d792e162bf7a889109550a0fc4c41523\"\n\"2af0c0d72dcbc2595299e1a1c2aeae549f7970e994c15e0ab02f113d740d38c32a4d8ec0\"\n\"79cd099d37d954ab7ef2800902cdf7c7a19fb14b3c98aaf4c6ad93fe9a9bc7a61229828e\"\n\"55ad4d6270d1bdbca9975d450f9be91e5699bd7ee22e8c9c22e355cf1f6793f3551cb510\"\n\"c1d5cd363bdf8cab063e6e49a6383221f1188d64692c1f84c910a696de2e72fb9886193f\"\n\"61ab6b41ad0ea894d37ff1261bf1fd1f187e0d0c38ab223d99ec6d6b1e6b079fc305e24e\"\n\"2d9500c98676e2d587434495d6e107b193c06fb12d5d8eaa7b0c001d08f4d91cae5bdcae\"\n\"6624ee755e95ca8e4c5ef5b903d7f5ba438abeffd6f16d82d88138f157e7a50d1c91fb50\"\n\"c770f6d222fcbf6daf791b1f8379e3b157a3b496ddb2e71650c1c4ac4fc5f2aceb5b3228\"\n\"ffc44e15c02d4baa9434e60928a93f21bc91cfd3c2719f53a8c9bcd2f2dee65a8bbc88f9\"\n\"5d7ced211fc3b04f6e8b74eb2026d66fd57fa0cccea43f0a0381782e6fee5660afed674d\"\n\"cb2c28cb54d2bdbbaf78e534b0742ede6b5e659b46cd516d5362a194dd0822f6417935c4\"\n\"ff05815b118fe5687cd8b050240015cfe449d9dfde1f4fdb105586e429b2c1849aac2791\"\n\"ef73bc54603190eba39037ec057e784bb92d497e705dfcde2addb3514b4f1926f12d5440\"\n\"850935779019b23bd0f2977a8c9478c424a7eaaeec04f3743a77bee2bec3937412e707bc\"\n\"92a070046e2f9c35fe5cc3f755bbb91a182e683591ab7e8cff40633730546e81522f588f\"\n\"07bdf142b78e115d2a22d2eb5664fcdb7574c1ee5ba9abd307d7d29078cd5223c222fc69\"\n\"60324c40cc639be84dad96b01059efce7b08538ebef89bafab834609c7e82774a14e5be6\"\n\"62067edba6111efa8ae270f5066442b17e3f31a793581c8a3f96d92921ec26981594e28a\"\n\"08987d020b97ad2ba5c662836e35fd3fd954bcec52b579528913959d0d942fbf1c4b9910\"\n\"ba010c3700359a4eb7616541257f0f7727cc71b580cc903f718ecc408a315b6bbfa7f6e3\"\n\"beb9d258804bd2731ee2fb75e763281baf1effc4690a23d5f952ab5d4311d4f5885af2eb\"\n\"f27cad9f6d84692cb903064bbd11ca751f919b4811b7722c6ec80c360521e34d357b5c8b\"\n\"ba6d42e5c632730f53add99ab8aa9c607b6796216753086ede158bc670d04900aca66ce8\"\n\"357bd72d19fb147b5fde8ee4df6a0184573a2e65ba3fd3a0cb04dac5eb36d17d2f639a6e\"\n\"b602645f3ab4da9de4c9999d6506e8e242a5a3216f9e79a4202558ecdc74249ad3caaf90\"\n\"71b4e653338b48b3ba3e9daf1e51e49384268d63f37ce87c6335de79175cdf542d661bcd\"\n\"74b8f5107d6ab492f54b7c3c31257ecb0b426b77ed2e2ed22bbfdaf49653e1d54e5988fa\"\n\"d71397546f9955659f22b3a4117fc823a1e87d6fb6fb8ab7d302a1316975e8baf0c0adbd\"\n\"35455655f6a596b6ac3be7c9a8ea34166119d5e70dfbc1aa6e14ff98eff95e94ef576656\"\n\"5d368ec8857fb0b029bcb990d420a5ca6bc7ab08053eb4dbfc4612a345d56faefc5e03a4\"\n\"43520b224de776a5b618e1aa16edc513d5fcefcd413031b0ddc958a6fca45d108fbde065\"\n\"3cf2d11cb00a71cd35f57993875598b4e33e2384623a0986859105d511c717c21d6534bf\"\n\"69fd3d7cf1682e4fc25298d90df951e77a316996beac61bb7078988118c906548af92cfe\"\n\"72cd4b102ffad584e5e721a0cdb5621ed07dda8955d84bea57a5afa4ba06289ddfac3a9e\"\n\"765538fd9392fc7904cedb65e38cd90967f01845ff819777a22d199f608e62c13e6ba98b\"\n\"40824b38c784bdb41d62c4014fc7e8d93be52695e975e54d1ff92b412f451177143d74a6\"\n\"bde0ee53a986043ab465a1ef315ac4c538e775ef4178fde5f2ea560a364de18b8fe9578a\"\n\"ad80027c3fd32dcf0967d9d03789b1cdf19040762f626289cf3af8afe5a8e0a152d9258e\"\n\"981872c1ec95cd7f8d65812e55cb5cbd8db61b3f068a23d9652372dfbf18d43a663c5a0d\"\n\"026b0898e383ce5c95b0ba7fb5ed6b7304c7c9d3ba64f38d1dc579465148ccfa7271f2e3\"\n\"e0e97e9ddac7c0874f0f396cf07851638a734df393687b7b0343afd1652ff32a2da17b3a\"\n\"4c99d79c02256c73f32625527e5666594a8a42a12135eddb022e743371b3ab7b12ad6785\"\n\"7635eed03558ac673d17280769b2368056276d5d72f5dbc75525f8a7558bd90b544aa6cb\"\n\"dd964e6c70be79441969bfdf471f17a2dc0c92\",\n   \"6144c4786145852e2a01b20604c369d1b9721019\",\n},{\n   14768,\n\"c9bed88d93806b89c2d028866842e6542ab88c895228c96c1f9f05125f8697c7402538b0\"\n\"6465b7ae33daef847500f73d20c598c86e4804e633e1c4466e61f3ed1e9baadc5723bbed\"\n\"9455a2ff4f99b852cfe6aa3442852ade0b18e4995ddab4250928165a9441de108d4a293d\"\n\"1d95935de022aa17f366a31d4f4c4c54557a4235a9d56473444787ddc5c06c87087aef24\"\n\"fa8280b7ac74d76ba685e4be7dc705e5a8a97c6c8fbd201ee5bf522438d23371c60c155d\"\n\"93352f8fb8cc9421fe4b66ffabad46909c2c1099944fc55ed424c90aecca4f50d0331153\"\n\"2e2844c3ff8ecb495de7ab26941cbf177b79ad7b05f918b713c417da8cf6e67db0a2dcee\"\n\"a9179d8d636191759e13955f4244f0c4f2d88842e3015641ef0417d6e54144e8246e4591\"\n\"6823e2c6e39bfa3b90b97781c44981710689f2ce20e70a26760d65f9971b291e12338461\"\n\"8b3b56710dde2afaa2d46b0e2164d5c9482729350a0e256b2aa6b3fb099b618ebd7c11ca\"\n\"62bdf176b502aedfdf9be57a8e4adbca4a4d6d8407984af2f6635f95a1e4930e375eb53f\"\n\"245ab2ade5340c281bda87afded1268e537955c9819168bd60fd440533c75c9b1865e03f\"\n\"de3a301d165f97aa6da236cf39cf3e49512f6350224f8d76ff02d0d3b9a99e5f70b23b9f\"\n\"a85f72849fc98790df246c3a0f4437940e60d42b4317f72e2eb055d343a614f7f9648005\"\n\"1e4dff186dff476462d9ced24dbb82eaa60cbbf6a0026e64001da36d30f529f48f3688b1\"\n\"0ce9378ef3f50f5106e5007cd0eb037136254fda4f20d048769bd51a9d8d09a1e469a482\"\n\"6aa0e25b6267b5a96abcb6e919a362fdd7b683d2f2dcec40ee5969311c07f6066ee22f36\"\n\"89ca08381c85bea470040e9541e7a451cd43d62c2aa292a9dc4b95e3a7c4de2ba29663f3\"\n\"8d5002eb64ceba6934bb1b0e2e55fba7fa706b514ebeeae1be4dd882d6512da066246a05\"\n\"1d8bd042593bd0513e9cc47806ccdc7097e75bc75b8603834c85cd084e0ade3cc2c2b7e8\"\n\"586eac62249f9769f5bdcd50e24e515f257548762db9adf3ee0846d67cfcd723d85d9588\"\n\"09e6dd406f4c2637557c356fc52490a2a0763429ee298a1c72c098bb810e740c15faffc6\"\n\"1e80cf6e18f86dc0e29bc150ce43ca71f5729356cd966277fd8b32366f6263c3a761b13d\"\n\"544a631a25e1c4c8dea8d794abed47ccb4069d20f1dcb54e40a673ffb5f7b2eb31fb7d44\"\n\"36fd8252f92dc35bb9a18fc55099b17e0807e79caf4f9641ee4bbbc2d6922508bcfae236\"\n\"475bf78bc796548bc8d60659e816af68e5e43352fa64b5086c97c22c60ddcbbbefb9d9ef\"\n\"7cd57c64454604793910f4f90aedb4fb824a86061a93bb79c9b0272a1ad0d24e8165f099\"\n\"ef6f14a6a4fea09845f280022e061804090d7ab79f7bddcbef264b6f7d4e9971eddb9ca7\"\n\"d0e79a8dbe7cff2fa59f514a608d66ae8c44d5e69745aa1b19995e366812064567d3ca20\"\n\"9e12994c901d1b1f489be7253615f7c339b5581afd4d262e879ab8480ecb18990d3db61f\"\n\"96895dcde9c065e645f52baafefcbe34d072dba373fd1c786fd56c3f3284be7260eaff9a\"\n\"6a8348b762ed59e20ea443313b1164db53c3989c32fcae5b366f190b9548e8cff46df961\"\n\"350369b490354ed8e530a91f5072967eff45c63540862fb2deab02b3ae05deac65414368\"\n\"ac3549f277da92b692947de47cba9c1579526931e31c3490c1d3605f9bafcf468c2e9b47\"\n\"981407ea40b0b59754621943095a2d4f4ba266ac545fe7447e54f69555a7ac9ff1e8f001\"\n\"834fa65f2d4523061726e4d3bf4680519032dc21b7389e9f3229e4c2295d354482f8b803\"\n\"b06ca3a8cb3ff786e60f6bc59dd3a5bfed63b0aa493bab78e97bbefb6633534d84de826f\"\n\"4e2ccc3069050d50a2caace6c9de15ffc2656988d94b736e5688df0351a3a6a4c875cd99\"\n\"ef304f3cc7a0585df2b0b3e6c62f86bba0d43de47b80c4eec1c4f98e60a36188219919cf\"\n\"36dc10ee11e174a67d226ad9e71f02a7fca26ad67a4862773f3defc6a747545314063e5f\"\n\"ce7a3f890ec57daa5532acfd027739832437c8a58dcbe11c2842e60e8ca64979d081fbd5\"\n\"a1a028f59317212fb5869abc689a156171d69e4f4c93b949c3459904c00192d3603cd184\"\n\"48d64b843c57f34aee7830f313e58e2abc41b44be46a96c845ffebcb7120e21d1d751046\"\n\"c072adf65dd901a39c8019742054be5e159ea88d0885ee05fcd4c189bafe5abb68603186\"\n\"5dc570b9342fa7f41fd5c1c87e68371ab19a83c82ae1d890c678102d5da8e6c29845657c\"\n\"027ba07362cba4d24950ab38e747925e22ce8df9eaec1ae2c6d23374b360c8352feb6cb9\"\n\"913e4fc49bde6caf5293030d0d234a8ecd616023cc668262591f812de208738e5336a9e6\"\n\"9f9be2479b86be1e1369761518dfc93797ed3a55308878a944581eba50bc9c7f7a0e75c7\"\n\"6a28acd95b277857726f3f684eefc215e0a696f47d65d30431d710d957c08ef96682b385\"\n\"0ee5ba1c8417aafc1af2846a127ec155b4b7fb369e90eb3a5c3793a3389bbc6b532ca32b\"\n\"f5e1f03c2280e71c6e1ae21312d4ff163eee16ebb1fdee8e887bb0d453829b4e6ed5fa70\"\n\"8f2053f29b81e277be46\",\n   \"a757ead499a6ec3d8ab9814f839117354ae563c8\"\n}\n};\n\nvoid test_sha1(void)\n{\n   unsigned char buffer[4000];\n   int i;\n   for (i=0; i < sizeof(sha1_tests) / sizeof(sha1_tests[0]); ++i) {\n      stb_uint len = sha1_tests[i].length / 8;\n      unsigned char digest[20], fdig[20];\n      unsigned int h;\n      assert(len <= sizeof(buffer));\n      assert(strlen(sha1_tests[i].message) == len*2);\n      assert(strlen(sha1_tests[i].digest) == 20 * 2);\n      for (h=0; h < len; ++h) {\n         char v[3];\n         v[0] = sha1_tests[i].message[h*2];\n         v[1] = sha1_tests[i].message[h*2+1];\n         v[2] = 0;\n         buffer[h] = (unsigned char) strtol(v, NULL, 16);\n      }\n      stb_sha1(digest, buffer, len);\n      for (h=0; h < 20; ++h) {\n         char v[3];\n         int res;\n         v[0] = sha1_tests[i].digest[h*2];\n         v[1] = sha1_tests[i].digest[h*2+1];\n         v[2] = 0;\n         res = digest[h] == strtol(v, NULL, 16);\n         c(res, sha1_tests[i].digest);\n         if (!res)\n            break;\n      }\n      {\n         int z;\n         FILE *f = fopen(\"data/test.bin\", \"wb\");\n         if (!f) stb_fatal(\"Couldn't write to test.bin\");\n         fwrite(buffer, len, 1, f);\n         fclose(f);\n         #ifdef _WIN32\n         z = stb_sha1_file(fdig, \"data/test.bin\");\n         if (!z) stb_fatal(\"Couldn't digest test.bin\");\n         c(memcmp(digest, fdig, 20)==0, \"stb_sh1_file\");\n         #endif\n      }\n   }\n}\n\n\n#if 0\n\nstb__obj zero, one;\n\nvoid test_packed_floats(void)\n{\n   stb__obj *p;\n   float x,y,*q;\n   clock_t a,b,c;\n   int i;\n   stb_float_init();\n   for (i=-10; i < 10; ++i) {\n      float f = (float) pow(10,i);\n      float g = f * 10;\n      float delta = (g - f) / 10000;\n      while (f < g) {\n         stb__obj z = stb_float(f);\n         float k = stb_getfloat(z);\n         float p = stb_getfloat_table(z);\n         assert((z & 1) == 1);\n         assert(f == k);\n         assert(k == p);\n         f += delta;\n      }\n   }\n\n   zero = stb_float(0);\n   one  = stb_float(1);\n\n   p = malloc(8192 * 4);\n   for (i=0; i < 8192; ++i)\n      p[i] = stb_rand();\n   for (i=0; i < 8192; ++i)\n      if ((stb_rand() & 31) < 28)\n         p[i] = zero;\n\n   q = malloc(4 * 1024);\n      \n   a = clock();\n\n   x = y = 0;\n   for (i=0; i < 200000000; ++i)\n      q[i&1023] = stb_getfloat_table(p[i&8191]);\n   b = clock();\n   for (i=0; i < 200000000; ++i)\n      q[i&1023] = stb_getfloat_table2(p[i&8191]);\n   c = clock();\n   free(p);\n\n   free(q);\n\n   printf(\"Table: %d\\nIFs: %d\\n\", b-a, c-b);\n}\n#endif\n\n\nvoid do_compressor(int argc,char**argv)\n{\n   char *p;\n   size_t slen;\n   unsigned int len;\n\n   int window;\n   if (argc == 2) {\n      p = stb_file(argv[1], &slen);\n      len = (unsigned int) slen;\n      if (p) {\n         unsigned int dlen, clen = stb_compress_tofile(\"data/dummy.bin\", p, len);\n         char *q = stb_decompress_fromfile(\"data/dummy.bin\", &dlen);\n\n         if (len != dlen) {\n            printf(\"FAILED %d -> %d\\n\", len, clen);\n         } else {\n            int z = memcmp(q,p,dlen);\n            if (z != 0) \n               printf(\"FAILED %d -> %d\\n\", len, clen);\n            else\n               printf(\"%d -> %d\\n\", len, clen);\n         }\n      }\n      return;\n   }\n\n   window = atoi(argv[1]);\n   if (window && argc == 4) {\n      p = stb_file(argv[3], &slen);\n      len = (int) slen;\n      if (p) {\n         stb_compress_hashsize(window);\n         stb_compress_tofile(argv[2], p, len);\n      }\n   } else if (argc == 3) {\n      p = stb_decompress_fromfile(argv[2], &len);\n      if (p) {\n         FILE *f = fopen(argv[1], \"wb\");\n         fwrite(p,1,len,f);\n         fclose(f);\n      } else {\n         fprintf(stderr, \"FAILED.\\n\");\n      }\n   } else {\n      fprintf(stderr, \"Usage: stb <hashsize> <output> <filetocompress>\\n\"\n                      \"   or  stb            <output> <filetodecompress>\\n\");\n   }\n}\n\n#if 0\n// naive backtracking implementation\nint wildmatch(char *expr, char *candidate)\n{\n   while(*expr) {\n      if (*expr == '?') {\n         if (!*candidate) return 0;\n         ++candidate;\n         ++expr;\n      } else if (*expr == '*') {\n         ++expr;\n         while (*expr == '*' || *expr =='?') ++expr;\n         // '*' at end of expression matches anything\n         if (!*expr) return 1;\n         // now scan candidate 'til first match\n         while (*candidate) {\n            if (*candidate == *expr) {\n               // check this candidate\n               if (stb_wildmatch(expr+1, candidate+1))\n                  return 1;\n               // if not, then backtrack\n            }\n            ++candidate;\n         }\n      } else {\n         if (*expr != *candidate)\n            return 0;\n         ++expr, ++candidate;\n      }\n   }\n   return *candidate != 0;\n}\n\nint stb_matcher_find_slow(stb_matcher *m, char *str)\n{\n   int result = 1;\n   int i,j,y,z;\n   uint16 *previous = NULL;\n   uint16 *current = NULL;\n   uint16 *temp;\n\n   stb_arr_setsize(previous, 4);\n   stb_arr_setsize(current, 4);\n\n   previous = stb__add_if_inactive(m, previous, m->start_node);\n   previous = stb__eps_closure(m,previous);\n   if (stb__clear_goalcheck(m, previous))\n      goto done;\n\n   while (*str) {\n      y = stb_arr_len(previous);\n      for (i=0; i < y; ++i) {\n         stb_nfa_node *n = &m->nodes[previous[i]];\n         z = stb_arr_len(n->out);\n         for (j=0; j < z; ++j) {\n            if (n->out[j].match == *str)\n               current = stb__add_if_inactive(m, current, n->out[j].node);\n            else if (n->out[j].match == -1) {\n               if (*str != '\\n')\n                  current = stb__add_if_inactive(m, current, n->out[j].node);\n            } else if (n->out[j].match < -1) {\n               int z = -n->out[j].match - 2;\n               if (m->charset[(uint8) *str] & (1 << z))\n                  current = stb__add_if_inactive(m, current, n->out[j].node);\n            }\n         }\n      }\n      ++str;\n      stb_arr_setlen(previous, 0);\n\n      temp = previous;\n      previous = current;\n      current = temp;\n\n      if (!m->match_start)\n         previous = stb__add_if_inactive(m, previous, m->start_node);\n      previous = stb__eps_closure(m,previous);\n      if (stb__clear_goalcheck(m, previous))\n         goto done;\n   }\n\n   result=0;\n\ndone:\n   stb_arr_free(previous);\n   stb_arr_free(current);\n\n   return result;\n}\n#endif\n\n\n\n\n\n#if 0 // parser generator\n//////////////////////////////////////////////////////////////////////////\n//\n//   stb_parser\n//\n//   Generates an LR(1) parser from a grammar, and can parse with it\n\n\n\n// Symbol representations\n//\n// Client:     Internal:\n//    -           c=0     e aka epsilon\n//    -           c=1     $ aka end of string\n//   > 0        2<=c<M    terminals (note these are remapped from a sparse layout)\n//   < 0        M<=c<N    non-terminals\n\n#define END 1\n#define EPS 0\n\nshort encode_term[4096];  // @TODO: malloc these\nshort encode_nonterm[4096];\nint first_nonterm, num_symbols, symset;\n#define encode_term(x)     encode_term[x]\n#define encode_nonterm(x)  encode_nonterm[~(x)]\n#define encode_symbol(x)   ((x) >= 0 ? encode_term(x) : encode_nonterm(x))\n\nstb_bitset **compute_first(short ** productions)\n{\n   int i, changed;\n   stb_bitset **first = malloc(sizeof(*first) * num_symbols);\n\n   assert(symset);\n   for (i=0; i < num_symbols; ++i)\n      first[i] = stb_bitset_new(0, symset);\n\n   for (i=END; i < first_nonterm; ++i)\n      stb_bitset_setbit(first[i], i);\n\n   for (i=0; i < stb_arr_len(productions); ++i) {\n      if (productions[i][2] == 0) {\n         int nt = encode_nonterm(productions[i][0]);\n         stb_bitset_setbit(first[nt], EPS);\n      }\n   }\n\n   do {\n      changed = 0;\n      for (i=0; i < stb_arr_len(productions); ++i) {\n         int j, nt = encode_nonterm(productions[i][0]);\n         for (j=2; productions[i][j]; ++j) {\n            int z = encode_symbol(productions[i][j]);\n            changed |= stb_bitset_unioneq_changed(first[nt], first[z], symset);\n            if (!stb_bitset_testbit(first[z], EPS))\n               break;\n         }\n         if (!productions[i][j] && !stb_bitset_testbit(first[nt], EPS)) {\n            stb_bitset_setbit(first[nt], EPS);\n            changed = 1;\n         }\n      }\n   } while (changed);\n   return first;\n}\n\nstb_bitset **compute_follow(short ** productions, stb_bitset **first, int start)\n{\n   int i,j,changed;\n   stb_bitset **follow = malloc(sizeof(*follow) * num_symbols);\n\n   assert(symset);\n   for (i=0; i < num_symbols; ++i)\n      follow[i] = (i >= first_nonterm ? stb_bitset_new(0, symset) : NULL);\n\n   stb_bitset_setbit(follow[start], END);\n   do {\n      changed = 0;\n      for (i=0; i < stb_arr_len(productions); ++i) {\n         int nt = encode_nonterm(productions[i][0]);\n         for (j=2; productions[i][j]; ++j) {\n            if (productions[i][j] < 0) {\n               int k,z = encode_nonterm(productions[i][j]);\n               for (k=j+1; productions[i][k]; ++k) {\n                  int q = encode_symbol(productions[i][k]);\n                  changed |= stb_bitset_unioneq_changed(follow[z], first[q], symset);\n                  if (!stb_bitset_testbit(first[q], EPS))\n                     break;\n               }\n               if (!productions[i][k] == 0)\n                  changed |= stb_bitset_unioneq_changed(follow[z], follow[nt], symset);\n            }\n         }\n      }\n   } while (changed);\n\n   for (i=first_nonterm; i < num_symbols; ++i)\n      stb_bitset_clearbit(follow[i], EPS);\n\n   return follow;\n}\n\nvoid first_for_prod_plus_sym(stb_bitset **first, stb_bitset *out, short *prod, int symbol)\n{\n   stb_bitset_clearall(out, symset);\n   for(;*prod;++prod) {\n      int z = encode_symbol(*prod);\n      stb_bitset_unioneq_changed(out, first[z], symset);\n      if (!stb_bitset_testbit(first[z], EPS))\n         return;\n   }\n   stb_bitset_unioneq_changed(out, first[symbol], symset);\n}\n\n#define Item(p,c,t)       ((void *) (size_t) (((t) << 18) + ((c) << 12) + ((p) << 2)))\n#define ItemProd(i)       ((((uint32) (size_t) (i)) >> 2) & 1023)\n#define ItemCursor(i)     ((((uint32) (size_t) (i)) >> 12) & 63)\n#define ItemLookahead(i)  (((uint32) (size_t) (i)) >> 18)\n\nstatic void pc(stb_ps *p)\n{\n}\n\ntypedef struct\n{\n   short *prod;\n   int prod_num;\n} ProdRef;\n\ntypedef struct\n{\n   stb_bitset **first;\n   stb_bitset **follow;\n   short **   prod;\n   ProdRef ** prod_by_nt;\n} Grammar;\n\nstb_ps *itemset_closure(Grammar g, stb_ps *set)\n{\n   stb_bitset *lookahead;\n   int changed,i,j,k, list_len;\n   if (set == NULL) return set;\n   lookahead = stb_bitset_new(0, symset);\n   do {\n      void **list = stb_ps_getlist(set, &list_len);\n      changed = 0;\n      for (i=0; i < list_len; ++i) {\n         ProdRef *prod;\n         int nt, *looklist;\n         int p = ItemProd(list[i]), c = ItemCursor(list[i]), t = ItemLookahead(list[i]);\n         if (g.prod[p][c] >= 0) continue;\n         nt = encode_nonterm(g.prod[p][c]);\n         first_for_prod_plus_sym(g.first, lookahead, g.prod[p]+c+1, t);\n         looklist = stb_bitset_getlist(lookahead, 1, first_nonterm);\n               \n         prod = g.prod_by_nt[nt];\n         for (j=0; j < stb_arr_len(prod); ++j) {\n            assert(prod[j].prod[0] == g.prod[p][c]);\n            // matched production; now iterate terminals\n            for (k=0; k < stb_arr_len(looklist); ++k) {\n               void *item = Item(prod[j].prod_num,2,looklist[k]);\n               if (!stb_ps_find(set, item)) {\n                  changed = 1;\n                  set = stb_ps_add(set, item);\n                  pc(set);\n               }\n            }\n         }\n         stb_arr_free(looklist);\n      }\n      free(list);\n   } while (changed);\n   free(lookahead);\n   return set;\n}\n\nstb_ps *itemset_goto(Grammar g, stb_ps *set, int sym)\n{\n   int i, listlen;\n   void **list = stb_ps_fastlist(set, &listlen);\n   stb_ps *out = NULL;\n   for (i=0; i < listlen; ++i) {\n      int p,c;\n      if (!stb_ps_fastlist_valid(list[i])) continue;\n      p = ItemProd(list[i]), c = ItemCursor(list[i]);\n      if (encode_symbol(g.prod[p][c]) == sym) {\n         void *z = Item(p,c+1,ItemLookahead(list[i]));\n         if (!stb_ps_find(out, z))\n            out = stb_ps_add(out, z);\n         pc(out);\n      }\n   }\n   return itemset_closure(g, out);\n}\n\nvoid itemset_all_nextsym(Grammar g, stb_bitset *out, stb_ps *set)\n{\n   int i, listlen;\n   void **list = stb_ps_fastlist(set, &listlen);\n   stb_bitset_clearall(out, symset);\n   pc(set);\n   for (i=0; i < listlen; ++i) {\n      if (stb_ps_fastlist_valid(list[i])) {\n         int p = ItemProd(list[i]);\n         int c = ItemCursor(list[i]);\n         if (g.prod[p][c])\n            stb_bitset_setbit(out, encode_symbol(g.prod[p][c]));\n      }\n   }\n}\n\nstb_ps ** generate_items(Grammar g, int start_prod)\n{\n   stb_ps ** all=NULL;\n   int i,j,k;\n   stb_bitset *try = stb_bitset_new(0,symset);\n   stb_ps *set = NULL;\n   void *item = Item(start_prod, 2, END);\n   set = stb_ps_add(set, item);\n   pc(set);\n   set = itemset_closure(g, set);\n   pc(set);\n   stb_arr_push(all, set);\n   for (i = 0; i < stb_arr_len(all); ++i) {\n      // only try symbols that appear in all[i]... there's a smarter way to do this,\n      // which is to take all[i], and divide it up by symbol\n      pc(all[i]);\n      itemset_all_nextsym(g, try, all[i]);\n      for (j = 1; j < num_symbols; ++j) {\n         if (stb_bitset_testbit(try, j)) {\n            stb_ps *out;\n            if (stb_arr_len(all) > 4) pc(all[4]);\n            if (i == 1 && j == 29) {\n               if (stb_arr_len(all) > 4) pc(all[4]);\n               out = itemset_goto(g, all[i], j);\n               if (stb_arr_len(all) > 4) pc(all[4]);\n            } else\n               out = itemset_goto(g, all[i], j);\n            pc(out);\n            if (stb_arr_len(all) > 4) pc(all[4]);\n            if (out != NULL) {\n               // add it to the array if it's not already there\n               for (k=0; k < stb_arr_len(all); ++k)\n                  if (stb_ps_eq(all[k], out))\n                     break;\n               if (k == stb_arr_len(all)) {\n                  stb_arr_push(all, out);\n                  pc(out);\n                  if (stb_arr_len(all) > 4) pc(all[4]);\n               } else\n                  stb_ps_delete(out);\n            }\n         }\n      }\n   }\n   free(try);\n   return all;\n}\n\ntypedef struct\n{\n   int num_stack;\n   int function;\n} Reduction;\n\ntypedef struct\n{\n   short *encode_term;\n   Reduction *reductions;\n   short **action_goto; // terminals are action, nonterminals are goto\n   int start;\n   int end_term;\n} Parser;\n\nenum\n{\n   A_error, A_accept, A_shift, A_reduce, A_conflict\n};\n\ntypedef struct\n{\n   uint8 type;\n   uint8 cursor;\n   short prod;\n   short value;\n} Action;\n\nParser *parser_create(short **productions, int num_prod, int start_nt, int end_term)\n{\n   short *mini_rule = malloc(4 * sizeof(mini_rule[0]));\n   Action *actions;\n   Grammar g;\n   stb_ps ** sets;\n   Parser *p = malloc(sizeof(*p));\n   int i,j,n;\n   stb_bitset *mapped;\n   int min_s=0, max_s=0, termset, ntset, num_states, num_reductions, init_prod;\n\n   int synth_start;\n\n   // remap sparse terminals and nonterminals\n\n   for (i=0; i < num_prod; ++i) {\n      for (j=2; productions[i][j]; ++j) {\n         if (productions[i][j] < min_s) min_s = productions[i][j];\n         if (productions[i][j] > max_s) max_s = productions[i][j];\n      }\n   }\n   synth_start = --min_s;\n\n   termset = (max_s + 32) >> 5;\n   ntset = (~min_s + 32) >> 5;\n   memset(encode_term, 0, sizeof(encode_term));\n   memset(encode_nonterm, 0, sizeof(encode_nonterm));\n\n   mapped = stb_bitset_new(0, termset);\n   n = 2;\n   for (i=0; i < num_prod; ++i)\n      for (j=2; productions[i][j]; ++j)\n         if (productions[i][j] > 0)\n            if (!stb_bitset_testbit(mapped, productions[i][j])) {\n               stb_bitset_setbit(mapped, productions[i][j]);\n               encode_term[productions[i][j]] = n++;\n            }\n   free(mapped);\n\n   first_nonterm = n;\n\n   mapped = stb_bitset_new(0, ntset);\n   for (i=0; i < num_prod; ++i)\n      for (j=2; productions[i][j]; ++j)\n         if (productions[i][j] < 0)\n            if (!stb_bitset_testbit(mapped, ~productions[i][j])) {\n               stb_bitset_setbit(mapped, ~productions[i][j]);\n               encode_nonterm[~productions[i][j]] = n++;\n            }\n   free(mapped);\n\n   // add a special start state for internal processing\n   p->start = n++;\n   encode_nonterm[synth_start] = p->start;\n   mini_rule[0] = synth_start;\n   mini_rule[1] = -32768;\n   mini_rule[2] = start_nt;\n   mini_rule[3] = 0;\n\n   p->end_term = end_term;\n\n   num_symbols = n;\n   \n   // create tables\n   g.prod = NULL;\n   g.prod_by_nt = malloc(num_symbols * sizeof(g.prod_by_nt[0]));\n   for (i=0; i < num_symbols; ++i)\n      g.prod_by_nt[i] = NULL;\n\n   for (i=0; i < num_prod; ++i) {\n      stb_arr_push(g.prod, productions[i]);\n   }\n   init_prod = stb_arr_len(g.prod);\n   stb_arr_push(g.prod, mini_rule);\n\n   num_reductions = stb_arr_len(g.prod);\n   p->reductions = malloc(num_reductions * sizeof(*p->reductions));\n\n   symset = (num_symbols + 31) >> 5;\n   g.first = compute_first(g.prod);\n   g.follow = compute_follow(g.prod, g.first, p->start);\n\n   for (i=0; i < stb_arr_len(g.prod); ++i) {\n      ProdRef pr = { g.prod[i], i };\n      stb_arr_push(g.prod_by_nt[encode_nonterm(g.prod[i][0])], pr);\n   }\n\n   sets = generate_items(g, init_prod);\n\n   num_states = stb_arr_len(sets);\n   // now generate tables\n\n   actions = malloc(sizeof(*actions) * first_nonterm);\n   p->action_goto = (short **) stb_array_block_alloc(num_states, sizeof(short) * num_symbols);\n   for (i=0; i < num_states; ++i) {\n      int j,n;\n      void **list = stb_ps_getlist(sets[i], &n);\n      memset(actions, 0, sizeof(*actions) * first_nonterm);\n      for (j=0; j < n; ++j) {\n         int p = ItemProd(list[j]), c = ItemCursor(list[j]), t = ItemLookahead(list[j]);\n         if (g.prod[p][c] == 0) {\n            if (p == init_prod) {\n               // @TODO: check for conflicts\n               assert(actions[t].type == A_error || actions[t].type == A_accept);\n               actions[t].type = A_accept;\n            } else {\n               // reduce production p\n               if (actions[t].type == A_reduce) {\n                  // is it the same reduction we already have?\n                  if (actions[t].prod != p) {\n                     // no, it's a reduce-reduce conflict!\n                     printf(\"Reduce-reduce conflict for rule %d and %d, lookahead %d\\n\", p, actions[t].prod, t);\n                     // @TODO: use precedence\n                     actions[t].type = A_conflict;\n                  }\n               } else if (actions[t].type == A_shift) {\n                  printf(\"Shift-reduce conflict for rule %d and %d, lookahead %d\\n\", actions[t].prod, p, t);\n                  actions[t].type = A_conflict;\n               } else if (actions[t].type == A_accept) {\n                  assert(0);\n               } else if (actions[t].type == A_error) {\n                  actions[t].type = A_reduce;\n                  actions[t].prod = p;\n               }\n            }\n         } else if (g.prod[p][c] > 0) {\n            int a = encode_symbol(g.prod[p][c]), k;\n            stb_ps *out = itemset_goto(g, sets[i], a);\n            for (k=0; k < stb_arr_len(sets); ++k)\n               if (stb_ps_eq(sets[k], out))\n                  break;\n            assert(k < stb_arr_len(sets));\n            // shift k\n            if (actions[a].type == A_shift) {\n               if (actions[a].value != k) {\n                  printf(\"Shift-shift conflict! Rule %d and %d with lookahead %d/%d\\n\", actions[a].prod, p, a,t);\n                  actions[a].type = A_conflict;\n               }\n            } else if (actions[a].type == A_reduce) {\n               printf(\"Shift-reduce conflict for rule %d and %d, lookahead %d/%d\\n\", p, actions[a].prod, a,t);\n               actions[a].type = A_conflict;\n            } else if (actions[a].type == A_accept) {\n               assert(0);\n            } else if (actions[a].type == A_error) {\n               actions[a].type = A_shift;\n               actions[a].prod = p;\n               actions[a].cursor = c;\n               actions[a].value  = k;\n            }\n         }\n      }\n      // @TODO: recompile actions into p->action_goto\n   }\n\n   free(mini_rule);\n   stb_pointer_array_free(g.first , num_symbols); free(g.first );\n   stb_pointer_array_free(g.follow, num_symbols); free(g.follow);\n   stb_arr_free(g.prod);\n   for (i=0; i < num_symbols; ++i)\n      stb_arr_free(g.prod_by_nt[i]);\n   free(g.prod_by_nt);\n   for (i=0; i < stb_arr_len(sets); ++i)\n      stb_ps_delete(sets[i]);\n   stb_arr_free(sets);\n\n   return p;\n}\n\nvoid parser_destroy(Parser *p)\n{\n   free(p);\n}\n\n#if 0\nenum nonterm\n{\n   N_globals = -50,\n   N_global, N_vardef, N_varinitlist, N_varinit, N_funcdef, N_optid, N_optparamlist,\n   N_paramlist, N_param, N_optinit, N_optcomma, N_statements, N_statement,\n   N_optexpr, N_assign, N_if, N_ifcore, N_else, N_dictdef, N_dictdef2,\n   N_dictdefitem, N_expr,\n   N__last\n};\n\nshort grammar[][10] =\n{\n   { N_globals    ,  0, N_globals, N_global                                 },\n   { N_globals    ,  0                                                      },\n   { N_global     ,  0, N_vardef                                            },\n   { N_global     ,  0, N_funcdef                                           },\n   { N_vardef     ,  0, ST_var, N_varinitlist,                               },\n   { N_varinitlist,  0, N_varinitlist, ',', N_varinit                       },\n   { N_varinitlist,  0, N_varinit,                                          },\n   { N_varinit    ,  0, ST_id, N_optinit,                                    },\n   { N_funcdef    ,  0, ST_func, N_optid, '(', N_optparamlist, ')', N_statements, ST_end },\n   { N_optid      ,  0, ST_id                                                },\n   { N_optid      ,  0,                                                     },\n   { N_optparamlist, 0,                                                     },\n   { N_optparamlist, 0, N_paramlist, N_optcomma                             },\n   { N_paramlist  ,  0, N_paramlist, ',', N_param                           },\n   { N_paramlist  ,  0, N_param                                             },\n   { N_param      ,  0, ST_id, N_optinit                                     },\n   { N_optinit    ,  0, '=', N_expr                                         },\n   { N_optinit    ,  0,                                                     },\n   { N_optcomma   ,  0, ','                                                 },\n   { N_optcomma   ,  0,                                                     },\n   { N_statements ,  0, N_statements, N_statement                           },\n   { N_statement  ,  0, N_statement, ';'                                    },\n   { N_statement  ,  0, N_varinit                                           },\n   { N_statement  ,  0, ST_return, N_expr                                    },\n   { N_statement  ,  0, ST_break , N_optexpr                                 },\n   { N_optexpr    ,  0, N_expr                                              },\n   { N_optexpr    ,  0,                                                     },\n   { N_statement  ,  0, ST_continue                                          },\n   { N_statement  ,  0, N_assign                                            },\n   { N_assign     ,  0, N_expr, '=', N_assign                               },\n   //{ N_assign     ,  0, N_expr                                              },\n   { N_statement  ,  0, ST_while, N_expr, N_statements, ST_end                },\n   { N_statement  ,  0, ST_if, N_if,                                         },\n   { N_if         ,  0, N_ifcore, ST_end,                                    },\n   { N_ifcore     ,  0, N_expr, ST_then, N_statements, N_else, ST_end         },\n   { N_else       ,  0, ST_elseif, N_ifcore                                  },\n   { N_else       ,  0, ST_else, N_statements                                },\n   { N_else       ,  0,                                                     },\n   { N_dictdef    ,  0, N_dictdef2, N_optcomma                              },\n   { N_dictdef2   ,  0, N_dictdef2, ',', N_dictdefitem                      },\n   { N_dictdef2   ,  0, N_dictdefitem                                       },\n   { N_dictdefitem,  0, ST_id, '=', N_expr                                   },\n   { N_dictdefitem,  0, N_expr                                              },\n   { N_expr       ,  0, ST_number                                            },\n   { N_expr       ,  0, ST_string                                            },\n   { N_expr       ,  0, ST_id                                                },\n   { N_expr       ,  0, N_funcdef                                           },\n   { N_expr       ,  0, '-', N_expr                                         },\n   { N_expr       ,  0, '{', N_dictdef, '}'                                 },\n   { N_expr       ,  0, '(', N_expr, ')'                                    },\n   { N_expr       ,  0, N_expr, '.', ST_id                                   },\n   { N_expr       ,  0, N_expr, '[', N_expr, ']'                            },\n   { N_expr       ,  0, N_expr, '(', N_dictdef, ')'                         },\n#if 0\n#define BINOP(op)  { N_expr, 0, N_expr, op, N_expr }\n   BINOP(ST_and), BINOP(ST_or), BINOP(ST_eq), BINOP(ST_ne),\n   BINOP(ST_le),  BINOP(ST_ge), BINOP('>') , BINOP('<' ),\n   BINOP('&'), BINOP('|'), BINOP('^'), BINOP('+'), BINOP('-'),\n   BINOP('*'), BINOP('/'), BINOP('%'),\n#undef BINOP\n#endif\n};\n\nshort *grammar_list[stb_arrcount(grammar)];\n\nvoid test_parser_generator(void)\n{\n   Parser *p;\n   int i;\n   assert(N__last <= 0);\n   for (i=0; i < stb_arrcount(grammar); ++i)\n      grammar_list[i] = grammar[i];\n   p = parser_create(grammar_list, stb_arrcount(grammar), N_globals, 0);\n   parser_destroy(p);\n}\n#endif\n#endif // parser generator\n\n#if 0\n// stb_threadtest.c\n\n\n#include <windows.h>\n#define STB_DEFINE\n//#define STB_THREAD_TEST\n#include \"../stb.h\"\n\n#define NUM_WORK 100\n\nvoid *work_consumer(void *p)\n{\n   stb__thread_sleep(20);\n   return NULL;\n}\n\nint pass;\nstb_threadqueue *tq1, *tq2, *tq3, *tq4;\nvolatile float t1,t2;\n\n//    with windows.h\n// Worked correctly with 100,000,000 enqueue/dequeue WAITLESS\n// (770 passes, 170000 per pass)\n// Worked correctly with   2,500,000 enqueue/dequeue !WAITLESS\n// (15 passes, 170000 per pass)\n// Worked correctly with   1,500,000 enqueue/dequeue WAITLESS && STB_THREAD_TEST\n// (9 passes, 170000 per pass)\n//    without windows.h\n// Worked correctly with   1,000,000 enqueue/dequeue WAITLESS && STB_THREAD_TEST\n// (6 passes, 170000 per pass)\n// Worked correctly with     500,000 enqueue/dequeue !WAITLESS && STB_THREAD_TEST\n// (3 passes, 170000 per pass)\n// Worked correctly with   1,000,000 enqueue/dequeue WAITLESS\n// (15 passes, 170000 per pass)\n#define WAITLESS\n\nvolatile int table[1000*1000*10];\n\nvoid wait(int n)\n{\n#ifndef WAITLESS\n   int j;\n   float y;\n   for (j=0; j < n; ++j)\n      y += 1 / (t1+j);\n   t2 = y;\n#endif\n}\n\nvoid *tq1_consumer(void *p)\n{\n   for(;;) {\n      int z;\n      float y = 0;\n      stb_threadq_get_block(tq1, &z);\n      wait(5000);\n      table[z] = pass;\n   }\n}\n\nvoid *tq2_consumer(void *p)\n{\n   for(;;) {\n      int z;\n      if (stb_threadq_get(tq2, &z))\n         table[z] = pass;\n      wait(1000);\n   }\n}\n\nvoid *tq3_consumer(void *p)\n{\n   for(;;) {\n      int z;\n      stb_threadq_get_block(tq3, &z);\n      table[z] = pass;\n      wait(500);\n   }\n}\n\nvoid *tq4_consumer(void *p)\n{\n   for (;;) {\n      int z;\n      stb_threadq_get_block(tq4, &z);\n      table[z] = pass;\n      wait(500);\n   }\n}\n\ntypedef struct\n{\n   int start, end;\n   stb_threadqueue *tq;\n   int delay;\n} write_data;\n\nvoid *writer(void *q)\n{\n   int i;\n   write_data *p = (write_data *) q;\n   for (i=p->start; i < p->end; ++i) {\n      stb_threadq_add_block(p->tq, &i);\n      #ifndef WAITLESS\n      if (p->delay) stb__thread_sleep(p->delay);\n      else {\n         int j;\n         float z = 0;\n         for (j=0; j <= 20; ++j)\n            z += 1 / (t1+j);\n         t2 = z;\n      }\n      #endif\n   }\n   return NULL;\n}\n\nwrite_data info[256];\nint pos;\n\nvoid start_writer(int z, int count, stb_threadqueue *tq, int delay)\n{\n   info[z].start = pos;\n   info[z].end = pos+count;\n   info[z].tq = tq;\n   info[z].delay = delay;\n   stb_create_thread(writer, &info[z]);\n   pos += count;\n}\n\nint main(int argc, char **argv)\n{\n   int i;\n   stb_sync s = stb_sync_new();\n   stb_sync_set_target(s, NUM_WORK+1);\n   stb_work_numthreads(2);\n   for (i=0; i < NUM_WORK; ++i) {\n      stb_work_reach(work_consumer, NULL, NULL, s);\n   }\n   printf(\"Started stb_work test.\\n\");\n\n   t1 = 1;\n\n   // create the queues\n   tq1 = stb_threadq_new(4, 4, TRUE , TRUE);\n   tq2 = stb_threadq_new(4, 4, TRUE , FALSE);\n   tq3 = stb_threadq_new(4, 4, FALSE, TRUE);\n   tq4 = stb_threadq_new(4, 4, FALSE, FALSE);\n\n   // start the consumers\n   stb_create_thread(tq1_consumer, NULL);\n   stb_create_thread(tq1_consumer, NULL);\n   stb_create_thread(tq1_consumer, NULL);\n\n   stb_create_thread(tq2_consumer, NULL);\n\n   stb_create_thread(tq3_consumer, NULL);\n   stb_create_thread(tq3_consumer, NULL);\n   stb_create_thread(tq3_consumer, NULL);\n   stb_create_thread(tq3_consumer, NULL);\n   stb_create_thread(tq3_consumer, NULL);\n   stb_create_thread(tq3_consumer, NULL);\n   stb_create_thread(tq3_consumer, NULL);\n\n   stb_create_thread(tq4_consumer, NULL);\n\n   for (pass=1; pass <= 5000; ++pass) {\n      int z = 0;\n      int last_n = -1;\n      int identical = 0;\n      pos = 0;\n      start_writer(z++, 50000, tq1, 0);\n      start_writer(z++, 50000, tq1, 0);\n      start_writer(z++, 50000, tq1, 0);\n\n      start_writer(z++, 5000, tq2, 1);\n      start_writer(z++, 3000, tq2, 3);\n      start_writer(z++, 2000, tq2, 5);\n\n      start_writer(z++, 5000, tq3, 3);\n\n      start_writer(z++, 5000, tq4, 3);\n      #ifndef WAITLESS\n      stb__thread_sleep(8000);\n      #endif\n      for(;;) {\n         int n =0;\n         for (i=0; i < pos; ++i) {\n            if (table[i] == pass)\n               ++n;\n         }\n         if (n == pos) break;\n         if (n == last_n) {\n            ++identical;\n            if (identical == 3) {\n               printf(\"Problem slots:\\n\");\n               for (i=0; i < pos; ++i) {\n                  if (table[i] != pass) printf(\"%d \", i);\n               }\n               printf(\"\\n\");\n            } else {\n               if (identical < 3)\n                  printf(\"Processed %d of %d\\n\", n, pos);\n               else\n                  printf(\".\");\n            }\n         } else {\n            identical = 0;\n            printf(\"Processed %d of %d\\n\", n, pos);\n         }\n         last_n = n;\n         #ifdef WAITLESS\n         stb__thread_sleep(750);\n         #else\n         stb__thread_sleep(3000);\n         #endif\n      }\n      printf(\"Finished pass %d\\n\", pass);\n   }\n\n   stb_sync_reach_and_wait(s);\n   printf(\"stb_work test completed ok.\\n\");\n   return 0;\n}\n#endif\n\n\n#if 0\n//////////////////////////////////////////////////////////////////////////////\n//\n//   collapse tree leaves up to parents until we only have N nodes\n//   useful for cmirror summaries\n\ntypedef struct stb_summary_tree\n{\n   struct stb_summary_tree **children;\n   int num_children;\n   float weight;\n} stb_summary_tree;\n\nSTB_EXTERN void *stb_summarize_tree(void *tree, int limit, float reweight);\n\n#ifdef STB_DEFINE\n\ntypedef struct stb_summary_tree2\n{\n   STB__ARR(struct stb_summary_tree2 *) children;\n   int num_children;\n   float weight;\n   float weight_with_all_children;\n   float makes_target_weight;\n   float weight_at_target;\n   stb_summary_tree *original;\n   struct stb_summary_tree2 *target;\n   STB__ARR(struct stb_summary_tree2 *) targeters;\n} stb_summary_tree2;\n\nstatic stb_summary_tree2 *stb__summarize_clone(stb_summary_tree *t)\n{\n   int i;\n   stb_summary_tree2 *s;\n   s = (stb_summary_tree2 *) malloc(sizeof(*s));\n   s->original = t;\n   s->weight = t->weight;\n   s->weight_with_all_children = 0;\n   s->weight_at_target = 0;\n   s->target = NULL;\n   s->targeters = NULL;\n   s->num_children = t->num_children;\n   s->children = NULL;\n   for (i=0; i < s->num_children; ++i)\n      stb_arr_push(s->children, stb__summarize_clone(t->children[i]));\n   return s;\n}\n\nstatic float stb__summarize_compute_targets(stb_summary_tree2 *parent, stb_summary_tree2 *node, float reweight, float weight)\n{\n   float total = 0;\n   if (node->weight == 0 && node->num_children == 1 && parent) {\n      node->target = parent;\n      return stb__summarize_compute_targets(parent, node->children[0], reweight, weight*reweight);\n   } else {\n      float total=0;\n      int i;\n      for (i=0; i < node->num_children; ++i)\n         total += stb__summarize_compute_targets(node, node->children[i], reweight, reweight);\n      node->weight_with_all_children = total + node->weight;\n      if (parent && node->weight_with_all_children) {\n         node->target = parent;\n         node->weight_at_target = node->weight_with_all_children * weight;\n         node->makes_target_weight = node->weight_at_target + parent->weight;\n         stb_arr_push(parent->targeters, node);\n      } else {\n         node->target = NULL;\n         node->weight_at_target = node->weight;\n         node->makes_target_weight = 0;\n      }\n      return node->weight_with_all_children * weight;\n   }      \n}\n\nstatic stb_summary_tree2 ** stb__summarize_make_array(STB__ARR(stb_summary_tree2 *) all, stb_summary_tree2 *tree)\n{\n   int i;\n   stb_arr_push(all, tree);\n   for (i=0; i < tree->num_children; ++i)\n      all = stb__summarize_make_array(all, tree->children[i]);\n   return all;\n}\n\ntypedef stb_summary_tree2 * stb__stree2;\nstb_define_sort(stb__summarysort, stb__stree2, (*a)->makes_target_weight < (*b)->makes_target_weight)\n\nvoid *stb_summarize_tree(void *tree, int limit, float reweight)\n{\n   int i,j,k;\n   STB__ARR(stb_summary_tree *) ret=NULL;\n   STB__ARR(stb_summary_tree2 *) all=NULL;\n\n   // first clone the tree so we can manipulate it\n   stb_summary_tree2 *t = stb__summarize_clone((stb_summary_tree *) tree);\n   if (reweight < 1) reweight = 1;\n\n   // now compute how far up the tree each node would get pushed\n   // there's no value in pushing a node up to an empty node with\n   // only one child, so we keep pushing it up\n   stb__summarize_compute_targets(NULL, t, reweight, 1);\n\n   all = stb__summarize_make_array(all, t);\n\n   // now we want to iteratively find the smallest 'makes_target_weight',\n   // update that, and then fix all the others (which will be all descendents)\n   // to do this efficiently, we need a heap or a sorted binary tree\n   // what we have is an array. maybe we can insertion sort the array?\n   stb__summarysort(all, stb_arr_len(all));\n\n   for (i=0; i < stb_arr_len(all) - limit; ++i) {\n      stb_summary_tree2 *src, *dest;\n      src = all[i];\n      dest = all[i]->target;\n      if (src->makes_target_weight == 0) continue;\n      assert(dest != NULL);\n\n      for (k=0; k < stb_arr_len(all); ++k)\n         if (all[k] == dest)\n            break;\n      assert(k != stb_arr_len(all));\n      assert(i < k);\n\n      // move weight from all[i] to target\n      src->weight = dest->makes_target_weight;\n      src->weight = 0;\n      src->makes_target_weight = 0;\n      // recompute effect of other descendents\n      for (j=0; j < stb_arr_len(dest->targeters); ++j) {\n         if (dest->targeters[j]->weight) {\n            dest->targeters[j]->makes_target_weight = dest->weight + dest->targeters[j]->weight_at_target;\n            assert(dest->targeters[j]->makes_target_weight <= dest->weight_with_all_children);\n         }\n      }\n      STB_(stb__summarysort,_ins_sort)(all+i, stb_arr_len(all)-i);\n   }\n   // now the elements in [ i..stb_arr_len(all) ) are the relevant ones\n   for (; i < stb_arr_len(all); ++i)\n      stb_arr_push(ret, all[i]->original);\n\n   // now free all our temp data\n   for (i=0; i < stb_arr_len(all); ++i) {\n      stb_arr_free(all[i]->children);\n      free(all[i]);\n   }\n   stb_arr_free(all);\n   return ret;\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "tests/stb.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"stb\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=stb - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"stb.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"stb.mak\" CFG=\"stb - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"stb - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"stb - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"stb - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /G6 /MT /W3 /GX /Z7 /O2 /Ob2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"VORBIS_TEST\" /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"stb - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\\stb\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /MTd /W3 /GX /Zi /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"TT_TEST\" /FR /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no /debug /machine:I386 /pdbtype:sept\n# SUBTRACT LINK32 /force\n\n!ENDIF \n\n# Begin Target\n\n# Name \"stb - Win32 Release\"\n# Name \"stb - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\grid_reachability.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\stb.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_c_lexer.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_connected_components.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_divide.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_ds.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_dxt.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_easy_font.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_herringbone_wang_tile.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_image.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_image_resize2.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_image_write.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_include.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_leakcheck.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_malloc.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_perlin.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_rect_pack.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_sprintf.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\stb_static.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_textedit.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_tilemap_editor.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_truetype.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_vorbis.c\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_voxel_render.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_c_compilation.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_c_lexer.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_ds.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_dxt.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_easyfont.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_image.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_image_write.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_packer.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_perlin.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_sprintf.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_truetype.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_vorbis.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_voxel.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\textedit_sample.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/stb.dsw",
    "content": "Microsoft Developer Studio Workspace File, Format Version 6.00\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\n\n###############################################################################\n\nProject: \"c_lexer_test\"=.\\c_lexer_test.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"herringbone\"=.\\herringbone.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"herringbone_map\"=.\\herringbone_map.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"image_test\"=.\\image_test.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"make_readme\"=..\\tools\\make_readme.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"resize\"=.\\resize.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"stb\"=.\\stb.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n    Begin Project Dependency\n    Project_Dep_Name stb_cpp\n    End Project Dependency\n    Begin Project Dependency\n    Project_Dep_Name image_test\n    End Project Dependency\n    Begin Project Dependency\n    Project_Dep_Name c_lexer_test\n    End Project Dependency\n}}}\n\n###############################################################################\n\nProject: \"stb_cpp\"=.\\stb_cpp.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"stblib\"=.\\stblib.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"unicode\"=..\\tools\\unicode\\unicode.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nProject: \"vorbseek\"=.\\vorbseek\\vorbseek.dsp - Package Owner=<4>\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<4>\n{{{\n}}}\n\n###############################################################################\n\nGlobal:\n\nPackage=<5>\n{{{\n}}}\n\nPackage=<3>\n{{{\n}}}\n\n###############################################################################\n\n"
  },
  {
    "path": "tests/stb_c_lexer_fuzzer.cpp",
    "content": "#define STB_C_LEX_C_DECIMAL_INTS    Y  \n#define STB_C_LEX_C_HEX_INTS        Y\n#define STB_C_LEX_C_OCTAL_INTS      Y\n#define STB_C_LEX_C_DECIMAL_FLOATS  Y\n#define STB_C_LEX_C99_HEX_FLOATS    Y\n#define STB_C_LEX_C_IDENTIFIERS     Y\n#define STB_C_LEX_C_DQ_STRINGS      Y\n#define STB_C_LEX_C_SQ_STRINGS      Y\n#define STB_C_LEX_C_CHARS           Y\n#define STB_C_LEX_C_COMMENTS        Y\n#define STB_C_LEX_CPP_COMMENTS      Y\n#define STB_C_LEX_C_COMPARISONS     Y\n#define STB_C_LEX_C_LOGICAL         Y\n#define STB_C_LEX_C_SHIFTS          Y \n#define STB_C_LEX_C_INCREMENTS      Y\n#define STB_C_LEX_C_ARROW           Y\n#define STB_C_LEX_EQUAL_ARROW       Y\n#define STB_C_LEX_C_BITWISEEQ       Y\n#define STB_C_LEX_C_ARITHEQ         Y\n\n#define STB_C_LEX_PARSE_SUFFIXES    Y\n#define STB_C_LEX_DECIMAL_SUFFIXES  \"uUlL\"\n#define STB_C_LEX_HEX_SUFFIXES      \"lL\"\n#define STB_C_LEX_OCTAL_SUFFIXES    \"lL\"\n#define STB_C_LEX_FLOAT_SUFFIXES    \"uulL\"\n\n#define STB_C_LEX_0_IS_EOF             N\n#define STB_C_LEX_INTEGERS_AS_DOUBLES  N\n#define STB_C_LEX_MULTILINE_DSTRINGS   Y\n#define STB_C_LEX_MULTILINE_SSTRINGS   Y\n#define STB_C_LEX_USE_STDLIB           N\n#define STB_C_LEX_DOLLAR_IDENTIFIER    Y\n#define STB_C_LEX_FLOAT_NO_DECIMAL     Y  \n\n#define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES  Y  \n#define STB_C_LEX_DISCARD_PREPROCESSOR    Y  \n#define STB_C_LEXER_DEFINITIONS         \n\n#define STB_C_LEXER_IMPLEMENTATION\n#define STB_C_LEXER_SELF_TEST\n#include \"../stb_c_lexer.h\"\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n\tif(size<3){\n\t\treturn 0;\n\t}\n\tchar *input_stream = (char *)malloc(size);\n\tif (input_stream == NULL){\n\t\treturn 0;\n\t}\n\tmemcpy(input_stream, data, size);\n\n\tstb_lexer lex;\n\tchar *input_end = input_stream+size-1;\n\tchar *store = (char *)malloc(0x10000);\n\tint len = 0x10000;\n\t\n\tstb_c_lexer_init(&lex, input_stream, input_end, store, len);\n\twhile (stb_c_lexer_get_token(&lex)) {\n\t\tif (lex.token == CLEX_parse_error) {\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tfree(input_stream);\n\tfree(store);\n\treturn 0;\n}\n"
  },
  {
    "path": "tests/stb_cpp.cpp",
    "content": "#define WIN32_MEAN_AND_LEAN\n#define WIN32_LEAN_AND_MEAN\n//#include <windows.h>\n#include <conio.h>\n#define STB_DEFINE\n#ifndef _M_AMD64\n#define STB_NPTR\n#endif\n#define STB_ONLY\n#include \"stb.h\"\n//#include \"stb_file.h\"\n\nint count;\nvoid c(int truth, const char *error)\n{\n   if (!truth) {\n      fprintf(stderr, \"Test failed: %s\\n\", error);\n      ++count;\n   }\n}\n\nchar *expects(stb_matcher *m, char *s, int result, int len, const char *str)\n{\n   int res2,len2=0;\n   res2 = stb_lex(m, s, &len2);\n   c(result == res2 && len == len2, str);\n   return s + len;\n}\n\nvoid test_lex(void)\n{\n   stb_matcher *m = stb_lex_matcher();\n   //         tok_en5 .3 20.1 20. .20 .1\n   char *s = (char*) \"tok_en5.3 20.1 20. .20.1\";\n\n   stb_lex_item(m, \"[a-zA-Z_][a-zA-Z0-9_]*\", 1   );\n   stb_lex_item(m, \"[0-9]*\\\\.?[0-9]*\"      , 2   );\n   stb_lex_item(m, \"[\\r\\n\\t ]+\"            , 3   );\n   stb_lex_item(m, \".\"                     , -99 );\n   s=expects(m,s,1,7, \"stb_lex 1\");\n   s=expects(m,s,2,2, \"stb_lex 2\");\n   s=expects(m,s,3,1, \"stb_lex 3\");\n   s=expects(m,s,2,4, \"stb_lex 4\");\n   s=expects(m,s,3,1, \"stb_lex 5\");\n   s=expects(m,s,2,3, \"stb_lex 6\");\n   s=expects(m,s,3,1, \"stb_lex 7\");\n   s=expects(m,s,2,3, \"stb_lex 8\");\n   s=expects(m,s,2,2, \"stb_lex 9\");\n   s=expects(m,s,0,0, \"stb_lex 10\");\n   stb_matcher_free(m);\n}\n\nint main(int argc, char **argv)\n{\n#if 0\n   char *p;\n   p = (char*) \"abcdefghijklmnopqrstuvwxyz\";\n   c(stb_ischar('c', p), \"stb_ischar 1\");\n   c(stb_ischar('x', p), \"stb_ischar 2\");\n   c(!stb_ischar('#', p), \"stb_ischar 3\");\n   c(!stb_ischar('X', p), \"stb_ischar 4\");\n   p = (char*) \"0123456789\";\n   c(!stb_ischar('c', p), \"stb_ischar 5\");\n   c(!stb_ischar('x', p), \"stb_ischar 6\");\n   c(!stb_ischar('#', p), \"stb_ischar 7\");\n   c(!stb_ischar('X', p), \"stb_ischar 8\");\n   p = (char*) \"#####\";\n   c(!stb_ischar('c', p), \"stb_ischar a\");\n   c(!stb_ischar('x', p), \"stb_ischar b\");\n   c(stb_ischar('#', p), \"stb_ischar c\");\n   c(!stb_ischar('X', p), \"stb_ischar d\");\n   p = (char*) \"xXyY\";\n   c(!stb_ischar('c', p), \"stb_ischar e\");\n   c(stb_ischar('x', p), \"stb_ischar f\");\n   c(!stb_ischar('#', p), \"stb_ischar g\");\n   c(stb_ischar('X', p), \"stb_ischar h\");\n#endif\n\n   test_lex();\n\n   if (count) {\n      _getch();\n   }\n   return 0;\n}\n"
  },
  {
    "path": "tests/stb_cpp.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"stb_cpp\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=stb_cpp - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"stb_cpp.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"stb_cpp.mak\" CFG=\"stb_cpp - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"stb_cpp - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"stb_cpp - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"stb_cpp - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /MT /W3 /GX /O2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"stb_cpp - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\\stb_cpp\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /MTd /W3 /GX /Zd /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"stb_cpp - Win32 Release\"\n# Name \"stb_cpp - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\stb_cpp.cpp\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_vorbis.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\test_cpp_compilation.cpp\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/stb_png.dict",
    "content": "header_png=\"\\x89PNG\\x0d\\x0a\\x1a\\x0a\"\n\nsection_idat=\"IDAT\"\nsection_iend=\"IEND\"\nsection_ihdr=\"IHDR\"\nsection_plte=\"PLTE\"\nsection_trns=\"tRNS\"\nsection_cgbi=\"CgBI\"\n"
  },
  {
    "path": "tests/stb_static.c",
    "content": "#define STBI_WINDOWS_UTF8\n#define STB_IMAGE_STATIC\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#define STB_IMAGE_WRITE_STATIC\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n//#include \"stb_image_write.h\"\n\n#define STBTT_STATIC\n#define STB_TRUETYPE_IMPLEMENTATION\n#include \"stb_truetype.h\"\n"
  },
  {
    "path": "tests/stbi_read_fuzzer.c",
    "content": "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define STB_IMAGE_IMPLEMENTATION\n\n#include \"../stb_image.h\"\n\n\nint LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n    int x, y, channels;\n\n    if(!stbi_info_from_memory(data, size, &x, &y, &channels)) return 0;\n\n    /* exit if the image is larger than ~80MB */\n    if(y && x > (80000000 / 4) / y) return 0;\n\n    unsigned char *img = stbi_load_from_memory(data, size, &x, &y, &channels, 4);\n\n    free(img);\n\n    return 0;\n}\n\n#ifdef __cplusplus\n}\n#endif"
  },
  {
    "path": "tests/stblib.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"stblib\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=stblib - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"stblib.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"stblib.mak\" CFG=\"stblib - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"stblib - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"stblib - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"stblib - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"stblib - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"stblib - Win32 Release\"\n# Name \"stblib - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\prerelease\\stb_lib.h\n# End Source File\n# Begin Source File\n\nSOURCE=..\\stb_regex.h\n# End Source File\n# Begin Source File\n\nSOURCE=.\\stblib_test.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\stblib_test_companion.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/stblib_test.c",
    "content": "#include \"prerelease/stb_lib.h\"\n#define STB_LIB_IMPLEMENTATION\n#include \"prerelease/stb_lib.h\"\n\n//#define STB_REGEX_IMPLEMENTATION\n//#include \"stb_regex.h\"\n\nint main(int argc, char **argv)\n{\n\n}"
  },
  {
    "path": "tests/stblib_test_companion.c",
    "content": "//#include \"stb_regex.h\"\n//#include \"stb_regex.h\"\n#include \"prerelease/stb_lib.h\"\n#include \"prerelease/stb_lib.h\"\n"
  },
  {
    "path": "tests/stretch_test.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"stretch_test\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=stretch_test - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"stretch_test.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"stretch_test.mak\" CFG=\"stretch_test - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"stretch_test - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"stretch_test - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"stretch_test - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /I \"..\\..\" /I \"..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"TT_TEST\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"stretch_test - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"stretch_test___Win32_Debug\"\n# PROP BASE Intermediate_Dir \"stretch_test___Win32_Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\\stretch_test\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I \"..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"stretch_test - Win32 Release\"\n# Name \"stretch_test - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\stretch_test.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tests/test.sbm",
    "content": "[link]\n-Xlinker advapi32.lib\n\n[args]\n-I .. -Wall -D_DEBUG\n\n[compilers]\n#clang for x64,vcvars_2015_x64,clang --analyze\nclang for x64,vcvars_2015_x64,clang\nclang for x86,vcvars_2015_x86,clang --target=i386-pc-windows-msvc\n\n#####    STATIC ANALYSIS\n#\n#[link]\n#\n#[args]\n#-I .. -Wall -D_DEBUG\n#\n#[compilers]\n#clang for x64,vcvars_2015_x64,clang --analyze\n#\n#####\n\n[link]\nadvapi32.lib\n\n[args]\n/nologo -I .. -W3 -WX -D_DEBUG\n\n[compilers]\nVS2015 for x64, vcvars_2015_x64\nVC6           , vcvars_vc6\nVS2008 for x86, vcvars_2008_x86\nVS2013 for x86, vcvars_2013_x86\nVS2015 for x86, vcvars_2015_x86\nclang-cl for x64, vcvars_2015_x64, clang-cl\nclang-cl for x86, vcvars_2015_x86, clang-cl --target=i386-pc-windows-msvc\n#these batch files don't path a cl executable on my machine?!?\n#VS2008 for x64, vcvars_2008_x64\n#VS2013 for x64, vcvars_2013_x64\n\n[projects]\nc_lexer_test.c\nimage_test.c image_write_test.c\ntest_cpp_compilation.cpp stb_cpp.cpp ../stb_vorbis.c\nresample_test.cpp \n-DTT_TEST test_c_compilation.c test_truetype.c \nmain.c stb.c \nmain.c stretchy_buffer_test.c\nmain.c test_c_compilation.c\nmain.c test_c_lexer.c\nmain.c test_dxt.c\nmain.c test_easyfont.c\nmain.c test_image.c\nmain.c test_image_write.c\nmain.c test_perlin.c\nmain.c test_sprintf.c\nmain.c test_vorbis.c ../stb_vorbis.c\nmain.c test_voxel.c\nmain.c textedit_sample.c\n"
  },
  {
    "path": "tests/test_c_compilation.c",
    "content": "#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#include \"stb_image_resize2.h\"\n\n#define STB_SPRINTF_IMPLEMENTATION\n#include \"stb_sprintf.h\"\n\n#define STB_PERLIN_IMPLEMENTATION\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#define STB_C_LEXER_IMPLEMENTATIOn\n#define STB_DIVIDE_IMPLEMENTATION\n#define STB_IMAGE_IMPLEMENTATION\n#define STB_HERRINGBONE_WANG_TILE_IMEPLEMENTATIOn\n#define STB_RECT_PACK_IMPLEMENTATION\n#define STB_VOXEL_RENDER_IMPLEMENTATION\n#define STB_EASY_FONT_IMPLEMENTATION\n#define STB_DXT_IMPLEMENTATION\n#define STB_INCLUDE_IMPLEMENTATION\n\n#include \"stb_herringbone_wang_tile.h\"\n#include \"stb_image.h\"\n#include \"stb_image_write.h\"\n#include \"stb_perlin.h\"\n#include \"stb_c_lexer.h\"\n#include \"stb_divide.h\"\n#include \"stb_rect_pack.h\"\n#include \"stb_dxt.h\"\n#include \"stb_include.h\"\n\n#include \"stb_ds.h\"\n\n#define STBVOX_CONFIG_MODE 1\n#include \"stb_voxel_render.h\"\n\nvoid STBTE_DRAW_RECT(int x0, int y0, int x1, int y1, unsigned int color)\n{\n}\n\nvoid STBTE_DRAW_TILE(int x0, int y0, unsigned short id, int highlight, float *data)\n{\n}\n\n#define STB_TILEMAP_EDITOR_IMPLEMENTATION\n//#include \"stb_tilemap_editor.h\"   // @TODO: it's broken\n\nint quicktest(void)\n{\n   char buffer[999];\n   stbsp_sprintf(buffer, \"test%%test\");\n   return 0;\n}"
  },
  {
    "path": "tests/test_c_lexer.c",
    "content": "#include \"stb_c_lexer.h\"\n\n#define STB_C_LEX_C_DECIMAL_INTS    Y   //  \"0|[1-9][0-9]*\"                        CLEX_intlit\n#define STB_C_LEX_C_HEX_INTS        Y   //  \"0x[0-9a-fA-F]+\"                       CLEX_intlit\n#define STB_C_LEX_C_OCTAL_INTS      Y   //  \"[0-7]+\"                               CLEX_intlit\n#define STB_C_LEX_C_DECIMAL_FLOATS  Y   //  \"[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?)     CLEX_floatlit\n#define STB_C_LEX_C99_HEX_FLOATS    N   //  \"0x{hex}+(.{hex}*)?[pP][-+]?{hex}+     CLEX_floatlit\n#define STB_C_LEX_C_IDENTIFIERS     Y   //  \"[_a-zA-Z][_a-zA-Z0-9]*\"               CLEX_id\n#define STB_C_LEX_C_DQ_STRINGS      Y   //  double-quote-delimited strings with escapes  CLEX_dqstring\n#define STB_C_LEX_C_SQ_STRINGS      N   //  single-quote-delimited strings with escapes  CLEX_ssstring\n#define STB_C_LEX_C_CHARS           Y   //  single-quote-delimited character with escape CLEX_charlits\n#define STB_C_LEX_C_COMMENTS        Y   //  \"/* comment */\"\n#define STB_C_LEX_CPP_COMMENTS      Y   //  \"// comment to end of line\\n\"\n#define STB_C_LEX_C_COMPARISONS     Y   //  \"==\" CLEX_eq  \"!=\" CLEX_noteq   \"<=\" CLEX_lesseq  \">=\" CLEX_greatereq\n#define STB_C_LEX_C_LOGICAL         Y   //  \"&&\"  CLEX_andand   \"||\"  CLEX_oror\n#define STB_C_LEX_C_SHIFTS          Y   //  \"<<\"  CLEX_shl      \">>\"  CLEX_shr\n#define STB_C_LEX_C_INCREMENTS      Y   //  \"++\"  CLEX_plusplus \"--\"  CLEX_minusminus\n#define STB_C_LEX_C_ARROW           Y   //  \"->\"  CLEX_arrow\n#define STB_C_LEX_EQUAL_ARROW       N   //  \"=>\"  CLEX_eqarrow\n#define STB_C_LEX_C_BITWISEEQ       Y   //  \"&=\"  CLEX_andeq    \"|=\"  CLEX_oreq     \"^=\"  CLEX_xoreq\n#define STB_C_LEX_C_ARITHEQ         Y   //  \"+=\"  CLEX_pluseq   \"-=\"  CLEX_minuseq\n                                        //  \"*=\"  CLEX_muleq    \"/=\"  CLEX_diveq    \"%=\" CLEX_modeq\n                                        //  if both STB_C_LEX_SHIFTS & STB_C_LEX_ARITHEQ:\n                                        //                      \"<<=\" CLEX_shleq    \">>=\" CLEX_shreq\n\n#define STB_C_LEX_PARSE_SUFFIXES    N   // letters after numbers are parsed as part of those numbers, and must be in suffix list below\n#define STB_C_LEX_DECIMAL_SUFFIXES  \"\"  // decimal integer suffixes e.g. \"uUlL\" -- these are returned as-is in string storage\n#define STB_C_LEX_HEX_SUFFIXES      \"\"  // e.g. \"uUlL\"\n#define STB_C_LEX_OCTAL_SUFFIXES    \"\"  // e.g. \"uUlL\"\n#define STB_C_LEX_FLOAT_SUFFIXES    \"\"  //\n\n#define STB_C_LEX_0_IS_EOF             Y  // if Y, ends parsing at '\\0'; if N, returns '\\0' as token\n#define STB_C_LEX_INTEGERS_AS_DOUBLES  N  // parses integers as doubles so they can be larger than 'int', but only if STB_C_LEX_STDLIB==N\n#define STB_C_LEX_MULTILINE_DSTRINGS   N  // allow newlines in double-quoted strings\n#define STB_C_LEX_MULTILINE_SSTRINGS   N  // allow newlines in single-quoted strings\n#define STB_C_LEX_USE_STDLIB           Y  // use strtod,strtol for parsing #s; otherwise inaccurate hack\n#define STB_C_LEX_DOLLAR_IDENTIFIER    Y  // allow $ as an identifier character\n#define STB_C_LEX_FLOAT_NO_DECIMAL     Y  // allow floats that have no decimal point if they have an exponent\n\n#define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES  N   // if Y, all CLEX_ token names are defined, even if never returned\n                                              // leaving it as N should help you catch config bugs\n\n#define STB_C_LEX_DISCARD_PREPROCESSOR    Y   // discard C-preprocessor directives (e.g. after prepocess\n                                              // still have #line, #pragma, etc)\n\n//#define STB_C_LEX_ISWHITE(str)    ... // return length in bytes of whitespace characters if first char is whitespace\n\n#define STB_C_LEXER_DEFINITIONS         // This line prevents the header file from replacing your definitions\n\n#include \"stb_c_lexer.h\"\n"
  },
  {
    "path": "tests/test_cpp_compilation.cpp",
    "content": "#define STB_IMAGE_WRITE_STATIC\n#define STBIWDEF static inline\n\n#include \"stb_image.h\"\n#include \"stb_rect_pack.h\"\n#include \"stb_truetype.h\"\n#include \"stb_image_write.h\"\n#include \"stb_c_lexer.h\"\n#include \"stb_perlin.h\"\n#include \"stb_dxt.h\"\n#include \"stb_divide.h\"\n#include \"stb_herringbone_wang_tile.h\"\n#include \"stb_ds.h\"\n#include \"stb_hexwave.h\"\n\n#include \"stb_sprintf.h\"\n#define STB_SPRINTF_IMPLEMENTATION\n#include \"stb_sprintf.h\"\n\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#define STB_TRUETYPE_IMPLEMENTATION\n#define STB_PERLIN_IMPLEMENTATION\n#define STB_DXT_IMPLEMENATION\n#define STB_C_LEXER_IMPLEMENTATIOn\n#define STB_DIVIDE_IMPLEMENTATION\n#define STB_IMAGE_IMPLEMENTATION\n#define STB_HERRINGBONE_WANG_TILE_IMPLEMENTATION\n#define STB_RECT_PACK_IMPLEMENTATION\n#define STB_VOXEL_RENDER_IMPLEMENTATION\n#define STB_CONNECTED_COMPONENTS_IMPLEMENTATION\n#define STB_HEXWAVE_IMPLEMENTATION\n#define STB_DS_IMPLEMENTATION\n#define STBDS_UNIT_TESTS\n\n#define STBI_MALLOC     my_malloc\n#define STBI_FREE       my_free\n#define STBI_REALLOC    my_realloc\n\nvoid *my_malloc(size_t) { return 0; }\nvoid *my_realloc(void *, size_t) { return 0; }\nvoid my_free(void *) { }\n\n#include \"stb_image.h\"\n#include \"stb_rect_pack.h\"\n#include \"stb_truetype.h\"\n#include \"stb_image_write.h\"\n#include \"stb_perlin.h\"\n#include \"stb_dxt.h\"\n#include \"stb_divide.h\"\n#include \"stb_herringbone_wang_tile.h\"\n#include \"stb_ds.h\"\n#include \"stb_hexwave.h\"\n\n#define STBCC_GRID_COUNT_X_LOG2  10\n#define STBCC_GRID_COUNT_Y_LOG2  10\n#include \"stb_connected_components.h\"\n\n#define STBVOX_CONFIG_MODE 1\n#include \"stb_voxel_render.h\"\n\n#define STBTE_DRAW_RECT(x0,y0,x1,y1,color)      do ; while(0)\n#define STBTE_DRAW_TILE(x,y,id,highlight,data)  do ; while(0)\n#define STB_TILEMAP_EDITOR_IMPLEMENTATION\n#include \"stb_tilemap_editor.h\"\n\n#include \"stb_easy_font.h\"\n\n#define STB_LEAKCHECK_IMPLEMENTATION\n#include \"stb_leakcheck.h\"\n\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\n#include \"stb_image_resize2.h\"\n\n//#include \"stretchy_buffer.h\"  // deprecating\n\n\n// avoid unused-function complaints\nvoid dummy2(void)\n{\n   stb_easy_font_spacing(1.0);\n   stb_easy_font_print(0,0,NULL,NULL,NULL,0);\n   stb_easy_font_width(NULL);\n   stb_easy_font_height(NULL);\n}\n\n\n////////////////////////////////////////////////////////////\n//\n// text edit\n\n#include <stdlib.h>\n#include <string.h> // memmove\n#include <ctype.h>  // isspace\n\n#define STB_TEXTEDIT_CHARTYPE   char\n#define STB_TEXTEDIT_STRING     text_control\n\n// get the base type\n#include \"stb_textedit.h\"\n\n// define our editor structure\ntypedef struct\n{\n   char *string;\n   int stringlen;\n   STB_TexteditState state;\n} text_control;\n\n// define the functions we need\nvoid layout_func(StbTexteditRow *row, STB_TEXTEDIT_STRING *str, int start_i)\n{\n   int remaining_chars = str->stringlen - start_i;\n   row->num_chars = remaining_chars > 20 ? 20 : remaining_chars; // should do real word wrap here\n   row->x0 = 0;\n   row->x1 = 20; // need to account for actual size of characters\n   row->baseline_y_delta = 1.25;\n   row->ymin = -1;\n   row->ymax =  0;\n}\n\nint delete_chars(STB_TEXTEDIT_STRING *str, int pos, int num)\n{\n   memmove(&str->string[pos], &str->string[pos+num], str->stringlen - (pos+num));\n   str->stringlen -= num;\n   return 1; // always succeeds\n}\n\nint insert_chars(STB_TEXTEDIT_STRING *str, int pos, STB_TEXTEDIT_CHARTYPE *newtext, int num)\n{\n   str->string = (char *) realloc(str->string, str->stringlen + num);\n   memmove(&str->string[pos+num], &str->string[pos], str->stringlen - pos);\n   memcpy(&str->string[pos], newtext, num);\n   str->stringlen += num;\n   return 1; // always succeeds\n}\n\n// define all the #defines needed \n\n#define KEYDOWN_BIT                    0x40000000\n\n#define STB_TEXTEDIT_STRINGLEN(tc)     ((tc)->stringlen)\n#define STB_TEXTEDIT_LAYOUTROW         layout_func\n#define STB_TEXTEDIT_GETWIDTH(tc,n,i)  (1) // quick hack for monospaced\n#define STB_TEXTEDIT_KEYTOTEXT(key)    (((key) & KEYDOWN_BIT) ? 0 : (key))\n#define STB_TEXTEDIT_GETCHAR(tc,i)     ((tc)->string[i])\n#define STB_TEXTEDIT_NEWLINE           '\\n'\n#define STB_TEXTEDIT_IS_SPACE(ch)      isspace(ch)\n#define STB_TEXTEDIT_DELETECHARS       delete_chars\n#define STB_TEXTEDIT_INSERTCHARS       insert_chars\n\n#define STB_TEXTEDIT_K_SHIFT           0x20000000\n#define STB_TEXTEDIT_K_CONTROL         0x10000000\n#define STB_TEXTEDIT_K_LEFT            (KEYDOWN_BIT | 1) // actually use VK_LEFT, SDLK_LEFT, etc\n#define STB_TEXTEDIT_K_RIGHT           (KEYDOWN_BIT | 2) // VK_RIGHT\n#define STB_TEXTEDIT_K_UP              (KEYDOWN_BIT | 3) // VK_UP\n#define STB_TEXTEDIT_K_DOWN            (KEYDOWN_BIT | 4) // VK_DOWN\n#define STB_TEXTEDIT_K_LINESTART       (KEYDOWN_BIT | 5) // VK_HOME\n#define STB_TEXTEDIT_K_LINEEND         (KEYDOWN_BIT | 6) // VK_END\n#define STB_TEXTEDIT_K_TEXTSTART       (STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_TEXTEND         (STB_TEXTEDIT_K_LINEEND   | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_DELETE          (KEYDOWN_BIT | 7) // VK_DELETE\n#define STB_TEXTEDIT_K_BACKSPACE       (KEYDOWN_BIT | 8) // VK_BACKSPACE\n#define STB_TEXTEDIT_K_UNDO            (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'z')\n#define STB_TEXTEDIT_K_REDO            (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'y')\n#define STB_TEXTEDIT_K_INSERT          (KEYDOWN_BIT | 9) // VK_INSERT\n#define STB_TEXTEDIT_K_WORDLEFT        (STB_TEXTEDIT_K_LEFT  | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_WORDRIGHT       (STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_PGUP            (KEYDOWN_BIT | 10) // VK_PGUP -- not implemented\n#define STB_TEXTEDIT_K_PGDOWN          (KEYDOWN_BIT | 11) // VK_PGDOWN -- not implemented\n\n#define STB_TEXTEDIT_IMPLEMENTATION\n#include \"stb_textedit.h\"\n\n\nvoid dummy3(void)\n{\n  stb_textedit_click(0,0,0,0);\n  stb_textedit_drag(0,0,0,0);\n  stb_textedit_cut(0,0);\n  stb_textedit_key(0,0,0);\n  stb_textedit_initialize_state(0,0);\n  stb_textedit_paste(0,0,0,0);\n}\n\n#include \"stb_c_lexer.h\"\n"
  },
  {
    "path": "tests/test_ds.c",
    "content": "#ifdef DS_PERF\n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_NONSTDC_NO_DEPRECATE\n#define _CRT_NON_CONFORMING_SWPRINTFS\n\n\n//#define STBDS_INTERNAL_SMALL_BUCKET    // make 64-bit bucket fit both keys and hash bits\n//#define STBDS_SIPHASH_2_4     // performance test 1_3 against 2_4\n//#define STBDS_INTERNAL_BUCKET_START    // don't bother offseting differently within bucket for different hash values\n//#define STBDS_FLUSH_CACHE  (1u<<20) // do this much memory traffic to flush the cache between some benchmarking measurements\n\n#include <stdio.h>\n\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#define STB_DEFINE\n#define STB_NO_REGISTRY\n#include \"../stb.h\"\n#endif\n\n#ifdef DS_TEST\n#define STBDS_UNIT_TESTS\n#define STBDS_SMALL_BUCKET\n#endif\n\n#ifdef DS_STATS\n#define STBDS_STATISTICS\n#endif\n\n#ifndef DS_PERF\n#define STBDS_ASSERT assert\n#include <assert.h>\n#endif\n\n#define STB_DS_IMPLEMENTATION\n#include \"../stb_ds.h\"\n\nsize_t churn_inserts, churn_deletes;\n\nvoid churn(int a, int b, int count)\n{\n  struct { int key,value; } *map=NULL;\n  int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i,i+1);\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      assert(k != 0);\n    }\n    assert(hmlen(map) == a);\n  }\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n}\n\n#ifdef DS_TEST\n#include <stdio.h>\nint main(int argc, char **argv)\n{\n  char *temp=NULL;\n  stbds_unit_tests();\n  arrins(temp, 0, 'a');\n  arrins(temp, arrlen(temp), 'b');\n  churn(0,100,1);\n  churn(3,7,50000);\n  churn(3,15,50000);\n  churn(16, 48, 25000);\n  churn(10, 15, 25000);\n  churn(200,500, 5000);\n  churn(2000,5000, 500);\n  churn(20000,50000, 50);\n  printf(\"Ok!\");\n  return 0;\n}\n#endif\n\n#ifdef DS_STATS\n#define MAX(a,b) ((a) > (b) ? (a) : (b))\nsize_t max_hit_probes, max_miss_probes, total_put_probes, total_miss_probes, churn_misses;\nvoid churn_stats(int a, int b, int count)\n{\n  struct { int key,value; } *map=NULL;\n  int i,j,n,k;\n  churn_misses = 0;\n  for (i=0; i < a; ++i) {\n    hmput(map,i,i+1);\n    max_hit_probes = MAX(max_hit_probes, stbds_hash_probes);\n    total_put_probes += stbds_hash_probes;\n    stbds_hash_probes = 0;\n  }\n    \n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n      max_hit_probes = MAX(max_hit_probes, stbds_hash_probes);\n      total_put_probes += stbds_hash_probes;\n      stbds_hash_probes = 0;\n    }\n    for (j=0; j < (b-a)*10; ++j) {\n      k=i+j;\n      (void) hmgeti(map,k); // miss\n      max_miss_probes = MAX(max_miss_probes, stbds_hash_probes);\n      total_miss_probes += stbds_hash_probes;\n      stbds_hash_probes = 0;\n      ++churn_misses;\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      stbds_hash_probes = 0;\n      assert(k);\n    }\n    assert(hmlen(map) == a);\n  }\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n}\n\nvoid reset_stats(void)\n{\n  stbds_array_grow=0, \n  stbds_hash_grow=0;\n  stbds_hash_shrink=0;\n  stbds_hash_rebuild=0;\n  stbds_hash_probes=0;\n  stbds_hash_alloc=0;\n  stbds_rehash_probes=0;\n  stbds_rehash_items=0;\n  max_hit_probes = 0;\n  max_miss_probes = 0;\n  total_put_probes = 0;\n  total_miss_probes = 0;\n}\n\nvoid print_churn_probe_stats(char *str)\n{\n  printf(\"Probes: %3d max hit, %3d max miss, %4.2f avg hit, %4.2f avg miss: %s\\n\",\n    (int) max_hit_probes, (int) max_miss_probes, (float) total_put_probes / churn_inserts, (float) total_miss_probes / churn_misses, str);\n  reset_stats();\n}\n\nint main(int arg, char **argv)\n{\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  return 0;\n}\n#endif\n\n\n#ifdef DS_PERF\n//char *strdup(const char *foo) { return 0; }\n//int stricmp(const char *a, const char *b) { return 0; }\n//int strnicmp(const char *a, const char *b, size_t n) { return 0; }\n\nunsigned __int64 t0, xsum, mn,mx,count;\nvoid begin(void)\n{\n  LARGE_INTEGER m;\n  QueryPerformanceCounter(&m);\n  t0 = m.QuadPart;\n  xsum = 0;\n  count = 0;\n  mx = 0;\n  mn = ~(unsigned __int64) 0;\n}\n\nvoid measure(void)\n{\n  unsigned __int64 t1, t;\n  LARGE_INTEGER m;\n  QueryPerformanceCounter(&m);\n  t1 = m.QuadPart;\n  t = t1-t0;\n  if (t1 < t0)\n    printf(\"ALERT: QueryPerformanceCounter was unordered!\\n\");\n  if (t < mn) mn = t;\n  if (t > mx) mx = t;\n  xsum += t;\n  ++count;\n  t0 = t1;\n}\n\nvoid dont_measure(void)\n{\n  LARGE_INTEGER m;\n  QueryPerformanceCounter(&m);\n  t0 = m.QuadPart;\n}\n\ndouble timer;\ndouble end(void)\n{\n  LARGE_INTEGER m;\n  QueryPerformanceFrequency(&m);\n\n  if (count > 3) {\n    // discard the highest and lowest\n    xsum -= mn;\n    xsum -= mx;\n    count -= 2;\n  }\n  timer = (double) (xsum) / count / m.QuadPart * 1000;\n  return timer;\n}\n\nvoid build(int a, int b, int count, int step)\n{\n  struct { int key,value; } *map=NULL;\n  int i,n;\n  for (i=0; i < a; ++i) {\n    n = i*step;\n    hmput(map,n,i+1);\n  }\n  measure();\n  churn_inserts = i;\n  hmfree(map);\n  dont_measure();\n}\n\n#ifdef STB__INCLUDE_STB_H\nvoid build_stb(int a, int b, int count, int step)\n{\n  stb_idict *d = stb_idict_new_size(8);\n  int i;\n  for (i=0; i < a; ++i)\n    stb_idict_add(d, i*step, i+1);\n  measure();\n  churn_inserts = i;\n  stb_idict_destroy(d);\n  dont_measure();\n}\n\nvoid multibuild_stb(int a, int b, int count, int step, int tables)\n{\n  stb_idict *d[50000];\n  int i,q;\n  for (q=0; q < tables; ++q)\n    d[q] = stb_idict_new_size(8);\n  dont_measure();\n  for (i=0; i < a; ++i)\n    for (q=0; q < tables; ++q)\n      stb_idict_add(d[q], i*step+q*771, i+1);\n  measure();\n  churn_inserts = i;\n  for (q=0; q < tables; ++q)\n    stb_idict_destroy(d[q]);\n  dont_measure();\n}\n\nint multisearch_stb(int a, int start, int end, int step, int tables)\n{\n  stb_idict *d[50000];\n  int i,q,total=0,v;\n  for (q=0; q < tables; ++q)\n    d[q] = stb_idict_new_size(8);\n  for (q=0; q < tables; ++q)\n    for (i=0; i < a; ++i)\n      stb_idict_add(d[q], i*step+q*771, i+1);\n  dont_measure();\n  for (i=start; i < end; ++i)\n    for (q=0; q < tables; ++q)\n      if (stb_idict_get_flag(d[q], i*step+q*771, &v))\n        total += v;\n  measure();\n  churn_inserts = i;\n  for (q=0; q < tables; ++q)\n    stb_idict_destroy(d[q]);\n  dont_measure();\n  return total;\n}\n#endif\n\nint multisearch(int a, int start, int end, int step, int tables)\n{\n  struct { int key,value; } *hash[50000];\n  int i,q,total=0;\n  for (q=0; q < tables; ++q)\n    hash[q] = NULL;\n  for (q=0; q < tables; ++q)\n    for (i=0; i < a; ++i)\n      hmput(hash[q], i*step+q*771, i+1);\n  dont_measure();\n  for (i=start; i < end; ++i)\n    for (q=0; q < tables; ++q)\n      total += hmget(hash[q], i*step+q*771);\n  measure();\n  churn_inserts = i;\n  for (q=0; q < tables; ++q)\n    hmfree(hash[q]);\n  dont_measure();\n  return total;\n}\n\nvoid churn_skip(unsigned int a, unsigned int b, int count)\n{\n  struct { unsigned int key,value; } *map=NULL;\n  unsigned int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i,i+1);\n  dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      assert(k != 0);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  hmfree(map);\n  dont_measure();\n}\n\ntypedef struct { int n[8]; } str32;\nvoid churn32(int a, int b, int count, int include_startup)\n{\n  struct { str32 key; int value; } *map=NULL;\n  int i,j,n;\n  str32 key = { 0 };\n  for (i=0; i < a; ++i) {\n    key.n[0] = i;\n    hmput(map,key,i+1);\n  }\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      key.n[0] = i;\n      hmput(map,key,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      key.n[0] = i-j-1;\n      hmdel(map,key);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  dont_measure();\n}\n\ntypedef struct { int n[32]; } str256;\nvoid churn256(int a, int b, int count, int include_startup)\n{\n  struct { str256 key; int value; } *map=NULL;\n  int i,j,n;\n  str256 key = { 0 };\n  for (i=0; i < a; ++i) {\n    key.n[0] = i;\n    hmput(map,key,i+1);\n  }\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      key.n[0] = i;\n      hmput(map,key,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      key.n[0] = i-j-1;\n      hmdel(map,key);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  dont_measure();\n}\n\nvoid churn8(int a, int b, int count, int include_startup)\n{\n  struct { size_t key,value; } *map=NULL;\n  int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i,i+1);\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      assert(k != 0);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  dont_measure();\n}\n\nvoid multichurn4(int a, int b, int count, int include_startup, int tables)\n{\n  struct { int key,value; } *map[50000];\n  int i,j,n,k,q;\n  for (q=0; q < tables; ++q)\n    map[q] = NULL;\n  dont_measure();\n\n  for (i=0; i < a; ++i)\n    for (q=0; q < tables; ++q)\n      hmput(map[q],i,i+1);\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      for (q=0; q < tables; ++q)\n        hmput(map[q],i,i+1);\n    }\n    assert(hmlen(map[0]) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      for (q=0; q < tables; ++q)\n        k = hmdel(map[q],k);\n      assert(k != 0);\n    }\n    assert(hmlen(map[0]) == a);\n  }\n  measure();\n  for (q=0; q < tables; ++q)\n    hmfree(map[q]);\n  churn_inserts = i * tables;\n  churn_deletes = (b-a) * n * tables;\n  dont_measure();\n}\n\nstruct {\n  unsigned __int64 start;\n  unsigned __int64 end;\n  int    table_size;\n} mstats[32][4000];\n\nconst int first_step = 64;\nconst int last_step = 384-48; // 32M\n\nvoid measure_build4(int step_log2)\n{\n  double length;\n  int i,j,k=0;\n  int step = 1 << step_log2;\n  unsigned __int64 t0,t1;\n  struct { int key,value; } *map=NULL;\n  double rdtsc_scale;\n  begin();\n  t0 = __rdtsc();\n\n  mstats[0][0].start = __rdtsc();\n  for (i=0; i < 256; ++i) {\n    hmput(map,k,k+1);\n    k += step;\n  }\n  mstats[0][first_step-1].end = __rdtsc();\n  mstats[0][first_step-1].table_size = k >> step_log2;\n  for (j=first_step; j < last_step; ++j) {\n    for (i=0; i < (1<<(j>>4)); ++i) {\n      hmput(map, k,k+1);\n      k += step;\n    }\n    mstats[0][j].end = __rdtsc();\n    mstats[0][j].table_size = k >> step_log2;\n  }\n  t1 = __rdtsc();\n  measure();\n  hmfree(map);\n  length = end();\n  rdtsc_scale = length / (t1-t0) * 1000;\n\n  for (j=1; j < last_step; ++j)\n    mstats[0][j].start = mstats[0][0].start;\n  for (j=first_step-1; j < last_step; ++j) {\n    printf(\"%12.4f,%12d,%12d,0,0,0\\n\", (mstats[0][j].end - mstats[0][j].start) * rdtsc_scale, mstats[0][j].table_size, mstats[0][j].table_size);\n  }\n}\n\n#ifdef STBDS_FLUSH_CACHE\nstatic int cache_index;\nchar dummy[8][STBDS_FLUSH_CACHE];\n\nint flush_cache(void)\n{\n  memmove(dummy[cache_index],dummy[cache_index]+1, sizeof(dummy[cache_index])-1);\n  cache_index = (cache_index+1)%8;\n  return dummy[cache_index][0];\n}\n#else\nint flush_cache(void) { return 0; }\n#endif\n\nint measure_average_lookup4(int step_log2)\n{\n  int total;\n  double length;\n  int i,j,k=0,q;\n  int step = 1 << step_log2;\n  unsigned __int64 t0,t1;\n  struct { int key,value; } *map=NULL;\n  double rdtsc_scale;\n  begin();\n  t0 = __rdtsc();\n\n  for (i=0; i < 128; ++i) {\n    hmput(map,k,k+1);\n    k += step;\n  }\n  for (j=first_step; j <= last_step; ++j) {\n    total += flush_cache();\n    mstats[0][j].start = __rdtsc();\n    for (q=i=0; i < 50000; ++i) {\n       total += hmget(map, q); // hit\n       if (++q == k) q = 0;\n    }\n    mstats[0][j].end = __rdtsc();\n    mstats[0][j].table_size = k;\n    total += flush_cache();\n    mstats[1][j].start = __rdtsc();\n    for (i=0; i < 50000; ++i) {\n       total += hmget(map, i+k); // miss\n    }\n    mstats[1][j].end = __rdtsc();\n    mstats[1][j].table_size = k;\n\n    // expand table\n    for (i=0; i < (1<<(j>>4)); ++i) {\n      hmput(map, k,k+1);\n      k += step;\n    }\n  }\n\n  t1 = __rdtsc();\n  measure();\n  hmfree(map);\n  length = end();\n  rdtsc_scale = length / (t1-t0) * 1000;\n\n  for (j=first_step; j <= last_step; ++j) {\n    // time,table_size,numins,numhit,nummiss,numperflush\n    printf(\"%12.4f,%12d,0,50000,0,0\\n\", (mstats[0][j].end - mstats[0][j].start) * rdtsc_scale, mstats[0][j].table_size);\n  }\n  for (j=first_step; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,0,50000,0\\n\", (mstats[1][j].end - mstats[1][j].start) * rdtsc_scale, mstats[1][j].table_size);\n  }\n  return total;\n}\n\nint measure_worst_lookup4_a(int step_log2)\n{\n  int total;\n  double length;\n  int i,j,k=0,q,worst_q,n,z,attempts;\n  int step = 1 << step_log2;\n  unsigned __int64 t0,t1;\n  unsigned __int64 m0,m1,worst;\n  struct { int key,value; } *map=NULL;\n  double rdtsc_scale;\n  begin();\n  t0 = __rdtsc();\n\n  memset(mstats, 0, sizeof(mstats));\n  for (j=first_step; j <= last_step; ++j)\n    mstats[0][j].end = mstats[1][j].end = ~(unsigned __int64) 0;\n\n  for(attempts=0; attempts < 2; ++attempts) {\n    k = 0;\n    stbds_rand_seed(0); // force us to get the same table every time\n    for (i=0; i < 128; ++i) {\n      hmput(map,k,k+1);\n      k += step;\n    }\n    for (j=first_step; j <= last_step; ++j) {\n      unsigned __int64 times[32];\n\n      // find the worst hit time\n      for (z=0; z < 2; ++z) { // try the bisectioning measurement 4 times\n        worst = 0;\n        for (n=0; n < 10; ++n) { // test 400 keys total\n          // find the worst time to hit 20 keys\n          q=0;\n          worst_q = 0;\n          total += flush_cache();\n          m0 = __rdtsc();\n          for (i=0; i < 20; ++i) {\n            total += hmget(map, q); // hit\n            if (++q == k) q = 0;\n          }\n          m1 = __rdtsc();\n          // for each n, check if this is the worst lookup we've seen\n          if (m1 - m0 > worst) {\n            worst = m1-m0;\n            worst_q = q - i;\n            if (worst_q < 0) q += k;\n          }\n        }\n        // after 400 keys, take the worst 20 keys, and try each one\n        worst = 0;\n        q = worst_q;\n        for (i=0; i < 20; ++i) {\n          total += flush_cache();\n          m0 = __rdtsc();\n          total += hmget(map, q); // hit\n          m1 = __rdtsc();\n          if (m1 - m0 > worst)\n            worst = m1-m0;\n          if (++q == k) q = 0;\n        }\n        times[z] = worst;\n      }\n      // find the worst time in the bunch\n      worst = 0;\n      for (i=0; i < z; ++i)\n        if (times[i] > worst)\n          worst = times[i];\n      // take the best of 'attempts', to discard outliers\n      if (worst < mstats[0][j].end)\n        mstats[0][j].end = worst;\n      mstats[0][j].start = 0;\n      mstats[0][j].table_size = k >> step_log2;\n\n      // find the worst miss time\n      for (z=0; z < 8; ++z) { // try the bisectioning measurement 8 times\n        worst = 0;\n        for (n=0; n < 20; ++n) { // test 400 keys total\n          // find the worst time to hit 20 keys\n          q=k;\n          worst_q = 0;\n          total += flush_cache();\n          m0 = __rdtsc();\n          for (i=0; i < 20; ++i) {\n            total += hmget(map, q); // hit\n          }\n          m1 = __rdtsc();\n          // for each n, check if this is the worst lookup we've seen\n          if (m1 - m0 > worst) {\n            worst = m1-m0;\n            worst_q = q - i;\n          }\n        }\n        // after 400 keys, take the worst 20 keys, and try each one\n        worst = 0;\n        q = worst_q;\n        for (i=0; i < 20; ++i) {\n          total += flush_cache();\n          m0 = __rdtsc();\n          total += hmget(map, q); // hit\n          m1 = __rdtsc();\n          if (m1 - m0 > worst)\n            worst = m1-m0;\n        }\n        times[z] = worst;\n      }\n      // find the worst time in the bunch\n      worst = 0;\n      for (i=0; i < z; ++i)\n        if (times[i] > worst)\n          worst = times[i];\n      if (worst < mstats[1][j].end)\n        mstats[1][j].end = worst;\n      mstats[1][j].start = 0;\n      mstats[1][j].table_size = k >> step_log2;\n\n      // expand table\n      for (i=0; i < (1<<(j>>4)); ++i) {\n        hmput(map, k,k+1);\n        k += step;\n      }\n    }\n    hmfree(map);\n  }\n\n  t1 = __rdtsc();\n  measure();\n  length = end();\n  rdtsc_scale = length / (t1-t0) * 1000;\n\n  for (j=first_step; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,1,0,1\\n\", (mstats[0][j].end - mstats[0][j].start) * rdtsc_scale, mstats[0][j].table_size);\n  }\n  for (j=first_step; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,0,1,1\\n\", (mstats[1][j].end - mstats[1][j].start) * rdtsc_scale, mstats[1][j].table_size);\n  }\n  return total;\n}\n\nint measure_worst_lookup4_b(int step_log2)\n{\n  int total;\n  double length;\n  int i,j,k=0,q,worst_q,n,z,attempts;\n  int step = 1 << step_log2;\n  unsigned __int64 t0,t1;\n  unsigned __int64 m0,m1,worst;\n  struct { int key,value; } *map=NULL;\n  double rdtsc_scale;\n  begin();\n  t0 = __rdtsc();\n\n  memset(mstats, 0, sizeof(mstats));\n  for (j=first_step; j <= last_step; ++j)\n    mstats[0][j].end = mstats[1][j].end = ~(unsigned __int64) 0;\n\n  k = 0;\n  stbds_rand_seed(0); // force us to get the same table every time\n  for (i=0; i < 128; ++i) {\n    hmput(map,k,k+1);\n    k += step;\n  }\n  for (j=first_step; j <= last_step; ++j) {\n    unsigned __int64 times[32];\n\n    // find the worst hit time\n    for (z=0; z < 8; ++z) { // try this 8 times\n      worst = 0;\n      q=0;\n      for (i=0; i < 5000; ++i) {\n        total += hmget(map, q);\n        m0 = __rdtsc();\n        total += hmget(map, q);\n        m1 = __rdtsc();\n        if (m1 - m0 > worst) {\n          worst = m1-m0;\n          worst_q = q - i;\n        }\n        if (++q == k) q = 0;\n      }\n      // now retry with the worst one, but find the shortest time for it\n      worst = ~(unsigned __int64) 0;\n      for (i=0; i < 4; ++i) {\n        total += flush_cache();\n        m0 = __rdtsc();\n        total += hmget(map,worst_q);\n        m1 = __rdtsc();\n        if (m1-m0 < worst)\n          worst = m1-m0;\n      }\n      times[z] = worst;\n    }\n\n    // find the worst of those\n    worst = 0;\n    for (i=0; i < z; ++i)\n      if (times[i] > worst)\n        worst = times[i];\n    mstats[0][j].start = 0;\n    mstats[0][j].end = worst;\n    mstats[0][j].table_size = k;\n\n    // find the worst miss time\n    for (z=0; z < 8; ++z) { // try this 8 times\n      worst = 0;\n      q=k;\n      for (i=0; i < 5000; ++i) {\n        total += hmget(map, q);\n        m0 = __rdtsc();\n        total += hmget(map, q);\n        m1 = __rdtsc();\n        if (m1 - m0 > worst) {\n          worst = m1-m0;\n          worst_q = q - i;\n        }\n        //printf(\"%6llu \", m1-m0);\n      }\n      // now retry with the worst one, but find the shortest time for it\n      worst = ~(unsigned __int64) 0;\n      for (i=0; i < 4; ++i) {\n        total += flush_cache();\n        m0 = __rdtsc();\n        total += hmget(map,worst_q);\n        m1 = __rdtsc();\n        if (m1-m0 < worst)\n          worst = m1-m0;\n      }\n      times[z] = worst;\n    }\n\n    // find the worst of those\n    worst = 0;\n    for (i=0; i < z; ++i)\n      if (times[i] > worst)\n        worst = times[i];\n    mstats[1][j].start = 0;\n    mstats[1][j].end = worst;\n    mstats[1][j].table_size = k;\n\n    // expand table\n    for (i=0; i < (1<<(j>>4)); ++i) {\n      hmput(map, k,k+1);\n      k += step;\n    }\n  }\n  hmfree(map);\n\n  t1 = __rdtsc();\n  measure();\n  length = end();\n  rdtsc_scale = length / (t1-t0) * 1000;\n\n  for (j=first_step+1; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,1,0,1\\n\", (mstats[0][j].end - mstats[0][j].start) * rdtsc_scale, mstats[0][j].table_size);\n  }\n  for (j=first_step+1; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,0,1,1\\n\", (mstats[1][j].end - mstats[1][j].start) * rdtsc_scale, mstats[1][j].table_size);\n  }\n  return total;\n}\n\nint measure_uncached_lookup4(int step_log2)\n{\n  int total;\n  double length;\n  int i,j,k=0,q;\n  int step = 1 << step_log2;\n  unsigned __int64 t0,t1;\n  struct { int key,value; } *map=NULL;\n  double rdtsc_scale;\n  begin();\n  t0 = __rdtsc();\n\n  map = NULL;\n  for (i=0; i < 128; ++i) {\n    hmput(map,k,k+1);\n    k += step;\n  }\n  for (j=first_step; j <= last_step; ++j) {\n    mstats[0][j].start = __rdtsc();\n    mstats[0][j].end = 0;\n    for (q=i=0; i < 512; ++i) {\n      if ((i & 3) == 0) {\n        mstats[0][j].end += __rdtsc();\n        total += flush_cache();\n        mstats[0][j].start += __rdtsc();\n      }\n      total += hmget(map, q); // hit\n      if (++q == k) q = 0;\n    }\n    mstats[0][j].end += __rdtsc();\n    mstats[0][j].table_size = k;\n    total += flush_cache();\n    mstats[1][j].end = 0;\n    mstats[1][j].start = __rdtsc();\n    for (i=0; i < 512; ++i) {\n      if ((i & 3) == 0) {\n        mstats[1][j].end += __rdtsc();\n        total += flush_cache();\n        mstats[1][j].start += __rdtsc();\n      }\n      total += hmget(map, i+k); // miss\n    }\n    mstats[1][j].end += __rdtsc();\n    mstats[1][j].table_size = k;\n\n    // expand table\n    for (i=0; i < (1<<(j>>4)); ++i) {\n      hmput(map, k,k+1);\n      k += step;\n    }\n  }\n  hmfree(map);\n\n  t1 = __rdtsc();\n  measure();\n  length = end();\n  rdtsc_scale = length / (t1-t0) * 1000;\n\n  for (j=first_step; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,512,0,4\\n\", (mstats[0][j].end - mstats[0][j].start) * rdtsc_scale, mstats[0][j].table_size);\n  }\n  for (j=first_step; j <= last_step; ++j) {\n    printf(\"%12.4f,%12d,0,0,512,4\\n\", (mstats[1][j].end - mstats[1][j].start) * rdtsc_scale, mstats[1][j].table_size);\n  }\n  return total;\n}\n\n\n\n\nint main(int arg, char **argv)\n{\n  int n,s,w;\n  double worst = 0;\n\n  printf(\"# size_t=%d,\", (int) sizeof(size_t));\n\n// number of cache-lines\n#ifdef STBDS_SMALL_BUCKET\n  printf(\"cacheline=%d,\", 1);\n#else\n  printf(\"cacheline=%d,\", sizeof(size_t)==8 ? 2 : 1);\n#endif\n#ifdef STBDS_FLUSH_CACHE\n  printf(\"%d,\", (int) stbds_log2(STBDS_FLUSH_CACHE));\n#else\n  printf(\"0,\");\n#endif\n#ifdef STBDS_BUCKET_START    // don't bother offseting differently within bucket for different hash values\n  printf(\"STBDS_BUCKET_START,\");\n#else\n  printf(\",\");\n#endif\n#ifdef STBDS_SIPHASH_2_4\n  printf(\"STBDS_SIPHASH_2_4,\");\n#else\n  printf(\",\");\n#endif\n  printf(\"\\n\");\n\n  measure_worst_lookup4_b(0);\n  //measure_worst_lookup4_a(0);\n  measure_average_lookup4(0);\n  measure_uncached_lookup4(0);\n  measure_build4(0);\n  return 0;\n\n#if 0\n  begin(); for (n=0; n < 2000; ++n) { build_stb(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { build_stb(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { build_stb(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { build_stb(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { build_stb(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table\\n\", timer);\n#endif\n\n#if 0\n  begin(); for (n=0; n < 2000; ++n) { churn32(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { churn32(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { churn32(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { churn32(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn32(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 32-byte key\\n\", timer);\n\n  begin(); for (n=0; n < 2000; ++n) { churn256(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { churn256(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { churn256(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { churn256(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn256(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 256-byte key\\n\", timer);\n#endif\n\n  begin(); for (n=0; n <   20; ++n) { multisearch_stb(2000,0,2000,1,1000);    } end(); printf(\"  // %7.2fms : 2,000,000 hits on 1,000   2K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { multisearch_stb(20000,0,2000,1,1000);   } end(); printf(\"  // %7.2fms : 2,000,000 hits on 1,000  20K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    6; ++n) { multisearch_stb(200000,0,2000,1,1000);  } end(); printf(\"  // %7.2fms : 2,000,000 hits on 1,000 200K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multisearch_stb(2000000,0,20000,1,100); } end(); printf(\"  // %7.2fms : 2,000,000 hits on   100   2M table w/ 4-byte key\\n\", timer);\n\n  begin(); for (n=0; n <   20; ++n) { multisearch    (2000,0,2000,1,1000);    } end(); printf(\"  // %7.2fms : 2,000,000 hits on 1,000   2K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { multisearch    (20000,0,2000,1,1000);   } end(); printf(\"  // %7.2fms : 2,000,000 hits on 1,000  20K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    6; ++n) { multisearch    (200000,0,2000,1,1000);  } end(); printf(\"  // %7.2fms : 2,000,000 hits on 1,000 200K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multisearch    (2000000,0,20000,1,100); } end(); printf(\"  // %7.2fms : 2,000,000 hits on   100   2M table w/ 4-byte key\\n\", timer);\n\n\n#if 1\n  begin(); for (n=0; n <    2; ++n) { multibuild_stb(2000,0,0,1,10000); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 10,000   2K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multibuild_stb(20000,0,0,1,1000); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating  1,000  20K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multibuild_stb(200000,0,0,1,100); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating    100 200K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multibuild_stb(2000000,0,0,1,10); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating     10   2M table w/ 4-byte key\\n\", timer);\n\n  begin(); for (n=0; n <    2; ++n) { multichurn4(2000,0,0,1,10000); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 10,000   2K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multichurn4(20000,0,0,1,1000); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating  1,000  20K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multichurn4(200000,0,0,1,100); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating    100 200K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { multichurn4(2000000,0,0,1,10); } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating     10   2M table w/ 4-byte key\\n\", timer);\n#endif\n\n  begin(); for (n=0; n < 2000; ++n) { build(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { build(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { build(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { build(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { build(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 4-byte key\\n\", timer);\n\n  begin(); for (n=0; n < 2000; ++n) { churn8(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { churn8(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { churn8(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { churn8(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn8(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 8-byte key\\n\", timer);\n\n  begin(); for (n=0; n <   60; ++n) { churn_skip(2000,2100,5000);            } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 2K table\\n\", timer);\n  begin(); for (n=0; n <   30; ++n) { churn_skip(20000,21000,500);           } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 20K table\\n\", timer);\n  begin(); for (n=0; n <   15; ++n) { churn_skip(200000,201000,500);         } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 200K table\\n\", timer);\n  begin(); for (n=0; n <    8; ++n) { churn_skip(2000000,2001000,500);       } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 2M table\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn_skip(20000000,20001000,500);     } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 20M table\\n\", timer);\n  begin(); for (n=0; n <    1; ++n) { churn_skip(200000000u,200001000u,500); } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 200M table\\n\", timer);\n  // even though the above measures a roughly fixed amount of work, we still have to build the table n times, hence the fewer measurements each time\n\n  begin(); for (n=0; n <   60; ++n) { churn_skip(1000,3000,250);             } end(); printf(\"  // %7.2fms :    500,000 inserts & deletes in 2K table\\n\", timer);\n  begin(); for (n=0; n <   15; ++n) { churn_skip(10000,30000,25);            } end(); printf(\"  // %7.2fms :    500,000 inserts & deletes in 20K table\\n\", timer);\n  begin(); for (n=0; n <    7; ++n) { churn_skip(100000,300000,10);          } end(); printf(\"  // %7.2fms :  2,000,000 inserts & deletes in 200K table\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { churn_skip(1000000,3000000,10);        } end(); printf(\"  // %7.2fms : 20,000,000 inserts & deletes in 2M table\\n\", timer);\n\n  // search for bad intervals.. in practice this just seems to measure execution variance\n  for (s = 2; s < 64; ++s) {\n    begin(); for (n=0; n < 50; ++n) { build(200000,0,0,s); } end();\n    if (timer > worst) {\n      worst = timer;\n      w = s;\n    }\n  }\n  for (; s <= 1024; s *= 2) {\n    begin(); for (n=0; n < 50; ++n) { build(200000,0,0,s); } end();\n    if (timer > worst) {\n      worst = timer;\n      w = s;\n    }\n  }\n  printf(\"  // %7.2fms(%d)   : Worst time from inserting 200,000 items with spacing %d.\\n\", worst, w, w);\n\n  return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/test_ds_cpp.cpp",
    "content": "#include <stdio.h>\n\n#ifdef DS_TEST\n#define STBDS_UNIT_TESTS\n#endif\n\n#ifdef DS_STATS\n#define STBDS_STATISTICS\n#endif\n\n#ifndef DS_PERF\n#define STBDS_ASSERT assert\n#include <assert.h>\n#endif\n\n//#define STBDS_SIPHASH_2_4\n#define STB_DS_IMPLEMENTATION\n#include \"../stb_ds.h\"\n\nsize_t churn_inserts, churn_deletes;\n\nvoid churn(int a, int b, int count)\n{\n  struct { int key,value; } *map=NULL;\n  int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i,i+1);\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      assert(k != 0);\n    }\n    assert(hmlen(map) == a);\n  }\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n}\n\n#ifdef DS_TEST\n#include <stdio.h>\nint main(int argc, char **argv)\n{\n  stbds_unit_tests();\n  churn(0,100,1);\n  churn(3,7,50000);\n  churn(3,15,50000);\n  churn(16, 48, 25000);\n  churn(10, 15, 25000);\n  churn(200,500, 5000);\n  churn(2000,5000, 500);\n  churn(20000,50000, 50);\n  printf(\"Ok!\");\n  return 0;\n}\n#endif\n\n#ifdef DS_STATS\n#define MAX(a,b) ((a) > (b) ? (a) : (b))\nsize_t max_hit_probes, max_miss_probes, total_put_probes, total_miss_probes, churn_misses;\nvoid churn_stats(int a, int b, int count)\n{\n  struct { int key,value; } *map=NULL;\n  int i,j,n,k;\n  churn_misses = 0;\n  for (i=0; i < a; ++i) {\n    hmput(map,i,i+1);\n    max_hit_probes = MAX(max_hit_probes, stbds_hash_probes);\n    total_put_probes += stbds_hash_probes;\n    stbds_hash_probes = 0;\n  }\n    \n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n      max_hit_probes = MAX(max_hit_probes, stbds_hash_probes);\n      total_put_probes += stbds_hash_probes;\n      stbds_hash_probes = 0;\n    }\n    for (j=0; j < (b-a)*10; ++j) {\n      k=i+j;\n      (void) hmgeti(map,k); // miss\n      max_miss_probes = MAX(max_miss_probes, stbds_hash_probes);\n      total_miss_probes += stbds_hash_probes;\n      stbds_hash_probes = 0;\n      ++churn_misses;\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      stbds_hash_probes = 0;\n      assert(k);\n    }\n    assert(hmlen(map) == a);\n  }\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n}\n\nvoid reset_stats(void)\n{\n  stbds_array_grow=0, \n  stbds_hash_grow=0;\n  stbds_hash_shrink=0;\n  stbds_hash_rebuild=0;\n  stbds_hash_probes=0;\n  stbds_hash_alloc=0;\n  stbds_rehash_probes=0;\n  stbds_rehash_items=0;\n  max_hit_probes = 0;\n  max_miss_probes = 0;\n  total_put_probes = 0;\n  total_miss_probes = 0;\n}\n\nvoid print_churn_probe_stats(char *str)\n{\n  printf(\"Probes: %3d max hit, %3d max miss, %4.2f avg hit, %4.2f avg miss: %s\\n\",\n    (int) max_hit_probes, (int) max_miss_probes, (float) total_put_probes / churn_inserts, (float) total_miss_probes / churn_misses, str);\n  reset_stats();\n}\n\nint main(int arg, char **argv)\n{\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(0,500000,1); print_churn_probe_stats(\"Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  churn_stats(49000,50000,500); print_churn_probe_stats(\"Deleting/Inserting 500000 items\");\n  return 0;\n}\n#endif\n\n#ifdef DS_PERF\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#define STB_DEFINE\n#define STB_NO_REGISTRY\n//#include \"../stb.h\"\n\n\nsize_t t0, sum, mn,mx,count;\nvoid begin(void)\n{\n  size_t t0;\n  LARGE_INTEGER m;\n  QueryPerformanceCounter(&m);\n  t0 = m.QuadPart;\n  sum = 0;\n  count = 0;\n  mx = 0;\n  mn = ~(size_t) 0;\n}\n\nvoid measure(void)\n{\n  size_t t1, t;\n  LARGE_INTEGER m;\n  QueryPerformanceCounter(&m);\n  t1 = m.QuadPart;\n  t = t1-t0;\n  if (t1 < t0)\n    printf(\"ALERT: QueryPerformanceCounter was unordered!\\n\");\n  if (t < mn) mn = t;\n  if (t > mx) mx = t;\n  sum += t;\n  ++count;\n  t0 = t1;\n}\n\nvoid dont_measure(void)\n{\n  size_t t1, t;\n  LARGE_INTEGER m;\n  QueryPerformanceCounter(&m);\n  t0 = m.QuadPart;\n}\n\ndouble timer;\nvoid end(void)\n{\n  LARGE_INTEGER m;\n  QueryPerformanceFrequency(&m);\n\n  if (count > 3) {\n    // discard the highest and lowest\n    sum -= mn;\n    sum -= mx;\n    count -= 2;\n  }\n  timer = (double) (sum) / count / m.QuadPart * 1000;\n}\n\nvoid build(int a, int b, int count, int step)\n{\n  struct { int key,value; } *map=NULL;\n  int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i*step,i+1);\n  measure();\n  churn_inserts = i;\n  hmfree(map);\n  dont_measure();\n}\n\n#ifdef STB__INCLUDE_STB_H\nvoid build_stb(int a, int b, int count, int step)\n{\n  stb_idict *d = stb_idict_new_size(8);\n  struct { int key,value; } *map=NULL;\n  int i,j,n,k;\n  for (i=0; i < a; ++i)\n    stb_idict_add(d, i*step, i+1);\n  measure();\n  churn_inserts = i;\n  stb_idict_destroy(d);\n  dont_measure();\n}\n#endif\n\nvoid churn_skip(unsigned int a, unsigned int b, int count)\n{\n  struct { unsigned int key,value; } *map=NULL;\n  unsigned int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i,i+1);\n  dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      assert(k != 0);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  hmfree(map);\n  dont_measure();\n}\n\ntypedef struct { int n[8]; } str32;\nvoid churn32(int a, int b, int count, int include_startup)\n{\n  struct { str32 key; int value; } *map=NULL;\n  int i,j,n;\n  str32 key = { 0 };\n  for (i=0; i < a; ++i) {\n    key.n[0] = i;\n    hmput(map,key,i+1);\n  }\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      key.n[0] = i;\n      hmput(map,key,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      key.n[0] = i-j-1;\n      hmdel(map,key);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  dont_measure();\n}\n\ntypedef struct { int n[32]; } str256;\nvoid churn256(int a, int b, int count, int include_startup)\n{\n  struct { str256 key; int value; } *map=NULL;\n  int i,j,n;\n  str256 key = { 0 };\n  for (i=0; i < a; ++i) {\n    key.n[0] = i;\n    hmput(map,key,i+1);\n  }\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      key.n[0] = i;\n      hmput(map,key,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      key.n[0] = i-j-1;\n      hmdel(map,key);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  dont_measure();\n}\n\nvoid churn8(int a, int b, int count, int include_startup)\n{\n  struct { size_t key,value; } *map=NULL;\n  int i,j,n,k;\n  for (i=0; i < a; ++i)\n    hmput(map,i,i+1);\n  if (!include_startup)\n    dont_measure();\n  for (n=0; n < count; ++n) {\n    for (j=a; j < b; ++j,++i) {\n      hmput(map,i,i+1);\n    }\n    assert(hmlen(map) == b);\n    for (j=a; j < b; ++j) {\n      k=i-j-1;\n      k = hmdel(map,k);\n      assert(k != 0);\n    }\n    assert(hmlen(map) == a);\n  }\n  measure();\n  hmfree(map);\n  churn_inserts = i;\n  churn_deletes = (b-a) * n;\n  dont_measure();\n}\n\n\nint main(int arg, char **argv)\n{\n  int n,s,w;\n  double worst = 0;\n\n#if 0\n  begin(); for (n=0; n < 2000; ++n) { build_stb(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { build_stb(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { build_stb(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { build_stb(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { build_stb(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table\\n\", timer);\n#endif\n\n  begin(); for (n=0; n < 2000; ++n) { churn8(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { churn8(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { churn8(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { churn8(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 8-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn8(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 8-byte key\\n\", timer);\n\n#if 0\n  begin(); for (n=0; n < 2000; ++n) { churn32(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { churn32(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { churn32(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { churn32(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 32-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn32(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 32-byte key\\n\", timer);\n\n  begin(); for (n=0; n < 2000; ++n) { churn256(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { churn256(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { churn256(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { churn256(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 256-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn256(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 256-byte key\\n\", timer);\n#endif\n\n  begin(); for (n=0; n < 2000; ++n) { build(2000,0,0,1);          } end(); printf(\"  // %7.2fms :      2,000 inserts creating 2K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <  500; ++n) { build(20000,0,0,1);         } end(); printf(\"  // %7.2fms :     20,000 inserts creating 20K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <  100; ++n) { build(200000,0,0,1);        } end(); printf(\"  // %7.2fms :    200,000 inserts creating 200K table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <   10; ++n) { build(2000000,0,0,1);       } end(); printf(\"  // %7.2fms :  2,000,000 inserts creating 2M table w/ 4-byte key\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { build(20000000,0,0,1);      } end(); printf(\"  // %7.2fms : 20,000,000 inserts creating 20M table w/ 4-byte key\\n\", timer);\n\n  begin(); for (n=0; n <   60; ++n) { churn_skip(2000,2100,5000);            } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 2K table\\n\", timer);\n  begin(); for (n=0; n <   30; ++n) { churn_skip(20000,21000,500);           } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 20K table\\n\", timer);\n  begin(); for (n=0; n <   15; ++n) { churn_skip(200000,201000,500);         } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 200K table\\n\", timer);\n  begin(); for (n=0; n <    8; ++n) { churn_skip(2000000,2001000,500);       } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 2M table\\n\", timer);\n  begin(); for (n=0; n <    5; ++n) { churn_skip(20000000,20001000,500);     } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 20M table\\n\", timer);\n  begin(); for (n=0; n <    1; ++n) { churn_skip(200000000u,200001000u,500); } end(); printf(\"  // %7.2fms : 500,000 inserts & deletes in 200M table\\n\", timer);\n  // even though the above measures a roughly fixed amount of work, we still have to build the table n times, hence the fewer measurements each time\n\n  begin(); for (n=0; n <   60; ++n) { churn_skip(1000,3000,250);             } end(); printf(\"  // %7.2fms :    500,000 inserts & deletes in 2K table\\n\", timer);\n  begin(); for (n=0; n <   15; ++n) { churn_skip(10000,30000,25);            } end(); printf(\"  // %7.2fms :    500,000 inserts & deletes in 20K table\\n\", timer);\n  begin(); for (n=0; n <    7; ++n) { churn_skip(100000,300000,10);          } end(); printf(\"  // %7.2fms :  2,000,000 inserts & deletes in 200K table\\n\", timer);\n  begin(); for (n=0; n <    2; ++n) { churn_skip(1000000,3000000,10);        } end(); printf(\"  // %7.2fms : 20,000,000 inserts & deletes in 2M table\\n\", timer);\n\n  // search for bad intervals.. in practice this just seems to measure execution variance\n  for (s = 2; s < 64; ++s) {\n    begin(); for (n=0; n < 50; ++n) { build(200000,0,0,s); } end();\n    if (timer > worst) {\n      worst = timer;\n      w = s;\n    }\n  }\n  for (; s <= 1024; s *= 2) {\n    begin(); for (n=0; n < 50; ++n) { build(200000,0,0,s); } end();\n    if (timer > worst) {\n      worst = timer;\n      w = s;\n    }\n  }\n  printf(\"  // %7.2fms(%d)   : Worst time from inserting 200,000 items with spacing %d.\\n\", worst, w, w);\n\n  return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/test_dxt.c",
    "content": "#include \"stb_dxt.h\"\n"
  },
  {
    "path": "tests/test_easyfont.c",
    "content": "#include \"stb_easy_font.h\"\n\nvoid ef_dummy(void)\n{\n   // suppress unsused-function warning\n   stb_easy_font_spacing(0);\n   stb_easy_font_print(0,0,0,0,0,0);\n   stb_easy_font_width(0);\n   stb_easy_font_height(0);\n}"
  },
  {
    "path": "tests/test_image.c",
    "content": "#ifdef __clang__\n#define STBIDEF static inline\n#endif\n\n#define STB_IMAGE_STATIC\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\""
  },
  {
    "path": "tests/test_image_write.c",
    "content": "#ifdef __clang__\n#define STBIWDEF static inline\n#endif\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#define STB_IMAGE_WRITE_STATIC\n#include \"stb_image_write.h\""
  },
  {
    "path": "tests/test_perlin.c",
    "content": "#include \"stb_perlin.h\""
  },
  {
    "path": "tests/test_png_paeth.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\n// Reference Paeth filter as per PNG spec\nstatic int ref_paeth(int a, int b, int c)\n{\n   int p = a + b - c;\n   int pa = abs(p-a);\n   int pb = abs(p-b);\n   int pc = abs(p-c);\n   if (pa <= pb && pa <= pc) return a;\n   if (pb <= pc) return b;\n   return c;\n}\n\n// Optimized Paeth filter\nstatic int opt_paeth(int a, int b, int c)\n{\n   int thresh = c*3 - (a + b);\n   int lo = a < b ? a : b;\n   int hi = a < b ? b : a;\n   int t0 = (hi <= thresh) ? lo : c;\n   int t1 = (thresh <= lo) ? hi : t0;\n   return t1;\n}\n\nint main()\n{\n   // Exhaustively test the functions match for all byte inputs a, b,c in [0,255]\n   for (int i = 0; i < (1 << 24); ++i) {\n      int a = i & 0xff;\n      int b = (i >> 8) & 0xff;\n      int c = (i >> 16) & 0xff;\n\n      int ref = ref_paeth(a, b, c);\n      int opt = opt_paeth(a, b, c);\n      if (ref != opt) {\n         fprintf(stderr, \"mismatch at a=%3d b=%3d c=%3d: ref=%3d opt=%3d\\n\", a, b, c, ref, opt);\n         return 1;\n      }\n   }\n\n   printf(\"all ok!\\n\");\n   return 0;\n}\n\n// vim:sw=3:sts=3:et\n"
  },
  {
    "path": "tests/test_png_regress.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\n#define STBI_WINDOWS_UTF8\n\n#ifdef _WIN32\n#define WIN32 // what stb.h checks\n#pragma comment(lib, \"advapi32.lib\")\n#endif\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#define STB_DEFINE\n#include \"deprecated/stb.h\"\n\nstatic unsigned int fnv1a_hash32(const stbi_uc *bytes, size_t len)\n{\n   unsigned int hash = 0x811c9dc5;\n   unsigned int mul = 0x01000193;\n   size_t i;\n\n   for (i = 0; i < len; ++i)\n      hash = (hash ^ bytes[i]) * mul;\n\n   return hash;\n}\n\n// The idea for this test is to leave pngsuite/ref_results.csv checked in,\n// and then you can run this test after making PNG loader changes. If the\n// ref results change (as per git diff), confirm that the change was\n// intentional. If so, commit them as well; if not, undo.\nint main()\n{\n   char **files;\n   FILE *csv_file;\n   int i;\n\n   files = stb_readdir_recursive(\"pngsuite\", \"*.png\");\n   if (!files) {\n      fprintf(stderr, \"pngsuite files not found!\\n\");\n      return 1;\n   }\n\n   // sort files by name\n   qsort(files, stb_arr_len(files), sizeof(char*), stb_qsort_strcmp(0));\n\n   csv_file = fopen(\"pngsuite/ref_results.csv\", \"w\");\n   if (!csv_file) {\n      fprintf(stderr, \"error opening ref results for writing!\\n\");\n      stb_readdir_free(files);\n      return 1;\n   }\n\n   fprintf(csv_file, \"filename,width,height,ncomp,error,hash\\n\");\n   for (i = 0; i < stb_arr_len(files); ++i) {\n      char *filename = files[i];\n      int width, height, ncomp;\n      stbi_uc *pixels = stbi_load(filename, &width, &height, &ncomp, 0);\n      const char *error = \"\";\n      unsigned int hash = 0;\n\n      if (!pixels)\n         error = stbi_failure_reason();\n      else {\n         hash = fnv1a_hash32(pixels, width * height * ncomp);\n         stbi_image_free(pixels);\n      }\n\n      fprintf(csv_file, \"%s,%d,%d,%d,%s,0x%08x\\n\", filename, width, height, ncomp, error, hash);\n   }\n\n   fclose(csv_file);\n   stb_readdir_free(files);\n}\n"
  },
  {
    "path": "tests/test_siphash.c",
    "content": "#include <stdio.h>\n\n#define STB_DS_IMPLEMENTATION\n#define STBDS_SIPHASH_2_4\n#define STBDS_TEST_SIPHASH_2_4\n#include \"../stb_ds.h\"\n\nint main(int argc, char **argv)\n{\n  unsigned char mem[64];\n  int i,j;\n  for (i=0; i < 64; ++i) mem[i] = i;\n  for (i=0; i < 64; ++i) {\n    size_t hash = stbds_hash_bytes(mem, i, 0);\n    printf(\"  { \");\n    for (j=0; j < 8; ++j)\n      printf(\"0x%02x, \", (unsigned char) ((hash >> (j*8)) & 255));\n    printf(\" },\\n\");\n  }\n  return 0;\n}"
  },
  {
    "path": "tests/test_sprintf.c",
    "content": "\n#define USE_STB 1\n\n#if USE_STB\n# include \"stb_sprintf.h\"\n# define SPRINTF stbsp_sprintf\n# define SNPRINTF stbsp_snprintf\n#else\n# include <locale.h>\n# define SPRINTF sprintf\n# define SNPRINTF snprintf\n#endif\n\n#include <assert.h>\n#include <math.h>    // for INFINITY, NAN\n#include <stddef.h>  // for ptrdiff_t\n#include <stdio.h>   // for printf\n#include <string.h>  // for strcmp, strncmp, strlen\n\n#if _MSC_VER && _MSC_VER <= 1600 \ntypedef int intmax_t;\ntypedef ptrdiff_t ssize_t;\n#else\n#include <stdint.h>  // for intmax_t, ssize_t\n#endif\n\n// stbsp_sprintf\n#define CHECK_END(str) \\\n   if (strcmp(buf, str) != 0 || (unsigned) ret != strlen(str)) { \\\n      printf(\"< '%s'\\n> '%s'\\n\", str, buf); \\\n      assert(!\"Fail\"); \\\n   }\n\n#define CHECK9(str, v1, v2, v3, v4, v5, v6, v7, v8, v9) { int ret = SPRINTF(buf, v1, v2, v3, v4, v5, v6, v7, v8, v9); CHECK_END(str); }\n#define CHECK8(str, v1, v2, v3, v4, v5, v6, v7, v8    ) { int ret = SPRINTF(buf, v1, v2, v3, v4, v5, v6, v7, v8    ); CHECK_END(str); }\n#define CHECK7(str, v1, v2, v3, v4, v5, v6, v7        ) { int ret = SPRINTF(buf, v1, v2, v3, v4, v5, v6, v7        ); CHECK_END(str); }\n#define CHECK6(str, v1, v2, v3, v4, v5, v6            ) { int ret = SPRINTF(buf, v1, v2, v3, v4, v5, v6            ); CHECK_END(str); }\n#define CHECK5(str, v1, v2, v3, v4, v5                ) { int ret = SPRINTF(buf, v1, v2, v3, v4, v5                ); CHECK_END(str); }\n#define CHECK4(str, v1, v2, v3, v4                    ) { int ret = SPRINTF(buf, v1, v2, v3, v4                    ); CHECK_END(str); }\n#define CHECK3(str, v1, v2, v3                        ) { int ret = SPRINTF(buf, v1, v2, v3                        ); CHECK_END(str); }\n#define CHECK2(str, v1, v2                            ) { int ret = SPRINTF(buf, v1, v2                            ); CHECK_END(str); }\n#define CHECK1(str, v1                                ) { int ret = SPRINTF(buf, v1                                ); CHECK_END(str); }\n\n#ifdef TEST_SPRINTF\nint main()\n{\n   char buf[1024];\n   int n = 0;\n   const double pow_2_75 = 37778931862957161709568.0;\n   const double pow_2_85 = 38685626227668133590597632.0;\n\n   // integers\n   CHECK4(\"a b     1\", \"%c %s     %d\", 'a', \"b\", 1);\n   CHECK2(\"abc     \", \"%-8.3s\", \"abcdefgh\");\n   CHECK2(\"+5\", \"%+2d\", 5);\n   CHECK2(\"  6\", \"% 3i\", 6);\n   CHECK2(\"-7  \", \"%-4d\", -7);\n   CHECK2(\"+0\", \"%+d\", 0);\n   CHECK3(\"     00003:     00004\", \"%10.5d:%10.5d\", 3, 4);\n   CHECK2(\"-100006789\", \"%d\", -100006789);\n   CHECK3(\"20 0020\", \"%u %04u\", 20u, 20u);\n   CHECK4(\"12 1e 3C\", \"%o %x %X\", 10u, 30u, 60u);\n   CHECK4(\" 12 1e 3C \", \"%3o %2x %-3X\", 10u, 30u, 60u);\n   CHECK4(\"012 0x1e 0X3C\", \"%#o %#x %#X\", 10u, 30u, 60u);\n   CHECK2(\"\", \"%.0x\", 0);\n#if USE_STB\n   CHECK2(\"0\", \"%.0d\", 0);  // stb_sprintf gives \"0\"\n#else\n   CHECK2(\"\",  \"%.0d\", 0);  // glibc gives \"\" as specified by C99(?)\n#endif\n   CHECK3(\"33 555\", \"%hi %ld\", (short)33, 555l);\n#if !defined(_MSC_VER) || _MSC_VER >= 1600\n   CHECK2(\"9888777666\", \"%llu\", 9888777666llu);\n#endif\n   CHECK4(\"-1 2 -3\", \"%ji %zi %ti\", (intmax_t)-1, (ssize_t)2, (ptrdiff_t)-3);\n\n   // floating-point numbers\n   CHECK2(\"-3.000000\", \"%f\", -3.0);\n   CHECK2(\"-8.8888888800\", \"%.10f\", -8.88888888);\n   CHECK2(\"880.0888888800\", \"%.10f\", 880.08888888);\n   CHECK2(\"4.1\", \"%.1f\", 4.1);\n   CHECK2(\" 0\", \"% .0f\", 0.1);\n   CHECK2(\"0.00\", \"%.2f\", 1e-4);\n   CHECK2(\"-5.20\", \"%+4.2f\", -5.2);\n   CHECK2(\"0.0       \", \"%-10.1f\", 0.);\n   CHECK2(\"-0.000000\", \"%f\", -0.);\n   CHECK2(\"0.000001\", \"%f\", 9.09834e-07);\n#if USE_STB  // rounding differences\n   CHECK2(\"38685626227668133600000000.0\", \"%.1f\", pow_2_85);\n   CHECK2(\"0.000000499999999999999978\", \"%.24f\", 5e-7);\n#else\n   CHECK2(\"38685626227668133590597632.0\", \"%.1f\", pow_2_85); // exact\n   CHECK2(\"0.000000499999999999999977\", \"%.24f\", 5e-7);\n#endif\n   CHECK2(\"0.000000000000000020000000\", \"%.24f\", 2e-17);\n   CHECK3(\"0.0000000100 100000000\", \"%.10f %.0f\", 1e-8, 1e+8);\n   CHECK2(\"100056789.0\", \"%.1f\", 100056789.0);\n   CHECK4(\" 1.23 %\", \"%*.*f %%\", 5, 2, 1.23);\n   CHECK2(\"-3.000000e+00\", \"%e\", -3.0);\n   CHECK2(\"4.1E+00\", \"%.1E\", 4.1);\n   CHECK2(\"-5.20e+00\", \"%+4.2e\", -5.2);\n   CHECK3(\"+0.3 -3\", \"%+g %+g\", 0.3, -3.0);\n   CHECK2(\"4\", \"%.1G\", 4.1);\n   CHECK2(\"-5.2\", \"%+4.2g\", -5.2);\n   CHECK2(\"3e-300\", \"%g\", 3e-300);\n   CHECK2(\"1\", \"%.0g\", 1.2);\n   CHECK3(\" 3.7 3.71\", \"% .3g %.3g\", 3.704, 3.706);\n   CHECK3(\"2e-315:1e+308\", \"%g:%g\", 2e-315, 1e+308);\n\n#if __STDC_VERSION__ >= 199901L\n#if USE_STB\n   CHECK4(\"Inf Inf NaN\", \"%g %G %f\", INFINITY, INFINITY, NAN);\n   CHECK2(\"N\", \"%.1g\", NAN);\n#else\n   CHECK4(\"inf INF nan\", \"%g %G %f\", INFINITY, INFINITY, NAN);\n   CHECK2(\"nan\", \"%.1g\", NAN);\n#endif\n#endif\n\n   // %n\n   CHECK3(\"aaa \", \"%.3s %n\", \"aaaaaaaaaaaaa\", &n);\n   assert(n == 4);\n\n#if __STDC_VERSION__ >= 199901L\n   // hex floats\n   CHECK2(\"0x1.fedcbap+98\", \"%a\", 0x1.fedcbap+98);\n   CHECK2(\"0x1.999999999999a0p-4\", \"%.14a\", 0.1);\n   CHECK2(\"0x1.0p-1022\", \"%.1a\", 0x1.ffp-1023);\n#if USE_STB  // difference in default precision and x vs X for %A\n   CHECK2(\"0x1.009117p-1022\", \"%a\", 2.23e-308);\n   CHECK2(\"-0x1.AB0P-5\", \"%.3A\", -0x1.abp-5);\n#else\n   CHECK2(\"0x1.0091177587f83p-1022\", \"%a\", 2.23e-308);\n   CHECK2(\"-0X1.AB0P-5\", \"%.3A\", -0X1.abp-5);\n#endif\n#endif\n\n   // %p\n#if USE_STB\n   CHECK2(\"0000000000000000\", \"%p\", (void*) NULL);\n#else\n   CHECK2(\"(nil)\", \"%p\", (void*) NULL);\n#endif\n\n   // snprintf\n   assert(SNPRINTF(buf, 100, \" %s     %d\",  \"b\", 123) == 10);\n   assert(strcmp(buf, \" b     123\") == 0);\n   assert(SNPRINTF(buf, 100, \"%f\", pow_2_75) == 30);\n   assert(strncmp(buf, \"37778931862957161709568.000000\", 17) == 0);\n   n = SNPRINTF(buf, 10, \"number %f\", 123.456789);\n   assert(strcmp(buf, \"number 12\") == 0);\n   assert(n == 17);  // written vs would-be written bytes\n   n = SNPRINTF(buf, 0, \"7 chars\");\n   assert(n == 7);\n   // stb_sprintf uses internal buffer of 512 chars - test longer string\n   assert(SPRINTF(buf, \"%d  %600s\", 3, \"abc\") == 603);\n   assert(strlen(buf) == 603);\n   SNPRINTF(buf, 550, \"%d  %600s\", 3, \"abc\");\n   assert(strlen(buf) == 549);\n   assert(SNPRINTF(buf, 600, \"%510s     %c\", \"a\", 'b') == 516);\n\n   // length check\n   assert(SNPRINTF(NULL, 0, \" %s     %d\",  \"b\", 123) == 10);\n\n   // ' modifier. Non-standard, but supported by glibc.\n#if !USE_STB\n   setlocale(LC_NUMERIC, \"\");  // C locale does not group digits\n#endif\n   CHECK2(\"1,200,000\", \"%'d\", 1200000);\n   CHECK2(\"-100,006,789\", \"%'d\", -100006789);\n#if !defined(_MSC_VER) || _MSC_VER >= 1600\n   CHECK2(\"9,888,777,666\", \"%'lld\", 9888777666ll);\n#endif\n   CHECK2(\"200,000,000.000000\", \"%'18f\", 2e8);\n   CHECK2(\"100,056,789\", \"%'.0f\", 100056789.0);\n   CHECK2(\"100,056,789.0\", \"%'.1f\", 100056789.0);\n#if USE_STB  // difference in leading zeros\n   CHECK2(\"000,001,200,000\", \"%'015d\", 1200000);\n#else\n   CHECK2(\"0000001,200,000\", \"%'015d\", 1200000);\n#endif\n\n   // things not supported by glibc\n#if USE_STB\n   CHECK2(\"null\", \"%s\", (char*) NULL);\n   CHECK2(\"123,4abc:\", \"%'x:\", 0x1234ABC);\n   CHECK2(\"100000000\", \"%b\", 256);\n   CHECK3(\"0b10 0B11\", \"%#b %#B\", 2, 3);\n#if !defined(_MSC_VER) || _MSC_VER >= 1600\n   CHECK4(\"2 3 4\", \"%I64d %I32d %Id\", 2ll, 3, 4ll);\n#endif\n   CHECK3(\"1k 2.54 M\", \"%$_d %$.2d\", 1000, 2536000);\n   CHECK3(\"2.42 Mi 2.4 M\", \"%$$.2d %$$$d\", 2536000, 2536000);\n\n   // different separators\n   stbsp_set_separators(' ', ',');\n   CHECK2(\"12 345,678900\", \"%'f\", 12345.6789);\n#endif\n\n   return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/test_truetype.c",
    "content": "#ifndef _CRT_SECURE_NO_WARNINGS\n// Fixes Compile Errors for Visual Studio 2005 or newer\n  #define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include <stdlib.h>\n\n// this isn't meant to compile standalone; link with test_c_compilation.c as well\n#include \"stb_rect_pack.h\"\n#define STB_TRUETYPE_IMPLEMENTATION\n#include \"stb_truetype.h\"\n#include \"stb_image_write.h\"\n\n#ifdef TT_TEST\n\n#include <stdio.h>\n\nunsigned char ttf_buffer[1 << 25];\nunsigned char output[512*100];\n\nvoid debug(void)\n{\n   stbtt_fontinfo font;\n   fread(ttf_buffer, 1, 1<<25, fopen(\"c:/x/lm/LiberationMono-Regular.ttf\", \"rb\"));\n   stbtt_InitFont(&font, ttf_buffer, 0);\n\n   stbtt_MakeGlyphBitmap(&font, output, 6, 9, 512, 5.172414E-03f, 5.172414E-03f, 54);\n}\n\n#define BITMAP_W  256\n#define BITMAP_H  512\nunsigned char temp_bitmap[BITMAP_H][BITMAP_W];\nstbtt_bakedchar cdata[256*2]; // ASCII 32..126 is 95 glyphs\nstbtt_packedchar pdata[256*2];\n\nint main(int argc, char **argv)\n{\n   stbtt_fontinfo font;\n   unsigned char *bitmap;\n   int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : '@'), s = (argc > 2 ? atoi(argv[2]) : 32);\n\n   //debug();\n\n   // @TODO: why is minglui.ttc failing? \n   //fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : \"c:/windows/fonts/mingliu.ttc\", \"rb\"));\n\n   fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : \"c:/windows/fonts/DejaVuSans.ttf\", \"rb\"));\n\n   stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));\n\n#if 0\n   {\n      stbtt__bitmap b;\n      stbtt__point p[2];\n      int wcount[2] = { 2,0 };\n      p[0].x = 0.2f;\n      p[0].y = 0.3f;\n      p[1].x = 3.8f;\n      p[1].y = 0.8f;\n      b.w = 16;\n      b.h = 2;\n      b.stride = 16;\n      b.pixels = malloc(b.w*b.h);\n      stbtt__rasterize(&b, p, wcount, 1, 1, 1, 0, 0, 0, 0, 0, NULL);\n      for (i=0; i < 8; ++i)\n         printf(\"%f\\n\", b.pixels[i]/255.0);\n   }\n#endif\n\n#if 1\n   {\n      static stbtt_pack_context pc;\n      static stbtt_packedchar cd[256];\n      static unsigned char atlas[1024*1024];\n\n      stbtt_PackBegin(&pc, atlas, 1024,1024,1024,1,NULL);\n      stbtt_PackFontRange(&pc, ttf_buffer, 0, 32.0, 0, 256, cd);\n      stbtt_PackEnd(&pc);\n   }\n#endif\n\n\n#if 1\n   {\n      static stbtt_pack_context pc;\n      static stbtt_packedchar cd[256];\n      static unsigned char atlas[1024*1024];\n      unsigned char *data;\n\n      data = stbtt_GetCodepointSDF(&font, stbtt_ScaleForPixelHeight(&font,32.0), 'u', 4, 128, 128/4, &w,&h,&i,&j);\n      for (j=0; j < h; ++j) {\n         for (i=0; i < w; ++i) {\n            putchar(\" .:ioVM@\"[data[j*w+i]>>5]);\n         }\n         putchar('\\n');\n      }\n   }\n#endif\n\n#if 0\n   stbtt_BakeFontBitmap(ttf_buffer,stbtt_GetFontOffsetForIndex(ttf_buffer,0), 40.0, temp_bitmap[0],BITMAP_W,BITMAP_H, 32,96, cdata); // no guarantee this fits!\n   stbi_write_png(\"fonttest1.png\", BITMAP_W, BITMAP_H, 1, temp_bitmap, 0);\n\n   {\n      stbtt_pack_context pc;\n      stbtt_PackBegin(&pc, temp_bitmap[0], BITMAP_W, BITMAP_H, 0, 1, NULL);\n      stbtt_PackFontRange(&pc, ttf_buffer, 0, 20.0, 32, 95, pdata);\n      stbtt_PackFontRange(&pc, ttf_buffer, 0, 20.0, 0xa0, 0x100-0xa0, pdata);\n      stbtt_PackEnd(&pc);\n      stbi_write_png(\"fonttest2.png\", BITMAP_W, BITMAP_H, 1, temp_bitmap, 0);\n   }\n\n   {\n      stbtt_pack_context pc;\n      stbtt_pack_range pr[2];\n      stbtt_PackBegin(&pc, temp_bitmap[0], BITMAP_W, BITMAP_H, 0, 1, NULL);\n\n      pr[0].chardata_for_range = pdata;\n      pr[0].array_of_unicode_codepoints = NULL;\n      pr[0].first_unicode_codepoint_in_range = 32;\n      pr[0].num_chars = 95;\n      pr[0].font_size = 20.0f;\n      pr[1].chardata_for_range = pdata+256;\n      pr[1].array_of_unicode_codepoints = NULL;\n      pr[1].first_unicode_codepoint_in_range = 0xa0;\n      pr[1].num_chars = 0x100 - 0xa0;\n      pr[1].font_size = 20.0f;\n\n      stbtt_PackSetOversampling(&pc, 2, 2);\n      stbtt_PackFontRanges(&pc, ttf_buffer, 0, pr, 2);\n      stbtt_PackEnd(&pc);\n      stbi_write_png(\"fonttest3.png\", BITMAP_W, BITMAP_H, 1, temp_bitmap, 0);\n   }\n   return 0;\n#endif\n\n   (void)stbtt_GetCodepointBitmapSubpixel(&font,\n\t\t\t\t\t 0.4972374737262726f,\n\t\t\t\t\t 0.4986416995525360f,\n\t\t\t\t\t 0.2391788959503174f,\n\t\t\t\t\t 0.1752119064331055f,\n\t\t\t\t\t 'd',\n\t\t\t\t\t &w, &h,\n\t\t\t\t\t 0,0);\n\n   bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, (float)s), c, &w, &h, 0,0);\n   for (j=0; j < h; ++j) {\n      for (i=0; i < w; ++i)\n         putchar(\" .:ioVM@\"[bitmap[j*w+i]>>5]);\n      putchar('\\n');\n   }\n   return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/test_vorbis.c",
    "content": "#define STB_VORBIS_HEADER_ONLY\n#include \"stb_vorbis.c\"\n#include \"stb.h\"\n\nextern void stb_vorbis_dumpmem(void);\n\n#ifdef VORBIS_TEST\nint main(int argc, char **argv)\n{\n   size_t memlen;\n   unsigned char *mem = stb_fileu(\"../../lib/vorbis/sample/sketch008.ogg\", &memlen);\n   int chan, samplerate;\n   short *output;\n   int samples = stb_vorbis_decode_memory(mem, memlen, &chan, &samplerate, &output);\n   stb_filewrite(\"c:/x/sketch008.raw\", output, samples*4);\n   return 0;\n}\n#endif\n"
  },
  {
    "path": "tests/test_voxel.c",
    "content": "#include \"stb_voxel_render.h\""
  },
  {
    "path": "tests/textedit_sample.c",
    "content": "// I haven't actually tested this yet, this is just to make sure it compiles\n\n#include <stdlib.h>\n#include <string.h> // memmove\n#include <ctype.h>  // isspace\n\n#define STB_TEXTEDIT_CHARTYPE   char\n#define STB_TEXTEDIT_STRING     text_control\n\n// get the base type\n#include \"stb_textedit.h\"\n\n// define our editor structure\ntypedef struct\n{\n   char *string;\n   int stringlen;\n   STB_TexteditState state;\n} text_control;\n\n// define the functions we need\nvoid layout_func(StbTexteditRow *row, STB_TEXTEDIT_STRING *str, int start_i)\n{\n   int remaining_chars = str->stringlen - start_i;\n   row->num_chars = remaining_chars > 20 ? 20 : remaining_chars; // should do real word wrap here\n   row->x0 = 0;\n   row->x1 = 20; // need to account for actual size of characters\n   row->baseline_y_delta = 1.25;\n   row->ymin = -1;\n   row->ymax =  0;\n}\n\nint delete_chars(STB_TEXTEDIT_STRING *str, int pos, int num)\n{\n   memmove(&str->string[pos], &str->string[pos+num], str->stringlen - (pos+num));\n   str->stringlen -= num;\n   return 1; // always succeeds\n}\n\nint insert_chars(STB_TEXTEDIT_STRING *str, int pos, STB_TEXTEDIT_CHARTYPE *newtext, int num)\n{\n   str->string = realloc(str->string, str->stringlen + num);\n   memmove(&str->string[pos+num], &str->string[pos], str->stringlen - pos);\n   memcpy(&str->string[pos], newtext, num);\n   str->stringlen += num;\n   return 1; // always succeeds\n}\n\n// define all the #defines needed \n\n#define KEYDOWN_BIT                    0x80000000\n\n#define STB_TEXTEDIT_STRINGLEN(tc)     ((tc)->stringlen)\n#define STB_TEXTEDIT_LAYOUTROW         layout_func\n#define STB_TEXTEDIT_GETWIDTH(tc,n,i)  (1) // quick hack for monospaced\n#define STB_TEXTEDIT_KEYTOTEXT(key)    (((key) & KEYDOWN_BIT) ? 0 : (key))\n#define STB_TEXTEDIT_GETCHAR(tc,i)     ((tc)->string[i])\n#define STB_TEXTEDIT_NEWLINE           '\\n'\n#define STB_TEXTEDIT_IS_SPACE(ch)      isspace(ch)\n#define STB_TEXTEDIT_DELETECHARS       delete_chars\n#define STB_TEXTEDIT_INSERTCHARS       insert_chars\n\n#define STB_TEXTEDIT_K_SHIFT           0x40000000\n#define STB_TEXTEDIT_K_CONTROL         0x20000000\n#define STB_TEXTEDIT_K_LEFT            (KEYDOWN_BIT | 1) // actually use VK_LEFT, SDLK_LEFT, etc\n#define STB_TEXTEDIT_K_RIGHT           (KEYDOWN_BIT | 2) // VK_RIGHT\n#define STB_TEXTEDIT_K_UP              (KEYDOWN_BIT | 3) // VK_UP\n#define STB_TEXTEDIT_K_DOWN            (KEYDOWN_BIT | 4) // VK_DOWN\n#define STB_TEXTEDIT_K_LINESTART       (KEYDOWN_BIT | 5) // VK_HOME\n#define STB_TEXTEDIT_K_LINEEND         (KEYDOWN_BIT | 6) // VK_END\n#define STB_TEXTEDIT_K_TEXTSTART       (STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_TEXTEND         (STB_TEXTEDIT_K_LINEEND   | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_DELETE          (KEYDOWN_BIT | 7) // VK_DELETE\n#define STB_TEXTEDIT_K_BACKSPACE       (KEYDOWN_BIT | 8) // VK_BACKSPACE\n#define STB_TEXTEDIT_K_UNDO            (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'z')\n#define STB_TEXTEDIT_K_REDO            (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'y')\n#define STB_TEXTEDIT_K_INSERT          (KEYDOWN_BIT | 9) // VK_INSERT\n#define STB_TEXTEDIT_K_WORDLEFT        (STB_TEXTEDIT_K_LEFT  | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_WORDRIGHT       (STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_CONTROL)\n#define STB_TEXTEDIT_K_PGUP            (KEYDOWN_BIT | 10) // VK_PGUP -- not implemented\n#define STB_TEXTEDIT_K_PGDOWN          (KEYDOWN_BIT | 11) // VK_PGDOWN -- not implemented\n\n#define STB_TEXTEDIT_IMPLEMENTATION\n#include \"stb_textedit.h\"\n\nvoid dummy3(void)\n{\n  stb_textedit_click(0,0,0,0);\n  stb_textedit_drag(0,0,0,0);\n  stb_textedit_cut(0,0);\n  stb_textedit_key(0,0,0);\n  stb_textedit_initialize_state(0,0);\n  stb_textedit_paste(0,0,0,0);\n}\n"
  },
  {
    "path": "tests/tilemap_editor_integration_example.c",
    "content": "// This isn't compilable as-is, as it was extracted from a working\n// integration-in-a-game and makes reference to symbols from that game.\n\n#include <assert.h>\n#include <ctype.h>\n#include \"game.h\"\n#include \"SDL.h\"\n#include \"stb_tilemap_editor.h\"\n\nextern void editor_draw_tile(int x, int y, unsigned short tile, int mode, float *props);\nextern void editor_draw_rect(int x0, int y0, int x1, int y1, unsigned char r, unsigned char g, unsigned char b);\n\nstatic int is_platform(short *tiles);\nstatic unsigned int prop_type(int n, short *tiles);\nstatic char *prop_name(int n, short *tiles);\nstatic float prop_range(int n, short *tiles, int is_max);\nstatic int allow_link(short *src, short *dest);\n\n#define STBTE_MAX_PROPERTIES  8\n\n#define STBTE_PROP_TYPE(n, tiledata, p) prop_type(n,tiledata)\n#define STBTE_PROP_NAME(n, tiledata, p) prop_name(n,tiledata)\n#define STBTE_PROP_MIN(n, tiledata, p)  prop_range(n,tiledata,0)\n#define STBTE_PROP_MAX(n, tiledata, p)  prop_range(n,tiledata,1)\n#define STBTE_PROP_FLOAT_SCALE(n,td,p)  (0.1)\n\n#define STBTE_ALLOW_LINK(srctile, srcprop, desttile, destprop) \\\n           allow_link(srctile, desttile)\n\n#define STBTE_LINK_COLOR(srctile, srcprop, desttile, destprop) \\\n          (is_platform(srctile) ? 0xff80ff : 0x808040)\n\n#define STBTE_DRAW_RECT(x0,y0,x1,y1,c)           \\\n          editor_draw_rect(x0,y0,x1,y1,(c)>>16,((c)>>8)&255,(c)&255)\n\n#define STBTE_DRAW_TILE(x,y,id,highlight,props)  \\\n          editor_draw_tile(x,y,id,highlight,props)\n\n\n\n#define STB_TILEMAP_EDITOR_IMPLEMENTATION\n#include \"stb_tilemap_editor.h\"\n\nstbte_tilemap *edit_map;\n\nvoid editor_key(enum stbte_action act)\n{\n   stbte_action(edit_map, act);\n}\n\nvoid editor_process_sdl_event(SDL_Event *e)\n{\n   switch (e->type) {\n      case SDL_MOUSEMOTION:\n      case SDL_MOUSEBUTTONDOWN:\n      case SDL_MOUSEBUTTONUP:\n      case SDL_MOUSEWHEEL:\n         stbte_mouse_sdl(edit_map, e, 1.0f/editor_scale,1.0f/editor_scale,0,0);\n         break;\n\n      case SDL_KEYDOWN:\n         if (in_editor) {\n            switch (e->key.keysym.sym) {\n               case SDLK_RIGHT: editor_key(STBTE_scroll_right); break;\n               case SDLK_LEFT : editor_key(STBTE_scroll_left ); break;\n               case SDLK_UP   : editor_key(STBTE_scroll_up   ); break;\n               case SDLK_DOWN : editor_key(STBTE_scroll_down ); break;\n            }\n            switch (e->key.keysym.scancode) {\n               case SDL_SCANCODE_S: editor_key(STBTE_tool_select); break;\n               case SDL_SCANCODE_B: editor_key(STBTE_tool_brush ); break;\n               case SDL_SCANCODE_E: editor_key(STBTE_tool_erase ); break;\n               case SDL_SCANCODE_R: editor_key(STBTE_tool_rectangle ); break;\n               case SDL_SCANCODE_I: editor_key(STBTE_tool_eyedropper); break;\n               case SDL_SCANCODE_L: editor_key(STBTE_tool_link);       break;\n               case SDL_SCANCODE_G: editor_key(STBTE_act_toggle_grid); break;\n            }\n            if ((e->key.keysym.mod & KMOD_CTRL) && !(e->key.keysym.mod & ~KMOD_CTRL)) {\n               switch (e->key.keysym.scancode) {\n                  case SDL_SCANCODE_X: editor_key(STBTE_act_cut  ); break;\n                  case SDL_SCANCODE_C: editor_key(STBTE_act_copy ); break;\n                  case SDL_SCANCODE_V: editor_key(STBTE_act_paste); break;\n                  case SDL_SCANCODE_Z: editor_key(STBTE_act_undo ); break;\n                  case SDL_SCANCODE_Y: editor_key(STBTE_act_redo ); break;\n               }\n            }\n         }\n         break;\n   }\n}\n\nvoid editor_init(void)\n{\n   int i;\n   edit_map = stbte_create_map(20,14, 8, 16,16, 100);\n\n   stbte_set_background_tile(edit_map, T_empty);\n\n   for (i=0; i < T__num_types; ++i) {\n      if (i != T_reserved1 && i != T_entry && i != T_doorframe)\n         stbte_define_tile(edit_map, 0+i, 1, \"Background\");\n   }\n   stbte_define_tile(edit_map, 256+O_player   , 8, \"Char\");\n   stbte_define_tile(edit_map, 256+O_robot    , 8, \"Char\");\n   for (i=O_lockeddoor; i < O__num_types-2; ++i)\n      if (i == O_platform || i == O_vplatform)\n         stbte_define_tile(edit_map, 256+i, 4, \"Object\");\n      else\n         stbte_define_tile(edit_map, 256+i, 2, \"Object\");\n\n   //stbte_set_layername(edit_map, 0, \"background\");\n   //stbte_set_layername(edit_map, 1, \"objects\");\n   //stbte_set_layername(edit_map, 2, \"platforms\");\n   //stbte_set_layername(edit_map, 3, \"characters\");\n}\n\nstatic int is_platform(short *tiles)\n{\n   // platforms are only on layer #2\n   return tiles[2] == 256 + O_platform || tiles[2] == 256 + O_vplatform;\n}\n\nstatic int is_object(short *tiles)\n{\n   return (tiles[1] >= 256 || tiles[2] >= 256 || tiles[3] >= 256);\n}\n\nstatic unsigned int prop_type(int n, short *tiles)\n{\n   if (is_platform(tiles)) {\n      static unsigned int platform_types[STBTE_MAX_PROPERTIES] = {\n         STBTE_PROP_bool,  // phantom\n         STBTE_PROP_int,   // x_adjust\n         STBTE_PROP_int,   // y_adjust\n         STBTE_PROP_float, // width\n         STBTE_PROP_float, // lspeed\n         STBTE_PROP_float, // rspeed\n         STBTE_PROP_bool,  // autoreturn\n         STBTE_PROP_bool,  // one-shot\n         // remainder get 0, means 'no property in this slot'\n      };\n      return platform_types[n];\n   } else if (is_object(tiles)) {\n      if (n == 0)\n         return STBTE_PROP_bool;\n   }\n   return 0;\n}\n\nstatic char *prop_name(int n, short *tiles)\n{\n   if (is_platform(tiles)) {\n      static char *platform_vars[STBTE_MAX_PROPERTIES] = {\n         \"phantom\",\n         \"x_adjust\",\n         \"y_adjust\",\n         \"width\",\n         \"lspeed\",\n         \"rspeed\",\n         \"autoreturn\",\n         \"one-shot\",\n      };\n      return platform_vars[n];\n   }\n   return \"phantom\";\n}\n\nstatic float prop_range(int n, short *tiles, int is_max)\n{\n   if (is_platform(tiles)) {\n      static float ranges[8][2] = {\n         {   0,  1 }, // phantom-flag, range is ignored\n         { -15, 15 }, // x_adjust\n         { -15, 15 }, // y_adjust\n         {   0,  6 }, // width\n         {   0, 10 }, // lspeed\n         {   0, 10 }, // rspeed\n         {   0,  1 }, // autoreturn, range is ignored\n         {   0,  1 }, // one-shot, range is ignored\n      };\n      return ranges[n][is_max];\n   }\n   return 0;\n}\n\nstatic int allow_link(short *src, short *dest)\n{\n   if (is_platform(src))\n      return dest[1] == 256+O_lever;\n   if (src[1] == 256+O_endpoint)\n      return is_platform(dest);\n   return 0;\n}\n"
  },
  {
    "path": "tests/truetype_test_win32.c",
    "content": "// tested in VC6 (1998) and VS 2019\n#define _CRT_SECURE_NO_WARNINGS\n#define WIN32_MEAN_AND_LEAN\n#include <windows.h>\n\n#include <stdio.h>\n#include <tchar.h>\n\n#define STB_TRUETYPE_IMPLEMENTATION\n#include \"stb_truetype.h\"\n\n#include <gl/gl.h>\n#include <gl/glu.h>\n\nint screen_x=1024, screen_y=768;\nGLuint tex;\n\nunsigned char ttf_buffer[1<<20];\nunsigned char temp_bitmap[1024*1024];\nstbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs\n\nvoid init(void)\n{\n   fread(ttf_buffer, 1, 1<<20, fopen(\"c:/windows/fonts/times.ttf\", \"rb\"));\n   stbtt_BakeFontBitmap(ttf_buffer,0, 64.0, temp_bitmap,1024,1024, 32,96, cdata);\n   glGenTextures(1, &tex);\n   glBindTexture(GL_TEXTURE_2D, tex);\n   glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 1024,1024,0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n}\n\nvoid print(float x, float y, char *text)\n{\n   // assume orthographic projection with units = screen pixels, origin at top left\n   glBindTexture(GL_TEXTURE_2D, tex);\n   glBegin(GL_QUADS);\n   while (*text) {\n      if (*text >= 32 && *text < 128) {\n         stbtt_aligned_quad q;\n         stbtt_GetBakedQuad(cdata, 1024,1024, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9\n         glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0);\n         glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0);\n         glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1);\n         glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1);\n      }\n      ++text;\n   }\n   glEnd();\n}\n\nvoid draw(void)\n{\n   glViewport(0,0,screen_x,screen_y);\n   glClearColor(0.45f,0.45f,0.75f,0);\n   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n   glDisable(GL_CULL_FACE);\n   glDisable(GL_DEPTH_TEST);\n   glDisable(GL_BLEND);\n\n   glMatrixMode(GL_PROJECTION);\n   glLoadIdentity();\n   glOrtho(0,screen_x,screen_y,0,-1,1);\n   glMatrixMode(GL_MODELVIEW);\n   glLoadIdentity();\n\n   glEnable(GL_TEXTURE_2D);\n   glEnable(GL_BLEND);\n   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n   glColor3f(1,1,1);\n\n   print(100,150, \"This is a simple test!\");\n\n   // show font bitmap\n   glBegin(GL_QUADS);\n      glTexCoord2f(0,0); glVertex2f(256,200+0);\n      glTexCoord2f(1,0); glVertex2f(768,200+0);\n      glTexCoord2f(1,1); glVertex2f(768,200+512);\n      glTexCoord2f(0,1); glVertex2f(256,200+512);\n   glEnd();\n}\n\n///////////////////////////////////////////////////////////////////////\n///\n///\n///  Windows OpenGL setup\n///\n///\n\nHINSTANCE app;\nHWND  window;\nHGLRC rc;\nHDC   dc;\n\n#pragma comment(lib, \"opengl32.lib\")\n#pragma comment(lib, \"glu32.lib\")\n#pragma comment(lib, \"winmm.lib\")\n\nint mySetPixelFormat(HWND win)\n{\n   PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1, PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA };\n   int                   pixel_format;\n   pfd.dwLayerMask  = PFD_MAIN_PLANE;\n   pfd.cColorBits   = 24;\n   pfd.cAlphaBits   = 8;\n   pfd.cDepthBits   = 24;\n   pfd.cStencilBits = 8;\n   pixel_format = ChoosePixelFormat(dc, &pfd);\n   if (!pixel_format) return FALSE;\n   if (!DescribePixelFormat(dc, pixel_format, sizeof(PIXELFORMATDESCRIPTOR), &pfd))\n      return FALSE;\n   SetPixelFormat(dc, pixel_format, &pfd);\n   return TRUE;\n}\n\nstatic int WINAPI WinProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)\n{\n   switch (msg) {\n      case WM_CREATE: {\n         LPCREATESTRUCT lpcs = (LPCREATESTRUCT) lparam;\n         dc = GetDC(wnd);\n         if (mySetPixelFormat(wnd)) {\n            rc = wglCreateContext(dc);\n            if (rc) {\n               wglMakeCurrent(dc, rc);\n               return 0;\n            }\n         }\n         return -1;\n      }\n\n      case WM_DESTROY:\n         wglMakeCurrent(NULL, NULL); \n         if (rc) wglDeleteContext(rc);\n         PostQuitMessage (0);\n         return 0;\n\n      default:\n         return DefWindowProc (wnd, msg, wparam, lparam);\n   }\n\n   return DefWindowProc (wnd, msg, wparam, lparam);\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)\n{\n   DWORD dwstyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;\n   WNDCLASSEX  wndclass;\n   wndclass.cbSize        = sizeof(wndclass);\n   wndclass.style         = CS_OWNDC;\n   wndclass.lpfnWndProc   = (WNDPROC) WinProc;\n   wndclass.cbClsExtra    = 0;\n   wndclass.cbWndExtra    = 0;\n   wndclass.hInstance     = hInstance;\n   wndclass.hIcon         = LoadIcon(hInstance, _T(\"appicon\"));\n   wndclass.hCursor       = LoadCursor(NULL,IDC_ARROW);\n   wndclass.hbrBackground = GetStockObject(NULL_BRUSH);\n   wndclass.lpszMenuName  = _T(\"truetype-test\");\n   wndclass.lpszClassName = _T(\"truetype-test\");\n   wndclass.hIconSm       = NULL;\n   app = hInstance;\n\n   if (!RegisterClassEx(&wndclass))\n      return 0;\n\n   window = CreateWindow(_T(\"truetype-test\"), _T(\"truetype test\"), dwstyle,\n                      CW_USEDEFAULT,0, screen_x, screen_y,\n                      NULL, NULL, app,  NULL);\n   ShowWindow(window, SW_SHOWNORMAL);\n   init();\n\n   for(;;) {\n      MSG msg;\n      if (GetMessage(&msg, NULL, 0, 0)) {\n         TranslateMessage(&msg);\n         DispatchMessage(&msg);\n      } else {\n         return 1;   // WM_QUIT\n      }\n      wglMakeCurrent(dc, rc);\n      draw();\n      SwapBuffers(dc);\n   }\n   return 0;\n}\n"
  },
  {
    "path": "tests/vorbseek/vorbseek.c",
    "content": "#include <assert.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#define STB_VORBIS_HEADER_ONLY\n#include \"stb_vorbis.c\"\n\n#define SAMPLES_TO_TEST 3000\n\nint test_count  [5] = { 5000, 3000, 2000, 50000, 50000 };\nint test_spacing[5] = {    1,  111, 3337,  7779, 72717 };\n\nint try_seeking(stb_vorbis *v, unsigned int pos, short *output, unsigned int num_samples)\n{\n   int count;\n   short samples[SAMPLES_TO_TEST*2];\n   assert(pos <= num_samples);\n\n   if (!stb_vorbis_seek(v, pos)) {\n      fprintf(stderr, \"Seek to %u returned error from stb_vorbis\\n\", pos);\n      return 0;\n   }\n\n   count = stb_vorbis_get_samples_short_interleaved(v, 2, samples, SAMPLES_TO_TEST*2);\n\n   if (count > (int) (num_samples - pos)) {\n      fprintf(stderr, \"Seek to %u allowed decoding %d samples when only %d should have been valid.\\n\",\n            pos, count, (int) (num_samples - pos));\n      return 0;\n   }\n\n   if (count < SAMPLES_TO_TEST && count < (int) (num_samples - pos)) {\n      fprintf(stderr, \"Seek to %u only decoded %d samples of %d attempted when at least %d should have been valid.\\n\",\n         pos, count, SAMPLES_TO_TEST, num_samples - pos);\n      return 0;                      \n   }\n\n   if (0 != memcmp(samples, output + pos*2, count*2)) {\n      int k;\n      for (k=0; k < SAMPLES_TO_TEST*2; ++k) {\n         if (samples[k] != output[k]) {\n            fprintf(stderr, \"Seek to %u produced incorrect samples starting at sample %u (short #%d in buffer).\\n\",\n                    pos, pos + (k/2), k);\n            break;\n         }\n      }\n      assert(k != SAMPLES_TO_TEST*2);\n      return 0;\n   }\n\n   return 1;\n}\n\nint main(int argc, char **argv)\n{\n   int num_chan, samprate;\n   int i, j, test, phase;\n   short *output;\n\n   if (argc == 1) {\n      fprintf(stderr, \"Usage: vorbseek {vorbisfile} [{vorbisfile]*]\\n\");\n      fprintf(stderr, \"Tests various seek offsets to make sure they're sample exact.\\n\");\n      return 0;\n   }\n\n   #if 0\n   {\n      // check that outofmem occurs correctly\n      stb_vorbis_alloc va;\n      va.alloc_buffer = malloc(1024*1024);\n      for (i=0; i < 1024*1024; i += 10) {\n         int error=0;\n         stb_vorbis *v;\n         va.alloc_buffer_length_in_bytes = i;\n         v = stb_vorbis_open_filename(argv[1], &error, &va);\n         if (v != NULL)\n            break;\n         printf(\"Error %d at %d\\n\", error, i);\n      }\n   }\n   #endif\n\n   for (j=1; j < argc; ++j) {\n      unsigned int successes=0, attempts = 0;\n      unsigned int num_samples = stb_vorbis_decode_filename(argv[j], &num_chan, &samprate, &output);\n\n      break;\n\n      if (num_samples == 0xffffffff) {\n         fprintf(stderr, \"Error: couldn't open file or not vorbis file: %s\\n\", argv[j]);\n         goto fail;\n      }\n\n      if (num_chan != 2) {\n         fprintf(stderr, \"vorbseek testing only works with files with 2 channels, %s has %d\\n\", argv[j], num_chan);\n         goto fail;\n      }\n\n      for (test=0; test < 5; ++test) {\n         int error;\n         stb_vorbis *v = stb_vorbis_open_filename(argv[j], &error, NULL);\n         if (v == NULL) {\n            fprintf(stderr, \"Couldn't re-open %s for test #%d\\n\", argv[j], test);\n            goto fail;\n         }\n         for (phase=0; phase < 3; ++phase) {\n            unsigned int base = phase == 0 ? 0 : phase == 1 ? num_samples - test_count[test]*test_spacing[test] : num_samples/3;\n            for (i=0; i < test_count[test]; ++i) {\n               unsigned int pos = base + i*test_spacing[test];\n               if (pos > num_samples) // this also catches underflows\n                  continue;\n               successes += try_seeking(v, pos, output, num_samples);\n               attempts += 1;\n            }\n         }\n         stb_vorbis_close(v);\n      }\n      printf(\"%d of %d seeks failed in %s (%d samples)\\n\", attempts-successes, attempts, argv[j], num_samples);\n      free(output);\n   }\n   return 0;\n  fail:\n   return 1;\n}"
  },
  {
    "path": "tests/vorbseek/vorbseek.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"vorbseek\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=vorbseek - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"vorbseek.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"vorbseek.mak\" CFG=\"vorbseek - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"vorbseek - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"vorbseek - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"vorbseek - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /Zd /O2 /I \"..\\..\" /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"vorbseek - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Ignore_Export_Lib 0\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ  /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I \"..\\..\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ  /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"vorbseek - Win32 Release\"\n# Name \"vorbseek - Win32 Debug\"\n# Begin Source File\n\nSOURCE=..\\..\\stb_vorbis.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\vorbseek.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tools/README.footer.md",
    "content": "\nFAQ\n---\n\n#### What's the license?\n\nThese libraries are in the public domain. You can do anything you\nwant with them. You have no legal obligation\nto do anything else, although I appreciate attribution.\n\nThey are also licensed under the MIT open source license, if you have lawyers\nwho are unhappy with public domain. Every source file includes an explicit\ndual-license for you to choose from.\n\n#### How do I use these libraries?\n\nThe idea behind single-header file libraries is that they're easy to distribute and deploy\nbecause all the code is contained in a single file. By default, the .h files in here act as\ntheir own header files, i.e. they declare the functions contained in the file but don't\nactually result in any code getting compiled.\n\nSo in addition, you should select _exactly one_ C/C++ source file that actually instantiates\nthe code, preferably a file you're not editing frequently. This file should define a\nspecific macro (this is documented per-library) to actually enable the function definitions.\nFor example, to use stb_image, you should have exactly one C/C++ file that doesn't\ninclude stb_image.h regularly, but instead does\n\n    #define STB_IMAGE_IMPLEMENTATION\n    #include \"stb_image.h\"\n\nThe right macro to define is pointed out right at the top of each of these libraries.\n\n#### <a name=\"other_libs\"></a> Are there other single-file public-domain/open source libraries with minimal dependencies out there?\n\n[Yes.](https://github.com/nothings/single_file_libs)\n\n#### If I wrap an stb library in a new library, does the new library have to be public domain/MIT?\n\nNo, because it's public domain you can freely relicense it to whatever license your new\nlibrary wants to be.\n\n#### What's the deal with SSE support in GCC-based compilers?\n\nstb_image will either use SSE2 (if you compile with -msse2) or\nwill not use any SIMD at all, rather than trying to detect the\nprocessor at runtime and handle it correctly. As I understand it,\nthe approved path in GCC for runtime-detection require\nyou to use multiple source files, one for each CPU configuration.\nBecause stb_image is a header-file library that compiles in only\none source file, there's no approved way to build both an\nSSE-enabled and a non-SSE-enabled variation.\n\nWhile we've tried to work around it, we've had multiple issues over\nthe years due to specific versions of gcc breaking what we're doing,\nso we've given up on it. See https://github.com/nothings/stb/issues/280\nand https://github.com/nothings/stb/issues/410 for examples.\n\n#### Some of these libraries seem redundant to existing open source libraries. Are they better somehow?\n\nGenerally they're only better in that they're easier to integrate,\neasier to use, and easier to release (single file; good API; no\nattribution requirement). They may be less featureful, slower,\nand/or use more memory. If you're already using an equivalent\nlibrary, there's probably no good reason to switch.\n\n#### Can I link directly to the table of stb libraries?\n\nYou can use [this URL](https://github.com/nothings/stb#stb_libs) to link directly to that list.\n\n#### Why do you list \"lines of code\"? It's a terrible metric.\n\nJust to give you some idea of the internal complexity of the library,\nto help you manage your expectations, or to let you know what you're\ngetting into. While not all the libraries are written in the same\nstyle, they're certainly similar styles, and so comparisons between\nthe libraries are probably still meaningful.\n\nNote though that the lines do include both the implementation, the\npart that corresponds to a header file, and the documentation.\n\n#### Why single-file headers?\n\nWindows doesn't have standard directories where libraries\nlive. That makes deploying libraries in Windows a lot more\npainful than open source developers on Unix-derivates generally\nrealize. (It also makes library dependencies a lot worse in Windows.)\n\nThere's also a common problem in Windows where a library was built\nagainst a different version of the runtime library, which causes\nlink conflicts and confusion. Shipping the libs as headers means\nyou normally just compile them straight into your project without\nmaking libraries, thus sidestepping that problem.\n\nMaking them a single file makes it very easy to just\ndrop them into a project that needs them. (Of course you can\nstill put them in a proper shared library tree if you want.)\n\nWhy not two files, one a header and one an implementation?\nThe difference between 10 files and 9 files is not a big deal,\nbut the difference between 2 files and 1 file is a big deal.\nYou don't need to zip or tar the files up, you don't have to\nremember to attach *two* files, etc.\n\n#### Why \"stb\"? Is this something to do with Set-Top Boxes?\n\nNo, they are just the initials for my name, Sean T. Barrett.\nThis was not chosen out of egomania, but as a moderately sane\nway of namespacing the filenames and source function names.\n\n#### Will you add more image types to stb_image.h?\n\nNo. As stb_image use has grown, it has become more important\nfor us to focus on security of the codebase. Adding new image\nformats increases the amount of code we need to secure, so it\nis no longer worth adding new formats.\n\n#### Do you have any advice on how to create my own single-file library?\n\nYes. https://github.com/nothings/stb/blob/master/docs/stb_howto.txt\n\n#### Why public domain?\n\nI prefer it over GPL, LGPL, BSD, zlib, etc. for many reasons.\nSome of them are listed here:\nhttps://github.com/nothings/stb/blob/master/docs/why_public_domain.md\n\n#### Why C?\n\nPrimarily, because I use C, not C++. But it does also make it easier\nfor other people to use them from other languages.\n\n#### Why not C99? stdint.h, declare-anywhere, etc.\n\nI still use MSVC 6 (1998) as my IDE because it has better human factors\nfor me than later versions of MSVC.\n"
  },
  {
    "path": "tools/README.header.md",
    "content": "stb\n===\n\nsingle-file public domain (or MIT licensed) libraries for C/C++\n\n# This project discusses security-relevant bugs in public in Github Issues and Pull Requests, and it may take significant time for security fixes to be implemented or merged. If this poses an unreasonable risk to your project, do not use stb libraries.\n\nNoteworthy:\n\n* image loader: [stb_image.h](stb_image.h)\n* image writer: [stb_image_write.h](stb_image_write.h)\n* image resizer: [stb_image_resize2.h](stb_image_resize2.h)\n* font text rasterizer: [stb_truetype.h](stb_truetype.h)\n* typesafe containers: [stb_ds.h](stb_ds.h)\n\nMost libraries by stb, except: stb_dxt by Fabian \"ryg\" Giesen, original stb_image_resize\nby Jorge L. \"VinoBS\" Rodriguez, and stb_image_resize2 and stb_sprintf by Jeff Roberts.\n\n<a name=\"stb_libs\"></a>\n\nlibrary    | latest version | category | LoC | description\n--------------------- | ---- | -------- | --- | --------------------------------\n"
  },
  {
    "path": "tools/README.list",
    "content": "stb_vorbis.c                | audio            | decode ogg vorbis files from file/memory to float/16-bit signed output\nstb_hexwave.h               | audio            | audio waveform synthesizer\nstb_image.h                 | graphics         | image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC\nstb_truetype.h              | graphics         | parse, decode, and rasterize characters from truetype fonts\nstb_image_write.h           | graphics         | image writing to disk: PNG, TGA, BMP\nstb_image_resize2.h         | graphics         | resize images larger/smaller with good quality\nstb_rect_pack.h             | graphics         | simple 2D rectangle packer with decent quality\nstb_perlin.h                | graphics         | perlin's revised simplex noise w/ different seeds\nstb_ds.h                    | utility          | typesafe dynamic array and hash tables for C, will compile in C++\nstb_sprintf.h               | utility          | fast sprintf, snprintf for C/C++\nstb_textedit.h              | user interface   | guts of a text editor for games etc implementing them from scratch\nstb_voxel_render.h          | 3D graphics      | Minecraft-esque voxel rendering \"engine\" with many more features\nstb_dxt.h                   | 3D graphics      | Fabian \"ryg\" Giesen's real-time DXT compressor\nstb_easy_font.h             | 3D graphics      | quick-and-dirty easy-to-deploy bitmap font for printing frame rate, etc\nstb_tilemap_editor.h        | game dev         | embeddable tilemap editor\nstb_herringbone_wang_tile.h | game dev         | herringbone Wang tile map generator\nstb_c_lexer.h               | parsing          | simplify writing parsers for C-like languages\nstb_divide.h                | math             | more useful 32-bit modulus e.g. \"euclidean divide\"\nstb_connected_components.h  | misc             | incrementally compute reachability on grids\nstb_leakcheck.h             | misc             | quick-and-dirty malloc/free leak-checking\nstb_include.h               | misc             | implement recursive #include support, particularly for GLSL\n"
  },
  {
    "path": "tools/build_matrix.c",
    "content": "#define STB_DEFINE\n#include \"stb.h\"\n\n// true if no error\nint run_command(char *batch_file, char *command)\n{\n   char buffer[4096];\n   if (batch_file[0]) {\n      sprintf(buffer, \"%s && %s\", batch_file, command);\n      return system(buffer) == 0;\n   } else {\n      return system(command) == 0;\n   }\n}\n\ntypedef struct\n{\n   char *compiler_name;\n   char *batchfile;\n   char *objdir;\n   char *compiler;\n   char *args;\n   char *link;\n} compiler_info;\n\ncompiler_info *compilers;\nchar *shared_args;\nchar *shared_link;\n\ntypedef struct\n{\n   char *filelist;\n} project_info;\n\nproject_info *projects;\n\nenum { NONE, IN_COMPILERS, IN_ARGS, IN_PROJECTS, IN_LINK };\n\nint main(int argc, char **argv)\n{\n   int state = NONE;\n   int i,j,n;\n   char **line;\n   if (argc != 2) stb_fatal(\"Usage: stb_build_matrix {build-file}\\n\");\n   line = stb_stringfile(argv[1], &n);\n   if (line == 0) stb_fatal(\"Couldn't open file '%s'\\n\", argv[1]);\n\n   for (i=0; i < n; ++i) {\n      char *p = stb_trimwhite(line[i]);\n      if (p[0] == 0) continue;\n      else if (p[0] == '#') continue;\n      else if (0 == stricmp(p, \"[compilers]\")) { state = IN_COMPILERS;                     }\n      else if (0 == stricmp(p, \"[args]\"     )) { state = IN_ARGS     ; shared_args = NULL; }\n      else if (0 == stricmp(p, \"[projects]\" )) { state = IN_PROJECTS ;                     }\n      else if (0 == stricmp(p, \"[link]\"     )) { state = IN_LINK     ; shared_link = NULL; }\n      else {\n         switch (state) {\n            case NONE: stb_fatal(\"Invalid text outside section at line %d.\", i+1);\n            case IN_COMPILERS: {\n               char buffer[4096];\n               int count;\n               compiler_info ci;\n               char **tokens = stb_tokens_stripwhite(p, \",\", &count), *batch;\n               if (count > 3) stb_fatal(\"Expecting name and batch file name at line %d.\", i+1);\n               batch = (count==1 ? tokens[0] : tokens[1]);\n               if (strlen(batch)) \n                  sprintf(buffer, \"c:\\\\%s.bat\", batch);\n               else\n                  strcpy(buffer, \"\");\n               ci.compiler_name = strdup(tokens[0]);\n               ci.batchfile     = strdup(buffer);\n               ci.compiler      = count==3 ? strdup(tokens[2]) : \"cl\";\n               if (0==strnicmp(batch, \"vcvars_\", 7))\n                  ci.objdir     = strdup(stb_sprintf(\"vs_%s_%d\", batch+7, i));\n               else\n                  ci.objdir     = strdup(stb_sprintf(\"%s_%d\", batch, i));\n               ci.args = shared_args;\n               ci.link = shared_link;\n               stb_arr_push(compilers, ci);\n               break;\n            }\n            case IN_ARGS: {\n               stb_arr_push(shared_args, ' ');\n               for (j=0; p[j] != 0; ++j)\n                  stb_arr_push(shared_args, p[j]);\n               break;\n            }\n            case IN_LINK: {\n               stb_arr_push(shared_link, ' ');\n               for (j=0; p[j] != 0; ++j)\n                  stb_arr_push(shared_link, p[j]);\n               break;\n            }\n            case IN_PROJECTS: {\n               project_info pi;\n               pi.filelist = strdup(p);\n               stb_arr_push(projects, pi);\n               break;\n            }\n         }\n      }\n   }\n\n   _mkdir(\"obj\");\n   for (j=0; j < stb_arr_len(compilers); ++j) {\n      char command[4096];\n      for (i=0; i < stb_arr_len(projects); ++i) {\n         int r;\n         _mkdir(stb_sprintf(\"obj/%s\", compilers[j].objdir));\n         if (stb_suffix(compilers[j].compiler, \"cl\"))\n            sprintf(command, \"%s %.*s %s /link %.*s\",\n                                     compilers[j].compiler,\n                                     stb_arr_len(compilers[j].args), compilers[j].args,\n                                     projects[i].filelist,\n                                     stb_arr_len(compilers[j].link), compilers[j].link);\n         else\n            sprintf(command, \"%s %.*s %s %.*s\",\n                                     compilers[j].compiler,\n                                     stb_arr_len(compilers[j].args), compilers[j].args,\n                                     projects[i].filelist,\n                                     stb_arr_len(compilers[j].link), compilers[j].link);\n         r = run_command(compilers[j].batchfile, command);\n         stbprint(\"{%c== Compiler %s == Building %s}\\n\", r ? '$' : '!', compilers[j].compiler_name, projects[i].filelist);\n         stb_copyfile(\"a.exe\", stb_sprintf(\"obj/%s/a.exe\", compilers[j].objdir));\n         //printf(\"Copy: %s to %s\\n\", \"a.exe\", stb_sprintf(\"obj/%s/a.exe\", compilers[j].objdir));\n         stb_copyfile(\"temp.exe\", stb_sprintf(\"obj/%s/temp.exe\", compilers[j].objdir));\n         system(\"if EXIST a.exe del /q a.exe\");\n         system(\"if EXIST temp.exe del /q temp.exe\");\n         system(\"if EXIST *.obj del /q *.obj\");\n         system(\"if EXIST *.o del /q *.o\");\n         if (!r)\n            return 1;\n      }\n   }\n\n   return 0;\n}\n"
  },
  {
    "path": "tools/easy_font_maker.c",
    "content": "// This program was used to encode the data for stb_simple_font.h\n\n#define STB_DEFINE\n#include \"stb.h\"\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\nint w,h;\nuint8 *data;\n\nint last_x[2], last_y[2];\nint num_seg[2], non_empty;\n#if 0\ntypedef struct\n{\n   unsigned short first_segment;\n   unsigned char advance;\n} chardata;\n\ntypedef struct\n{\n   unsigned char x:4;\n   unsigned char y:4;\n   unsigned char len:3;\n   unsigned char dir:1;\n} segment;\n\nsegment *segments;\n\nvoid add_seg(int x, int y, int len, int horizontal)\n{\n   segment s;\n   s.x = x;\n   s.y = y;\n   s.len = len;\n   s.dir = horizontal;\n   assert(s.x == x);\n   assert(s.y == y);\n   assert(s.len == len);\n   stb_arr_push(segments, s);\n}\n#else\ntypedef struct\n{\n   unsigned char first_segment:8;\n   unsigned char first_v_segment:8;\n   unsigned char advance:5;\n   unsigned char voff:1;\n} chardata;\n\n#define X_LIMIT 1\n#define LEN_LIMIT 7\n\ntypedef struct\n{\n   unsigned char dx:1;\n   unsigned char y:4;\n   unsigned char len:3;\n} segment;\n\nsegment *segments;\nsegment *vsegments;\n\nvoid add_seg(int x, int y, int len, int horizontal)\n{\n   segment s;\n\n   while (x - last_x[horizontal] > X_LIMIT) {\n      add_seg(last_x[horizontal] + X_LIMIT, 0, 0, horizontal);\n   }\n   while (len > LEN_LIMIT) {\n      add_seg(x, y, LEN_LIMIT, horizontal);\n      len -= LEN_LIMIT;\n      x += LEN_LIMIT*horizontal;\n      y += LEN_LIMIT*!horizontal;\n   }\n\n   s.dx = x - last_x[horizontal];\n   s.y = y;\n   s.len = len;\n   non_empty += len != 0;\n   //assert(s.x == x);\n   assert(s.y == y);\n   assert(s.len == len);\n   ++num_seg[horizontal];\n   if (horizontal)\n      stb_arr_push(segments, s);\n   else\n      stb_arr_push(vsegments, s);\n   last_x[horizontal] = x;\n}\n\nvoid print_segments(segment *s)\n{\n   int i, hpos;\n   printf(\"   \");\n   hpos = 4;\n   for (i=0; i < stb_arr_len(s); ++i) {\n      // repack for portability\n      unsigned char seg = s[i].len + s[i].dx*8 + s[i].y*16;\n      hpos += printf(\"%d,\", seg);\n      if (hpos > 72 && i+1 < stb_arr_len(s)) {\n         hpos = 4;\n         printf(\"\\n    \");\n      }\n   }\n   printf(\"\\n\");\n}\n\n#endif\n\nchardata charinfo[128];\n\nint parse_char(int x, chardata *c, int offset)\n{\n   int start_x = x, end_x, top_y = 0, y;\n\n   c->first_segment = stb_arr_len(segments);\n   c->first_v_segment = stb_arr_len(vsegments) - offset;\n   assert(c->first_segment == stb_arr_len(segments));\n   assert(c->first_v_segment + offset == stb_arr_len(vsegments));\n\n   // find advance distance\n   end_x = x+1;\n   while (data[end_x*3] == 255)\n      ++end_x;\n   c->advance = end_x - start_x + 1;\n\n   last_x[0] = last_x[1] = 0;\n   last_y[0] = last_y[1] = 0;\n\n   for (y=2; y < h; ++y) {\n      for (x=start_x; x < end_x; ++x) {\n         if (data[y*3*w+x*3+1] < 255) {\n            top_y = y;\n            break;\n         }\n      }\n      if (top_y)\n         break;\n   }\n   c->voff = top_y > 2;\n   if (top_y > 2) \n      top_y = 3;\n\n   for (x=start_x; x < end_x; ++x) {\n      int y;\n      for (y=2; y < h; ++y) {\n         if (data[y*3*w+x*3+1] < 255) {\n            if (data[y*3*w+x*3+0] == 255) { // red\n               int len=0;\n               while (y+len < h && data[(y+len)*3*w+x*3+0] == 255 && data[(y+len)*3*w+x*3+1] == 0) {\n                  data[(y+len)*3*w+x*3+0] = 0;\n                  ++len;\n               }\n               add_seg(x-start_x,y-top_y,len,0);\n            }\n            if (data[y*3*w+x*3+2] == 255) { // blue\n               int len=0;\n               while (x+len < end_x && data[y*3*w+(x+len)*3+2] == 255 && data[y*3*w+(x+len)*3+1] == 0) {\n                  data[y*3*w+(x+len)*3+2] = 0;\n                  ++len;\n               }\n               add_seg(x-start_x,y-top_y,len,1);\n            }\n         }\n      }\n   }\n   return end_x;\n}\n\n\nint main(int argc, char **argv)\n{\n   int c, x=0;\n   data = stbi_load(\"easy_font_raw.png\", &w, &h, 0, 3);\n   for (c=32; c < 127; ++c) {\n      x = parse_char(x, &charinfo[c], 0);\n      printf(\"%3d -- %3d %3d\\n\", c, charinfo[c].first_segment, charinfo[c].first_v_segment);\n   }\n   printf(\"===\\n\");\n   printf(\"%d %d %d\\n\", num_seg[0], num_seg[1], non_empty);\n   printf(\"%d\\n\", sizeof(segments[0]) * stb_arr_len(segments));\n   printf(\"%d\\n\", sizeof(segments[0]) * stb_arr_len(segments) + sizeof(segments[0]) * stb_arr_len(vsegments) + sizeof(charinfo[32])*95);\n\n   printf(\"struct {\\n\"\n          \"    unsigned char advance;\\n\"\n          \"    unsigned char h_seg;\\n\"\n          \"    unsigned char v_seg;\\n\"\n          \"} stb_easy_font_charinfo[96] = {\\n\");\n   charinfo[c].first_segment = stb_arr_len(segments);\n   charinfo[c].first_v_segment = stb_arr_len(vsegments);\n   for (c=32; c < 128; ++c) {\n      if ((c & 3) == 0) printf(\"    \");\n      printf(\"{ %2d,%3d,%3d },\",\n         charinfo[c].advance + 16*charinfo[c].voff,\n         charinfo[c].first_segment,\n         charinfo[c].first_v_segment);\n      if ((c & 3) == 3) printf(\"\\n\"); else printf(\"  \");\n   }\n   printf(\"};\\n\\n\");\n\n   printf(\"unsigned char stb_easy_font_hseg[%d] = {\\n\", stb_arr_len(segments));\n      print_segments(segments);\n   printf(\"};\\n\\n\");\n\n   printf(\"unsigned char stb_easy_font_vseg[%d] = {\\n\", stb_arr_len(vsegments));\n      print_segments(vsegments);\n   printf(\"};\\n\");\n   return 0;\n}\n"
  },
  {
    "path": "tools/make_readme.c",
    "content": "#define STB_DEFINE\n#include \"../stb.h\"\n\nint main(int argc, char  **argv)\n{\n   int i;\n   int hlen, flen, listlen, total_lines = 0;\n   char *header = stb_file(\"README.header.md\", &hlen);      // stb_file - read file into malloc()ed buffer\n   char *footer = stb_file(\"README.footer.md\", &flen);      // stb_file - read file into malloc()ed buffer\n   char **list  = stb_stringfile(\"README.list\", &listlen);  // stb_stringfile - read file lines into malloced array of strings\n\n   FILE *f = fopen(\"../README.md\", \"wb\");\n\n   fprintf(f, \"<!---   THIS FILE IS AUTOMATICALLY GENERATED, DO NOT CHANGE IT BY HAND   --->\\r\\n\\r\\n\");\n   fwrite(header, 1, hlen, f);\n\n   for (i=0; i < listlen; ++i) {\n      int num,j;\n      char **tokens = stb_tokens_stripwhite(list[i], \"|\", &num);  // stb_tokens -- tokenize string into malloced array of strings\n      int num_lines;\n      char **lines = stb_stringfile(stb_sprintf(\"../%s\", tokens[0]), &num_lines);\n      char *s1, *s2,*s3;\n      if (lines == NULL) stb_fatal(\"Couldn't open '%s'\", tokens[0]);\n      s1 = strchr(lines[0], '-');\n      if (!s1) stb_fatal(\"Couldn't find '-' before version number in %s\", tokens[0]); // stb_fatal -- print error message & exit\n      s2 = strchr(s1+2, '-');\n      if (!s2) stb_fatal(\"Couldn't find '-' after version number in %s\", tokens[0]);  // stb_fatal -- print error message & exit\n      *s2 = 0;\n      s1 += 1;\n      s1 = stb_trimwhite(s1);                  // stb_trimwhite -- advance pointer to after whitespace & delete trailing whitespace\n      if (*s1 == 'v') ++s1;\n      s3 = tokens[0];\n      stb_trimwhite(s3);\n      fprintf(f, \"**[\");\n      if (strlen(s3) < 21) {\n         fprintf(f, \"%s\", tokens[0]);\n      } else {\n         char buffer[256];\n         strncpy(buffer, s3, 18);\n         buffer[18] = 0;   \n         strcat(buffer, \"...\");\n         fprintf(f, \"%s\", buffer);\n      }\n      fprintf(f, \"](%s)**\", tokens[0]);\n      fprintf(f, \" | %s\", s1);\n      s1 = stb_trimwhite(tokens[1]);           // stb_trimwhite -- advance pointer to after whitespace & delete trailing whitespace\n      s2 = stb_dupreplace(s1, \" \", \"&nbsp;\");  // stb_dupreplace -- search & replace string and malloc result\n      fprintf(f, \" | %s\", s2);\n      free(s2);\n      fprintf(f, \" | %d\", num_lines);\n      total_lines += num_lines;\n      for (j=2; j < num; ++j)\n         fprintf(f, \" | %s\", tokens[j]);\n      fprintf(f, \"\\r\\n\");\n   }\n\n   fprintf(f, \"\\r\\n\");\n   fprintf(f, \"Total libraries: %d\\r\\n\", listlen);\n   fprintf(f, \"Total lines of C code: %d\\r\\n\\r\\n\", total_lines);\n\n   fwrite(footer, 1, flen, f);\n   fclose(f);\n\n   return 0;\n}\n"
  },
  {
    "path": "tools/make_readme.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"make_readme\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=make_readme - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"make_readme.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"make_readme.mak\" CFG=\"make_readme - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"make_readme - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"make_readme - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"make_readme - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"make_readme - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\\make_readme\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /FD /GZ /c\n# SUBTRACT CPP /YX\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"make_readme - Win32 Release\"\n# Name \"make_readme - Win32 Debug\"\n# Begin Source File\n\nSOURCE=.\\make_readme.c\n# End Source File\n# Begin Source File\n\nSOURCE=.\\README.header.md\n# End Source File\n# Begin Source File\n\nSOURCE=.\\README.list\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tools/mr.bat",
    "content": "debug\\make_readme\n"
  },
  {
    "path": "tools/trailing_whitespace.c",
    "content": "#define STB_DEFINE\n#include \"stb.h\"\n\nint main(int argc, char **argv)\n{\n   int i;\n   for (i=1; i < argc; ++i) {\n      int len;\n      FILE *f;\n      char *s = stb_file(argv[i], &len);\n      char *end, *src, *dest;\n      if (s == NULL) {\n         printf(\"Couldn't read file '%s'.\\n\", argv[i]);\n         continue; \n      }\n      end = s + len;\n      src = dest = s;\n      while (src < end) {\n         char *start=0;\n         while (src < end && *src != '\\n' && *src != '\\r')\n            *dest++ = *src++;\n         while (dest-1 > s && (dest[-1] == ' ' || dest[-1] == '\\t'))\n            --dest;\n         while (src < end && (*src == '\\n' || *src == '\\r'))\n            *dest++ = *src++;\n      }\n      f = fopen(argv[i], \"wb\");\n      fwrite(s, 1, dest-s, f);\n      fclose(f);\n   }\n    return 0;\n}\n"
  },
  {
    "path": "tools/unicode/unicode.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"unicode\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\n# ** DO NOT EDIT **\n\n# TARGTYPE \"Win32 (x86) Console Application\" 0x0103\n\nCFG=unicode - Win32 Debug\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n!MESSAGE use the Export Makefile command and run\n!MESSAGE \n!MESSAGE NMAKE /f \"unicode.mak\".\n!MESSAGE \n!MESSAGE You can specify a configuration when running NMAKE\n!MESSAGE by defining the macro CFG on the command line. For example:\n!MESSAGE \n!MESSAGE NMAKE /f \"unicode.mak\" CFG=\"unicode - Win32 Debug\"\n!MESSAGE \n!MESSAGE Possible choices for configuration are:\n!MESSAGE \n!MESSAGE \"unicode - Win32 Release\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \"unicode - Win32 Debug\" (based on \"Win32 (x86) Console Application\")\n!MESSAGE \n\n# Begin Project\n# PROP AllowPerConfigDependencies 0\n# PROP Scc_ProjName \"\"\n# PROP Scc_LocalPath \"\"\nCPP=cl.exe\nRSC=rc.exe\n\n!IF  \"$(CFG)\" == \"unicode - Win32 Release\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 0\n# PROP BASE Output_Dir \"Release\"\n# PROP BASE Intermediate_Dir \"Release\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 0\n# PROP Output_Dir \"Release\"\n# PROP Intermediate_Dir \"Release\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD CPP /nologo /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /c\n# ADD BASE RSC /l 0x409 /d \"NDEBUG\"\n# ADD RSC /l 0x409 /d \"NDEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\n\n!ELSEIF  \"$(CFG)\" == \"unicode - Win32 Debug\"\n\n# PROP BASE Use_MFC 0\n# PROP BASE Use_Debug_Libraries 1\n# PROP BASE Output_Dir \"Debug\"\n# PROP BASE Intermediate_Dir \"Debug\"\n# PROP BASE Target_Dir \"\"\n# PROP Use_MFC 0\n# PROP Use_Debug_Libraries 1\n# PROP Output_Dir \"Debug\"\n# PROP Intermediate_Dir \"Debug\"\n# PROP Target_Dir \"\"\n# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ  /c\n# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /YX /FD /GZ  /c\n# ADD BASE RSC /l 0x409 /d \"_DEBUG\"\n# ADD RSC /l 0x409 /d \"_DEBUG\"\nBSC32=bscmake.exe\n# ADD BASE BSC32 /nologo\n# ADD BSC32 /nologo\nLINK32=link.exe\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\n\n!ENDIF \n\n# Begin Target\n\n# Name \"unicode - Win32 Release\"\n# Name \"unicode - Win32 Debug\"\n# Begin Source File\n\nSOURCE=..\\unicode.c\n# End Source File\n# End Target\n# End Project\n"
  },
  {
    "path": "tools/unicode.c",
    "content": "#define STB_DEFINE\n#include \"../stb.h\"\n\n// create unicode mappings\n//\n// Two kinds of mappings:\n//     map to a number\n//     map to a bit\n//\n// For mapping to a number, we use the following strategy:\n//\n//   User supplies:\n//     1. a table of numbers (for now we use uint16, so full Unicode table is 4MB)\n//     2. a \"don't care\" value\n//     3. define a 'fallback' value (typically 0)\n//     4. define a fast-path range (typically 0..255 or 0..1023) [@TODO: automate detecting this]\n//\n//   Code:\n//     1. Determine range of *end* of unicode codepoints (U+10FFFF and down) which\n//        all have the same value (or don't care). If large enough, emit this as a\n//        special case in the code.\n//     2. Repeat above, limited to at most U+FFFF.\n//     3. Cluster the data into intervals of 8,16,32,64,128,256 numeric values.\n//        3a. If all the values in an interval are fallback/dont-care, no further processing\n//        3b. Find the \"trimmed range\" outside which all the values are the fallback or don't care\n//        3c. Find the \"special trimmed range\" outside which all the values are some constant or don't care\n//     4. Pack the clusters into continuous memory, and find previous instances of\n//        the cluster. Repeat for trimmed & special-trimmed. In the first case, find\n//        previous instances of the cluster (allow don't-care to match in either\n//        direction), both aligned and mis-aligned; in the latter, starting where\n//        things start or mis-aligned. Build an index table specifying the\n//        location of each cluster (and its length). Allow an extra indirection here;\n//        the full-sized index can index a smaller table which has the actual offset\n//        (and lengths).\n//     5. Associate with each packed continuous memory above the amount of memory\n//        required to store the data w/ smallest datatype (of uint8, uint16, uint32).\n//        Discard the continuous memory. Recurse on each index table, but avoid the\n//        smaller packing.\n//\n// For mapping to a bit, we pack the results for 8 characters into a byte, and then apply\n// the above strategy. Note that there may be more optimal approaches with e.g. packing\n// 8 different bits into a single structure, though, which we should explore eventually.\n\n\n// currently we limit *indices* to being 2^16, and we pack them as\n//      index + end_trim*2^16 + start_trim*2^24; specials have to go in a separate table\ntypedef uint32 uval;\n#define UVAL_DONT_CARE_DEFAULT 0xffffffff\n\ntypedef struct\n{\n   uval *input;\n   uint32 dont_care;\n   uint32 fallback;\n   int  fastpath;\n   int  length;\n   int  depth;\n   int  has_sign;\n   int  splittable;\n   int  replace_fallback_with_codepoint;\n   size_t input_size;\n   size_t inherited_storage;\n} table;\n\ntypedef struct\n{\n   int   split_log2;\n   table result; // index into not-returned table\n   int   storage;\n} output;\n\ntypedef struct\n{\n   table t;\n   char **output_name;\n} info;\n\ntypedef struct\n{\n   size_t path;\n   size_t size;\n} result;\n\ntypedef struct\n{\n   uint8 trim_end;\n   uint8 trim_start;\n   uint8 special;\n   uint8 aligned;\n   uint8 indirect;\n\n   uint16 overhead; // add some forced overhead for each mode to avoid getting complex encoding when it doesn't save much\n\n} mode_info;\n\nmode_info modes[] =\n{\n   {   0,0,0,0,0,    32, },\n   {   0,0,0,0,1,   100, },\n   {   0,0,0,1,0,    32, },\n   {   0,0,0,1,1,   100, },\n   {   0,0,1,0,1,   100, },\n   {   0,0,1,1,0,    32, },\n   {   0,0,1,1,1,   200, },\n   {   1,0,0,0,0,   100, },\n   {   1,0,0,0,1,   120, },\n   {   1,1,0,0,0,   100, },\n   {   1,1,0,0,1,   130, },\n   {   1,0,1,0,0,   130, },\n   {   1,0,1,0,1,   180, },\n   {   1,1,1,0,0,   180, },\n   {   1,1,1,0,1,   200, },\n};\n\n#define MODECOUNT  (sizeof(modes)/sizeof(modes[0]))\n#define CLUSTERSIZECOUNT   6    // 8,16, 32,64,  128,256\n\nsize_t size_for_max_number(uint32 number)\n{\n   if (number == 0) return 0;\n   if (number < 256) return 1;\n   if (number < 256*256) return 2;\n   if (number < 256*256*256) return 3;\n   return 4;\n}\n\nsize_t size_for_max_number_aligned(uint32 number)\n{\n   size_t n = size_for_max_number(number);\n   return n == 3 ? 4 : n;\n}\n\nuval get_data(uval *data, int offset, uval *end)\n{\n   if (data + offset >= end)\n      return 0;\n   else\n      return data[offset];\n}\n\nint safe_len(uval *data, int len, uval *end)\n{\n   if (len > end - data)\n      return end - data;\n   return len;\n}\n\nuval tempdata[256];\nint dirty=0;\n\nsize_t find_packed(uval **packed, uval *data, int len, int aligned, int fastpath, uval *end, int offset, int replace)\n{\n   int packlen = stb_arr_len(*packed);\n   int i,p;\n\n   if (data+len > end || replace) {\n      int safelen = safe_len(data, len, end);\n      memset(tempdata, 0, dirty*sizeof(tempdata[0]));\n      memcpy(tempdata, data, safelen * sizeof(data[0]));\n      data = tempdata;\n      dirty = len;\n   }\n   if (replace) {\n      int i;\n      int safelen = safe_len(data, len, end);\n      for (i=0; i < safelen; ++i)\n         if (data[i] == 0)\n            data[i] = offset+i;\n   }\n\n   if (len <= 0)\n      return 0;\n   if (!fastpath) {\n      if (aligned) {\n         for (i=0; i < packlen; i += len)\n            if ((*packed)[i] == data[0] && 0==memcmp(&(*packed)[i], data, len * sizeof(uval)))\n               return i / len;\n      } else {\n         for (i=0; i < packlen-len+1; i +=  1 )\n            if ((*packed)[i] == data[0] && 0==memcmp(&(*packed)[i], data, len * sizeof(uval)))\n               return i;\n      }\n   }\n   p = stb_arr_len(*packed);\n   for (i=0; i < len; ++i)\n      stb_arr_push(*packed, data[i]);\n   return p;\n}\n\nvoid output_table(char *name1, char *name2, uval *data, int length, int sign, char **names)\n{\n   char temp[20];\n   uval maxv = 0;\n   int bytes, numlen, at_newline;\n   int linelen = 79; // @TODO: make table more readable by choosing a length that's a multiple?\n   int i,pos, do_split=0;\n   for (i=0; i < length; ++i)\n      if (sign)\n         maxv = stb_max(maxv, (uval)abs((int)data[i]));\n      else\n         maxv = stb_max(maxv, data[i]);\n   bytes = size_for_max_number_aligned(maxv);\n   sprintf(temp, \"%d\", maxv);\n   numlen=strlen(temp);\n   if (sign)\n      ++numlen;\n   \n   if (bytes == 0)\n      return;\n\n   printf(\"uint%d %s%s[%d] = {\\n\", bytes*8, name1, name2, length);\n   at_newline = 1;\n   for (i=0; i < length; ++i) {\n      if (pos + numlen + 2 > linelen) {\n         printf(\"\\n\");\n         at_newline = 1;\n         pos = 0;\n      }\n      if (at_newline) {\n         printf(\"  \");\n         pos = 2;\n         at_newline = 0;\n      } else {\n         printf(\" \");\n         ++pos;\n      }\n      printf(\"%*d,\", numlen, data[i]);\n      pos += numlen+1;\n   }\n   if (!at_newline) printf(\"\\n\");\n   printf(\"};\\n\");\n}\n\nvoid output_table_with_trims(char *name1, char *name2, uval *data, int length)\n{\n   uval maxt=0, maxp=0;\n   int i,d,s,e, count;\n   // split the table into two pieces\n   uval *trims = NULL;\n\n   if (length == 0)\n      return;\n\n   for (i=0; i < stb_arr_len(data); ++i) {\n      stb_arr_push(trims, data[i] >> 16);\n      data[i] &= 0xffff;\n      maxt = stb_max(maxt, trims[i]);\n      maxp = stb_max(maxp, data[i]);\n   }\n\n   d=s=e=1;\n   if (maxt >= 256) {\n      // need to output start & end values\n      if (maxp >= 256) {\n         // can pack into a single table\n         printf(\"struct { uint16 val; uint8 start, end; } %s%s[%d] = {\\n\", name1, name2, length);\n      } else {\n         output_table(name1, name2, data, length, 0, 0);\n         d=0;\n         printf(\"struct { uint8 start, end; } %s%s_trim[%d] = {\\n\", name1, name2, length);\n      }\n   } else if (maxt > 0) {\n      if (maxp >= 256) {\n         output_table(name1, name2, data, length, 0, 0);\n         output_table(name1, stb_sprintf(\"%s_end\", name2), trims, length, 0, 0);\n         return;\n      } else {\n         printf(\"struct { uint8 val, end; } %s%s[%d] = {\\n\", name1, name2, length);\n         s=0;\n      }\n   } else {\n      output_table(name1, name2, data, length, 0, 0);\n      return;\n   }\n   // d or s can be zero (but not both), e is always present and last\n   count = d + s + e;\n   assert(count >= 2 && count <= 3);\n\n   {\n      char temp[60];\n      uval maxv = 0;\n      int numlen, at_newline, len;\n      int linelen = 79; // @TODO: make table more readable by choosing a length that's a multiple?\n      int i,pos, do_split=0;\n      numlen = 0;\n      for (i=0; i < length; ++i) {\n         if (count == 2)\n            sprintf(temp, \"{%d,%d}\", d ? data[i] : (trims[i]>>8), trims[i]&255);\n         else\n            sprintf(temp, \"{%d,%d,%d}\", data[i], trims[i]>>8, trims[i]&255);\n         len = strlen(temp);\n         numlen = stb_max(len, numlen);\n      }\n   \n      at_newline = 1;\n      for (i=0; i < length; ++i) {\n         if (pos + numlen + 2 > linelen) {\n            printf(\"\\n\");\n            at_newline = 1;\n            pos = 0;\n         }\n         if (at_newline) {\n            printf(\"  \");\n            pos = 2;\n            at_newline = 0;\n         } else {\n            printf(\" \");\n            ++pos;\n         }\n         if (count == 2)\n            sprintf(temp, \"{%d,%d}\", d ? data[i] : (trims[i]>>8), trims[i]&255);\n         else\n            sprintf(temp, \"{%d,%d,%d}\", data[i], trims[i]>>8, trims[i]&255);\n         printf(\"%*s,\", numlen, temp);\n         pos += numlen+1;\n      }\n      if (!at_newline) printf(\"\\n\");\n      printf(\"};\\n\");\n   }\n}\n\nint weight=1;\n\ntable pack_for_mode(table *t, int mode, char *table_name)\n{\n   size_t extra_size;\n   int i;\n   uval maxv;\n   mode_info mi = modes[mode % MODECOUNT];\n   int size = 8 << (mode / MODECOUNT);\n   table newtab;\n   uval *packed = NULL;\n   uval *index = NULL;\n   uval *indirect = NULL;\n   uval *specials = NULL;\n   newtab.dont_care = UVAL_DONT_CARE_DEFAULT;\n   if (table_name)\n      printf(\"// clusters of %d\\n\", size);\n   for (i=0; i < t->length; i += size) {\n      uval newval;\n      int fastpath = (i < t->fastpath);\n      if (mi.special) {\n         int end_trim = size-1;\n         int start_trim = 0;\n         uval special;\n         // @TODO: pick special from start or end instead of only end depending on which is longer\n         for(;;) {\n            special = t->input[i + end_trim];\n            if (special != t->dont_care || end_trim == 0)\n               break;\n            --end_trim;\n         }\n         // at this point, special==inp[end_trim], and end_trim >= 0\n         if (special == t->dont_care && !fastpath) {\n            // entire block is don't care, so OUTPUT don't care\n            stb_arr_push(index, newtab.dont_care);\n            continue;\n         } else {\n            uval pos, trim;\n            if (mi.trim_end && !fastpath) {\n               while (end_trim >= 0) {\n                  if (t->input[i + end_trim] == special || t->input[i + end_trim] == t->dont_care)\n                     --end_trim;\n                  else\n                     break;\n               }\n            }\n\n            if (mi.trim_start && !fastpath) {\n               while (start_trim < end_trim) {\n                  if (t->input[i + start_trim] == special || t->input[i + start_trim] == t->dont_care)\n                     ++start_trim;\n                  else\n                     break;\n               }\n            }\n\n            // end_trim points to the last character we have to output\n\n            // find the first match, or add it\n            pos = find_packed(&packed, &t->input[i+start_trim], end_trim-start_trim+1, mi.aligned, fastpath, &t->input[t->length], i+start_trim, t->replace_fallback_with_codepoint);\n\n            // encode as a uval\n            if (!mi.trim_end) {\n               if (end_trim == 0)\n                  pos = special;\n               else\n                  pos = pos | 0x80000000;\n            } else {\n               assert(end_trim < size && end_trim >= -1);\n               if (!fastpath) assert(end_trim < size-1); // special always matches last one\n               assert(end_trim < size && end_trim+1 >= 0);\n               if (!fastpath) assert(end_trim+1 < size);\n\n               if (mi.trim_start)\n                  trim = start_trim*256 + (end_trim+1);\n               else\n                  trim = end_trim+1;\n\n               assert(pos < 65536); // @TODO: if this triggers, just bail on this search path\n               pos = pos + (trim << 16);\n            }\n\n            newval = pos;\n\n            stb_arr_push(specials, special);\n         }\n      } else if (mi.trim_end) {\n         int end_trim = size-1;\n         int start_trim = 0;\n         uval pos, trim;\n\n         while (end_trim >= 0 && !fastpath)\n            if (t->input[i + end_trim] == t->fallback || t->input[i + end_trim] == t->dont_care)\n               --end_trim;\n            else\n               break;\n\n         if (mi.trim_start && !fastpath) {\n            while (start_trim < end_trim) {\n               if (t->input[i + start_trim] == t->fallback || t->input[i + start_trim] == t->dont_care)\n                  ++start_trim;\n               else\n                  break;\n            }\n         }\n\n         // end_trim points to the last character we have to output, and can be -1\n         ++end_trim; // make exclusive at end\n\n         if (end_trim == 0 && size == 256)\n            start_trim = end_trim = 1;  // we can't make encode a length from 0..256 in 8 bits, so restrict end_trim to 1..256\n\n         // find the first match, or add it\n         pos = find_packed(&packed, &t->input[i+start_trim], end_trim - start_trim, mi.aligned, fastpath, &t->input[t->length], i+start_trim, t->replace_fallback_with_codepoint);\n\n         assert(end_trim <= size && end_trim >= 0);\n         if (size == 256)\n            assert(end_trim-1 < 256 && end_trim-1 >= 0);\n         else\n            assert(end_trim < 256 && end_trim >= 0);\n         if (size == 256)\n            --end_trim;\n\n         if (mi.trim_start)\n            trim = start_trim*256 + end_trim;\n         else\n            trim = end_trim;\n\n         assert(pos < 65536); // @TODO: if this triggers, just bail on this search path\n         pos = pos + (trim << 16);\n\n         newval = pos;\n      } else {\n         newval = find_packed(&packed, &t->input[i], size, mi.aligned, fastpath, &t->input[t->length], i, t->replace_fallback_with_codepoint);\n      }\n\n      if (mi.indirect) {\n         int j;\n         for (j=0; j < stb_arr_len(indirect); ++j)\n            if (indirect[j] == newval)\n               break;\n         if (j == stb_arr_len(indirect))\n            stb_arr_push(indirect, newval);\n         stb_arr_push(index, j);\n      } else {\n         stb_arr_push(index, newval);\n      }\n   }\n\n   // total up the new size for everything but the index table\n   extra_size = mi.overhead * weight; // not the actual overhead cost; a penalty to avoid excessive complexity\n   extra_size += 150; // per indirection\n   if (table_name)\n      extra_size = 0;\n   \n   if (t->has_sign) {\n      // 'packed' contains two values, which should be packed positive & negative for size\n      uval maxv2;\n      for (i=0; i < stb_arr_len(packed); ++i)\n         if (packed[i] & 0x80000000)\n            maxv2 = stb_max(maxv2, packed[i]);\n         else\n            maxv  = stb_max(maxv, packed[i]);\n      maxv = stb_max(maxv, maxv2) << 1;\n   } else {\n      maxv = 0;\n      for (i=0; i < stb_arr_len(packed); ++i)\n         if (packed[i] > maxv && packed[i] != t->dont_care)\n            maxv = packed[i];\n   }\n   extra_size += stb_arr_len(packed) * (t->splittable ? size_for_max_number(maxv) : size_for_max_number_aligned(maxv));\n   if (table_name) {\n      if (t->splittable)\n         output_table_with_trims(table_name, \"\", packed, stb_arr_len(packed));\n      else\n         output_table(table_name, \"\", packed, stb_arr_len(packed), t->has_sign, NULL);\n   }\n\n   maxv = 0;\n   for (i=0; i < stb_arr_len(specials); ++i)\n      if (specials[i] > maxv)\n         maxv = specials[i];\n   extra_size += stb_arr_len(specials) * size_for_max_number_aligned(maxv);\n   if (table_name)\n      output_table(table_name, \"_default\", specials, stb_arr_len(specials), 0, NULL);\n\n   maxv = 0;\n   for (i=0; i < stb_arr_len(indirect); ++i)\n      if (indirect[i] > maxv)\n         maxv = indirect[i];\n   extra_size += stb_arr_len(indirect) * size_for_max_number(maxv);\n\n   if (table_name && stb_arr_len(indirect)) {\n      if (mi.trim_end)\n         output_table_with_trims(table_name, \"_index\", indirect, stb_arr_len(indirect));\n      else {\n         assert(0); // this case should only trigger in very extreme circumstances\n         output_table(table_name, \"_index\", indirect, stb_arr_len(indirect), 0, NULL);\n      }\n      mi.trim_end = mi.special = 0;\n   }\n\n   if (table_name)\n      printf(\"// above tables should be %d bytes\\n\", extra_size);\n\n   maxv = 0;\n   for (i=0; i < stb_arr_len(index); ++i)\n      if (index[i] > maxv && index[i] != t->dont_care)\n         maxv = index[i];\n   newtab.splittable = mi.trim_end;\n   newtab.input_size = newtab.splittable ? size_for_max_number(maxv) : size_for_max_number_aligned(maxv);\n   newtab.input = index;\n   newtab.length = stb_arr_len(index);\n   newtab.inherited_storage = t->inherited_storage + extra_size;\n   newtab.fastpath = 0;\n   newtab.depth = t->depth+1;\n   stb_arr_free(indirect);\n   stb_arr_free(packed);\n   stb_arr_free(specials);\n\n   return newtab;\n}\n\nresult pack_table(table *t, size_t path, int min_storage)\n{\n   int i;\n   result best;\n   best.size = t->inherited_storage + t->input_size * t->length;\n   best.path = path;\n\n   if ((int) t->inherited_storage > min_storage) {\n      best.size = stb_max(best.size, t->inherited_storage);\n      return best;\n   }\n\n   if (t->length <= 256 || t->depth >= 4) {\n      //printf(\"%08x: %7d\\n\", best.path, best.size);\n      return best;\n   }\n\n   path <<= 7;\n   for (i=0; i < MODECOUNT * CLUSTERSIZECOUNT; ++i) {\n      table newtab;\n      result r;\n      newtab = pack_for_mode(t, i, 0);\n      r = pack_table(&newtab, path+i+1, min_storage);\n      if (r.size < best.size)\n         best = r;\n      stb_arr_free(newtab.input);\n      //printf(\"Size: %6d + %6d\\n\", newtab.inherited_storage, newtab.input_size * newtab.length);\n   }\n   return best;\n}\n\nint pack_table_by_modes(table *t, int *modes)\n{\n   table s = *t;\n   while (*modes > -1) {\n      table newtab;\n      newtab = pack_for_mode(&s, *modes, 0);\n      if (s.input != t->input)\n         stb_arr_free(s.input);\n      s = newtab;\n      ++modes;\n   }\n   return s.inherited_storage + s.input_size * s.length;\n}\n\nint strip_table(table *t, int exceptions)\n{\n   uval terminal_value;\n   int p = t->length-1;\n   while (t->input[p] == t->dont_care)\n      --p;\n   terminal_value = t->input[p];\n\n   while (p >= 0x10000) {\n      if (t->input[p] != terminal_value && t->input[p] != t->dont_care) {\n         if (exceptions)\n            --exceptions;\n         else\n            break;\n      }\n      --p;\n   }\n   return p+1; // p is a character we must output\n}\n\nvoid optimize_table(table *t, char *table_name)\n{\n   int modelist[3] = { 85, -1 };\n   int modes[8];\n   int num_modes = 0;\n   int decent_size;\n   result r;\n   size_t path;\n   table s;\n\n   // strip tail end of table\n   int orig_length = t->length;\n   int threshhold = 0xffff;\n   int p = strip_table(t, 2);\n   int len_saved = t->length - p;\n   if (len_saved >= threshhold) {\n      t->length = p;\n      while (p > 0x10000) {\n         p = strip_table(t, 0);\n         len_saved = t->length - p;\n         if (len_saved < 0x10000)\n            break;\n         len_saved = orig_length - p;\n         if (len_saved < threshhold)\n            break;\n         threshhold *= 2;\n      }\n   }\n\n   t->depth = 1;\n\n\n   // find size of table if we use path 86\n   decent_size = pack_table_by_modes(t, modelist);\n\n\n   #if 1\n   // find best packing of remainder of table by exploring tree of packings\n   r = pack_table(t, 0, decent_size);\n   // use the computed 'path' to evaluate and output tree\n   path = r.path;\n   #else\n   path = 86;//90;//132097;\n   #endif\n\n   while (path) {\n      modes[num_modes++] = (path & 127) - 1;\n      path >>= 7;\n   }\n\n   printf(\"// modes: %d\\n\", r.path);\n   s = *t;\n   while (num_modes > 0) {\n      char name[256];\n      sprintf(name, \"%s_%d\", table_name, num_modes+1);\n      --num_modes;\n      s = pack_for_mode(&s, modes[num_modes], name);\n   }\n   // output the final table as-is\n   if (s.splittable)\n      output_table_with_trims(table_name, \"_1\", s.input, s.length);\n   else\n      output_table(table_name, \"_1\", s.input, s.length, 0, NULL);\n}\n\nuval unicode_table[0x110000];\n\ntypedef struct\n{\n   uval lo,hi;\n} char_range;\n\nchar_range get_range(char *str)\n{\n   char_range cr;\n   char *p;\n   cr.lo = strtol(str, &p, 16);\n   p = stb_skipwhite(p);\n   if (*p == '.')\n      cr.hi = strtol(p+2, NULL, 16);\n   else\n      cr.hi = cr.lo;\n   return cr;\n}\n\nchar *skip_semi(char *s, int count)\n{\n   while (count) {\n      s = strchr(s, ';');\n      assert(s != NULL);\n      ++s;\n      --count;\n   }\n   return s;\n}\n\nint main(int argc, char **argv)\n{\n   table t;\n   uval maxv=0;\n   int i,n=0;\n   char **s = stb_stringfile(\"../../data/UnicodeData.txt\", &n);\n   assert(s);\n   for (i=0; i < n; ++i) {\n      if (s[i][0] == '#' || s[i][0] == '\\n' || s[i][0] == 0)\n         ;\n      else {\n         char_range cr = get_range(s[i]);\n         char *t = skip_semi(s[i], 13);\n         uval j, v;\n         if (*t == ';' || *t == '\\n' || *t == 0)\n            v = 0;\n         else {\n            v = strtol(t, NULL, 16);\n            if (v < 65536) {\n               maxv = stb_max(v, maxv);\n               for (j=cr.lo; j <= cr.hi; ++j) {\n                  unicode_table[j] = v;\n                  //printf(\"%06x => %06x\\n\", j, v);\n               }\n            }\n         }\n      }\n   }\n\n   t.depth = 0;\n   t.dont_care = UVAL_DONT_CARE_DEFAULT;\n   t.fallback = 0;\n   t.fastpath = 256;\n   t.inherited_storage = 0;\n   t.has_sign = 0;\n   t.splittable = 0;\n   t.input = unicode_table;\n   t.input_size = size_for_max_number(maxv);\n   t.length = 0x110000;\n   t.replace_fallback_with_codepoint = 1;\n\n   optimize_table(&t, \"stbu_upppercase\");\n   return 0;\n}\n"
  }
]