Skip to content
Myr

stb.h

This file

Path

deprecated/stb.h

13,111 lines · 407.8 KiB · C

Last changed by

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

History of this file

Take it

1/* stb.h - v2.37 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h2          no warranty is offered or implied; use this code at your own risk34   This is a single header file with a bunch of useful utilities5   for getting stuff done in C/C++.67   Documentation: http://nothings.org/stb/stb_h.html8   Unit tests:    http://nothings.org/stb/stb.c910 ============================================================================11   You MUST1213      #define STB_DEFINE1415   in EXACTLY _one_ C or C++ file that includes this header, BEFORE the16   include, like this:1718      #define STB_DEFINE19      #include "stb.h"2021   All other files should just #include "stb.h" without the #define.22 ============================================================================2324Version History2526   2.36   various fixes27   2.35   fix clang-cl issues with swprintf28   2.34   fix warnings29   2.33   more fixes to random numbers30   2.32   stb_intcmprev, stb_uidict, fix random numbers on Linux31   2.31   stb_ucharcmp32   2.30   MinGW fix33   2.29   attempt to fix use of swprintf()34   2.28   various new functionality35   2.27   test _WIN32 not WIN32 in STB_THREADS36   2.26   various warning & bugfixes37   2.25   various warning & bugfixes38   2.24   various warning & bugfixes39   2.23   fix 2.2240   2.22   64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name41   2.21   utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements42   2.20   fix to hash "copy" function--reported by someone with handle "!="43   2.19   ???44   2.18   stb_readdir_subdirs_mask45   2.17   stb_cfg_dir46   2.16   fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper47   2.15   upgraded hash table template to allow:48            - aggregate keys (explicit comparison func for EMPTY and DEL keys)49            - "static" implementations (so they can be culled if unused)50   2.14   stb_mprintf51   2.13   reduce identifiable strings in STB_NO_STB_STRINGS52   2.12   fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in53   2.11   fix bug in stb_dirtree_get() which caused "c://path" sorts of stuff54   2.10   STB_F(), STB_I() inline constants (also KI,KU,KF,KD)55   2.09   stb_box_face_vertex_axis_side56   2.08   bugfix stb_trimwhite()57   2.07   colored printing in windows (why are we in 1985?)58   2.06   comparison functions are now functions-that-return-functions and59          accept a struct-offset as a parameter (not thread-safe)60   2.05   compile and pass tests under Linux (but no threads); thread cleanup61   2.04   stb_cubic_bezier_1d, smoothstep, avoid dependency on registry62   2.03   ?63   2.02   remove integrated documentation64   2.01   integrate various fixes; stb_force_uniprocessor65   2.00   revised stb_dupe to use multiple hashes66   1.99   stb_charcmp67   1.98   stb_arr_deleten, stb_arr_insertn68   1.97   fix stb_newell_normal()69   1.96   stb_hash_number()70   1.95   hack stb__rec_max; clean up recursion code to use new functions71   1.94   stb_dirtree; rename stb_extra to stb_ptrmap72   1.93   stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra')73   1.92   stb_threadqueue--multi reader/writer queue, fixed size or resizeable74   1.91   stb_bgio_* for reading disk asynchronously75   1.90   stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread76          joining; workqueue supports stb_sync instead of stb_semaphore77   1.89   support ';' in constant-string wildcards; stb_mutex wrapper (can78          implement with EnterCriticalRegion eventually)79   1.88   portable threading API (only for win32 so far); worker thread queue80   1.87   fix wildcard handling in stb_readdir_recursive81   1.86   support ';' in wildcards82   1.85   make stb_regex work with non-constant strings;83               beginnings of stb_introspect()84   1.84   (forgot to make notes)85   1.83   whoops, stb_keep_if_different wasn't deleting the temp file86   1.82   bring back stb_compress from stb_file.h for cmirror87   1.81   various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release88   1.80   stb_readdir returns utf8; write own utf8-utf16 because lib was wrong89   1.79   stb_write90   1.78   calloc() support for malloc wrapper, STB_FASTMALLOC91   1.77   STB_FASTMALLOC92   1.76   STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear)93   1.75   alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs;94          hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst95   1.74   stb_replaceinplace; use stdlib C function to convert utf8 to UTF-1696   1.73   fix performance bug & leak in stb_ischar (C++ port lost a 'static')97   1.72   remove stb_block, stb_block_manager, stb_decompress (to stb_file.h)98   1.71   stb_trimwhite, stb_tokens_nested, etc.99   1.70   back out 1.69 because it might problemize mixed builds; stb_filec()100   1.69   (stb_file returns 'char *' in C++)101   1.68   add a special 'tree root' data type for stb_bst; stb_arr_end102   1.67   full C++ port. (stb_block_manager)103   1.66   stb_newell_normal104   1.65   stb_lex_item_wild -- allow wildcard items which MUST match entirely105   1.64   stb_data106   1.63   stb_log_name107   1.62   stb_define_sort; C++ cleanup108   1.61   stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?)109   1.60   stb_delete_directory_recursive110   1.59   stb_readdir_recursive111   1.58   stb_bst variant with parent pointer for O(1) iteration, not O(log N)112   1.57   replace LCG random with Mersenne Twister (found a public domain one)113   1.56   stb_perfect_hash, stb_ischar, stb_regex114   1.55   new stb_bst API allows multiple BSTs per node (e.g. secondary keys)115   1.54   bugfix: stb_define_hash, stb_wildmatch, regexp116   1.53   stb_define_hash; recoded stb_extra, stb_sdict use it117   1.52   stb_rand_define, stb_bst, stb_reverse118   1.51   fix 'stb_arr_setlen(NULL, 0)'119   1.50   stb_wordwrap120   1.49   minor improvements to enable the scripting language121   1.48   better approach for stb_arr using stb_malloc; more invasive, clearer122   1.47   stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex)123   1.46   stb_wrapper_*, STB_MALLOC_WRAPPER124   1.45   lightly tested DFA acceleration of regexp searching125   1.44   wildcard matching & searching; regexp matching & searching126   1.43   stb_temp127   1.42   allow stb_arr to use stb_malloc/realloc; note this is global128   1.41   make it compile in C++; (disable stb_arr in C++)129   1.40   stb_dupe tweak; stb_swap; stb_substr130   1.39   stb_dupe; improve stb_file_max to be less stupid131   1.38   stb_sha1_file: generate sha1 for file, even > 4GB132   1.37   stb_file_max; partial support for utf8 filenames in Windows133   1.36   remove STB__NO_PREFIX - poor interaction with IDE, not worth it134          streamline stb_arr to make it separately publishable135   1.35   bugfixes for stb_sdict, stb_malloc(0), stristr136   1.34   (streaming interfaces for stb_compress)137   1.33   stb_alloc; bug in stb_getopt; remove stb_overflow138   1.32   (stb_compress returns, smaller&faster; encode window & 64-bit len)139   1.31   stb_prefix_count140   1.30   (STB__NO_PREFIX - remove stb_ prefixes for personal projects)141   1.29   stb_fput_varlen64, etc.142   1.28   stb_sha1143   1.27   ?144   1.26   stb_extra145   1.25   ?146   1.24   stb_copyfile147   1.23   stb_readdir148   1.22   ?149   1.21   ?150   1.20   ?151   1.19   ?152   1.18   ?153   1.17   ?154   1.16   ?155   1.15   stb_fixpath, stb_splitpath, stb_strchr2156   1.14   stb_arr157   1.13   ?stb, stb_log, stb_fatal158   1.12   ?stb_hash2159   1.11   miniML160   1.10   stb_crc32, stb_adler32161   1.09   stb_sdict162   1.08   stb_bitreverse, stb_ispow2, stb_big32163          stb_fopen, stb_fput_varlen, stb_fput_ranged164          stb_fcmp, stb_feq165   1.07   (stb_encompress)166   1.06   stb_compress167   1.05   stb_tokens, (stb_hheap)168   1.04   stb_rand169   1.03   ?(s-strings)170   1.02   ?stb_filelen, stb_tokens171   1.01   stb_tolower172   1.00   stb_hash, stb_intcmp173          stb_file, stb_stringfile, stb_fgets174          stb_prefix, stb_strlower, stb_strtok175          stb_image176          (stb_array), (stb_arena)177178Parenthesized items have since been removed.179180LICENSE181182 See end of file for license information.183184CREDITS185186 Written by Sean Barrett.187188 Fixes:189  Philipp Wiesemann190  Robert Nix191  r-lyeh192  blackpawn193  github:Mojofreem194  Ryan Whitworth195  Vincent Isambart196  Mike Sartain197  Eugene Opalev198  Tim Sjostrand199  github:infatum200  Dave Butler (Croepha)201  Ethan Lee (flibitijibibo)202  Brian Collins203  Kyle Langley204*/205206#include <stdarg.h>207208#ifndef STB__INCLUDE_STB_H209#define STB__INCLUDE_STB_H210211#define STB_VERSION  1212213#ifdef STB_INTROSPECT214   #define STB_DEFINE215#endif216217#ifdef STB_DEFINE_THREADS218   #ifndef STB_DEFINE219   #define STB_DEFINE220   #endif221   #ifndef STB_THREADS222   #define STB_THREADS223   #endif224#endif225226#if defined(_WIN32) && !defined(__MINGW32__)227   #ifndef _CRT_SECURE_NO_WARNINGS228   #define _CRT_SECURE_NO_WARNINGS229   #endif230   #ifndef _CRT_NONSTDC_NO_DEPRECATE231   #define _CRT_NONSTDC_NO_DEPRECATE232   #endif233   #ifndef _CRT_NON_CONFORMING_SWPRINTFS234   #define _CRT_NON_CONFORMING_SWPRINTFS235   #endif236   #if !defined(_MSC_VER) || _MSC_VER > 1700237   #include <intrin.h> // _BitScanReverse238   #endif239#endif240241#include <stdlib.h>     // stdlib could have min/max242#include <stdio.h>      // need FILE243#include <string.h>     // stb_define_hash needs memcpy/memset244#include <time.h>       // stb_dirtree245#ifdef __MINGW32__246   #include <fcntl.h>   // O_RDWR247#endif248249#ifdef STB_PERSONAL250   typedef int Bool;251   #define False 0252   #define True 1253#endif254255#ifdef STB_MALLOC_WRAPPER_PAGED256   #define STB_MALLOC_WRAPPER_DEBUG257#endif258#ifdef STB_MALLOC_WRAPPER_DEBUG259   #define STB_MALLOC_WRAPPER260#endif261#ifdef STB_MALLOC_WRAPPER_FASTMALLOC262   #define STB_FASTMALLOC263   #define STB_MALLOC_WRAPPER264#endif265266#ifdef STB_FASTMALLOC267   #ifndef _WIN32268      #undef STB_FASTMALLOC269   #endif270#endif271272#ifdef STB_DEFINE273   #include <assert.h>274   #include <stdarg.h>275   #include <stddef.h>276   #include <ctype.h>277   #include <math.h>278   #ifndef _WIN32279   #include <unistd.h>280   #else281   #include <io.h>      // _mktemp282   #include <direct.h>  // _rmdir283   #endif284   #include <sys/types.h> // stat()/_stat()285   #include <sys/stat.h>  // stat()/_stat()286#endif287288#define stb_min(a,b)   ((a) < (b) ? (a) : (b))289#define stb_max(a,b)   ((a) > (b) ? (a) : (b))290291#ifndef STB_ONLY292   #if !defined(__cplusplus) && !defined(min) && !defined(max)293     #define min(x,y) stb_min(x,y)294     #define max(x,y) stb_max(x,y)295   #endif296297   #ifndef M_PI298     #define M_PI  3.14159265358979323846f299   #endif300301   #ifndef TRUE302     #define TRUE  1303     #define FALSE 0304   #endif305306   #ifndef deg2rad307   #define deg2rad(a)  ((a)*(M_PI/180))308   #endif309   #ifndef rad2deg310   #define rad2deg(a)  ((a)*(180/M_PI))311   #endif312313   #ifndef swap314   #ifndef __cplusplus315   #define swap(TYPE,a,b)  \316               do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0)317   #endif318   #endif319320   typedef unsigned char  uint8 ;321   typedef   signed char   int8 ;322   typedef unsigned short uint16;323   typedef   signed short  int16;324  #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)325   typedef unsigned long  uint32;326   typedef   signed long   int32;327  #else328   typedef unsigned int   uint32;329   typedef   signed int    int32;330  #endif331332   typedef unsigned char  uchar ;333   typedef unsigned short ushort;334   typedef unsigned int   uint  ;335   typedef unsigned long  ulong ;336337   // produce compile errors if the sizes aren't right338   typedef char stb__testsize16[sizeof(int16)==2];339   typedef char stb__testsize32[sizeof(int32)==4];340#endif341342#ifndef STB_TRUE343  #define STB_TRUE 1344  #define STB_FALSE 0345#endif346347// if we're STB_ONLY, can't rely on uint32 or even uint, so all the348// variables we'll use herein need typenames prefixed with 'stb':349typedef unsigned char stb_uchar;350typedef unsigned char stb_uint8;351typedef unsigned int  stb_uint;352typedef unsigned short stb_uint16;353typedef          short stb_int16;354typedef   signed char  stb_int8;355#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)356  typedef unsigned long  stb_uint32;357  typedef          long  stb_int32;358#else359  typedef unsigned int   stb_uint32;360  typedef          int   stb_int32;361#endif362typedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];363typedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];364365#ifdef _MSC_VER366  typedef unsigned __int64 stb_uint64;367  typedef          __int64 stb_int64;368  #define STB_IMM_UINT64(literalui64) (literalui64##ui64)369  #define STB_IMM_INT64(literali64) (literali64##i64)370#else371  // ??372  typedef unsigned long long stb_uint64;373  typedef          long long stb_int64;374  #define STB_IMM_UINT64(literalui64) (literalui64##ULL)375  #define STB_IMM_INT64(literali64) (literali64##LL)376#endif377typedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];378379// add platform-specific ways of checking for sizeof(char*) == 8,380// and make those define STB_PTR64381#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)382  #define STB_PTR64383#endif384385#ifdef STB_PTR64386typedef char stb__testsize2_ptr[sizeof(char *) == 8];387typedef stb_uint64 stb_uinta;388typedef stb_int64  stb_inta;389#else390typedef char stb__testsize2_ptr[sizeof(char *) == 4];391typedef stb_uint32 stb_uinta;392typedef stb_int32  stb_inta;393#endif394typedef char stb__testsize2_uinta[sizeof(stb_uinta)==sizeof(char*) ? 1 : -1];395396// if so, we should define an int type that is the pointer size. until then,397// we'll have to make do with this (which is not the same at all!)398399typedef union400{401   unsigned int i;402   void * p;403} stb_uintptr;404405406#ifdef __cplusplus407   #define STB_EXTERN   extern "C"408#else409   #define STB_EXTERN   extern410#endif411412// check for well-known debug defines413#if defined(DEBUG) || defined(_DEBUG) || defined(DBG)414   #ifndef NDEBUG415      #define STB_DEBUG416   #endif417#endif418419#ifdef STB_DEBUG420   #include <assert.h>421#endif422423//////////////////////////////////////////////////////////////////////////////424//425//                         C library function platform handling426//427428#ifdef STB_DEFINE429430#if defined(_WIN32) &&  defined(__STDC_WANT_SECURE_LIB__)431static FILE * stb_p_fopen(const char *filename, const char *mode)432{433   FILE *f;434   if (0 == fopen_s(&f, filename, mode))435      return f;436   else437      return NULL;438}439static FILE * stb_p_wfopen(const wchar_t *filename, const wchar_t *mode)440{441   FILE *f;442   if (0 == _wfopen_s(&f, filename, mode))443      return f;444   else445      return NULL;446}447static char *stb_p_strcpy_s(char *a, size_t size, const char *b)448{449   strcpy_s(a,size,b);450   return a;451}452static char *stb_p_strncpy_s(char *a, size_t size, const char *b, size_t count)453{454   strncpy_s(a,size,b,count);455   return a;456}457#define stb_p_mktemp(s)  (_mktemp_s(s, strlen(s)+1) == 0)458#define stb_p_sprintf    sprintf_s459#define stb_p_size(x)    ,(x)460#else461#define stb_p_fopen      fopen462#define stb_p_wfopen     _wfopen463#define stb_p_strcpy_s(a,s,b)     strcpy(a,b)464#define stb_p_strncpy_s(a,s,b,c)  strncpy(a,b,c)465#define stb_p_mktemp(s)  (mktemp(s) != NULL)466467#define stb_p_sprintf    sprintf468#define stb_p_size(x)469#endif470471#if defined(_WIN32)472#define stb_p_vsnprintf  _vsnprintf473#else474#define stb_p_vsnprintf  vsnprintf475#endif476#endif // STB_DEFINE477478#if defined(_WIN32) && (_MSC_VER >= 1300)479#define stb_p_stricmp    _stricmp480#define stb_p_strnicmp   _strnicmp481#define stb_p_strdup     _strdup482#else483#define stb_p_strdup     strdup484#define stb_p_stricmp    stricmp485#define stb_p_strnicmp   strnicmp486#endif487488STB_EXTERN void stb_wrapper_malloc(void *newp, size_t sz, char *file, int line);489STB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line);490STB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, size_t sz, char *file, int line);491STB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line);492STB_EXTERN void stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line));493STB_EXTERN void stb_wrapper_dump(char *filename);494STB_EXTERN size_t stb_wrapper_allocsize(void *oldp);495STB_EXTERN void stb_wrapper_check(void *oldp);496497#ifdef STB_DEFINE498// this is a special function used inside malloc wrapper499// to do allocations that aren't tracked (to avoid500// reentrancy). Of course if someone _else_ wraps realloc,501// this breaks, but if they're doing that AND the malloc502// wrapper they need to explicitly check for reentrancy.503//504// only define realloc_raw() and we do realloc(NULL,sz)505// for malloc() and realloc(p,0) for free().506static void * stb__realloc_raw(void *p, int sz)507{508   if (p == NULL) return malloc(sz);509   if (sz == 0)   { free(p); return NULL; }510   return realloc(p,sz);511}512#endif513514#ifdef _WIN32515STB_EXTERN void * stb_smalloc(size_t sz);516STB_EXTERN void   stb_sfree(void *p);517STB_EXTERN void * stb_srealloc(void *p, size_t sz);518STB_EXTERN void * stb_scalloc(size_t n, size_t sz);519STB_EXTERN char * stb_sstrdup(char *s);520#endif521522#ifdef STB_FASTMALLOC523#define malloc  stb_smalloc524#define free    stb_sfree525#define realloc stb_srealloc526#define strdup  stb_sstrdup527#define calloc  stb_scalloc528#endif529530#ifndef STB_MALLOC_ALLCHECK531   #define stb__check(p)  1532#else533   #ifndef STB_MALLOC_WRAPPER534      #error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER535   #else536      #define stb__check(p) stb_mcheck(p)537   #endif538#endif539540#ifdef STB_MALLOC_WRAPPER541   STB_EXTERN void * stb__malloc(size_t, char *, int);542   STB_EXTERN void * stb__realloc(void *, size_t, char *, int);543   STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int);544   STB_EXTERN void   stb__free(void *, char *file, int);545   STB_EXTERN char * stb__strdup(char *s, char *file, int);546   STB_EXTERN void   stb_malloc_checkall(void);547   STB_EXTERN void   stb_malloc_check_counter(int init_delay, int rep_delay);548   #ifndef STB_MALLOC_WRAPPER_DEBUG549      #define stb_mcheck(p) 1550   #else551      STB_EXTERN int   stb_mcheck(void *);552   #endif553554555   #ifdef STB_DEFINE556557   #ifdef STB_MALLOC_WRAPPER_DEBUG558      #define STB__PAD   32559      #define STB__BIAS  16560      #define STB__SIG   0x51b01234561      #define STB__FIXSIZE(sz)  (((sz+3) & ~3) + STB__PAD)562      #define STB__ptr(x,y)   ((char *) (x) + (y))563   #else564      #define STB__ptr(x,y)   (x)565      #define STB__FIXSIZE(sz)  (sz)566   #endif567568   #ifdef STB_MALLOC_WRAPPER_DEBUG569   int stb_mcheck(void *p)570   {571      unsigned int sz;572      if (p == NULL) return 1;573      p = ((char *) p) - STB__BIAS;574      sz = * (unsigned int *) p;575      assert(* (unsigned int *) STB__ptr(p,4) == STB__SIG);576      assert(* (unsigned int *) STB__ptr(p,8) == STB__SIG);577      assert(* (unsigned int *) STB__ptr(p,12) == STB__SIG);578      assert(* (unsigned int *) STB__ptr(p,sz-4) == STB__SIG+1);579      assert(* (unsigned int *) STB__ptr(p,sz-8) == STB__SIG+1);580      assert(* (unsigned int *) STB__ptr(p,sz-12) == STB__SIG+1);581      assert(* (unsigned int *) STB__ptr(p,sz-16) == STB__SIG+1);582      stb_wrapper_check(STB__ptr(p, STB__BIAS));583      return 1;584   }585586   static void stb__check2(void *p, size_t sz, char *file, int line)587   {588      stb_mcheck(p);589   }590591   void stb_malloc_checkall(void)592   {593      stb_wrapper_listall(stb__check2);594   }595   #else596   void stb_malloc_checkall(void) { }597   #endif598599   static int stb__malloc_wait=(1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter;600   void stb_malloc_check_counter(int init_delay, int rep_delay)601   {602      stb__malloc_wait = init_delay;603      stb__malloc_next_wait = rep_delay;604   }605606   void stb_mcheck_all(void)607   {608      #ifdef STB_MALLOC_WRAPPER_DEBUG609      ++stb__malloc_iter;610      if (--stb__malloc_wait <= 0) {611         stb_malloc_checkall();612         stb__malloc_wait = stb__malloc_next_wait;613      }614      #endif615   }616617   #ifdef STB_MALLOC_WRAPPER_PAGED618   #define STB__WINDOWS_PAGE (1 << 12)619   #ifndef _WINDOWS_620   STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);621   STB_EXTERN __declspec(dllimport) int   __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);622   #endif623   #endif624625   static void *stb__malloc_final(size_t sz)626   {627      #ifdef STB_MALLOC_WRAPPER_PAGED628      size_t aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE-1);629      char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE630      if (p == NULL) return p;631      VirtualAlloc(p, aligned,   0x1000, 0x04); // COMMIT, READWRITE632      return p;633      #else634      return malloc(sz);635      #endif636   }637638   static void stb__free_final(void *p)639   {640      #ifdef STB_MALLOC_WRAPPER_PAGED641      VirtualFree(p, 0, 0x8000); // RELEASE642      #else643      free(p);644      #endif645   }646647   int stb__malloc_failure;648   #ifdef STB_MALLOC_WRAPPER_PAGED649   static void *stb__realloc_final(void *p, size_t sz, size_t old_sz)650   {651      void *q = stb__malloc_final(sz);652      if (q == NULL)653          return ++stb__malloc_failure, q;654      // @TODO: deal with p being smaller!655      memcpy(q, p, sz < old_sz ? sz : old_sz);656      stb__free_final(p);657      return q;658   }659   #endif660661   void stb__free(void *p, char *file, int line)662   {663      stb_mcheck_all();664      if (!p) return;665      #ifdef STB_MALLOC_WRAPPER_DEBUG666      stb_mcheck(p);667      #endif668      stb_wrapper_free(p,file,line);669      #ifdef STB_MALLOC_WRAPPER_DEBUG670         p = STB__ptr(p,-STB__BIAS);671         * (unsigned int *) STB__ptr(p,0) = 0xdeadbeef;672         * (unsigned int *) STB__ptr(p,4) = 0xdeadbeef;673         * (unsigned int *) STB__ptr(p,8) = 0xdeadbeef;674         * (unsigned int *) STB__ptr(p,12) = 0xdeadbeef;675      #endif676      stb__free_final(p);677   }678679   void * stb__malloc(size_t sz, char *file, int line)680   {681      void *p;682      stb_mcheck_all();683      if (sz == 0) return NULL;684      p = stb__malloc_final(STB__FIXSIZE(sz));685      if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));686      if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));687      if (p == NULL) {688         ++stb__malloc_failure;689         #ifdef STB_MALLOC_WRAPPER_DEBUG690         stb_malloc_checkall();691         #endif692         return p;693      }694      #ifdef STB_MALLOC_WRAPPER_DEBUG695      * (int *) STB__ptr(p,0) = STB__FIXSIZE(sz);696      * (unsigned int *) STB__ptr(p,4) = STB__SIG;697      * (unsigned int *) STB__ptr(p,8) = STB__SIG;698      * (unsigned int *) STB__ptr(p,12) = STB__SIG;699      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-4) = STB__SIG+1;700      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-8) = STB__SIG+1;701      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-12) = STB__SIG+1;702      * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-16) = STB__SIG+1;703      p = STB__ptr(p, STB__BIAS);704      #endif705      stb_wrapper_malloc(p,sz,file,line);706      return p;707   }708709   void * stb__realloc(void *p, size_t sz, char *file, int line)710   {711      void *q;712713      stb_mcheck_all();714      if (p == NULL) return stb__malloc(sz,file,line);715      if (sz == 0  ) { stb__free(p,file,line); return NULL; }716717      #ifdef STB_MALLOC_WRAPPER_DEBUG718         stb_mcheck(p);719         p = STB__ptr(p,-STB__BIAS);720      #endif721      #ifdef STB_MALLOC_WRAPPER_PAGED722      {723         size_t n = stb_wrapper_allocsize(STB__ptr(p,STB__BIAS));724         if (!n)725            stb_wrapper_check(STB__ptr(p,STB__BIAS));726         q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n));727      }728      #else729      q = realloc(p, STB__FIXSIZE(sz));730      #endif731      if (q == NULL)732         return ++stb__malloc_failure, q;733      #ifdef STB_MALLOC_WRAPPER_DEBUG734      * (int *) STB__ptr(q,0) = STB__FIXSIZE(sz);735      * (unsigned int *) STB__ptr(q,4) = STB__SIG;736      * (unsigned int *) STB__ptr(q,8) = STB__SIG;737      * (unsigned int *) STB__ptr(q,12) = STB__SIG;738      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-4) = STB__SIG+1;739      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-8) = STB__SIG+1;740      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-12) = STB__SIG+1;741      * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-16) = STB__SIG+1;742743      q = STB__ptr(q, STB__BIAS);744      p = STB__ptr(p, STB__BIAS);745      #endif746      stb_wrapper_realloc(p,q,sz,file,line);747      return q;748   }749750   STB_EXTERN int stb_log2_ceil(size_t);751   static void *stb__calloc(size_t n, size_t sz, char *file, int line)752   {753      void *q;754      stb_mcheck_all();755      if (n == 0 || sz == 0) return NULL;756      if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL;757      q = stb__malloc(n*sz, file, line);758      if (q) memset(q, 0, n*sz);759      return q;760   }761762   char * stb__strdup(char *s, char *file, int line)763   {764      char *p;765      stb_mcheck_all();766      p = stb__malloc(strlen(s)+1, file, line);767      if (!p) return p;768      stb_p_strcpy_s(p, strlen(s)+1, s);769      return p;770   }771   #endif // STB_DEFINE772773   #ifdef STB_FASTMALLOC774   #undef malloc775   #undef realloc776   #undef free777   #undef strdup778   #undef calloc779   #endif780781   // include everything that might define these, BEFORE making macros782   #include <stdlib.h>783   #include <string.h>784   #include <malloc.h>785786   #define malloc(s)      stb__malloc (  s, __FILE__, __LINE__)787   #define realloc(p,s)   stb__realloc(p,s, __FILE__, __LINE__)788   #define calloc(n,s)    stb__calloc (n,s, __FILE__, __LINE__)789   #define free(p)        stb__free   (p,   __FILE__, __LINE__)790   #define strdup(p)      stb__strdup (p,   __FILE__, __LINE__)791#endif792793//////////////////////////////////////////////////////////////////////////////794//795//                         Windows pretty display796//797798STB_EXTERN void stbprint(const char *fmt, ...);799STB_EXTERN char *stb_sprintf(const char *fmt, ...);800STB_EXTERN char *stb_mprintf(const char *fmt, ...);801STB_EXTERN int  stb_snprintf(char *s, size_t n, const char *fmt, ...);802STB_EXTERN int  stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);803804#ifdef STB_DEFINE805int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)806{807   int res;808   #ifdef _WIN32809      #ifdef __STDC_WANT_SECURE_LIB__810      res = _vsnprintf_s(s, n, _TRUNCATE, fmt, v);811      #else812      res = stb_p_vsnprintf(s,n,fmt,v);813      #endif814   #else815   res = vsnprintf(s,n,fmt,v);816   #endif817   if (n) s[n-1] = 0;818   // Unix returns length output would require, Windows returns negative when truncated.819   return (res >= (int) n || res < 0) ? -1 : res;820}821822int stb_snprintf(char *s, size_t n, const char *fmt, ...)823{824   int res;825   va_list v;826   va_start(v,fmt);827   res = stb_vsnprintf(s, n, fmt, v);828   va_end(v);829   return res;830}831832char *stb_sprintf(const char *fmt, ...)833{834   static char buffer[1024];835   va_list v;836   va_start(v,fmt);837   stb_vsnprintf(buffer,1024,fmt,v);838   va_end(v);839   return buffer;840}841842char *stb_mprintf(const char *fmt, ...)843{844   static char buffer[1024];845   va_list v;846   va_start(v,fmt);847   stb_vsnprintf(buffer,1024,fmt,v);848   va_end(v);849   return stb_p_strdup(buffer);850}851852#ifdef _WIN32853854#ifndef _WINDOWS_855STB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *);856STB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int);857STB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short);858#endif859860static void stb__print_one(void *handle, char *s, ptrdiff_t  len)861{862   if (len)863      if (0==WriteConsoleA(handle, s, (unsigned) len, NULL,NULL))864         // if it fails, maybe redirected, so output normally...865         // but it's supriously reporting failure now on Win7 and later866         {}//fwrite(s, 1, (unsigned) len, stdout);867}868869static void stb__print(char *s)870{871   void *handle = GetStdHandle((unsigned int) -11); // STD_OUTPUT_HANDLE872   int pad=0; // number of padding characters to add873874   char *t = s;875   while (*s) {876      int lpad;877      while (*s && *s != '{') {878         if (pad) {879            if (*s == '\r' || *s == '\n')880               pad = 0;881            else if (s[0] == ' ' && s[1] == ' ') {882               stb__print_one(handle, t, s-t);883               t = s;884               while (pad) {885                  stb__print_one(handle, t, 1);886                  --pad;887               }888            }889         }890         ++s;891      }892      if (!*s) break;893      stb__print_one(handle, t, s-t);894      if (s[1] == '{') {895         ++s;896         continue;897      }898899      if (s[1] == '#') {900         t = s+3;901         if (isxdigit(s[2]))902            if (isdigit(s[2]))903               SetConsoleTextAttribute(handle, s[2] - '0');904            else905               SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10);906         else {907            SetConsoleTextAttribute(handle, 0x0f);908            t=s+2;909         }910      } else if (s[1] == '!') {911         SetConsoleTextAttribute(handle, 0x0c);912         t = s+2;913      } else if (s[1] == '@') {914         SetConsoleTextAttribute(handle, 0x09);915         t = s+2;916      } else if (s[1] == '$') {917         SetConsoleTextAttribute(handle, 0x0a);918         t = s+2;919      } else {920         SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey921         t = s+1;922      }923924      lpad = (int) (t-s);925      s = t;926      while (*s && *s != '}') ++s;927      if (!*s) break;928      stb__print_one(handle, t, s-t);929      if (s[1] == '}') {930         t = s+2;931      } else {932         pad += 1+lpad;933         t = s+1;934      }935      s=t;936      SetConsoleTextAttribute(handle, 0x07);937   }938   stb__print_one(handle, t, s-t);939   SetConsoleTextAttribute(handle, 0x07);940}941942void stbprint(const char *fmt, ...)943{944   int res;945   char buffer[1024];946   char *tbuf = buffer;947   va_list v;948949   va_start(v,fmt);950   res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v);951   va_end(v);952953   if (res < 0) {954      tbuf = (char *) malloc(16384);955      va_start(v,fmt);956      res = stb_vsnprintf(tbuf,16384, fmt, v);957      va_end(v);958      tbuf[16383] = 0;959   }960961   stb__print(tbuf);962963   if (tbuf != buffer)964      free(tbuf);965}966967#else  // _WIN32968void stbprint(const char *fmt, ...)969{970   va_list v;971   va_start(v,fmt);972   vprintf(fmt,v);973   va_end(v);974}975#endif // _WIN32976#endif // STB_DEFINE977978979980//////////////////////////////////////////////////////////////////////////////981//982//                         Windows UTF8 filename handling983//984// Windows stupidly treats 8-bit filenames as some dopey code page,985// rather than utf-8. If we want to use utf8 filenames, we have to986// convert them to WCHAR explicitly and call WCHAR versions of the987// file functions. So, ok, we do.988989990#ifdef _WIN32991   #define stb__fopen(x,y)    stb_p_wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))992   #define stb__windows(x,y)  x993#else994   #define stb__fopen(x,y)    stb_p_fopen(x,y)995   #define stb__windows(x,y)  y996#endif997998999typedef unsigned short stb__wchar;10001001STB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *str, int n);1002STB_EXTERN char       * stb_to_utf8  (char *buffer, const stb__wchar *str, int n);10031004STB_EXTERN stb__wchar *stb__from_utf8(const char *str);1005STB_EXTERN stb__wchar *stb__from_utf8_alt(const char *str);1006STB_EXTERN char *stb__to_utf8(const stb__wchar *str);100710081009#ifdef STB_DEFINE1010stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *ostr, int n)1011{1012   unsigned char *str = (unsigned char *) ostr;1013   stb_uint32 c;1014   int i=0;1015   --n;1016   while (*str) {1017      if (i >= n)1018         return NULL;1019      if (!(*str & 0x80))1020         buffer[i++] = *str++;1021      else if ((*str & 0xe0) == 0xc0) {1022         if (*str < 0xc2) return NULL;1023         c = (*str++ & 0x1f) << 6;1024         if ((*str & 0xc0) != 0x80) return NULL;1025         buffer[i++] = c + (*str++ & 0x3f);1026      } else if ((*str & 0xf0) == 0xe0) {1027         if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;1028         if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below1029         c = (*str++ & 0x0f) << 12;1030         if ((*str & 0xc0) != 0x80) return NULL;1031         c += (*str++ & 0x3f) << 6;1032         if ((*str & 0xc0) != 0x80) return NULL;1033         buffer[i++] = c + (*str++ & 0x3f);1034      } else if ((*str & 0xf8) == 0xf0) {1035         if (*str > 0xf4) return NULL;1036         if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;1037         if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below1038         c = (*str++ & 0x07) << 18;1039         if ((*str & 0xc0) != 0x80) return NULL;1040         c += (*str++ & 0x3f) << 12;1041         if ((*str & 0xc0) != 0x80) return NULL;1042         c += (*str++ & 0x3f) << 6;1043         if ((*str & 0xc0) != 0x80) return NULL;1044         c += (*str++ & 0x3f);1045         // utf-8 encodings of values used in surrogate pairs are invalid1046         if ((c & 0xFFFFF800) == 0xD800) return NULL;1047         if (c >= 0x10000) {1048            c -= 0x10000;1049            if (i + 2 > n) return NULL;1050            buffer[i++] = 0xD800 | (0x3ff & (c >> 10));1051            buffer[i++] = 0xDC00 | (0x3ff & (c      ));1052         }1053      } else1054         return NULL;1055   }1056   buffer[i] = 0;1057   return buffer;1058}10591060char * stb_to_utf8(char *buffer, const stb__wchar *str, int n)1061{1062   int i=0;1063   --n;1064   while (*str) {1065      if (*str < 0x80) {1066         if (i+1 > n) return NULL;1067         buffer[i++] = (char) *str++;1068      } else if (*str < 0x800) {1069         if (i+2 > n) return NULL;1070         buffer[i++] = 0xc0 + (*str >> 6);1071         buffer[i++] = 0x80 + (*str & 0x3f);1072         str += 1;1073      } else if (*str >= 0xd800 && *str < 0xdc00) {1074         stb_uint32 c;1075         if (i+4 > n) return NULL;1076         c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;1077         buffer[i++] = 0xf0 + (c >> 18);1078         buffer[i++] = 0x80 + ((c >> 12) & 0x3f);1079         buffer[i++] = 0x80 + ((c >>  6) & 0x3f);1080         buffer[i++] = 0x80 + ((c      ) & 0x3f);1081         str += 2;1082      } else if (*str >= 0xdc00 && *str < 0xe000) {1083         return NULL;1084      } else {1085         if (i+3 > n) return NULL;1086         buffer[i++] = 0xe0 + (*str >> 12);1087         buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);1088         buffer[i++] = 0x80 + ((*str     ) & 0x3f);1089         str += 1;1090      }1091   }1092   buffer[i] = 0;1093   return buffer;1094}10951096stb__wchar *stb__from_utf8(const char *str)1097{1098   static stb__wchar buffer[4096];1099   return stb_from_utf8(buffer, str, 4096);1100}11011102stb__wchar *stb__from_utf8_alt(const char *str)1103{1104   static stb__wchar buffer[4096];1105   return stb_from_utf8(buffer, str, 4096);1106}11071108char *stb__to_utf8(const stb__wchar *str)1109{1110   static char buffer[4096];1111   return stb_to_utf8(buffer, str, 4096);1112}11131114#endif11151116//////////////////////////////////////////////////////////////////////////////1117//1118//                         Miscellany1119//11201121STB_EXTERN void stb_fatal(const char *fmt, ...);1122STB_EXTERN void stb_(char *fmt, ...);1123STB_EXTERN void stb_append_to_file(char *file, char *fmt, ...);1124STB_EXTERN void stb_log(int active);1125STB_EXTERN void stb_log_fileline(int active);1126STB_EXTERN void stb_log_name(char *filename);11271128STB_EXTERN void stb_swap(void *p, void *q, size_t sz);1129STB_EXTERN void *stb_copy(void *p, size_t sz);1130STB_EXTERN void stb_pointer_array_free(void *p, int len);1131STB_EXTERN void **stb_array_block_alloc(int count, int blocksize);11321133#define stb_arrcount(x)   (sizeof(x)/sizeof((x)[0]))113411351136STB_EXTERN int  stb__record_fileline(const char *f, int n);11371138#ifdef STB_DEFINE11391140static char *stb__file;1141static int   stb__line;11421143int  stb__record_fileline(const char *f, int n)1144{1145   stb__file = (char*) f;1146   stb__line = n;1147   return 0;1148}11491150void stb_fatal(const char *s, ...)1151{1152   va_list a;1153   if (stb__file)1154      fprintf(stderr, "[%s:%d] ", stb__file, stb__line);1155   va_start(a,s);1156   fputs("Fatal error: ", stderr);1157   vfprintf(stderr, s, a);1158   va_end(a);1159   fputs("\n", stderr);1160   #ifdef STB_DEBUG1161   #ifdef _MSC_VER1162   #ifndef STB_PTR641163   __asm int 3;   // trap to debugger!1164   #else1165   __debugbreak();1166   #endif1167   #else1168   __builtin_trap();1169   #endif1170   #endif1171   exit(1);1172}11731174static int stb__log_active=1, stb__log_fileline=1;11751176void stb_log(int active)1177{1178   stb__log_active = active;1179}11801181void stb_log_fileline(int active)1182{1183   stb__log_fileline = active;1184}11851186#ifdef STB_NO_STB_STRINGS1187const char *stb__log_filename = "temp.log";1188#else1189const char *stb__log_filename = "stb.log";1190#endif11911192void stb_log_name(char *s)1193{1194   stb__log_filename = s;1195}11961197void stb_(char *s, ...)1198{1199   if (stb__log_active) {1200      FILE *f = stb_p_fopen(stb__log_filename, "a");1201      if (f) {1202         va_list a;1203         if (stb__log_fileline && stb__file)1204            fprintf(f, "[%s:%4d] ", stb__file, stb__line);1205         va_start(a,s);1206         vfprintf(f, s, a);1207         va_end(a);1208         fputs("\n", f);1209         fclose(f);1210      }1211   }1212}12131214void stb_append_to_file(char *filename, char *s, ...)1215{1216   FILE *f = stb_p_fopen(filename, "a");1217   if (f) {1218      va_list a;1219      va_start(a,s);1220      vfprintf(f, s, a);1221      va_end(a);1222      fputs("\n", f);1223      fclose(f);1224   }1225}122612271228typedef struct { char d[4]; } stb__4;1229typedef struct { char d[8]; } stb__8;12301231// optimize the small cases, though you shouldn't be calling this for those!1232void stb_swap(void *p, void *q, size_t sz)1233{1234   char buffer[256];1235   if (p == q) return;1236   if (sz == 4) {1237      stb__4 temp    = * ( stb__4 *) p;1238      * (stb__4 *) p = * ( stb__4 *) q;1239      * (stb__4 *) q = temp;1240      return;1241   } else if (sz == 8) {1242      stb__8 temp    = * ( stb__8 *) p;1243      * (stb__8 *) p = * ( stb__8 *) q;1244      * (stb__8 *) q = temp;1245      return;1246   }12471248   while (sz > sizeof(buffer)) {1249      stb_swap(p, q, sizeof(buffer));1250      p = (char *) p + sizeof(buffer);1251      q = (char *) q + sizeof(buffer);1252      sz -= sizeof(buffer);1253   }12541255   memcpy(buffer, p     , sz);1256   memcpy(p     , q     , sz);1257   memcpy(q     , buffer, sz);1258}12591260void *stb_copy(void *p, size_t sz)1261{1262   void *q = malloc(sz);1263   memcpy(q, p, sz);1264   return q;1265}12661267void stb_pointer_array_free(void *q, int len)1268{1269   void **p = (void **) q;1270   int i;1271   for (i=0; i < len; ++i)1272      free(p[i]);1273}12741275void **stb_array_block_alloc(int count, int blocksize)1276{1277   int i;1278   char *p = (char *) malloc(sizeof(void *) * count + count * blocksize);1279   void **q;1280   if (p == NULL) return NULL;1281   q = (void **) p;1282   p += sizeof(void *) * count;1283   for (i=0; i < count; ++i)1284      q[i] = p + i * blocksize;1285   return q;1286}1287#endif12881289#ifdef STB_DEBUG1290   // tricky hack to allow recording FILE,LINE even in varargs functions1291   #define STB__RECORD_FILE(x)  (stb__record_fileline(__FILE__, __LINE__),(x))1292   #define stb_log              STB__RECORD_FILE(stb_log)1293   #define stb_                 STB__RECORD_FILE(stb_)1294   #ifndef STB_FATAL_CLEAN1295   #define stb_fatal            STB__RECORD_FILE(stb_fatal)1296   #endif1297   #define STB__DEBUG(x)        x1298#else1299   #define STB__DEBUG(x)1300#endif13011302//////////////////////////////////////////////////////////////////////////////1303//1304//                         stb_temp1305//13061307#define stb_temp(block, sz)     stb__temp(block, sizeof(block), (sz))13081309STB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz);1310STB_EXTERN void   stb_tempfree(void *block, void *ptr);13111312#ifdef STB_DEFINE13131314void * stb__temp(void *b, int b_sz, int want_sz)1315{1316   if (b_sz >= want_sz)1317      return b;1318   else1319      return malloc(want_sz);1320}13211322void   stb_tempfree(void *b, void *p)1323{1324   if (p != b)1325      free(p);1326}1327#endif132813291330//////////////////////////////////////////////////////////////////////////////1331//1332//                      math/sampling operations1333//133413351336#define stb_lerp(t,a,b)               ( (a) + (t) * (float) ((b)-(a)) )1337#define stb_unlerp(t,a,b)             ( ((t) - (a)) / (float) ((b) - (a)) )13381339#define stb_clamp(x,xmin,xmax)  ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x))13401341STB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize);1342STB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis);1343STB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt);13441345STB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps);1346STB_EXTERN int stb_is_prime(unsigned int m);1347STB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n);13481349STB_EXTERN float stb_smoothstep(float t);1350STB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3);13511352STB_EXTERN double stb_linear_remap(double x, double a, double b,1353                                             double c, double d);13541355#ifdef STB_DEFINE1356float stb_smoothstep(float t)1357{1358   return (3 - 2*t)*(t*t);1359}13601361float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3)1362{1363   float it = 1-t;1364   return it*it*it*p0 + 3*it*it*t*p1 + 3*it*t*t*p2 + t*t*t*p3;1365}13661367void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize)1368{1369   int i,j;1370   float p;1371   normal[0] = normal[1] = normal[2] = 0;1372   for (i=num_vert-1,j=0; j < num_vert; i=j++) {1373      float *u = vert[i];1374      float *v = vert[j];1375      normal[0] += (u[1] - v[1]) * (u[2] + v[2]);1376      normal[1] += (u[2] - v[2]) * (u[0] + v[0]);1377      normal[2] += (u[0] - v[0]) * (u[1] + v[1]);1378   }1379   if (normalize) {1380      p = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2];1381      p = (float) (1.0 / sqrt(p));1382      normal[0] *= p;1383      normal[1] *= p;1384      normal[2] *= p;1385   }1386}13871388int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis)1389{1390   static int box_vertices[6][4][3] =1391   {1392      { { 1,1,1 }, { 1,0,1 }, { 1,0,0 }, { 1,1,0 } },1393      { { 0,0,0 }, { 0,0,1 }, { 0,1,1 }, { 0,1,0 } },1394      { { 0,0,0 }, { 0,1,0 }, { 1,1,0 }, { 1,0,0 } },1395      { { 0,0,0 }, { 1,0,0 }, { 1,0,1 }, { 0,0,1 } },1396      { { 1,1,1 }, { 0,1,1 }, { 0,0,1 }, { 1,0,1 } },1397      { { 1,1,1 }, { 1,1,0 }, { 0,1,0 }, { 0,1,1 } },1398   };1399   assert(face_number >= 0 && face_number < 6);1400   assert(vertex_number >= 0 && vertex_number < 4);1401   assert(axis >= 0 && axis < 3);1402   return box_vertices[face_number][vertex_number][axis];1403}14041405void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt)1406{1407   float sign = 1, p, cp = *curpos;1408   if (cp == target_pos) return;1409   if (target_pos < cp) {1410      target_pos = -target_pos;1411      cp = -cp;1412      sign = -1;1413   }1414   // first decelerate1415   if (cp < 0) {1416      p = cp + deacc * dt;1417      if (p > 0) {1418         p = 0;1419         dt = dt - cp / deacc;1420         if (dt < 0) dt = 0;1421      } else {1422         dt = 0;1423      }1424      cp = p;1425   }1426   // now accelerate1427   p = cp + acc*dt;1428   if (p > target_pos) p = target_pos;1429   *curpos = p * sign;1430   // @TODO: testing1431}14321433float stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel)1434{1435   return 0; // @TODO1436}14371438int stb_float_eq(float x, float y, float delta, int max_ulps)1439{1440   if (fabs(x-y) <= delta) return 1;1441   if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1;1442   return 0;1443}14441445int stb_is_prime(unsigned int m)1446{1447   unsigned int i,j;1448   if (m < 2) return 0;1449   if (m == 2) return 1;1450   if (!(m & 1)) return 0;1451   if (m % 3 == 0) return (m == 3);1452   for (i=5; (j=i*i), j <= m && j > i; i += 6) {1453      if (m %   i   == 0) return 0;1454      if (m % (i+2) == 0) return 0;1455   }1456   return 1;1457}14581459unsigned int stb_power_of_two_nearest_prime(int n)1460{1461   static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1,1462                                   0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 };1463   if (!tab[0]) {1464      int i;1465      for (i=0; i < 32; ++i)1466         tab[i] = (1 << i) + 2*tab[i] - 1;1467      tab[1] = 2;1468      tab[0] = 1;1469   }1470   if (n >= 32) return 0xfffffffb;1471   return tab[n];1472}14731474double stb_linear_remap(double x, double x_min, double x_max,1475                                  double out_min, double out_max)1476{1477   return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);1478}1479#endif14801481// create a macro so it's faster, but you can get at the function pointer1482#define stb_linear_remap(t,a,b,c,d)   stb_lerp(stb_unlerp(t,a,b),c,d)148314841485//////////////////////////////////////////////////////////////////////////////1486//1487//                         bit operations1488//14891490#define stb_big32(c)    (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])1491#define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0])1492#define stb_big16(c)    ((c)[0]*256 + (c)[1])1493#define stb_little16(c) ((c)[1]*256 + (c)[0])14941495STB_EXTERN          int stb_bitcount(unsigned int a);1496STB_EXTERN unsigned int stb_bitreverse8(unsigned char n);1497STB_EXTERN unsigned int stb_bitreverse(unsigned int n);14981499STB_EXTERN          int stb_is_pow2(size_t);1500STB_EXTERN          int stb_log2_ceil(size_t);1501STB_EXTERN          int stb_log2_floor(size_t);15021503STB_EXTERN          int stb_lowbit8(unsigned int n);1504STB_EXTERN          int stb_highbit8(unsigned int n);15051506#ifdef STB_DEFINE1507int stb_bitcount(unsigned int a)1508{1509   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 21510   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 41511   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits1512   a = (a + (a >> 8)); // max 16 per 8 bits1513   a = (a + (a >> 16)); // max 32 per 8 bits1514   return a & 0xff;1515}15161517unsigned int stb_bitreverse8(unsigned char n)1518{1519   n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1);1520   n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2);1521   return (unsigned char) ((n >> 4) + (n << 4));1522}15231524unsigned int stb_bitreverse(unsigned int n)1525{1526  n = ((n & 0xAAAAAAAA) >>  1) | ((n & 0x55555555) << 1);1527  n = ((n & 0xCCCCCCCC) >>  2) | ((n & 0x33333333) << 2);1528  n = ((n & 0xF0F0F0F0) >>  4) | ((n & 0x0F0F0F0F) << 4);1529  n = ((n & 0xFF00FF00) >>  8) | ((n & 0x00FF00FF) << 8);1530  return (n >> 16) | (n << 16);1531}15321533int stb_is_pow2(size_t n)1534{1535   return (n & (n-1)) == 0;1536}15371538// tricky use of 4-bit table to identify 5 bit positions (note the '-1')1539// 3-bit table would require another tree level; 5-bit table wouldn't save one1540#if defined(_WIN32) && !defined(__MINGW32__)1541#pragma warning(push)1542#pragma warning(disable: 4035)  // disable warning about no return value1543int stb_log2_floor(size_t n)1544{1545   #if _MSC_VER > 17001546   unsigned long i;1547   #ifdef STB_PTR641548   _BitScanReverse64(&i, n);1549   #else1550   _BitScanReverse(&i, n);1551   #endif1552   return i != 0 ? i : -1;1553   #else1554   __asm {1555      bsr eax,n1556      jnz done1557      mov eax,-11558   }1559   done:;1560   #endif1561}1562#pragma warning(pop)1563#else1564int stb_log2_floor(size_t n)1565{1566   static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 };15671568#ifdef STB_PTR641569   if (n >= ((size_t) 1u << 32))1570        return stb_log2_floor(n >> 32);1571#endif15721573   // 2 compares if n < 16, 3 compares otherwise1574   if (n < (1U << 14))1575        if (n < (1U <<  4))        return     0 + log2_4[n      ];1576        else if (n < (1U <<  9))      return  5 + log2_4[n >>  5];1577             else                     return 10 + log2_4[n >> 10];1578   else if (n < (1U << 24))1579             if (n < (1U << 19))      return 15 + log2_4[n >> 15];1580             else                     return 20 + log2_4[n >> 20];1581        else if (n < (1U << 29))      return 25 + log2_4[n >> 25];1582             else                     return 30 + log2_4[n >> 30];1583}1584#endif15851586// define ceil from floor1587int stb_log2_ceil(size_t n)1588{1589   if (stb_is_pow2(n))  return     stb_log2_floor(n);1590   else                 return 1 + stb_log2_floor(n);1591}15921593int stb_highbit8(unsigned int n)1594{1595   return stb_log2_ceil(n&255);1596}15971598int stb_lowbit8(unsigned int n)1599{1600   static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 };1601   int k = lowbit4[n & 15];1602   if (k >= 0) return k;1603   k = lowbit4[(n >> 4) & 15];1604   if (k >= 0) return k+4;1605   return k;1606}1607#endif1608160916101611//////////////////////////////////////////////////////////////////////////////1612//1613//                            qsort Compare Routines1614//16151616#ifdef _WIN321617   #define stb_stricmp(a,b) stb_p_stricmp(a,b)1618   #define stb_strnicmp(a,b,n) stb_p_strnicmp(a,b,n)1619#else1620   #define stb_stricmp(a,b) strcasecmp(a,b)1621   #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)1622#endif162316241625STB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);1626STB_EXTERN int (*stb_intcmprev(int offset))(const void *a, const void *b);1627STB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);1628STB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);1629STB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);1630STB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);1631STB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);16321633#ifdef STB_DEFINE1634static int stb__intcmpoffset, stb__ucharcmpoffset, stb__strcmpoffset;1635static int stb__floatcmpoffset, stb__doublecmpoffset;1636static int stb__memcmpoffset, stb__memcmpsize;16371638int stb__intcmp(const void *a, const void *b)1639{1640   const int p = *(const int *) ((const char *) a + stb__intcmpoffset);1641   const int q = *(const int *) ((const char *) b + stb__intcmpoffset);1642   return p < q ? -1 : p > q;1643}16441645int stb__intcmprev(const void *a, const void *b)1646{1647   const int p = *(const int *) ((const char *) a + stb__intcmpoffset);1648   const int q = *(const int *) ((const char *) b + stb__intcmpoffset);1649   return q < p ? -1 : q > p;1650}16511652int stb__ucharcmp(const void *a, const void *b)1653{1654   const int p = *(const unsigned char *) ((const char *) a + stb__ucharcmpoffset);1655   const int q = *(const unsigned char *) ((const char *) b + stb__ucharcmpoffset);1656   return p < q ? -1 : p > q;1657}16581659int stb__floatcmp(const void *a, const void *b)1660{1661   const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);1662   const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);1663   return p < q ? -1 : p > q;1664}16651666int stb__doublecmp(const void *a, const void *b)1667{1668   const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);1669   const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);1670   return p < q ? -1 : p > q;1671}16721673int stb__qsort_strcmp(const void *a, const void *b)1674{1675   const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);1676   const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);1677   return strcmp(p,q);1678}16791680int stb__qsort_stricmp(const void *a, const void *b)1681{1682   const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);1683   const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);1684   return stb_stricmp(p,q);1685}16861687int stb__memcmp(const void *a, const void *b)1688{1689   return memcmp((char *) a + stb__memcmpoffset, (char *) b + stb__memcmpoffset, stb__memcmpsize);1690}16911692int (*stb_intcmp(int offset))(const void *, const void *)1693{1694   stb__intcmpoffset = offset;1695   return &stb__intcmp;1696}16971698int (*stb_intcmprev(int offset))(const void *, const void *)1699{1700   stb__intcmpoffset = offset;1701   return &stb__intcmprev;1702}17031704int (*stb_ucharcmp(int offset))(const void *, const void *)1705{1706   stb__ucharcmpoffset = offset;1707   return &stb__ucharcmp;1708}17091710int (*stb_qsort_strcmp(int offset))(const void *, const void *)1711{1712   stb__strcmpoffset = offset;1713   return &stb__qsort_strcmp;1714}17151716int (*stb_qsort_stricmp(int offset))(const void *, const void *)1717{1718   stb__strcmpoffset = offset;1719   return &stb__qsort_stricmp;1720}17211722int (*stb_floatcmp(int offset))(const void *, const void *)1723{1724   stb__floatcmpoffset = offset;1725   return &stb__floatcmp;1726}17271728int (*stb_doublecmp(int offset))(const void *, const void *)1729{1730   stb__doublecmpoffset = offset;1731   return &stb__doublecmp;1732}17331734int (*stb_memcmp(int offset, int size))(const void *, const void *)1735{1736   stb__memcmpoffset = offset;1737   stb__memcmpsize = size;1738   return &stb__memcmp;1739}1740#endif17411742//////////////////////////////////////////////////////////////////////////////1743//1744//                           Binary Search Toolkit1745//17461747typedef struct1748{1749   int minval, maxval, guess;1750   int mode, step;1751} stb_search;17521753STB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest);1754STB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest);1755STB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done17561757#ifdef STB_DEFINE1758enum1759{1760   STB_probe_binary_smallest,1761   STB_probe_binary_largest,1762   STB_probe_open_smallest,1763   STB_probe_open_largest,1764};17651766static int stb_probe_guess(stb_search *s, int *result)1767{1768   switch(s->mode) {1769      case STB_probe_binary_largest:1770         if (s->minval == s->maxval) {1771            *result = s->minval;1772            return 0;1773         }1774         assert(s->minval < s->maxval);1775         // if a < b, then a < p <= b1776         s->guess = s->minval + (((unsigned) s->maxval - s->minval + 1) >> 1);1777         break;17781779      case STB_probe_binary_smallest:1780         if (s->minval == s->maxval) {1781            *result = s->minval;1782            return 0;1783         }1784         assert(s->minval < s->maxval);1785         // if a < b, then a <= p < b1786         s->guess = s->minval + (((unsigned) s->maxval - s->minval) >> 1);1787         break;1788      case STB_probe_open_smallest:1789      case STB_probe_open_largest:1790         s->guess = s->maxval;  // guess the current maxval1791         break;1792   }1793   *result = s->guess;1794   return 1;1795}17961797int stb_probe(stb_search *s, int compare, int *result)1798{1799   switch(s->mode) {1800      case STB_probe_open_smallest:1801      case STB_probe_open_largest: {1802         if (compare <= 0) {1803            // then it lies within minval & maxval1804            if (s->mode == STB_probe_open_smallest)1805               s->mode = STB_probe_binary_smallest;1806            else1807               s->mode = STB_probe_binary_largest;1808         } else {1809            // otherwise, we need to probe larger1810            s->minval  = s->maxval + 1;1811            s->maxval  = s->minval + s->step;1812            s->step   += s->step;1813         }1814         break;1815      }1816      case STB_probe_binary_smallest: {1817         // if compare < 0, then s->minval <= a <  p1818         // if compare = 0, then s->minval <= a <= p1819         // if compare > 0, then         p <  a <= s->maxval1820         if (compare <= 0)1821            s->maxval = s->guess;1822         else1823            s->minval = s->guess+1;1824         break;1825      }1826      case STB_probe_binary_largest: {1827         // if compare < 0, then s->minval <= a < p1828         // if compare = 0, then         p <= a <= s->maxval1829         // if compare > 0, then         p <  a <= s->maxval1830         if (compare < 0)1831            s->maxval = s->guess-1;1832         else1833            s->minval = s->guess;1834         break;1835      }1836   }1837   return stb_probe_guess(s, result);1838}18391840int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest)1841{1842   int r;1843   if (maxv < minv) return minv-1;1844   s->minval = minv;1845   s->maxval = maxv;1846   s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest;1847   stb_probe_guess(s, &r);1848   return r;1849}18501851int stb_search_open(stb_search *s, int minv, int find_smallest)1852{1853   int r;1854   s->step   = 4;1855   s->minval = minv;1856   s->maxval = minv+s->step;1857   s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest;1858   stb_probe_guess(s, &r);1859   return r;1860}1861#endif18621863//////////////////////////////////////////////////////////////////////////////1864//1865//                           String Processing1866//18671868#define stb_prefixi(s,t)  (0==stb_strnicmp((s),(t),strlen(t)))18691870enum stb_splitpath_flag1871{1872   STB_PATH = 1,1873   STB_FILE = 2,1874   STB_EXT  = 4,1875   STB_PATH_FILE = STB_PATH + STB_FILE,1876   STB_FILE_EXT  = STB_FILE + STB_EXT,1877   STB_EXT_NO_PERIOD = 8,1878};18791880STB_EXTERN char * stb_skipwhite(char *s);1881STB_EXTERN char * stb_trimwhite(char *s);1882STB_EXTERN char * stb_skipnewline(char *s);1883STB_EXTERN char * stb_strncpy(char *s, char *t, int n);1884STB_EXTERN char * stb_substr(char *t, int n);1885STB_EXTERN char * stb_duplower(char *s);1886STB_EXTERN void   stb_tolower (char *s);1887STB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);1888STB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);1889STB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);1890STB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);1891STB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);1892STB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);1893STB_EXTERN void   stb_replaceinplace(char *s, char *find, char *replace);1894STB_EXTERN char * stb_splitpath(char *output, char *src, int flag);1895STB_EXTERN char * stb_splitpathdup(char *src, int flag);1896STB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);1897STB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);1898STB_EXTERN void   stb_fixpath(char *path);1899STB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);1900STB_EXTERN int    stb_suffix (char *s, char *t);1901STB_EXTERN int    stb_suffixi(char *s, char *t);1902STB_EXTERN int    stb_prefix (char *s, char *t);1903STB_EXTERN char * stb_strichr(char *s, char t);1904STB_EXTERN char * stb_stristr(char *s, char *t);1905STB_EXTERN int    stb_prefix_count(char *s, char *t);1906STB_EXTERN const char * stb_plural(int n);  // "s" or ""1907STB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);19081909STB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);1910STB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);1911STB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);1912STB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);1913STB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);1914STB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);1915STB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);1916// with 'quoted', allow delimiters to appear inside quotation marks, and don't1917// strip whitespace inside them (and we delete the quotation marks unless they1918// appear back to back, in which case they're considered escaped)19191920#ifdef STB_DEFINE19211922size_t stb_strscpy(char *d, const char *s, size_t n)1923{1924   size_t len = strlen(s);1925   if (len >= n) {1926      if (n) d[0] = 0;1927      return 0;1928   }1929   stb_p_strcpy_s(d,n,s);1930   return len;1931}19321933const char *stb_plural(int n)1934{1935   return n == 1 ? "" : "s";1936}19371938int stb_prefix(char *s, char *t)1939{1940   while (*t)1941      if (*s++ != *t++)1942         return STB_FALSE;1943   return STB_TRUE;1944}19451946int stb_prefix_count(char *s, char *t)1947{1948   int c=0;1949   while (*t) {1950      if (*s++ != *t++)1951         break;1952      ++c;1953   }1954   return c;1955}19561957int stb_suffix(char *s, char *t)1958{1959   size_t n = strlen(s);1960   size_t m = strlen(t);1961   if (m <= n)1962      return 0 == strcmp(s+n-m, t);1963   else1964      return 0;1965}19661967int stb_suffixi(char *s, char *t)1968{1969   size_t n = strlen(s);1970   size_t m = strlen(t);1971   if (m <= n)1972      return 0 == stb_stricmp(s+n-m, t);1973   else1974      return 0;1975}19761977// originally I was using this table so that I could create known sentinel1978// values--e.g. change whitetable[0] to be true if I was scanning for whitespace,1979// and false if I was scanning for nonwhite. I don't appear to be using that1980// functionality anymore (I do for tokentable, though), so just replace it1981// with isspace()1982char *stb_skipwhite(char *s)1983{1984   while (isspace((unsigned char) *s)) ++s;1985   return s;1986}19871988char *stb_skipnewline(char *s)1989{1990   if (s[0] == '\r' || s[0] == '\n') {1991      if (s[0]+s[1] == '\r' + '\n') ++s;1992      ++s;1993   }1994   return s;1995}19961997char *stb_trimwhite(char *s)1998{1999   int i,n;2000   s = stb_skipwhite(s);

The first 2,000 of 13,111 lines.